OSDN Git Service

e53dfb5b826e2b0d6a9eb77958023c3a106cd731
[sagit-ice-cold/kernel_xiaomi_msm8998.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                 ++ctx->pin_count;
3501
3502                 return ctx;
3503         }
3504
3505         err = -EINVAL;
3506         ctxn = pmu->task_ctx_nr;
3507         if (ctxn < 0)
3508                 goto errout;
3509
3510         if (event->attach_state & PERF_ATTACH_TASK_DATA) {
3511                 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
3512                 if (!task_ctx_data) {
3513                         err = -ENOMEM;
3514                         goto errout;
3515                 }
3516         }
3517
3518 retry:
3519         ctx = perf_lock_task_context(task, ctxn, &flags);
3520         if (ctx) {
3521                 clone_ctx = unclone_ctx(ctx);
3522                 ++ctx->pin_count;
3523
3524                 if (task_ctx_data && !ctx->task_ctx_data) {
3525                         ctx->task_ctx_data = task_ctx_data;
3526                         task_ctx_data = NULL;
3527                 }
3528                 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3529
3530                 if (clone_ctx)
3531                         put_ctx(clone_ctx);
3532         } else {
3533                 ctx = alloc_perf_context(pmu, task);
3534                 err = -ENOMEM;
3535                 if (!ctx)
3536                         goto errout;
3537
3538                 if (task_ctx_data) {
3539                         ctx->task_ctx_data = task_ctx_data;
3540                         task_ctx_data = NULL;
3541                 }
3542
3543                 err = 0;
3544                 mutex_lock(&task->perf_event_mutex);
3545                 /*
3546                  * If it has already passed perf_event_exit_task().
3547                  * we must see PF_EXITING, it takes this mutex too.
3548                  */
3549                 if (task->flags & PF_EXITING)
3550                         err = -ESRCH;
3551                 else if (task->perf_event_ctxp[ctxn])
3552                         err = -EAGAIN;
3553                 else {
3554                         get_ctx(ctx);
3555                         ++ctx->pin_count;
3556                         rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3557                 }
3558                 mutex_unlock(&task->perf_event_mutex);
3559
3560                 if (unlikely(err)) {
3561                         put_ctx(ctx);
3562
3563                         if (err == -EAGAIN)
3564                                 goto retry;
3565                         goto errout;
3566                 }
3567         }
3568
3569         kfree(task_ctx_data);
3570         return ctx;
3571
3572 errout:
3573         kfree(task_ctx_data);
3574         return ERR_PTR(err);
3575 }
3576
3577 static void perf_event_free_filter(struct perf_event *event);
3578 static void perf_event_free_bpf_prog(struct perf_event *event);
3579
3580 static void free_event_rcu(struct rcu_head *head)
3581 {
3582         struct perf_event *event;
3583
3584         event = container_of(head, struct perf_event, rcu_head);
3585         if (event->ns)
3586                 put_pid_ns(event->ns);
3587         perf_event_free_filter(event);
3588         kfree(event);
3589 }
3590
3591 static void ring_buffer_attach(struct perf_event *event,
3592                                struct ring_buffer *rb);
3593
3594 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3595 {
3596         if (event->parent)
3597                 return;
3598
3599         if (is_cgroup_event(event))
3600                 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3601 }
3602
3603 static void unaccount_event(struct perf_event *event)
3604 {
3605         if (event->parent)
3606                 return;
3607
3608         if (event->attach_state & PERF_ATTACH_TASK)
3609                 static_key_slow_dec_deferred(&perf_sched_events);
3610         if (event->attr.mmap || event->attr.mmap_data)
3611                 atomic_dec(&nr_mmap_events);
3612         if (event->attr.comm)
3613                 atomic_dec(&nr_comm_events);
3614         if (event->attr.task)
3615                 atomic_dec(&nr_task_events);
3616         if (event->attr.freq)
3617                 atomic_dec(&nr_freq_events);
3618         if (event->attr.context_switch) {
3619                 static_key_slow_dec_deferred(&perf_sched_events);
3620                 atomic_dec(&nr_switch_events);
3621         }
3622         if (is_cgroup_event(event))
3623                 static_key_slow_dec_deferred(&perf_sched_events);
3624         if (has_branch_stack(event))
3625                 static_key_slow_dec_deferred(&perf_sched_events);
3626
3627         unaccount_event_cpu(event, event->cpu);
3628 }
3629
3630 /*
3631  * The following implement mutual exclusion of events on "exclusive" pmus
3632  * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
3633  * at a time, so we disallow creating events that might conflict, namely:
3634  *
3635  *  1) cpu-wide events in the presence of per-task events,
3636  *  2) per-task events in the presence of cpu-wide events,
3637  *  3) two matching events on the same context.
3638  *
3639  * The former two cases are handled in the allocation path (perf_event_alloc(),
3640  * __free_event()), the latter -- before the first perf_install_in_context().
3641  */
3642 static int exclusive_event_init(struct perf_event *event)
3643 {
3644         struct pmu *pmu = event->pmu;
3645
3646         if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3647                 return 0;
3648
3649         /*
3650          * Prevent co-existence of per-task and cpu-wide events on the
3651          * same exclusive pmu.
3652          *
3653          * Negative pmu::exclusive_cnt means there are cpu-wide
3654          * events on this "exclusive" pmu, positive means there are
3655          * per-task events.
3656          *
3657          * Since this is called in perf_event_alloc() path, event::ctx
3658          * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
3659          * to mean "per-task event", because unlike other attach states it
3660          * never gets cleared.
3661          */
3662         if (event->attach_state & PERF_ATTACH_TASK) {
3663                 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
3664                         return -EBUSY;
3665         } else {
3666                 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
3667                         return -EBUSY;
3668         }
3669
3670         return 0;
3671 }
3672
3673 static void exclusive_event_destroy(struct perf_event *event)
3674 {
3675         struct pmu *pmu = event->pmu;
3676
3677         if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3678                 return;
3679
3680         /* see comment in exclusive_event_init() */
3681         if (event->attach_state & PERF_ATTACH_TASK)
3682                 atomic_dec(&pmu->exclusive_cnt);
3683         else
3684                 atomic_inc(&pmu->exclusive_cnt);
3685 }
3686
3687 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
3688 {
3689         if ((e1->pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) &&
3690             (e1->cpu == e2->cpu ||
3691              e1->cpu == -1 ||
3692              e2->cpu == -1))
3693                 return true;
3694         return false;
3695 }
3696
3697 /* Called under the same ctx::mutex as perf_install_in_context() */
3698 static bool exclusive_event_installable(struct perf_event *event,
3699                                         struct perf_event_context *ctx)
3700 {
3701         struct perf_event *iter_event;
3702         struct pmu *pmu = event->pmu;
3703
3704         if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3705                 return true;
3706
3707         list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
3708                 if (exclusive_event_match(iter_event, event))
3709                         return false;
3710         }
3711
3712         return true;
3713 }
3714
3715 static void __free_event(struct perf_event *event)
3716 {
3717         if (!event->parent) {
3718                 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3719                         put_callchain_buffers();
3720         }
3721
3722         perf_event_free_bpf_prog(event);
3723
3724         if (event->destroy)
3725                 event->destroy(event);
3726
3727         if (event->ctx)
3728                 put_ctx(event->ctx);
3729
3730         if (event->pmu) {
3731                 exclusive_event_destroy(event);
3732                 module_put(event->pmu->module);
3733         }
3734
3735         call_rcu(&event->rcu_head, free_event_rcu);
3736 }
3737
3738 static void _free_event(struct perf_event *event)
3739 {
3740         irq_work_sync(&event->pending);
3741
3742         unaccount_event(event);
3743
3744         if (event->rb) {
3745                 /*
3746                  * Can happen when we close an event with re-directed output.
3747                  *
3748                  * Since we have a 0 refcount, perf_mmap_close() will skip
3749                  * over us; possibly making our ring_buffer_put() the last.
3750                  */
3751                 mutex_lock(&event->mmap_mutex);
3752                 ring_buffer_attach(event, NULL);
3753                 mutex_unlock(&event->mmap_mutex);
3754         }
3755
3756         if (is_cgroup_event(event))
3757                 perf_detach_cgroup(event);
3758
3759         __free_event(event);
3760 }
3761
3762 /*
3763  * Used to free events which have a known refcount of 1, such as in error paths
3764  * where the event isn't exposed yet and inherited events.
3765  */
3766 static void free_event(struct perf_event *event)
3767 {
3768         if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3769                                 "unexpected event refcount: %ld; ptr=%p\n",
3770                                 atomic_long_read(&event->refcount), event)) {
3771                 /* leak to avoid use-after-free */
3772                 return;
3773         }
3774
3775         _free_event(event);
3776 }
3777
3778 /*
3779  * Remove user event from the owner task.
3780  */
3781 static void perf_remove_from_owner(struct perf_event *event)
3782 {
3783         struct task_struct *owner;
3784
3785         rcu_read_lock();
3786         owner = ACCESS_ONCE(event->owner);
3787         /*
3788          * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3789          * !owner it means the list deletion is complete and we can indeed
3790          * free this event, otherwise we need to serialize on
3791          * owner->perf_event_mutex.
3792          */
3793         smp_read_barrier_depends();
3794         if (owner) {
3795                 /*
3796                  * Since delayed_put_task_struct() also drops the last
3797                  * task reference we can safely take a new reference
3798                  * while holding the rcu_read_lock().
3799                  */
3800                 get_task_struct(owner);
3801         }
3802         rcu_read_unlock();
3803
3804         if (owner) {
3805                 /*
3806                  * If we're here through perf_event_exit_task() we're already
3807                  * holding ctx->mutex which would be an inversion wrt. the
3808                  * normal lock order.
3809                  *
3810                  * However we can safely take this lock because its the child
3811                  * ctx->mutex.
3812                  */
3813                 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
3814
3815                 /*
3816                  * We have to re-check the event->owner field, if it is cleared
3817                  * we raced with perf_event_exit_task(), acquiring the mutex
3818                  * ensured they're done, and we can proceed with freeing the
3819                  * event.
3820                  */
3821                 if (event->owner)
3822                         list_del_init(&event->owner_entry);
3823                 mutex_unlock(&owner->perf_event_mutex);
3824                 put_task_struct(owner);
3825         }
3826 }
3827
3828 static void put_event(struct perf_event *event)
3829 {
3830         struct perf_event_context *ctx;
3831
3832         if (!atomic_long_dec_and_test(&event->refcount))
3833                 return;
3834
3835         if (!is_kernel_event(event))
3836                 perf_remove_from_owner(event);
3837
3838         /*
3839          * There are two ways this annotation is useful:
3840          *
3841          *  1) there is a lock recursion from perf_event_exit_task
3842          *     see the comment there.
3843          *
3844          *  2) there is a lock-inversion with mmap_sem through
3845          *     perf_read_group(), which takes faults while
3846          *     holding ctx->mutex, however this is called after
3847          *     the last filedesc died, so there is no possibility
3848          *     to trigger the AB-BA case.
3849          */
3850         ctx = perf_event_ctx_lock_nested(event, SINGLE_DEPTH_NESTING);
3851         WARN_ON_ONCE(ctx->parent_ctx);
3852         perf_remove_from_context(event, true);
3853         perf_event_ctx_unlock(event, ctx);
3854
3855         _free_event(event);
3856 }
3857
3858 int perf_event_release_kernel(struct perf_event *event)
3859 {
3860         put_event(event);
3861         return 0;
3862 }
3863 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3864
3865 /*
3866  * Called when the last reference to the file is gone.
3867  */
3868 static int perf_release(struct inode *inode, struct file *file)
3869 {
3870         put_event(file->private_data);
3871         return 0;
3872 }
3873
3874 /*
3875  * Remove all orphanes events from the context.
3876  */
3877 static void orphans_remove_work(struct work_struct *work)
3878 {
3879         struct perf_event_context *ctx;
3880         struct perf_event *event, *tmp;
3881
3882         ctx = container_of(work, struct perf_event_context,
3883                            orphans_remove.work);
3884
3885         mutex_lock(&ctx->mutex);
3886         list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry) {
3887                 struct perf_event *parent_event = event->parent;
3888
3889                 if (!is_orphaned_child(event))
3890                         continue;
3891
3892                 perf_remove_from_context(event, true);
3893
3894                 mutex_lock(&parent_event->child_mutex);
3895                 list_del_init(&event->child_list);
3896                 mutex_unlock(&parent_event->child_mutex);
3897
3898                 free_event(event);
3899                 put_event(parent_event);
3900         }
3901
3902         raw_spin_lock_irq(&ctx->lock);
3903         ctx->orphans_remove_sched = false;
3904         raw_spin_unlock_irq(&ctx->lock);
3905         mutex_unlock(&ctx->mutex);
3906
3907         put_ctx(ctx);
3908 }
3909
3910 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3911 {
3912         struct perf_event *child;
3913         u64 total = 0;
3914
3915         *enabled = 0;
3916         *running = 0;
3917
3918         mutex_lock(&event->child_mutex);
3919
3920         (void)perf_event_read(event, false);
3921         total += perf_event_count(event);
3922
3923         *enabled += event->total_time_enabled +
3924                         atomic64_read(&event->child_total_time_enabled);
3925         *running += event->total_time_running +
3926                         atomic64_read(&event->child_total_time_running);
3927
3928         list_for_each_entry(child, &event->child_list, child_list) {
3929                 (void)perf_event_read(child, false);
3930                 total += perf_event_count(child);
3931                 *enabled += child->total_time_enabled;
3932                 *running += child->total_time_running;
3933         }
3934         mutex_unlock(&event->child_mutex);
3935
3936         return total;
3937 }
3938 EXPORT_SYMBOL_GPL(perf_event_read_value);
3939
3940 static int __perf_read_group_add(struct perf_event *leader,
3941                                         u64 read_format, u64 *values)
3942 {
3943         struct perf_event *sub;
3944         int n = 1; /* skip @nr */
3945         int ret;
3946
3947         ret = perf_event_read(leader, true);
3948         if (ret)
3949                 return ret;
3950
3951         /*
3952          * Since we co-schedule groups, {enabled,running} times of siblings
3953          * will be identical to those of the leader, so we only publish one
3954          * set.
3955          */
3956         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
3957                 values[n++] += leader->total_time_enabled +
3958                         atomic64_read(&leader->child_total_time_enabled);
3959         }
3960
3961         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
3962                 values[n++] += leader->total_time_running +
3963                         atomic64_read(&leader->child_total_time_running);
3964         }
3965
3966         /*
3967          * Write {count,id} tuples for every sibling.
3968          */
3969         values[n++] += perf_event_count(leader);
3970         if (read_format & PERF_FORMAT_ID)
3971                 values[n++] = primary_event_id(leader);
3972
3973         list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3974                 values[n++] += perf_event_count(sub);
3975                 if (read_format & PERF_FORMAT_ID)
3976                         values[n++] = primary_event_id(sub);
3977         }
3978
3979         return 0;
3980 }
3981
3982 static int perf_read_group(struct perf_event *event,
3983                                    u64 read_format, char __user *buf)
3984 {
3985         struct perf_event *leader = event->group_leader, *child;
3986         struct perf_event_context *ctx = leader->ctx;
3987         int ret;
3988         u64 *values;
3989
3990         lockdep_assert_held(&ctx->mutex);
3991
3992         values = kzalloc(event->read_size, GFP_KERNEL);
3993         if (!values)
3994                 return -ENOMEM;
3995
3996         values[0] = 1 + leader->nr_siblings;
3997
3998         /*
3999          * By locking the child_mutex of the leader we effectively
4000          * lock the child list of all siblings.. XXX explain how.
4001          */
4002         mutex_lock(&leader->child_mutex);
4003
4004         ret = __perf_read_group_add(leader, read_format, values);
4005         if (ret)
4006                 goto unlock;
4007
4008         list_for_each_entry(child, &leader->child_list, child_list) {
4009                 ret = __perf_read_group_add(child, read_format, values);
4010                 if (ret)
4011                         goto unlock;
4012         }
4013
4014         mutex_unlock(&leader->child_mutex);
4015
4016         ret = event->read_size;
4017         if (copy_to_user(buf, values, event->read_size))
4018                 ret = -EFAULT;
4019         goto out;
4020
4021 unlock:
4022         mutex_unlock(&leader->child_mutex);
4023 out:
4024         kfree(values);
4025         return ret;
4026 }
4027
4028 static int perf_read_one(struct perf_event *event,
4029                                  u64 read_format, char __user *buf)
4030 {
4031         u64 enabled, running;
4032         u64 values[4];
4033         int n = 0;
4034
4035         values[n++] = perf_event_read_value(event, &enabled, &running);
4036         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4037                 values[n++] = enabled;
4038         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4039                 values[n++] = running;
4040         if (read_format & PERF_FORMAT_ID)
4041                 values[n++] = primary_event_id(event);
4042
4043         if (copy_to_user(buf, values, n * sizeof(u64)))
4044                 return -EFAULT;
4045
4046         return n * sizeof(u64);
4047 }
4048
4049 static bool is_event_hup(struct perf_event *event)
4050 {
4051         bool no_children;
4052
4053         if (event->state != PERF_EVENT_STATE_EXIT)
4054                 return false;
4055
4056         mutex_lock(&event->child_mutex);
4057         no_children = list_empty(&event->child_list);
4058         mutex_unlock(&event->child_mutex);
4059         return no_children;
4060 }
4061
4062 /*
4063  * Read the performance event - simple non blocking version for now
4064  */
4065 static ssize_t
4066 __perf_read(struct perf_event *event, char __user *buf, size_t count)
4067 {
4068         u64 read_format = event->attr.read_format;
4069         int ret;
4070
4071         /*
4072          * Return end-of-file for a read on a event that is in
4073          * error state (i.e. because it was pinned but it couldn't be
4074          * scheduled on to the CPU at some point).
4075          */
4076         if (event->state == PERF_EVENT_STATE_ERROR)
4077                 return 0;
4078
4079         if (count < event->read_size)
4080                 return -ENOSPC;
4081
4082         WARN_ON_ONCE(event->ctx->parent_ctx);
4083         if (read_format & PERF_FORMAT_GROUP)
4084                 ret = perf_read_group(event, read_format, buf);
4085         else
4086                 ret = perf_read_one(event, read_format, buf);
4087
4088         return ret;
4089 }
4090
4091 static ssize_t
4092 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
4093 {
4094         struct perf_event *event = file->private_data;
4095         struct perf_event_context *ctx;
4096         int ret;
4097
4098         ctx = perf_event_ctx_lock(event);
4099         ret = __perf_read(event, buf, count);
4100         perf_event_ctx_unlock(event, ctx);
4101
4102         return ret;
4103 }
4104
4105 static unsigned int perf_poll(struct file *file, poll_table *wait)
4106 {
4107         struct perf_event *event = file->private_data;
4108         struct ring_buffer *rb;
4109         unsigned int events = POLLHUP;
4110
4111         poll_wait(file, &event->waitq, wait);
4112
4113         if (is_event_hup(event))
4114                 return events;
4115
4116         /*
4117          * Pin the event->rb by taking event->mmap_mutex; otherwise
4118          * perf_event_set_output() can swizzle our rb and make us miss wakeups.
4119          */
4120         mutex_lock(&event->mmap_mutex);
4121         rb = event->rb;
4122         if (rb)
4123                 events = atomic_xchg(&rb->poll, 0);
4124         mutex_unlock(&event->mmap_mutex);
4125         return events;
4126 }
4127
4128 static void _perf_event_reset(struct perf_event *event)
4129 {
4130         (void)perf_event_read(event, false);
4131         local64_set(&event->count, 0);
4132         perf_event_update_userpage(event);
4133 }
4134
4135 /*
4136  * Holding the top-level event's child_mutex means that any
4137  * descendant process that has inherited this event will block
4138  * in sync_child_event if it goes to exit, thus satisfying the
4139  * task existence requirements of perf_event_enable/disable.
4140  */
4141 static void perf_event_for_each_child(struct perf_event *event,
4142                                         void (*func)(struct perf_event *))
4143 {
4144         struct perf_event *child;
4145
4146         WARN_ON_ONCE(event->ctx->parent_ctx);
4147
4148         mutex_lock(&event->child_mutex);
4149         func(event);
4150         list_for_each_entry(child, &event->child_list, child_list)
4151                 func(child);
4152         mutex_unlock(&event->child_mutex);
4153 }
4154
4155 static void perf_event_for_each(struct perf_event *event,
4156                                   void (*func)(struct perf_event *))
4157 {
4158         struct perf_event_context *ctx = event->ctx;
4159         struct perf_event *sibling;
4160
4161         lockdep_assert_held(&ctx->mutex);
4162
4163         event = event->group_leader;
4164
4165         perf_event_for_each_child(event, func);
4166         list_for_each_entry(sibling, &event->sibling_list, group_entry)
4167                 perf_event_for_each_child(sibling, func);
4168 }
4169
4170 struct period_event {
4171         struct perf_event *event;
4172         u64 value;
4173 };
4174
4175 static int __perf_event_period(void *info)
4176 {
4177         struct period_event *pe = info;
4178         struct perf_event *event = pe->event;
4179         struct perf_event_context *ctx = event->ctx;
4180         u64 value = pe->value;
4181         bool active;
4182
4183         raw_spin_lock(&ctx->lock);
4184         if (event->attr.freq) {
4185                 event->attr.sample_freq = value;
4186         } else {
4187                 event->attr.sample_period = value;
4188                 event->hw.sample_period = value;
4189         }
4190
4191         active = (event->state == PERF_EVENT_STATE_ACTIVE);
4192         if (active) {
4193                 perf_pmu_disable(ctx->pmu);
4194                 event->pmu->stop(event, PERF_EF_UPDATE);
4195         }
4196
4197         local64_set(&event->hw.period_left, 0);
4198
4199         if (active) {
4200                 event->pmu->start(event, PERF_EF_RELOAD);
4201                 perf_pmu_enable(ctx->pmu);
4202         }
4203         raw_spin_unlock(&ctx->lock);
4204
4205         return 0;
4206 }
4207
4208 static int perf_event_period(struct perf_event *event, u64 __user *arg)
4209 {
4210         struct period_event pe = { .event = event, };
4211         struct perf_event_context *ctx = event->ctx;
4212         struct task_struct *task;
4213         u64 value;
4214
4215         if (!is_sampling_event(event))
4216                 return -EINVAL;
4217
4218         if (copy_from_user(&value, arg, sizeof(value)))
4219                 return -EFAULT;
4220
4221         if (!value)
4222                 return -EINVAL;
4223
4224         if (event->attr.freq && value > sysctl_perf_event_sample_rate)
4225                 return -EINVAL;
4226
4227         task = ctx->task;
4228         pe.value = value;
4229
4230         if (!task) {
4231                 cpu_function_call(event->cpu, __perf_event_period, &pe);
4232                 return 0;
4233         }
4234
4235 retry:
4236         if (!task_function_call(task, __perf_event_period, &pe))
4237                 return 0;
4238
4239         raw_spin_lock_irq(&ctx->lock);
4240         if (ctx->is_active) {
4241                 raw_spin_unlock_irq(&ctx->lock);
4242                 task = ctx->task;
4243                 goto retry;
4244         }
4245
4246         if (event->attr.freq) {
4247                 event->attr.sample_freq = value;
4248         } else {
4249                 event->attr.sample_period = value;
4250                 event->hw.sample_period = value;
4251         }
4252
4253         local64_set(&event->hw.period_left, 0);
4254         raw_spin_unlock_irq(&ctx->lock);
4255
4256         return 0;
4257 }
4258
4259 static const struct file_operations perf_fops;
4260
4261 static inline int perf_fget_light(int fd, struct fd *p)
4262 {
4263         struct fd f = fdget(fd);
4264         if (!f.file)
4265                 return -EBADF;
4266
4267         if (f.file->f_op != &perf_fops) {
4268                 fdput(f);
4269                 return -EBADF;
4270         }
4271         *p = f;
4272         return 0;
4273 }
4274
4275 static int perf_event_set_output(struct perf_event *event,
4276                                  struct perf_event *output_event);
4277 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
4278 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
4279
4280 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
4281 {
4282         void (*func)(struct perf_event *);
4283         u32 flags = arg;
4284
4285         switch (cmd) {
4286         case PERF_EVENT_IOC_ENABLE:
4287                 func = _perf_event_enable;
4288                 break;
4289         case PERF_EVENT_IOC_DISABLE:
4290                 func = _perf_event_disable;
4291                 break;
4292         case PERF_EVENT_IOC_RESET:
4293                 func = _perf_event_reset;
4294                 break;
4295
4296         case PERF_EVENT_IOC_REFRESH:
4297                 return _perf_event_refresh(event, arg);
4298
4299         case PERF_EVENT_IOC_PERIOD:
4300                 return perf_event_period(event, (u64 __user *)arg);
4301
4302         case PERF_EVENT_IOC_ID:
4303         {
4304                 u64 id = primary_event_id(event);
4305
4306                 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
4307                         return -EFAULT;
4308                 return 0;
4309         }
4310
4311         case PERF_EVENT_IOC_SET_OUTPUT:
4312         {
4313                 int ret;
4314                 if (arg != -1) {
4315                         struct perf_event *output_event;
4316                         struct fd output;
4317                         ret = perf_fget_light(arg, &output);
4318                         if (ret)
4319                                 return ret;
4320                         output_event = output.file->private_data;
4321                         ret = perf_event_set_output(event, output_event);
4322                         fdput(output);
4323                 } else {
4324                         ret = perf_event_set_output(event, NULL);
4325                 }
4326                 return ret;
4327         }
4328
4329         case PERF_EVENT_IOC_SET_FILTER:
4330                 return perf_event_set_filter(event, (void __user *)arg);
4331
4332         case PERF_EVENT_IOC_SET_BPF:
4333                 return perf_event_set_bpf_prog(event, arg);
4334
4335         default:
4336                 return -ENOTTY;
4337         }
4338
4339         if (flags & PERF_IOC_FLAG_GROUP)
4340                 perf_event_for_each(event, func);
4341         else
4342                 perf_event_for_each_child(event, func);
4343
4344         return 0;
4345 }
4346
4347 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
4348 {
4349         struct perf_event *event = file->private_data;
4350         struct perf_event_context *ctx;
4351         long ret;
4352
4353         ctx = perf_event_ctx_lock(event);
4354         ret = _perf_ioctl(event, cmd, arg);
4355         perf_event_ctx_unlock(event, ctx);
4356
4357         return ret;
4358 }
4359
4360 #ifdef CONFIG_COMPAT
4361 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
4362                                 unsigned long arg)
4363 {
4364         switch (_IOC_NR(cmd)) {
4365         case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
4366         case _IOC_NR(PERF_EVENT_IOC_ID):
4367                 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
4368                 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
4369                         cmd &= ~IOCSIZE_MASK;
4370                         cmd |= sizeof(void *) << IOCSIZE_SHIFT;
4371                 }
4372                 break;
4373         }
4374         return perf_ioctl(file, cmd, arg);
4375 }
4376 #else
4377 # define perf_compat_ioctl NULL
4378 #endif
4379
4380 int perf_event_task_enable(void)
4381 {
4382         struct perf_event_context *ctx;
4383         struct perf_event *event;
4384
4385         mutex_lock(&current->perf_event_mutex);
4386         list_for_each_entry(event, &current->perf_event_list, owner_entry) {
4387                 ctx = perf_event_ctx_lock(event);
4388                 perf_event_for_each_child(event, _perf_event_enable);
4389                 perf_event_ctx_unlock(event, ctx);
4390         }
4391         mutex_unlock(&current->perf_event_mutex);
4392
4393         return 0;
4394 }
4395
4396 int perf_event_task_disable(void)
4397 {
4398         struct perf_event_context *ctx;
4399         struct perf_event *event;
4400
4401         mutex_lock(&current->perf_event_mutex);
4402         list_for_each_entry(event, &current->perf_event_list, owner_entry) {
4403                 ctx = perf_event_ctx_lock(event);
4404                 perf_event_for_each_child(event, _perf_event_disable);
4405                 perf_event_ctx_unlock(event, ctx);
4406         }
4407         mutex_unlock(&current->perf_event_mutex);
4408
4409         return 0;
4410 }
4411
4412 static int perf_event_index(struct perf_event *event)
4413 {
4414         if (event->hw.state & PERF_HES_STOPPED)
4415                 return 0;
4416
4417         if (event->state != PERF_EVENT_STATE_ACTIVE)
4418                 return 0;
4419
4420         return event->pmu->event_idx(event);
4421 }
4422
4423 static void calc_timer_values(struct perf_event *event,
4424                                 u64 *now,
4425                                 u64 *enabled,
4426                                 u64 *running)
4427 {
4428         u64 ctx_time;
4429
4430         *now = perf_clock();
4431         ctx_time = event->shadow_ctx_time + *now;
4432         *enabled = ctx_time - event->tstamp_enabled;
4433         *running = ctx_time - event->tstamp_running;
4434 }
4435
4436 static void perf_event_init_userpage(struct perf_event *event)
4437 {
4438         struct perf_event_mmap_page *userpg;
4439         struct ring_buffer *rb;
4440
4441         rcu_read_lock();
4442         rb = rcu_dereference(event->rb);
4443         if (!rb)
4444                 goto unlock;
4445
4446         userpg = rb->user_page;
4447
4448         /* Allow new userspace to detect that bit 0 is deprecated */
4449         userpg->cap_bit0_is_deprecated = 1;
4450         userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
4451         userpg->data_offset = PAGE_SIZE;
4452         userpg->data_size = perf_data_size(rb);
4453
4454 unlock:
4455         rcu_read_unlock();
4456 }
4457
4458 void __weak arch_perf_update_userpage(
4459         struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
4460 {
4461 }
4462
4463 /*
4464  * Callers need to ensure there can be no nesting of this function, otherwise
4465  * the seqlock logic goes bad. We can not serialize this because the arch
4466  * code calls this from NMI context.
4467  */
4468 void perf_event_update_userpage(struct perf_event *event)
4469 {
4470         struct perf_event_mmap_page *userpg;
4471         struct ring_buffer *rb;
4472         u64 enabled, running, now;
4473
4474         rcu_read_lock();
4475         rb = rcu_dereference(event->rb);
4476         if (!rb)
4477                 goto unlock;
4478
4479         /*
4480          * compute total_time_enabled, total_time_running
4481          * based on snapshot values taken when the event
4482          * was last scheduled in.
4483          *
4484          * we cannot simply called update_context_time()
4485          * because of locking issue as we can be called in
4486          * NMI context
4487          */
4488         calc_timer_values(event, &now, &enabled, &running);
4489
4490         userpg = rb->user_page;
4491         /*
4492          * Disable preemption so as to not let the corresponding user-space
4493          * spin too long if we get preempted.
4494          */
4495         preempt_disable();
4496         ++userpg->lock;
4497         barrier();
4498         userpg->index = perf_event_index(event);
4499         userpg->offset = perf_event_count(event);
4500         if (userpg->index)
4501                 userpg->offset -= local64_read(&event->hw.prev_count);
4502
4503         userpg->time_enabled = enabled +
4504                         atomic64_read(&event->child_total_time_enabled);
4505
4506         userpg->time_running = running +
4507                         atomic64_read(&event->child_total_time_running);
4508
4509         arch_perf_update_userpage(event, userpg, now);
4510
4511         barrier();
4512         ++userpg->lock;
4513         preempt_enable();
4514 unlock:
4515         rcu_read_unlock();
4516 }
4517
4518 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
4519 {
4520         struct perf_event *event = vma->vm_file->private_data;
4521         struct ring_buffer *rb;
4522         int ret = VM_FAULT_SIGBUS;
4523
4524         if (vmf->flags & FAULT_FLAG_MKWRITE) {
4525                 if (vmf->pgoff == 0)
4526                         ret = 0;
4527                 return ret;
4528         }
4529
4530         rcu_read_lock();
4531         rb = rcu_dereference(event->rb);
4532         if (!rb)
4533                 goto unlock;
4534
4535         if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
4536                 goto unlock;
4537
4538         vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
4539         if (!vmf->page)
4540                 goto unlock;
4541
4542         get_page(vmf->page);
4543         vmf->page->mapping = vma->vm_file->f_mapping;
4544         vmf->page->index   = vmf->pgoff;
4545
4546         ret = 0;
4547 unlock:
4548         rcu_read_unlock();
4549
4550         return ret;
4551 }
4552
4553 static void ring_buffer_attach(struct perf_event *event,
4554                                struct ring_buffer *rb)
4555 {
4556         struct ring_buffer *old_rb = NULL;
4557         unsigned long flags;
4558
4559         if (event->rb) {
4560                 /*
4561                  * Should be impossible, we set this when removing
4562                  * event->rb_entry and wait/clear when adding event->rb_entry.
4563                  */
4564                 WARN_ON_ONCE(event->rcu_pending);
4565
4566                 old_rb = event->rb;
4567                 spin_lock_irqsave(&old_rb->event_lock, flags);
4568                 list_del_rcu(&event->rb_entry);
4569                 spin_unlock_irqrestore(&old_rb->event_lock, flags);
4570
4571                 event->rcu_batches = get_state_synchronize_rcu();
4572                 event->rcu_pending = 1;
4573         }
4574
4575         if (rb) {
4576                 if (event->rcu_pending) {
4577                         cond_synchronize_rcu(event->rcu_batches);
4578                         event->rcu_pending = 0;
4579                 }
4580
4581                 spin_lock_irqsave(&rb->event_lock, flags);
4582                 list_add_rcu(&event->rb_entry, &rb->event_list);
4583                 spin_unlock_irqrestore(&rb->event_lock, flags);
4584         }
4585
4586         rcu_assign_pointer(event->rb, rb);
4587
4588         if (old_rb) {
4589                 ring_buffer_put(old_rb);
4590                 /*
4591                  * Since we detached before setting the new rb, so that we
4592                  * could attach the new rb, we could have missed a wakeup.
4593                  * Provide it now.
4594                  */
4595                 wake_up_all(&event->waitq);
4596         }
4597 }
4598
4599 static void ring_buffer_wakeup(struct perf_event *event)
4600 {
4601         struct ring_buffer *rb;
4602
4603         rcu_read_lock();
4604         rb = rcu_dereference(event->rb);
4605         if (rb) {
4606                 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
4607                         wake_up_all(&event->waitq);
4608         }
4609         rcu_read_unlock();
4610 }
4611
4612 struct ring_buffer *ring_buffer_get(struct perf_event *event)
4613 {
4614         struct ring_buffer *rb;
4615
4616         rcu_read_lock();
4617         rb = rcu_dereference(event->rb);
4618         if (rb) {
4619                 if (!atomic_inc_not_zero(&rb->refcount))
4620                         rb = NULL;
4621         }
4622         rcu_read_unlock();
4623
4624         return rb;
4625 }
4626
4627 void ring_buffer_put(struct ring_buffer *rb)
4628 {
4629         if (!atomic_dec_and_test(&rb->refcount))
4630                 return;
4631
4632         WARN_ON_ONCE(!list_empty(&rb->event_list));
4633
4634         call_rcu(&rb->rcu_head, rb_free_rcu);
4635 }
4636
4637 static void perf_mmap_open(struct vm_area_struct *vma)
4638 {
4639         struct perf_event *event = vma->vm_file->private_data;
4640
4641         atomic_inc(&event->mmap_count);
4642         atomic_inc(&event->rb->mmap_count);
4643
4644         if (vma->vm_pgoff)
4645                 atomic_inc(&event->rb->aux_mmap_count);
4646
4647         if (event->pmu->event_mapped)
4648                 event->pmu->event_mapped(event);
4649 }
4650
4651 /*
4652  * A buffer can be mmap()ed multiple times; either directly through the same
4653  * event, or through other events by use of perf_event_set_output().
4654  *
4655  * In order to undo the VM accounting done by perf_mmap() we need to destroy
4656  * the buffer here, where we still have a VM context. This means we need
4657  * to detach all events redirecting to us.
4658  */
4659 static void perf_mmap_close(struct vm_area_struct *vma)
4660 {
4661         struct perf_event *event = vma->vm_file->private_data;
4662
4663         struct ring_buffer *rb = ring_buffer_get(event);
4664         struct user_struct *mmap_user = rb->mmap_user;
4665         int mmap_locked = rb->mmap_locked;
4666         unsigned long size = perf_data_size(rb);
4667
4668         if (event->pmu->event_unmapped)
4669                 event->pmu->event_unmapped(event);
4670
4671         /*
4672          * rb->aux_mmap_count will always drop before rb->mmap_count and
4673          * event->mmap_count, so it is ok to use event->mmap_mutex to
4674          * serialize with perf_mmap here.
4675          */
4676         if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
4677             atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
4678                 atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm);
4679                 vma->vm_mm->pinned_vm -= rb->aux_mmap_locked;
4680
4681                 rb_free_aux(rb);
4682                 mutex_unlock(&event->mmap_mutex);
4683         }
4684
4685         atomic_dec(&rb->mmap_count);
4686
4687         if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
4688                 goto out_put;
4689
4690         ring_buffer_attach(event, NULL);
4691         mutex_unlock(&event->mmap_mutex);
4692
4693         /* If there's still other mmap()s of this buffer, we're done. */
4694         if (atomic_read(&rb->mmap_count))
4695                 goto out_put;
4696
4697         /*
4698          * No other mmap()s, detach from all other events that might redirect
4699          * into the now unreachable buffer. Somewhat complicated by the
4700          * fact that rb::event_lock otherwise nests inside mmap_mutex.
4701          */
4702 again:
4703         rcu_read_lock();
4704         list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
4705                 if (!atomic_long_inc_not_zero(&event->refcount)) {
4706                         /*
4707                          * This event is en-route to free_event() which will
4708                          * detach it and remove it from the list.
4709                          */
4710                         continue;
4711                 }
4712                 rcu_read_unlock();
4713
4714                 mutex_lock(&event->mmap_mutex);
4715                 /*
4716                  * Check we didn't race with perf_event_set_output() which can
4717                  * swizzle the rb from under us while we were waiting to
4718                  * acquire mmap_mutex.
4719                  *
4720                  * If we find a different rb; ignore this event, a next
4721                  * iteration will no longer find it on the list. We have to
4722                  * still restart the iteration to make sure we're not now
4723                  * iterating the wrong list.
4724                  */
4725                 if (event->rb == rb)
4726                         ring_buffer_attach(event, NULL);
4727
4728                 mutex_unlock(&event->mmap_mutex);
4729                 put_event(event);
4730
4731                 /*
4732                  * Restart the iteration; either we're on the wrong list or
4733                  * destroyed its integrity by doing a deletion.
4734                  */
4735                 goto again;
4736         }
4737         rcu_read_unlock();
4738
4739         /*
4740          * It could be there's still a few 0-ref events on the list; they'll
4741          * get cleaned up by free_event() -- they'll also still have their
4742          * ref on the rb and will free it whenever they are done with it.
4743          *
4744          * Aside from that, this buffer is 'fully' detached and unmapped,
4745          * undo the VM accounting.
4746          */
4747
4748         atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4749         vma->vm_mm->pinned_vm -= mmap_locked;
4750         free_uid(mmap_user);
4751
4752 out_put:
4753         ring_buffer_put(rb); /* could be last */
4754 }
4755
4756 static const struct vm_operations_struct perf_mmap_vmops = {
4757         .open           = perf_mmap_open,
4758         .close          = perf_mmap_close, /* non mergable */
4759         .fault          = perf_mmap_fault,
4760         .page_mkwrite   = perf_mmap_fault,
4761 };
4762
4763 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
4764 {
4765         struct perf_event *event = file->private_data;
4766         unsigned long user_locked, user_lock_limit;
4767         struct user_struct *user = current_user();
4768         unsigned long locked, lock_limit;
4769         struct ring_buffer *rb = NULL;
4770         unsigned long vma_size;
4771         unsigned long nr_pages;
4772         long user_extra = 0, extra = 0;
4773         int ret = 0, flags = 0;
4774
4775         /*
4776          * Don't allow mmap() of inherited per-task counters. This would
4777          * create a performance issue due to all children writing to the
4778          * same rb.
4779          */
4780         if (event->cpu == -1 && event->attr.inherit)
4781                 return -EINVAL;
4782
4783         if (!(vma->vm_flags & VM_SHARED))
4784                 return -EINVAL;
4785
4786         vma_size = vma->vm_end - vma->vm_start;
4787
4788         if (vma->vm_pgoff == 0) {
4789                 nr_pages = (vma_size / PAGE_SIZE) - 1;
4790         } else {
4791                 /*
4792                  * AUX area mapping: if rb->aux_nr_pages != 0, it's already
4793                  * mapped, all subsequent mappings should have the same size
4794                  * and offset. Must be above the normal perf buffer.
4795                  */
4796                 u64 aux_offset, aux_size;
4797
4798                 if (!event->rb)
4799                         return -EINVAL;
4800
4801                 nr_pages = vma_size / PAGE_SIZE;
4802
4803                 mutex_lock(&event->mmap_mutex);
4804                 ret = -EINVAL;
4805
4806                 rb = event->rb;
4807                 if (!rb)
4808                         goto aux_unlock;
4809
4810                 aux_offset = ACCESS_ONCE(rb->user_page->aux_offset);
4811                 aux_size = ACCESS_ONCE(rb->user_page->aux_size);
4812
4813                 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
4814                         goto aux_unlock;
4815
4816                 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
4817                         goto aux_unlock;
4818
4819                 /* already mapped with a different offset */
4820                 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
4821                         goto aux_unlock;
4822
4823                 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
4824                         goto aux_unlock;
4825
4826                 /* already mapped with a different size */
4827                 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
4828                         goto aux_unlock;
4829
4830                 if (!is_power_of_2(nr_pages))
4831                         goto aux_unlock;
4832
4833                 if (!atomic_inc_not_zero(&rb->mmap_count))
4834                         goto aux_unlock;
4835
4836                 if (rb_has_aux(rb)) {
4837                         atomic_inc(&rb->aux_mmap_count);
4838                         ret = 0;
4839                         goto unlock;
4840                 }
4841
4842                 atomic_set(&rb->aux_mmap_count, 1);
4843                 user_extra = nr_pages;
4844
4845                 goto accounting;
4846         }
4847
4848         /*
4849          * If we have rb pages ensure they're a power-of-two number, so we
4850          * can do bitmasks instead of modulo.
4851          */
4852         if (nr_pages != 0 && !is_power_of_2(nr_pages))
4853                 return -EINVAL;
4854
4855         if (vma_size != PAGE_SIZE * (1 + nr_pages))
4856                 return -EINVAL;
4857
4858         WARN_ON_ONCE(event->ctx->parent_ctx);
4859 again:
4860         mutex_lock(&event->mmap_mutex);
4861         if (event->rb) {
4862                 if (event->rb->nr_pages != nr_pages) {
4863                         ret = -EINVAL;
4864                         goto unlock;
4865                 }
4866
4867                 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4868                         /*
4869                          * Raced against perf_mmap_close() through
4870                          * perf_event_set_output(). Try again, hope for better
4871                          * luck.
4872                          */
4873                         mutex_unlock(&event->mmap_mutex);
4874                         goto again;
4875                 }
4876
4877                 goto unlock;
4878         }
4879
4880         user_extra = nr_pages + 1;
4881
4882 accounting:
4883         user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
4884
4885         /*
4886          * Increase the limit linearly with more CPUs:
4887          */
4888         user_lock_limit *= num_online_cpus();
4889
4890         user_locked = atomic_long_read(&user->locked_vm) + user_extra;
4891
4892         if (user_locked > user_lock_limit)
4893                 extra = user_locked - user_lock_limit;
4894
4895         lock_limit = rlimit(RLIMIT_MEMLOCK);
4896         lock_limit >>= PAGE_SHIFT;
4897         locked = vma->vm_mm->pinned_vm + extra;
4898
4899         if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
4900                 !capable(CAP_IPC_LOCK)) {
4901                 ret = -EPERM;
4902                 goto unlock;
4903         }
4904
4905         WARN_ON(!rb && event->rb);
4906
4907         if (vma->vm_flags & VM_WRITE)
4908                 flags |= RING_BUFFER_WRITABLE;
4909
4910         if (!rb) {
4911                 rb = rb_alloc(nr_pages,
4912                               event->attr.watermark ? event->attr.wakeup_watermark : 0,
4913                               event->cpu, flags);
4914
4915                 if (!rb) {
4916                         ret = -ENOMEM;
4917                         goto unlock;
4918                 }
4919
4920                 atomic_set(&rb->mmap_count, 1);
4921                 rb->mmap_user = get_current_user();
4922                 rb->mmap_locked = extra;
4923
4924                 ring_buffer_attach(event, rb);
4925
4926                 perf_event_init_userpage(event);
4927                 perf_event_update_userpage(event);
4928         } else {
4929                 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
4930                                    event->attr.aux_watermark, flags);
4931                 if (!ret)
4932                         rb->aux_mmap_locked = extra;
4933         }
4934
4935 unlock:
4936         if (!ret) {
4937                 atomic_long_add(user_extra, &user->locked_vm);
4938                 vma->vm_mm->pinned_vm += extra;
4939
4940                 atomic_inc(&event->mmap_count);
4941         } else if (rb) {
4942                 atomic_dec(&rb->mmap_count);
4943         }
4944 aux_unlock:
4945         mutex_unlock(&event->mmap_mutex);
4946
4947         /*
4948          * Since pinned accounting is per vm we cannot allow fork() to copy our
4949          * vma.
4950          */
4951         vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
4952         vma->vm_ops = &perf_mmap_vmops;
4953
4954         if (event->pmu->event_mapped)
4955                 event->pmu->event_mapped(event);
4956
4957         return ret;
4958 }
4959
4960 static int perf_fasync(int fd, struct file *filp, int on)
4961 {
4962         struct inode *inode = file_inode(filp);
4963         struct perf_event *event = filp->private_data;
4964         int retval;
4965
4966         mutex_lock(&inode->i_mutex);
4967         retval = fasync_helper(fd, filp, on, &event->fasync);
4968         mutex_unlock(&inode->i_mutex);
4969
4970         if (retval < 0)
4971                 return retval;
4972
4973         return 0;
4974 }
4975
4976 static const struct file_operations perf_fops = {
4977         .llseek                 = no_llseek,
4978         .release                = perf_release,
4979         .read                   = perf_read,
4980         .poll                   = perf_poll,
4981         .unlocked_ioctl         = perf_ioctl,
4982         .compat_ioctl           = perf_compat_ioctl,
4983         .mmap                   = perf_mmap,
4984         .fasync                 = perf_fasync,
4985 };
4986
4987 /*
4988  * Perf event wakeup
4989  *
4990  * If there's data, ensure we set the poll() state and publish everything
4991  * to user-space before waking everybody up.
4992  */
4993
4994 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
4995 {
4996         /* only the parent has fasync state */
4997         if (event->parent)
4998                 event = event->parent;
4999         return &event->fasync;
5000 }
5001
5002 void perf_event_wakeup(struct perf_event *event)
5003 {
5004         ring_buffer_wakeup(event);
5005
5006         if (event->pending_kill) {
5007                 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
5008                 event->pending_kill = 0;
5009         }
5010 }
5011
5012 static void perf_pending_event(struct irq_work *entry)
5013 {
5014         struct perf_event *event = container_of(entry,
5015                         struct perf_event, pending);
5016         int rctx;
5017
5018         rctx = perf_swevent_get_recursion_context();
5019         /*
5020          * If we 'fail' here, that's OK, it means recursion is already disabled
5021          * and we won't recurse 'further'.
5022          */
5023
5024         if (event->pending_disable) {
5025                 event->pending_disable = 0;
5026                 __perf_event_disable(event);
5027         }
5028
5029         if (event->pending_wakeup) {
5030                 event->pending_wakeup = 0;
5031                 perf_event_wakeup(event);
5032         }
5033
5034         if (rctx >= 0)
5035                 perf_swevent_put_recursion_context(rctx);
5036 }
5037
5038 /*
5039  * We assume there is only KVM supporting the callbacks.
5040  * Later on, we might change it to a list if there is
5041  * another virtualization implementation supporting the callbacks.
5042  */
5043 struct perf_guest_info_callbacks *perf_guest_cbs;
5044
5045 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5046 {
5047         perf_guest_cbs = cbs;
5048         return 0;
5049 }
5050 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
5051
5052 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5053 {
5054         perf_guest_cbs = NULL;
5055         return 0;
5056 }
5057 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
5058
5059 static void
5060 perf_output_sample_regs(struct perf_output_handle *handle,
5061                         struct pt_regs *regs, u64 mask)
5062 {
5063         int bit;
5064
5065         for_each_set_bit(bit, (const unsigned long *) &mask,
5066                          sizeof(mask) * BITS_PER_BYTE) {
5067                 u64 val;
5068
5069                 val = perf_reg_value(regs, bit);
5070                 perf_output_put(handle, val);
5071         }
5072 }
5073
5074 static void perf_sample_regs_user(struct perf_regs *regs_user,
5075                                   struct pt_regs *regs,
5076                                   struct pt_regs *regs_user_copy)
5077 {
5078         if (user_mode(regs)) {
5079                 regs_user->abi = perf_reg_abi(current);
5080                 regs_user->regs = regs;
5081         } else if (current->mm) {
5082                 perf_get_regs_user(regs_user, regs, regs_user_copy);
5083         } else {
5084                 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
5085                 regs_user->regs = NULL;
5086         }
5087 }
5088
5089 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
5090                                   struct pt_regs *regs)
5091 {
5092         regs_intr->regs = regs;
5093         regs_intr->abi  = perf_reg_abi(current);
5094 }
5095
5096
5097 /*
5098  * Get remaining task size from user stack pointer.
5099  *
5100  * It'd be better to take stack vma map and limit this more
5101  * precisly, but there's no way to get it safely under interrupt,
5102  * so using TASK_SIZE as limit.
5103  */
5104 static u64 perf_ustack_task_size(struct pt_regs *regs)
5105 {
5106         unsigned long addr = perf_user_stack_pointer(regs);
5107
5108         if (!addr || addr >= TASK_SIZE)
5109                 return 0;
5110
5111         return TASK_SIZE - addr;
5112 }
5113
5114 static u16
5115 perf_sample_ustack_size(u16 stack_size, u16 header_size,
5116                         struct pt_regs *regs)
5117 {
5118         u64 task_size;
5119
5120         /* No regs, no stack pointer, no dump. */
5121         if (!regs)
5122                 return 0;
5123
5124         /*
5125          * Check if we fit in with the requested stack size into the:
5126          * - TASK_SIZE
5127          *   If we don't, we limit the size to the TASK_SIZE.
5128          *
5129          * - remaining sample size
5130          *   If we don't, we customize the stack size to
5131          *   fit in to the remaining sample size.
5132          */
5133
5134         task_size  = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
5135         stack_size = min(stack_size, (u16) task_size);
5136
5137         /* Current header size plus static size and dynamic size. */
5138         header_size += 2 * sizeof(u64);
5139
5140         /* Do we fit in with the current stack dump size? */
5141         if ((u16) (header_size + stack_size) < header_size) {
5142                 /*
5143                  * If we overflow the maximum size for the sample,
5144                  * we customize the stack dump size to fit in.
5145                  */
5146                 stack_size = USHRT_MAX - header_size - sizeof(u64);
5147                 stack_size = round_up(stack_size, sizeof(u64));
5148         }
5149
5150         return stack_size;
5151 }
5152
5153 static void
5154 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
5155                           struct pt_regs *regs)
5156 {
5157         /* Case of a kernel thread, nothing to dump */
5158         if (!regs) {
5159                 u64 size = 0;
5160                 perf_output_put(handle, size);
5161         } else {
5162                 unsigned long sp;
5163                 unsigned int rem;
5164                 u64 dyn_size;
5165
5166                 /*
5167                  * We dump:
5168                  * static size
5169                  *   - the size requested by user or the best one we can fit
5170                  *     in to the sample max size
5171                  * data
5172                  *   - user stack dump data
5173                  * dynamic size
5174                  *   - the actual dumped size
5175                  */
5176
5177                 /* Static size. */
5178                 perf_output_put(handle, dump_size);
5179
5180                 /* Data. */
5181                 sp = perf_user_stack_pointer(regs);
5182                 rem = __output_copy_user(handle, (void *) sp, dump_size);
5183                 dyn_size = dump_size - rem;
5184
5185                 perf_output_skip(handle, rem);
5186
5187                 /* Dynamic size. */
5188                 perf_output_put(handle, dyn_size);
5189         }
5190 }
5191
5192 static void __perf_event_header__init_id(struct perf_event_header *header,
5193                                          struct perf_sample_data *data,
5194                                          struct perf_event *event)
5195 {
5196         u64 sample_type = event->attr.sample_type;
5197
5198         data->type = sample_type;
5199         header->size += event->id_header_size;
5200
5201         if (sample_type & PERF_SAMPLE_TID) {
5202                 /* namespace issues */
5203                 data->tid_entry.pid = perf_event_pid(event, current);
5204                 data->tid_entry.tid = perf_event_tid(event, current);
5205         }
5206
5207         if (sample_type & PERF_SAMPLE_TIME)
5208                 data->time = perf_event_clock(event);
5209
5210         if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
5211                 data->id = primary_event_id(event);
5212
5213         if (sample_type & PERF_SAMPLE_STREAM_ID)
5214                 data->stream_id = event->id;
5215
5216         if (sample_type & PERF_SAMPLE_CPU) {
5217                 data->cpu_entry.cpu      = raw_smp_processor_id();
5218                 data->cpu_entry.reserved = 0;
5219         }
5220 }
5221
5222 void perf_event_header__init_id(struct perf_event_header *header,
5223                                 struct perf_sample_data *data,
5224                                 struct perf_event *event)
5225 {
5226         if (event->attr.sample_id_all)
5227                 __perf_event_header__init_id(header, data, event);
5228 }
5229
5230 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
5231                                            struct perf_sample_data *data)
5232 {
5233         u64 sample_type = data->type;
5234
5235         if (sample_type & PERF_SAMPLE_TID)
5236                 perf_output_put(handle, data->tid_entry);
5237
5238         if (sample_type & PERF_SAMPLE_TIME)
5239                 perf_output_put(handle, data->time);
5240
5241         if (sample_type & PERF_SAMPLE_ID)
5242                 perf_output_put(handle, data->id);
5243
5244         if (sample_type & PERF_SAMPLE_STREAM_ID)
5245                 perf_output_put(handle, data->stream_id);
5246
5247         if (sample_type & PERF_SAMPLE_CPU)
5248                 perf_output_put(handle, data->cpu_entry);
5249
5250         if (sample_type & PERF_SAMPLE_IDENTIFIER)
5251                 perf_output_put(handle, data->id);
5252 }
5253
5254 void perf_event__output_id_sample(struct perf_event *event,
5255                                   struct perf_output_handle *handle,
5256                                   struct perf_sample_data *sample)
5257 {
5258         if (event->attr.sample_id_all)
5259                 __perf_event__output_id_sample(handle, sample);
5260 }
5261
5262 static void perf_output_read_one(struct perf_output_handle *handle,
5263                                  struct perf_event *event,
5264                                  u64 enabled, u64 running)
5265 {
5266         u64 read_format = event->attr.read_format;
5267         u64 values[4];
5268         int n = 0;
5269
5270         values[n++] = perf_event_count(event);
5271         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5272                 values[n++] = enabled +
5273                         atomic64_read(&event->child_total_time_enabled);
5274         }
5275         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5276                 values[n++] = running +
5277                         atomic64_read(&event->child_total_time_running);
5278         }
5279         if (read_format & PERF_FORMAT_ID)
5280                 values[n++] = primary_event_id(event);
5281
5282         __output_copy(handle, values, n * sizeof(u64));
5283 }
5284
5285 static void perf_output_read_group(struct perf_output_handle *handle,
5286                             struct perf_event *event,
5287                             u64 enabled, u64 running)
5288 {
5289         struct perf_event *leader = event->group_leader, *sub;
5290         u64 read_format = event->attr.read_format;
5291         u64 values[5];
5292         int n = 0;
5293
5294         values[n++] = 1 + leader->nr_siblings;
5295
5296         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5297                 values[n++] = enabled;
5298
5299         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5300                 values[n++] = running;
5301
5302         if ((leader != event) &&
5303             (leader->state == PERF_EVENT_STATE_ACTIVE))
5304                 leader->pmu->read(leader);
5305
5306         values[n++] = perf_event_count(leader);
5307         if (read_format & PERF_FORMAT_ID)
5308                 values[n++] = primary_event_id(leader);
5309
5310         __output_copy(handle, values, n * sizeof(u64));
5311
5312         list_for_each_entry(sub, &leader->sibling_list, group_entry) {
5313                 n = 0;
5314
5315                 if ((sub != event) &&
5316                     (sub->state == PERF_EVENT_STATE_ACTIVE))
5317                         sub->pmu->read(sub);
5318
5319                 values[n++] = perf_event_count(sub);
5320                 if (read_format & PERF_FORMAT_ID)
5321                         values[n++] = primary_event_id(sub);
5322
5323                 __output_copy(handle, values, n * sizeof(u64));
5324         }
5325 }
5326
5327 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
5328                                  PERF_FORMAT_TOTAL_TIME_RUNNING)
5329
5330 /*
5331  * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
5332  *
5333  * The problem is that its both hard and excessively expensive to iterate the
5334  * child list, not to mention that its impossible to IPI the children running
5335  * on another CPU, from interrupt/NMI context.
5336  */
5337 static void perf_output_read(struct perf_output_handle *handle,
5338                              struct perf_event *event)
5339 {
5340         u64 enabled = 0, running = 0, now;
5341         u64 read_format = event->attr.read_format;
5342
5343         /*
5344          * compute total_time_enabled, total_time_running
5345          * based on snapshot values taken when the event
5346          * was last scheduled in.
5347          *
5348          * we cannot simply called update_context_time()
5349          * because of locking issue as we are called in
5350          * NMI context
5351          */
5352         if (read_format & PERF_FORMAT_TOTAL_TIMES)
5353                 calc_timer_values(event, &now, &enabled, &running);
5354
5355         if (event->attr.read_format & PERF_FORMAT_GROUP)
5356                 perf_output_read_group(handle, event, enabled, running);
5357         else
5358                 perf_output_read_one(handle, event, enabled, running);
5359 }
5360
5361 void perf_output_sample(struct perf_output_handle *handle,
5362                         struct perf_event_header *header,
5363                         struct perf_sample_data *data,
5364                         struct perf_event *event)
5365 {
5366         u64 sample_type = data->type;
5367
5368         perf_output_put(handle, *header);
5369
5370         if (sample_type & PERF_SAMPLE_IDENTIFIER)
5371                 perf_output_put(handle, data->id);
5372
5373         if (sample_type & PERF_SAMPLE_IP)
5374                 perf_output_put(handle, data->ip);
5375
5376         if (sample_type & PERF_SAMPLE_TID)
5377                 perf_output_put(handle, data->tid_entry);
5378
5379         if (sample_type & PERF_SAMPLE_TIME)
5380                 perf_output_put(handle, data->time);
5381
5382         if (sample_type & PERF_SAMPLE_ADDR)
5383                 perf_output_put(handle, data->addr);
5384
5385         if (sample_type & PERF_SAMPLE_ID)
5386                 perf_output_put(handle, data->id);
5387
5388         if (sample_type & PERF_SAMPLE_STREAM_ID)
5389                 perf_output_put(handle, data->stream_id);
5390
5391         if (sample_type & PERF_SAMPLE_CPU)
5392                 perf_output_put(handle, data->cpu_entry);
5393
5394         if (sample_type & PERF_SAMPLE_PERIOD)
5395                 perf_output_put(handle, data->period);
5396
5397         if (sample_type & PERF_SAMPLE_READ)
5398                 perf_output_read(handle, event);
5399
5400         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5401                 if (data->callchain) {
5402                         int size = 1;
5403
5404                         if (data->callchain)
5405                                 size += data->callchain->nr;
5406
5407                         size *= sizeof(u64);
5408
5409                         __output_copy(handle, data->callchain, size);
5410                 } else {
5411                         u64 nr = 0;
5412                         perf_output_put(handle, nr);
5413                 }
5414         }
5415
5416         if (sample_type & PERF_SAMPLE_RAW) {
5417                 if (data->raw) {
5418                         u32 raw_size = data->raw->size;
5419                         u32 real_size = round_up(raw_size + sizeof(u32),
5420                                                  sizeof(u64)) - sizeof(u32);
5421                         u64 zero = 0;
5422
5423                         perf_output_put(handle, real_size);
5424                         __output_copy(handle, data->raw->data, raw_size);
5425                         if (real_size - raw_size)
5426                                 __output_copy(handle, &zero, real_size - raw_size);
5427                 } else {
5428                         struct {
5429                                 u32     size;
5430                                 u32     data;
5431                         } raw = {
5432                                 .size = sizeof(u32),
5433                                 .data = 0,
5434                         };
5435                         perf_output_put(handle, raw);
5436                 }
5437         }
5438
5439         if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5440                 if (data->br_stack) {
5441                         size_t size;
5442
5443                         size = data->br_stack->nr
5444                              * sizeof(struct perf_branch_entry);
5445
5446                         perf_output_put(handle, data->br_stack->nr);
5447                         perf_output_copy(handle, data->br_stack->entries, size);
5448                 } else {
5449                         /*
5450                          * we always store at least the value of nr
5451                          */
5452                         u64 nr = 0;
5453                         perf_output_put(handle, nr);
5454                 }
5455         }
5456
5457         if (sample_type & PERF_SAMPLE_REGS_USER) {
5458                 u64 abi = data->regs_user.abi;
5459
5460                 /*
5461                  * If there are no regs to dump, notice it through
5462                  * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5463                  */
5464                 perf_output_put(handle, abi);
5465
5466                 if (abi) {
5467                         u64 mask = event->attr.sample_regs_user;
5468                         perf_output_sample_regs(handle,
5469                                                 data->regs_user.regs,
5470                                                 mask);
5471                 }
5472         }
5473
5474         if (sample_type & PERF_SAMPLE_STACK_USER) {
5475                 perf_output_sample_ustack(handle,
5476                                           data->stack_user_size,
5477                                           data->regs_user.regs);
5478         }
5479
5480         if (sample_type & PERF_SAMPLE_WEIGHT)
5481                 perf_output_put(handle, data->weight);
5482
5483         if (sample_type & PERF_SAMPLE_DATA_SRC)
5484                 perf_output_put(handle, data->data_src.val);
5485
5486         if (sample_type & PERF_SAMPLE_TRANSACTION)
5487                 perf_output_put(handle, data->txn);
5488
5489         if (sample_type & PERF_SAMPLE_REGS_INTR) {
5490                 u64 abi = data->regs_intr.abi;
5491                 /*
5492                  * If there are no regs to dump, notice it through
5493                  * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5494                  */
5495                 perf_output_put(handle, abi);
5496
5497                 if (abi) {
5498                         u64 mask = event->attr.sample_regs_intr;
5499
5500                         perf_output_sample_regs(handle,
5501                                                 data->regs_intr.regs,
5502                                                 mask);
5503                 }
5504         }
5505
5506         if (!event->attr.watermark) {
5507                 int wakeup_events = event->attr.wakeup_events;
5508
5509                 if (wakeup_events) {
5510                         struct ring_buffer *rb = handle->rb;
5511                         int events = local_inc_return(&rb->events);
5512
5513                         if (events >= wakeup_events) {
5514                                 local_sub(wakeup_events, &rb->events);
5515                                 local_inc(&rb->wakeup);
5516                         }
5517                 }
5518         }
5519 }
5520
5521 void perf_prepare_sample(struct perf_event_header *header,
5522                          struct perf_sample_data *data,
5523                          struct perf_event *event,
5524                          struct pt_regs *regs)
5525 {
5526         u64 sample_type = event->attr.sample_type;
5527
5528         header->type = PERF_RECORD_SAMPLE;
5529         header->size = sizeof(*header) + event->header_size;
5530
5531         header->misc = 0;
5532         header->misc |= perf_misc_flags(regs);
5533
5534         __perf_event_header__init_id(header, data, event);
5535
5536         if (sample_type & PERF_SAMPLE_IP)
5537                 data->ip = perf_instruction_pointer(regs);
5538
5539         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5540                 int size = 1;
5541
5542                 data->callchain = perf_callchain(event, regs);
5543
5544                 if (data->callchain)
5545                         size += data->callchain->nr;
5546
5547                 header->size += size * sizeof(u64);
5548         }
5549
5550         if (sample_type & PERF_SAMPLE_RAW) {
5551                 int size = sizeof(u32);
5552
5553                 if (data->raw)
5554                         size += data->raw->size;
5555                 else
5556                         size += sizeof(u32);
5557
5558                 header->size += round_up(size, sizeof(u64));
5559         }
5560
5561         if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5562                 int size = sizeof(u64); /* nr */
5563                 if (data->br_stack) {
5564                         size += data->br_stack->nr
5565                               * sizeof(struct perf_branch_entry);
5566                 }
5567                 header->size += size;
5568         }
5569
5570         if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
5571                 perf_sample_regs_user(&data->regs_user, regs,
5572                                       &data->regs_user_copy);
5573
5574         if (sample_type & PERF_SAMPLE_REGS_USER) {
5575                 /* regs dump ABI info */
5576                 int size = sizeof(u64);
5577
5578                 if (data->regs_user.regs) {
5579                         u64 mask = event->attr.sample_regs_user;
5580                         size += hweight64(mask) * sizeof(u64);
5581                 }
5582
5583                 header->size += size;
5584         }
5585
5586         if (sample_type & PERF_SAMPLE_STACK_USER) {
5587                 /*
5588                  * Either we need PERF_SAMPLE_STACK_USER bit to be allways
5589                  * processed as the last one or have additional check added
5590                  * in case new sample type is added, because we could eat
5591                  * up the rest of the sample size.
5592                  */
5593                 u16 stack_size = event->attr.sample_stack_user;
5594                 u16 size = sizeof(u64);
5595
5596                 stack_size = perf_sample_ustack_size(stack_size, header->size,
5597                                                      data->regs_user.regs);
5598
5599                 /*
5600                  * If there is something to dump, add space for the dump
5601                  * itself and for the field that tells the dynamic size,
5602                  * which is how many have been actually dumped.
5603                  */
5604                 if (stack_size)
5605                         size += sizeof(u64) + stack_size;
5606
5607                 data->stack_user_size = stack_size;
5608                 header->size += size;
5609         }
5610
5611         if (sample_type & PERF_SAMPLE_REGS_INTR) {
5612                 /* regs dump ABI info */
5613                 int size = sizeof(u64);
5614
5615                 perf_sample_regs_intr(&data->regs_intr, regs);
5616
5617                 if (data->regs_intr.regs) {
5618                         u64 mask = event->attr.sample_regs_intr;
5619
5620                         size += hweight64(mask) * sizeof(u64);
5621                 }
5622
5623                 header->size += size;
5624         }
5625 }
5626
5627 void perf_event_output(struct perf_event *event,
5628                         struct perf_sample_data *data,
5629                         struct pt_regs *regs)
5630 {
5631         struct perf_output_handle handle;
5632         struct perf_event_header header;
5633
5634         /* protect the callchain buffers */
5635         rcu_read_lock();
5636
5637         perf_prepare_sample(&header, data, event, regs);
5638
5639         if (perf_output_begin(&handle, event, header.size))
5640                 goto exit;
5641
5642         perf_output_sample(&handle, &header, data, event);
5643
5644         perf_output_end(&handle);
5645
5646 exit:
5647         rcu_read_unlock();
5648 }
5649
5650 /*
5651  * read event_id
5652  */
5653
5654 struct perf_read_event {
5655         struct perf_event_header        header;
5656
5657         u32                             pid;
5658         u32                             tid;
5659 };
5660
5661 static void
5662 perf_event_read_event(struct perf_event *event,
5663                         struct task_struct *task)
5664 {
5665         struct perf_output_handle handle;
5666         struct perf_sample_data sample;
5667         struct perf_read_event read_event = {
5668                 .header = {
5669                         .type = PERF_RECORD_READ,
5670                         .misc = 0,
5671                         .size = sizeof(read_event) + event->read_size,
5672                 },
5673                 .pid = perf_event_pid(event, task),
5674                 .tid = perf_event_tid(event, task),
5675         };
5676         int ret;
5677
5678         perf_event_header__init_id(&read_event.header, &sample, event);
5679         ret = perf_output_begin(&handle, event, read_event.header.size);
5680         if (ret)
5681                 return;
5682
5683         perf_output_put(&handle, read_event);
5684         perf_output_read(&handle, event);
5685         perf_event__output_id_sample(event, &handle, &sample);
5686
5687         perf_output_end(&handle);
5688 }
5689
5690 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
5691
5692 static void
5693 perf_event_aux_ctx(struct perf_event_context *ctx,
5694                    perf_event_aux_output_cb output,
5695                    void *data)
5696 {
5697         struct perf_event *event;
5698
5699         list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5700                 if (event->state < PERF_EVENT_STATE_INACTIVE)
5701                         continue;
5702                 if (!event_filter_match(event))
5703                         continue;
5704                 output(event, data);
5705         }
5706 }
5707
5708 static void
5709 perf_event_aux_task_ctx(perf_event_aux_output_cb output, void *data,
5710                         struct perf_event_context *task_ctx)
5711 {
5712         rcu_read_lock();
5713         preempt_disable();
5714         perf_event_aux_ctx(task_ctx, output, data);
5715         preempt_enable();
5716         rcu_read_unlock();
5717 }
5718
5719 static void
5720 perf_event_aux(perf_event_aux_output_cb output, void *data,
5721                struct perf_event_context *task_ctx)
5722 {
5723         struct perf_cpu_context *cpuctx;
5724         struct perf_event_context *ctx;
5725         struct pmu *pmu;
5726         int ctxn;
5727
5728         /*
5729          * If we have task_ctx != NULL we only notify
5730          * the task context itself. The task_ctx is set
5731          * only for EXIT events before releasing task
5732          * context.
5733          */
5734         if (task_ctx) {
5735                 perf_event_aux_task_ctx(output, data, task_ctx);
5736                 return;
5737         }
5738
5739         rcu_read_lock();
5740         list_for_each_entry_rcu(pmu, &pmus, entry) {
5741                 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
5742                 if (cpuctx->unique_pmu != pmu)
5743                         goto next;
5744                 perf_event_aux_ctx(&cpuctx->ctx, output, data);
5745                 ctxn = pmu->task_ctx_nr;
5746                 if (ctxn < 0)
5747                         goto next;
5748                 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
5749                 if (ctx)
5750                         perf_event_aux_ctx(ctx, output, data);
5751 next:
5752                 put_cpu_ptr(pmu->pmu_cpu_context);
5753         }
5754         rcu_read_unlock();
5755 }
5756
5757 /*
5758  * task tracking -- fork/exit
5759  *
5760  * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
5761  */
5762
5763 struct perf_task_event {
5764         struct task_struct              *task;
5765         struct perf_event_context       *task_ctx;
5766
5767         struct {
5768                 struct perf_event_header        header;
5769
5770                 u32                             pid;
5771                 u32                             ppid;
5772                 u32                             tid;
5773                 u32                             ptid;
5774                 u64                             time;
5775         } event_id;
5776 };
5777
5778 static int perf_event_task_match(struct perf_event *event)
5779 {
5780         return event->attr.comm  || event->attr.mmap ||
5781                event->attr.mmap2 || event->attr.mmap_data ||
5782                event->attr.task;
5783 }
5784
5785 static void perf_event_task_output(struct perf_event *event,
5786                                    void *data)
5787 {
5788         struct perf_task_event *task_event = data;
5789         struct perf_output_handle handle;
5790         struct perf_sample_data sample;
5791         struct task_struct *task = task_event->task;
5792         int ret, size = task_event->event_id.header.size;
5793
5794         if (!perf_event_task_match(event))
5795                 return;
5796
5797         perf_event_header__init_id(&task_event->event_id.header, &sample, event);
5798
5799         ret = perf_output_begin(&handle, event,
5800                                 task_event->event_id.header.size);
5801         if (ret)
5802                 goto out;
5803
5804         task_event->event_id.pid = perf_event_pid(event, task);
5805         task_event->event_id.ppid = perf_event_pid(event, current);
5806
5807         task_event->event_id.tid = perf_event_tid(event, task);
5808         task_event->event_id.ptid = perf_event_tid(event, current);
5809
5810         task_event->event_id.time = perf_event_clock(event);
5811
5812         perf_output_put(&handle, task_event->event_id);
5813
5814         perf_event__output_id_sample(event, &handle, &sample);
5815
5816         perf_output_end(&handle);
5817 out:
5818         task_event->event_id.header.size = size;
5819 }
5820
5821 static void perf_event_task(struct task_struct *task,
5822                               struct perf_event_context *task_ctx,
5823                               int new)
5824 {
5825         struct perf_task_event task_event;
5826
5827         if (!atomic_read(&nr_comm_events) &&
5828             !atomic_read(&nr_mmap_events) &&
5829             !atomic_read(&nr_task_events))
5830                 return;
5831
5832         task_event = (struct perf_task_event){
5833                 .task     = task,
5834                 .task_ctx = task_ctx,
5835                 .event_id    = {
5836                         .header = {
5837                                 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
5838                                 .misc = 0,
5839                                 .size = sizeof(task_event.event_id),
5840                         },
5841                         /* .pid  */
5842                         /* .ppid */
5843                         /* .tid  */
5844                         /* .ptid */
5845                         /* .time */
5846                 },
5847         };
5848
5849         perf_event_aux(perf_event_task_output,
5850                        &task_event,
5851                        task_ctx);
5852 }
5853
5854 void perf_event_fork(struct task_struct *task)
5855 {
5856         perf_event_task(task, NULL, 1);
5857 }
5858
5859 /*
5860  * comm tracking
5861  */
5862
5863 struct perf_comm_event {
5864         struct task_struct      *task;
5865         char                    *comm;
5866         int                     comm_size;
5867
5868         struct {
5869                 struct perf_event_header        header;
5870
5871                 u32                             pid;
5872                 u32                             tid;
5873         } event_id;
5874 };
5875
5876 static int perf_event_comm_match(struct perf_event *event)
5877 {
5878         return event->attr.comm;
5879 }
5880
5881 static void perf_event_comm_output(struct perf_event *event,
5882                                    void *data)
5883 {
5884         struct perf_comm_event *comm_event = data;
5885         struct perf_output_handle handle;
5886         struct perf_sample_data sample;
5887         int size = comm_event->event_id.header.size;
5888         int ret;
5889
5890         if (!perf_event_comm_match(event))
5891                 return;
5892
5893         perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
5894         ret = perf_output_begin(&handle, event,
5895                                 comm_event->event_id.header.size);
5896
5897         if (ret)
5898                 goto out;
5899
5900         comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
5901         comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
5902
5903         perf_output_put(&handle, comm_event->event_id);
5904         __output_copy(&handle, comm_event->comm,
5905                                    comm_event->comm_size);
5906
5907         perf_event__output_id_sample(event, &handle, &sample);
5908
5909         perf_output_end(&handle);
5910 out:
5911         comm_event->event_id.header.size = size;
5912 }
5913
5914 static void perf_event_comm_event(struct perf_comm_event *comm_event)
5915 {
5916         char comm[TASK_COMM_LEN];
5917         unsigned int size;
5918
5919         memset(comm, 0, sizeof(comm));
5920         strlcpy(comm, comm_event->task->comm, sizeof(comm));
5921         size = ALIGN(strlen(comm)+1, sizeof(u64));
5922
5923         comm_event->comm = comm;
5924         comm_event->comm_size = size;
5925
5926         comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
5927
5928         perf_event_aux(perf_event_comm_output,
5929                        comm_event,
5930                        NULL);
5931 }
5932
5933 void perf_event_comm(struct task_struct *task, bool exec)
5934 {
5935         struct perf_comm_event comm_event;
5936
5937         if (!atomic_read(&nr_comm_events))
5938                 return;
5939
5940         comm_event = (struct perf_comm_event){
5941                 .task   = task,
5942                 /* .comm      */
5943                 /* .comm_size */
5944                 .event_id  = {
5945                         .header = {
5946                                 .type = PERF_RECORD_COMM,
5947                                 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
5948                                 /* .size */
5949                         },
5950                         /* .pid */
5951                         /* .tid */
5952                 },
5953         };
5954
5955         perf_event_comm_event(&comm_event);
5956 }
5957
5958 /*
5959  * mmap tracking
5960  */
5961
5962 struct perf_mmap_event {
5963         struct vm_area_struct   *vma;
5964
5965         const char              *file_name;
5966         int                     file_size;
5967         int                     maj, min;
5968         u64                     ino;
5969         u64                     ino_generation;
5970         u32                     prot, flags;
5971
5972         struct {
5973                 struct perf_event_header        header;
5974
5975                 u32                             pid;
5976                 u32                             tid;
5977                 u64                             start;
5978                 u64                             len;
5979                 u64                             pgoff;
5980         } event_id;
5981 };
5982
5983 static int perf_event_mmap_match(struct perf_event *event,
5984                                  void *data)
5985 {
5986         struct perf_mmap_event *mmap_event = data;
5987         struct vm_area_struct *vma = mmap_event->vma;
5988         int executable = vma->vm_flags & VM_EXEC;
5989
5990         return (!executable && event->attr.mmap_data) ||
5991                (executable && (event->attr.mmap || event->attr.mmap2));
5992 }
5993
5994 static void perf_event_mmap_output(struct perf_event *event,
5995                                    void *data)
5996 {
5997         struct perf_mmap_event *mmap_event = data;
5998         struct perf_output_handle handle;
5999         struct perf_sample_data sample;
6000         int size = mmap_event->event_id.header.size;
6001         int ret;
6002
6003         if (!perf_event_mmap_match(event, data))
6004                 return;
6005
6006         if (event->attr.mmap2) {
6007                 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
6008                 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
6009                 mmap_event->event_id.header.size += sizeof(mmap_event->min);
6010                 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
6011                 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
6012                 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
6013                 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
6014         }
6015
6016         perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
6017         ret = perf_output_begin(&handle, event,
6018                                 mmap_event->event_id.header.size);
6019         if (ret)
6020                 goto out;
6021
6022         mmap_event->event_id.pid = perf_event_pid(event, current);
6023         mmap_event->event_id.tid = perf_event_tid(event, current);
6024
6025         perf_output_put(&handle, mmap_event->event_id);
6026
6027         if (event->attr.mmap2) {
6028                 perf_output_put(&handle, mmap_event->maj);
6029                 perf_output_put(&handle, mmap_event->min);
6030                 perf_output_put(&handle, mmap_event->ino);
6031                 perf_output_put(&handle, mmap_event->ino_generation);
6032                 perf_output_put(&handle, mmap_event->prot);
6033                 perf_output_put(&handle, mmap_event->flags);
6034         }
6035
6036         __output_copy(&handle, mmap_event->file_name,
6037                                    mmap_event->file_size);
6038
6039         perf_event__output_id_sample(event, &handle, &sample);
6040
6041         perf_output_end(&handle);
6042 out:
6043         mmap_event->event_id.header.size = size;
6044 }
6045
6046 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
6047 {
6048         struct vm_area_struct *vma = mmap_event->vma;
6049         struct file *file = vma->vm_file;
6050         int maj = 0, min = 0;
6051         u64 ino = 0, gen = 0;
6052         u32 prot = 0, flags = 0;
6053         unsigned int size;
6054         char tmp[16];
6055         char *buf = NULL;
6056         char *name;
6057
6058         if (vma->vm_flags & VM_READ)
6059                 prot |= PROT_READ;
6060         if (vma->vm_flags & VM_WRITE)
6061                 prot |= PROT_WRITE;
6062         if (vma->vm_flags & VM_EXEC)
6063                 prot |= PROT_EXEC;
6064
6065         if (vma->vm_flags & VM_MAYSHARE)
6066                 flags = MAP_SHARED;
6067         else
6068                 flags = MAP_PRIVATE;
6069
6070         if (vma->vm_flags & VM_DENYWRITE)
6071                 flags |= MAP_DENYWRITE;
6072         if (vma->vm_flags & VM_MAYEXEC)
6073                 flags |= MAP_EXECUTABLE;
6074         if (vma->vm_flags & VM_LOCKED)
6075                 flags |= MAP_LOCKED;
6076         if (vma->vm_flags & VM_HUGETLB)
6077                 flags |= MAP_HUGETLB;
6078
6079         if (file) {
6080                 struct inode *inode;
6081                 dev_t dev;
6082
6083                 buf = kmalloc(PATH_MAX, GFP_KERNEL);
6084                 if (!buf) {
6085                         name = "//enomem";
6086                         goto cpy_name;
6087                 }
6088                 /*
6089                  * d_path() works from the end of the rb backwards, so we
6090                  * need to add enough zero bytes after the string to handle
6091                  * the 64bit alignment we do later.
6092                  */
6093                 name = file_path(file, buf, PATH_MAX - sizeof(u64));
6094                 if (IS_ERR(name)) {
6095                         name = "//toolong";
6096                         goto cpy_name;
6097                 }
6098                 inode = file_inode(vma->vm_file);
6099                 dev = inode->i_sb->s_dev;
6100                 ino = inode->i_ino;
6101                 gen = inode->i_generation;
6102                 maj = MAJOR(dev);
6103                 min = MINOR(dev);
6104
6105                 goto got_name;
6106         } else {
6107                 if (vma->vm_ops && vma->vm_ops->name) {
6108                         name = (char *) vma->vm_ops->name(vma);
6109                         if (name)
6110                                 goto cpy_name;
6111                 }
6112
6113                 name = (char *)arch_vma_name(vma);
6114                 if (name)
6115                         goto cpy_name;
6116
6117                 if (vma->vm_start <= vma->vm_mm->start_brk &&
6118                                 vma->vm_end >= vma->vm_mm->brk) {
6119                         name = "[heap]";
6120                         goto cpy_name;
6121                 }
6122                 if (vma->vm_start <= vma->vm_mm->start_stack &&
6123                                 vma->vm_end >= vma->vm_mm->start_stack) {
6124                         name = "[stack]";
6125                         goto cpy_name;
6126                 }
6127
6128                 name = "//anon";
6129                 goto cpy_name;
6130         }
6131
6132 cpy_name:
6133         strlcpy(tmp, name, sizeof(tmp));
6134         name = tmp;
6135 got_name:
6136         /*
6137          * Since our buffer works in 8 byte units we need to align our string
6138          * size to a multiple of 8. However, we must guarantee the tail end is
6139          * zero'd out to avoid leaking random bits to userspace.
6140          */
6141         size = strlen(name)+1;
6142         while (!IS_ALIGNED(size, sizeof(u64)))
6143                 name[size++] = '\0';
6144
6145         mmap_event->file_name = name;
6146         mmap_event->file_size = size;
6147         mmap_event->maj = maj;
6148         mmap_event->min = min;
6149         mmap_event->ino = ino;
6150         mmap_event->ino_generation = gen;
6151         mmap_event->prot = prot;
6152         mmap_event->flags = flags;
6153
6154         if (!(vma->vm_flags & VM_EXEC))
6155                 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
6156
6157         mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
6158
6159         perf_event_aux(perf_event_mmap_output,
6160                        mmap_event,
6161                        NULL);
6162
6163         kfree(buf);
6164 }
6165
6166 void perf_event_mmap(struct vm_area_struct *vma)
6167 {
6168         struct perf_mmap_event mmap_event;
6169
6170         if (!atomic_read(&nr_mmap_events))
6171                 return;
6172
6173         mmap_event = (struct perf_mmap_event){
6174                 .vma    = vma,
6175                 /* .file_name */
6176                 /* .file_size */
6177                 .event_id  = {
6178                         .header = {
6179                                 .type = PERF_RECORD_MMAP,
6180                                 .misc = PERF_RECORD_MISC_USER,
6181                                 /* .size */
6182                         },
6183                         /* .pid */
6184                         /* .tid */
6185                         .start  = vma->vm_start,
6186                         .len    = vma->vm_end - vma->vm_start,
6187                         .pgoff  = (u64)vma->vm_pgoff << PAGE_SHIFT,
6188                 },
6189                 /* .maj (attr_mmap2 only) */
6190                 /* .min (attr_mmap2 only) */
6191                 /* .ino (attr_mmap2 only) */
6192                 /* .ino_generation (attr_mmap2 only) */
6193                 /* .prot (attr_mmap2 only) */
6194                 /* .flags (attr_mmap2 only) */
6195         };
6196
6197         perf_event_mmap_event(&mmap_event);
6198 }
6199
6200 void perf_event_aux_event(struct perf_event *event, unsigned long head,
6201                           unsigned long size, u64 flags)
6202 {
6203         struct perf_output_handle handle;
6204         struct perf_sample_data sample;
6205         struct perf_aux_event {
6206                 struct perf_event_header        header;
6207                 u64                             offset;
6208                 u64                             size;
6209                 u64                             flags;
6210         } rec = {
6211                 .header = {
6212                         .type = PERF_RECORD_AUX,
6213                         .misc = 0,
6214                         .size = sizeof(rec),
6215                 },
6216                 .offset         = head,
6217                 .size           = size,
6218                 .flags          = flags,
6219         };
6220         int ret;
6221
6222         perf_event_header__init_id(&rec.header, &sample, event);
6223         ret = perf_output_begin(&handle, event, rec.header.size);
6224
6225         if (ret)
6226                 return;
6227
6228         perf_output_put(&handle, rec);
6229         perf_event__output_id_sample(event, &handle, &sample);
6230
6231         perf_output_end(&handle);
6232 }
6233
6234 /*
6235  * Lost/dropped samples logging
6236  */
6237 void perf_log_lost_samples(struct perf_event *event, u64 lost)
6238 {
6239         struct perf_output_handle handle;
6240         struct perf_sample_data sample;
6241         int ret;
6242
6243         struct {
6244                 struct perf_event_header        header;
6245                 u64                             lost;
6246         } lost_samples_event = {
6247                 .header = {
6248                         .type = PERF_RECORD_LOST_SAMPLES,
6249                         .misc = 0,
6250                         .size = sizeof(lost_samples_event),
6251                 },
6252                 .lost           = lost,
6253         };
6254
6255         perf_event_header__init_id(&lost_samples_event.header, &sample, event);
6256
6257         ret = perf_output_begin(&handle, event,
6258                                 lost_samples_event.header.size);
6259         if (ret)
6260                 return;
6261
6262         perf_output_put(&handle, lost_samples_event);
6263         perf_event__output_id_sample(event, &handle, &sample);
6264         perf_output_end(&handle);
6265 }
6266
6267 /*
6268  * context_switch tracking
6269  */
6270
6271 struct perf_switch_event {
6272         struct task_struct      *task;
6273         struct task_struct      *next_prev;
6274
6275         struct {
6276                 struct perf_event_header        header;
6277                 u32                             next_prev_pid;
6278                 u32                             next_prev_tid;
6279         } event_id;
6280 };
6281
6282 static int perf_event_switch_match(struct perf_event *event)
6283 {
6284         return event->attr.context_switch;
6285 }
6286
6287 static void perf_event_switch_output(struct perf_event *event, void *data)
6288 {
6289         struct perf_switch_event *se = data;
6290         struct perf_output_handle handle;
6291         struct perf_sample_data sample;
6292         int ret;
6293
6294         if (!perf_event_switch_match(event))
6295                 return;
6296
6297         /* Only CPU-wide events are allowed to see next/prev pid/tid */
6298         if (event->ctx->task) {
6299                 se->event_id.header.type = PERF_RECORD_SWITCH;
6300                 se->event_id.header.size = sizeof(se->event_id.header);
6301         } else {
6302                 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
6303                 se->event_id.header.size = sizeof(se->event_id);
6304                 se->event_id.next_prev_pid =
6305                                         perf_event_pid(event, se->next_prev);
6306                 se->event_id.next_prev_tid =
6307                                         perf_event_tid(event, se->next_prev);
6308         }
6309
6310         perf_event_header__init_id(&se->event_id.header, &sample, event);
6311
6312         ret = perf_output_begin(&handle, event, se->event_id.header.size);
6313         if (ret)
6314                 return;
6315
6316         if (event->ctx->task)
6317                 perf_output_put(&handle, se->event_id.header);
6318         else
6319                 perf_output_put(&handle, se->event_id);
6320
6321         perf_event__output_id_sample(event, &handle, &sample);
6322
6323         perf_output_end(&handle);
6324 }
6325
6326 static void perf_event_switch(struct task_struct *task,
6327                               struct task_struct *next_prev, bool sched_in)
6328 {
6329         struct perf_switch_event switch_event;
6330
6331         /* N.B. caller checks nr_switch_events != 0 */
6332
6333         switch_event = (struct perf_switch_event){
6334                 .task           = task,
6335                 .next_prev      = next_prev,
6336                 .event_id       = {
6337                         .header = {
6338                                 /* .type */
6339                                 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
6340                                 /* .size */
6341                         },
6342                         /* .next_prev_pid */
6343                         /* .next_prev_tid */
6344                 },
6345         };
6346
6347         perf_event_aux(perf_event_switch_output,
6348                        &switch_event,
6349                        NULL);
6350 }
6351
6352 /*
6353  * IRQ throttle logging
6354  */
6355
6356 static void perf_log_throttle(struct perf_event *event, int enable)
6357 {
6358         struct perf_output_handle handle;
6359         struct perf_sample_data sample;
6360         int ret;
6361
6362         struct {
6363                 struct perf_event_header        header;
6364                 u64                             time;
6365                 u64                             id;
6366                 u64                             stream_id;
6367         } throttle_event = {
6368                 .header = {
6369                         .type = PERF_RECORD_THROTTLE,
6370                         .misc = 0,
6371                         .size = sizeof(throttle_event),
6372                 },
6373                 .time           = perf_event_clock(event),
6374                 .id             = primary_event_id(event),
6375                 .stream_id      = event->id,
6376         };
6377
6378         if (enable)
6379                 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
6380
6381         perf_event_header__init_id(&throttle_event.header, &sample, event);
6382
6383         ret = perf_output_begin(&handle, event,
6384                                 throttle_event.header.size);
6385         if (ret)
6386                 return;
6387
6388         perf_output_put(&handle, throttle_event);
6389         perf_event__output_id_sample(event, &handle, &sample);
6390         perf_output_end(&handle);
6391 }
6392
6393 static void perf_log_itrace_start(struct perf_event *event)
6394 {
6395         struct perf_output_handle handle;
6396         struct perf_sample_data sample;
6397         struct perf_aux_event {
6398                 struct perf_event_header        header;
6399                 u32                             pid;
6400                 u32                             tid;
6401         } rec;
6402         int ret;
6403
6404         if (event->parent)
6405                 event = event->parent;
6406
6407         if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
6408             event->hw.itrace_started)
6409                 return;
6410
6411         rec.header.type = PERF_RECORD_ITRACE_START;
6412         rec.header.misc = 0;
6413         rec.header.size = sizeof(rec);
6414         rec.pid = perf_event_pid(event, current);
6415         rec.tid = perf_event_tid(event, current);
6416
6417         perf_event_header__init_id(&rec.header, &sample, event);
6418         ret = perf_output_begin(&handle, event, rec.header.size);
6419
6420         if (ret)
6421                 return;
6422
6423         perf_output_put(&handle, rec);
6424         perf_event__output_id_sample(event, &handle, &sample);
6425
6426         perf_output_end(&handle);
6427 }
6428
6429 /*
6430  * Generic event overflow handling, sampling.
6431  */
6432
6433 static int __perf_event_overflow(struct perf_event *event,
6434                                    int throttle, struct perf_sample_data *data,
6435                                    struct pt_regs *regs)
6436 {
6437         int events = atomic_read(&event->event_limit);
6438         struct hw_perf_event *hwc = &event->hw;
6439         u64 seq;
6440         int ret = 0;
6441
6442         /*
6443          * Non-sampling counters might still use the PMI to fold short
6444          * hardware counters, ignore those.
6445          */
6446         if (unlikely(!is_sampling_event(event)))
6447                 return 0;
6448
6449         seq = __this_cpu_read(perf_throttled_seq);
6450         if (seq != hwc->interrupts_seq) {
6451                 hwc->interrupts_seq = seq;
6452                 hwc->interrupts = 1;
6453         } else {
6454                 hwc->interrupts++;
6455                 if (unlikely(throttle
6456                              && hwc->interrupts >= max_samples_per_tick)) {
6457                         __this_cpu_inc(perf_throttled_count);
6458                         hwc->interrupts = MAX_INTERRUPTS;
6459                         perf_log_throttle(event, 0);
6460                         tick_nohz_full_kick();
6461                         ret = 1;
6462                 }
6463         }
6464
6465         if (event->attr.freq) {
6466                 u64 now = perf_clock();
6467                 s64 delta = now - hwc->freq_time_stamp;
6468
6469                 hwc->freq_time_stamp = now;
6470
6471                 if (delta > 0 && delta < 2*TICK_NSEC)
6472                         perf_adjust_period(event, delta, hwc->last_period, true);
6473         }
6474
6475         /*
6476          * XXX event_limit might not quite work as expected on inherited
6477          * events
6478          */
6479
6480         event->pending_kill = POLL_IN;
6481         if (events && atomic_dec_and_test(&event->event_limit)) {
6482                 ret = 1;
6483                 event->pending_kill = POLL_HUP;
6484                 event->pending_disable = 1;
6485                 irq_work_queue(&event->pending);
6486         }
6487
6488         if (event->overflow_handler)
6489                 event->overflow_handler(event, data, regs);
6490         else
6491                 perf_event_output(event, data, regs);
6492
6493         if (*perf_event_fasync(event) && event->pending_kill) {
6494                 event->pending_wakeup = 1;
6495                 irq_work_queue(&event->pending);
6496         }
6497
6498         return ret;
6499 }
6500
6501 int perf_event_overflow(struct perf_event *event,
6502                           struct perf_sample_data *data,
6503                           struct pt_regs *regs)
6504 {
6505         return __perf_event_overflow(event, 1, data, regs);
6506 }
6507
6508 /*
6509  * Generic software event infrastructure
6510  */
6511
6512 struct swevent_htable {
6513         struct swevent_hlist            *swevent_hlist;
6514         struct mutex                    hlist_mutex;
6515         int                             hlist_refcount;
6516
6517         /* Recursion avoidance in each contexts */
6518         int                             recursion[PERF_NR_CONTEXTS];
6519 };
6520
6521 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
6522
6523 /*
6524  * We directly increment event->count and keep a second value in
6525  * event->hw.period_left to count intervals. This period event
6526  * is kept in the range [-sample_period, 0] so that we can use the
6527  * sign as trigger.
6528  */
6529
6530 u64 perf_swevent_set_period(struct perf_event *event)
6531 {
6532         struct hw_perf_event *hwc = &event->hw;
6533         u64 period = hwc->last_period;
6534         u64 nr, offset;
6535         s64 old, val;
6536
6537         hwc->last_period = hwc->sample_period;
6538
6539 again:
6540         old = val = local64_read(&hwc->period_left);
6541         if (val < 0)
6542                 return 0;
6543
6544         nr = div64_u64(period + val, period);
6545         offset = nr * period;
6546         val -= offset;
6547         if (local64_cmpxchg(&hwc->period_left, old, val) != old)
6548                 goto again;
6549
6550         return nr;
6551 }
6552
6553 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
6554                                     struct perf_sample_data *data,
6555                                     struct pt_regs *regs)
6556 {
6557         struct hw_perf_event *hwc = &event->hw;
6558         int throttle = 0;
6559
6560         if (!overflow)
6561                 overflow = perf_swevent_set_period(event);
6562
6563         if (hwc->interrupts == MAX_INTERRUPTS)
6564                 return;
6565
6566         for (; overflow; overflow--) {
6567                 if (__perf_event_overflow(event, throttle,
6568                                             data, regs)) {
6569                         /*
6570                          * We inhibit the overflow from happening when
6571                          * hwc->interrupts == MAX_INTERRUPTS.
6572                          */
6573                         break;
6574                 }
6575                 throttle = 1;
6576         }
6577 }
6578
6579 static void perf_swevent_event(struct perf_event *event, u64 nr,
6580                                struct perf_sample_data *data,
6581                                struct pt_regs *regs)
6582 {
6583         struct hw_perf_event *hwc = &event->hw;
6584
6585         local64_add(nr, &event->count);
6586
6587         if (!regs)
6588                 return;
6589
6590         if (!is_sampling_event(event))
6591                 return;
6592
6593         if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
6594                 data->period = nr;
6595                 return perf_swevent_overflow(event, 1, data, regs);
6596         } else
6597                 data->period = event->hw.last_period;
6598
6599         if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
6600                 return perf_swevent_overflow(event, 1, data, regs);
6601
6602         if (local64_add_negative(nr, &hwc->period_left))
6603                 return;
6604
6605         perf_swevent_overflow(event, 0, data, regs);
6606 }
6607
6608 static int perf_exclude_event(struct perf_event *event,
6609                               struct pt_regs *regs)
6610 {
6611         if (event->hw.state & PERF_HES_STOPPED)
6612                 return 1;
6613
6614         if (regs) {
6615                 if (event->attr.exclude_user && user_mode(regs))
6616                         return 1;
6617
6618                 if (event->attr.exclude_kernel && !user_mode(regs))
6619                         return 1;
6620         }
6621
6622         return 0;
6623 }
6624
6625 static int perf_swevent_match(struct perf_event *event,
6626                                 enum perf_type_id type,
6627                                 u32 event_id,
6628                                 struct perf_sample_data *data,
6629                                 struct pt_regs *regs)
6630 {
6631         if (event->attr.type != type)
6632                 return 0;
6633
6634         if (event->attr.config != event_id)
6635                 return 0;
6636
6637         if (perf_exclude_event(event, regs))
6638                 return 0;
6639
6640         return 1;
6641 }
6642
6643 static inline u64 swevent_hash(u64 type, u32 event_id)
6644 {
6645         u64 val = event_id | (type << 32);
6646
6647         return hash_64(val, SWEVENT_HLIST_BITS);
6648 }
6649
6650 static inline struct hlist_head *
6651 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
6652 {
6653         u64 hash = swevent_hash(type, event_id);
6654
6655         return &hlist->heads[hash];
6656 }
6657
6658 /* For the read side: events when they trigger */
6659 static inline struct hlist_head *
6660 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
6661 {
6662         struct swevent_hlist *hlist;
6663
6664         hlist = rcu_dereference(swhash->swevent_hlist);
6665         if (!hlist)
6666                 return NULL;
6667
6668         return __find_swevent_head(hlist, type, event_id);
6669 }
6670
6671 /* For the event head insertion and removal in the hlist */
6672 static inline struct hlist_head *
6673 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
6674 {
6675         struct swevent_hlist *hlist;
6676         u32 event_id = event->attr.config;
6677         u64 type = event->attr.type;
6678
6679         /*
6680          * Event scheduling is always serialized against hlist allocation
6681          * and release. Which makes the protected version suitable here.
6682          * The context lock guarantees that.
6683          */
6684         hlist = rcu_dereference_protected(swhash->swevent_hlist,
6685                                           lockdep_is_held(&event->ctx->lock));
6686         if (!hlist)
6687                 return NULL;
6688
6689         return __find_swevent_head(hlist, type, event_id);
6690 }
6691
6692 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
6693                                     u64 nr,
6694                                     struct perf_sample_data *data,
6695                                     struct pt_regs *regs)
6696 {
6697         struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6698         struct perf_event *event;
6699         struct hlist_head *head;
6700
6701         rcu_read_lock();
6702         head = find_swevent_head_rcu(swhash, type, event_id);
6703         if (!head)
6704                 goto end;
6705
6706         hlist_for_each_entry_rcu(event, head, hlist_entry) {
6707                 if (perf_swevent_match(event, type, event_id, data, regs))
6708                         perf_swevent_event(event, nr, data, regs);
6709         }
6710 end:
6711         rcu_read_unlock();
6712 }
6713
6714 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
6715
6716 int perf_swevent_get_recursion_context(void)
6717 {
6718         struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6719
6720         return get_recursion_context(swhash->recursion);
6721 }
6722 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
6723
6724 inline void perf_swevent_put_recursion_context(int rctx)
6725 {
6726         struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6727
6728         put_recursion_context(swhash->recursion, rctx);
6729 }
6730
6731 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6732 {
6733         struct perf_sample_data data;
6734
6735         if (WARN_ON_ONCE(!regs))
6736                 return;
6737
6738         perf_sample_data_init(&data, addr, 0);
6739         do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
6740 }
6741
6742 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6743 {
6744         int rctx;
6745
6746         preempt_disable_notrace();
6747         rctx = perf_swevent_get_recursion_context();
6748         if (unlikely(rctx < 0))
6749                 goto fail;
6750
6751         ___perf_sw_event(event_id, nr, regs, addr);
6752
6753         perf_swevent_put_recursion_context(rctx);
6754 fail:
6755         preempt_enable_notrace();
6756 }
6757
6758 static void perf_swevent_read(struct perf_event *event)
6759 {
6760 }
6761
6762 static int perf_swevent_add(struct perf_event *event, int flags)
6763 {
6764         struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6765         struct hw_perf_event *hwc = &event->hw;
6766         struct hlist_head *head;
6767
6768         if (is_sampling_event(event)) {
6769                 hwc->last_period = hwc->sample_period;
6770                 perf_swevent_set_period(event);
6771         }
6772
6773         hwc->state = !(flags & PERF_EF_START);
6774
6775         head = find_swevent_head(swhash, event);
6776         if (WARN_ON_ONCE(!head))
6777                 return -EINVAL;
6778
6779         hlist_add_head_rcu(&event->hlist_entry, head);
6780         perf_event_update_userpage(event);
6781
6782         return 0;
6783 }
6784
6785 static void perf_swevent_del(struct perf_event *event, int flags)
6786 {
6787         hlist_del_rcu(&event->hlist_entry);
6788 }
6789
6790 static void perf_swevent_start(struct perf_event *event, int flags)
6791 {
6792         event->hw.state = 0;
6793 }
6794
6795 static void perf_swevent_stop(struct perf_event *event, int flags)
6796 {
6797         event->hw.state = PERF_HES_STOPPED;
6798 }
6799
6800 /* Deref the hlist from the update side */
6801 static inline struct swevent_hlist *
6802 swevent_hlist_deref(struct swevent_htable *swhash)
6803 {
6804         return rcu_dereference_protected(swhash->swevent_hlist,
6805                                          lockdep_is_held(&swhash->hlist_mutex));
6806 }
6807
6808 static void swevent_hlist_release(struct swevent_htable *swhash)
6809 {
6810         struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
6811
6812         if (!hlist)
6813                 return;
6814
6815         RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
6816         kfree_rcu(hlist, rcu_head);
6817 }
6818
6819 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
6820 {
6821         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6822
6823         mutex_lock(&swhash->hlist_mutex);
6824
6825         if (!--swhash->hlist_refcount)
6826                 swevent_hlist_release(swhash);
6827
6828         mutex_unlock(&swhash->hlist_mutex);
6829 }
6830
6831 static void swevent_hlist_put(struct perf_event *event)
6832 {
6833         int cpu;
6834
6835         for_each_possible_cpu(cpu)
6836                 swevent_hlist_put_cpu(event, cpu);
6837 }
6838
6839 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
6840 {
6841         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6842         int err = 0;
6843
6844         mutex_lock(&swhash->hlist_mutex);
6845         if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
6846                 struct swevent_hlist *hlist;
6847
6848                 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
6849                 if (!hlist) {
6850                         err = -ENOMEM;
6851                         goto exit;
6852                 }
6853                 rcu_assign_pointer(swhash->swevent_hlist, hlist);
6854         }
6855         swhash->hlist_refcount++;
6856 exit:
6857         mutex_unlock(&swhash->hlist_mutex);
6858
6859         return err;
6860 }
6861
6862 static int swevent_hlist_get(struct perf_event *event)
6863 {
6864         int err;
6865         int cpu, failed_cpu;
6866
6867         get_online_cpus();
6868         for_each_possible_cpu(cpu) {
6869                 err = swevent_hlist_get_cpu(event, cpu);
6870                 if (err) {
6871                         failed_cpu = cpu;
6872                         goto fail;
6873                 }
6874         }
6875         put_online_cpus();
6876
6877         return 0;
6878 fail:
6879         for_each_possible_cpu(cpu) {
6880                 if (cpu == failed_cpu)
6881                         break;
6882                 swevent_hlist_put_cpu(event, cpu);
6883         }
6884
6885         put_online_cpus();
6886         return err;
6887 }
6888
6889 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
6890
6891 static void sw_perf_event_destroy(struct perf_event *event)
6892 {
6893         u64 event_id = event->attr.config;
6894
6895         WARN_ON(event->parent);
6896
6897         static_key_slow_dec(&perf_swevent_enabled[event_id]);
6898         swevent_hlist_put(event);
6899 }
6900
6901 static int perf_swevent_init(struct perf_event *event)
6902 {
6903         u64 event_id = event->attr.config;
6904
6905         if (event->attr.type != PERF_TYPE_SOFTWARE)
6906                 return -ENOENT;
6907
6908         /*
6909          * no branch sampling for software events
6910          */
6911         if (has_branch_stack(event))
6912                 return -EOPNOTSUPP;
6913
6914         switch (event_id) {
6915         case PERF_COUNT_SW_CPU_CLOCK:
6916         case PERF_COUNT_SW_TASK_CLOCK:
6917                 return -ENOENT;
6918
6919         default:
6920                 break;
6921         }
6922
6923         if (event_id >= PERF_COUNT_SW_MAX)
6924                 return -ENOENT;
6925
6926         if (!event->parent) {
6927                 int err;
6928
6929                 err = swevent_hlist_get(event);
6930                 if (err)
6931                         return err;
6932
6933                 static_key_slow_inc(&perf_swevent_enabled[event_id]);
6934                 event->destroy = sw_perf_event_destroy;
6935         }
6936
6937         return 0;
6938 }
6939
6940 static struct pmu perf_swevent = {
6941         .task_ctx_nr    = perf_sw_context,
6942
6943         .capabilities   = PERF_PMU_CAP_NO_NMI,
6944
6945         .event_init     = perf_swevent_init,
6946         .add            = perf_swevent_add,
6947         .del            = perf_swevent_del,
6948         .start          = perf_swevent_start,
6949         .stop           = perf_swevent_stop,
6950         .read           = perf_swevent_read,
6951 };
6952
6953 #ifdef CONFIG_EVENT_TRACING
6954
6955 static int perf_tp_filter_match(struct perf_event *event,
6956                                 struct perf_sample_data *data)
6957 {
6958         void *record = data->raw->data;
6959
6960         /* only top level events have filters set */
6961         if (event->parent)
6962                 event = event->parent;
6963
6964         if (likely(!event->filter) || filter_match_preds(event->filter, record))
6965                 return 1;
6966         return 0;
6967 }
6968
6969 static int perf_tp_event_match(struct perf_event *event,
6970                                 struct perf_sample_data *data,
6971                                 struct pt_regs *regs)
6972 {
6973         if (event->hw.state & PERF_HES_STOPPED)
6974                 return 0;
6975         /*
6976          * All tracepoints are from kernel-space.
6977          */
6978         if (event->attr.exclude_kernel)
6979                 return 0;
6980
6981         if (!perf_tp_filter_match(event, data))
6982                 return 0;
6983
6984         return 1;
6985 }
6986
6987 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
6988                    struct pt_regs *regs, struct hlist_head *head, int rctx,
6989                    struct task_struct *task)
6990 {
6991         struct perf_sample_data data;
6992         struct perf_event *event;
6993
6994         struct perf_raw_record raw = {
6995                 .size = entry_size,
6996                 .data = record,
6997         };
6998
6999         perf_sample_data_init(&data, addr, 0);
7000         data.raw = &raw;
7001
7002         hlist_for_each_entry_rcu(event, head, hlist_entry) {
7003                 if (perf_tp_event_match(event, &data, regs))
7004                         perf_swevent_event(event, count, &data, regs);
7005         }
7006
7007         /*
7008          * If we got specified a target task, also iterate its context and
7009          * deliver this event there too.
7010          */
7011         if (task && task != current) {
7012                 struct perf_event_context *ctx;
7013                 struct trace_entry *entry = record;
7014
7015                 rcu_read_lock();
7016                 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
7017                 if (!ctx)
7018                         goto unlock;
7019
7020                 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7021                         if (event->cpu != smp_processor_id())
7022                                 continue;
7023                         if (event->attr.type != PERF_TYPE_TRACEPOINT)
7024                                 continue;
7025                         if (event->attr.config != entry->type)
7026                                 continue;
7027                         if (perf_tp_event_match(event, &data, regs))
7028                                 perf_swevent_event(event, count, &data, regs);
7029                 }
7030 unlock:
7031                 rcu_read_unlock();
7032         }
7033
7034         perf_swevent_put_recursion_context(rctx);
7035 }
7036 EXPORT_SYMBOL_GPL(perf_tp_event);
7037
7038 static void tp_perf_event_destroy(struct perf_event *event)
7039 {
7040         perf_trace_destroy(event);
7041 }
7042
7043 static int perf_tp_event_init(struct perf_event *event)
7044 {
7045         int err;
7046
7047         if (event->attr.type != PERF_TYPE_TRACEPOINT)
7048                 return -ENOENT;
7049
7050         /*
7051          * no branch sampling for tracepoint events
7052          */
7053         if (has_branch_stack(event))
7054                 return -EOPNOTSUPP;
7055
7056         err = perf_trace_init(event);
7057         if (err)
7058                 return err;
7059
7060         event->destroy = tp_perf_event_destroy;
7061
7062         return 0;
7063 }
7064
7065 static struct pmu perf_tracepoint = {
7066         .task_ctx_nr    = perf_sw_context,
7067
7068         .event_init     = perf_tp_event_init,
7069         .add            = perf_trace_add,
7070         .del            = perf_trace_del,
7071         .start          = perf_swevent_start,
7072         .stop           = perf_swevent_stop,
7073         .read           = perf_swevent_read,
7074 };
7075
7076 static inline void perf_tp_register(void)
7077 {
7078         perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
7079 }
7080
7081 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7082 {
7083         char *filter_str;
7084         int ret;
7085
7086         if (event->attr.type != PERF_TYPE_TRACEPOINT)
7087                 return -EINVAL;
7088
7089         filter_str = strndup_user(arg, PAGE_SIZE);
7090         if (IS_ERR(filter_str))
7091                 return PTR_ERR(filter_str);
7092
7093         ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
7094
7095         kfree(filter_str);
7096         return ret;
7097 }
7098
7099 static void perf_event_free_filter(struct perf_event *event)
7100 {
7101         ftrace_profile_free_filter(event);
7102 }
7103
7104 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7105 {
7106         struct bpf_prog *prog;
7107
7108         if (event->attr.type != PERF_TYPE_TRACEPOINT)
7109                 return -EINVAL;
7110
7111         if (event->tp_event->prog)
7112                 return -EEXIST;
7113
7114         if (!(event->tp_event->flags & TRACE_EVENT_FL_UKPROBE))
7115                 /* bpf programs can only be attached to u/kprobes */
7116                 return -EINVAL;
7117
7118         prog = bpf_prog_get(prog_fd);
7119         if (IS_ERR(prog))
7120                 return PTR_ERR(prog);
7121
7122         if (prog->type != BPF_PROG_TYPE_KPROBE) {
7123                 /* valid fd, but invalid bpf program type */
7124                 bpf_prog_put(prog);
7125                 return -EINVAL;
7126         }
7127
7128         event->tp_event->prog = prog;
7129         event->tp_event->bpf_prog_owner = event;
7130
7131         return 0;
7132 }
7133
7134 static void perf_event_free_bpf_prog(struct perf_event *event)
7135 {
7136         struct bpf_prog *prog;
7137
7138         if (!event->tp_event)
7139                 return;
7140
7141         prog = event->tp_event->prog;
7142         if (prog && event->tp_event->bpf_prog_owner == event) {
7143                 event->tp_event->prog = NULL;
7144                 bpf_prog_put(prog);
7145         }
7146 }
7147
7148 #else
7149
7150 static inline void perf_tp_register(void)
7151 {
7152 }
7153
7154 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7155 {
7156         return -ENOENT;
7157 }
7158
7159 static void perf_event_free_filter(struct perf_event *event)
7160 {
7161 }
7162
7163 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7164 {
7165         return -ENOENT;
7166 }
7167
7168 static void perf_event_free_bpf_prog(struct perf_event *event)
7169 {
7170 }
7171 #endif /* CONFIG_EVENT_TRACING */
7172
7173 #ifdef CONFIG_HAVE_HW_BREAKPOINT
7174 void perf_bp_event(struct perf_event *bp, void *data)
7175 {
7176         struct perf_sample_data sample;
7177         struct pt_regs *regs = data;
7178
7179         perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
7180
7181         if (!bp->hw.state && !perf_exclude_event(bp, regs))
7182                 perf_swevent_event(bp, 1, &sample, regs);
7183 }
7184 #endif
7185
7186 /*
7187  * hrtimer based swevent callback
7188  */
7189
7190 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
7191 {
7192         enum hrtimer_restart ret = HRTIMER_RESTART;
7193         struct perf_sample_data data;
7194         struct pt_regs *regs;
7195         struct perf_event *event;
7196         u64 period;
7197
7198         event = container_of(hrtimer, struct perf_event, hw.hrtimer);
7199
7200         if (event->state != PERF_EVENT_STATE_ACTIVE)
7201                 return HRTIMER_NORESTART;
7202
7203         event->pmu->read(event);
7204
7205         perf_sample_data_init(&data, 0, event->hw.last_period);
7206         regs = get_irq_regs();
7207
7208         if (regs && !perf_exclude_event(event, regs)) {
7209                 if (!(event->attr.exclude_idle && is_idle_task(current)))
7210                         if (__perf_event_overflow(event, 1, &data, regs))
7211                                 ret = HRTIMER_NORESTART;
7212         }
7213
7214         period = max_t(u64, 10000, event->hw.sample_period);
7215         hrtimer_forward_now(hrtimer, ns_to_ktime(period));
7216
7217         return ret;
7218 }
7219
7220 static void perf_swevent_start_hrtimer(struct perf_event *event)
7221 {
7222         struct hw_perf_event *hwc = &event->hw;
7223         s64 period;
7224
7225         if (!is_sampling_event(event))
7226                 return;
7227
7228         period = local64_read(&hwc->period_left);
7229         if (period) {
7230                 if (period < 0)
7231                         period = 10000;
7232
7233                 local64_set(&hwc->period_left, 0);
7234         } else {
7235                 period = max_t(u64, 10000, hwc->sample_period);
7236         }
7237         hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
7238                       HRTIMER_MODE_REL_PINNED);
7239 }
7240
7241 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
7242 {
7243         struct hw_perf_event *hwc = &event->hw;
7244
7245         if (is_sampling_event(event)) {
7246                 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
7247                 local64_set(&hwc->period_left, ktime_to_ns(remaining));
7248
7249                 hrtimer_cancel(&hwc->hrtimer);
7250         }
7251 }
7252
7253 static void perf_swevent_init_hrtimer(struct perf_event *event)
7254 {
7255         struct hw_perf_event *hwc = &event->hw;
7256
7257         if (!is_sampling_event(event))
7258                 return;
7259
7260         hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7261         hwc->hrtimer.function = perf_swevent_hrtimer;
7262
7263         /*
7264          * Since hrtimers have a fixed rate, we can do a static freq->period
7265          * mapping and avoid the whole period adjust feedback stuff.
7266          */
7267         if (event->attr.freq) {
7268                 long freq = event->attr.sample_freq;
7269
7270                 event->attr.sample_period = NSEC_PER_SEC / freq;
7271                 hwc->sample_period = event->attr.sample_period;
7272                 local64_set(&hwc->period_left, hwc->sample_period);
7273                 hwc->last_period = hwc->sample_period;
7274                 event->attr.freq = 0;
7275         }
7276 }
7277
7278 /*
7279  * Software event: cpu wall time clock
7280  */
7281
7282 static void cpu_clock_event_update(struct perf_event *event)
7283 {
7284         s64 prev;
7285         u64 now;
7286
7287         now = local_clock();
7288         prev = local64_xchg(&event->hw.prev_count, now);
7289         local64_add(now - prev, &event->count);
7290 }
7291
7292 static void cpu_clock_event_start(struct perf_event *event, int flags)
7293 {
7294         local64_set(&event->hw.prev_count, local_clock());
7295         perf_swevent_start_hrtimer(event);
7296 }
7297
7298 static void cpu_clock_event_stop(struct perf_event *event, int flags)
7299 {
7300         perf_swevent_cancel_hrtimer(event);
7301         cpu_clock_event_update(event);
7302 }
7303
7304 static int cpu_clock_event_add(struct perf_event *event, int flags)
7305 {
7306         if (flags & PERF_EF_START)
7307                 cpu_clock_event_start(event, flags);
7308         perf_event_update_userpage(event);
7309
7310         return 0;
7311 }
7312
7313 static void cpu_clock_event_del(struct perf_event *event, int flags)
7314 {
7315         cpu_clock_event_stop(event, flags);
7316 }
7317
7318 static void cpu_clock_event_read(struct perf_event *event)
7319 {
7320         cpu_clock_event_update(event);
7321 }
7322
7323 static int cpu_clock_event_init(struct perf_event *event)
7324 {
7325         if (event->attr.type != PERF_TYPE_SOFTWARE)
7326                 return -ENOENT;
7327
7328         if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
7329                 return -ENOENT;
7330
7331         /*
7332          * no branch sampling for software events
7333          */
7334         if (has_branch_stack(event))
7335                 return -EOPNOTSUPP;
7336
7337         perf_swevent_init_hrtimer(event);
7338
7339         return 0;
7340 }
7341
7342 static struct pmu perf_cpu_clock = {
7343         .task_ctx_nr    = perf_sw_context,
7344
7345         .capabilities   = PERF_PMU_CAP_NO_NMI,
7346
7347         .event_init     = cpu_clock_event_init,
7348         .add            = cpu_clock_event_add,
7349         .del            = cpu_clock_event_del,
7350         .start          = cpu_clock_event_start,
7351         .stop           = cpu_clock_event_stop,
7352         .read           = cpu_clock_event_read,
7353 };
7354
7355 /*
7356  * Software event: task time clock
7357  */
7358
7359 static void task_clock_event_update(struct perf_event *event, u64 now)
7360 {
7361         u64 prev;
7362         s64 delta;
7363
7364         prev = local64_xchg(&event->hw.prev_count, now);
7365         delta = now - prev;
7366         local64_add(delta, &event->count);
7367 }
7368
7369 static void task_clock_event_start(struct perf_event *event, int flags)
7370 {
7371         local64_set(&event->hw.prev_count, event->ctx->time);
7372         perf_swevent_start_hrtimer(event);
7373 }
7374
7375 static void task_clock_event_stop(struct perf_event *event, int flags)
7376 {
7377         perf_swevent_cancel_hrtimer(event);
7378         task_clock_event_update(event, event->ctx->time);
7379 }
7380
7381 static int task_clock_event_add(struct perf_event *event, int flags)
7382 {
7383         if (flags & PERF_EF_START)
7384                 task_clock_event_start(event, flags);
7385         perf_event_update_userpage(event);
7386
7387         return 0;
7388 }
7389
7390 static void task_clock_event_del(struct perf_event *event, int flags)
7391 {
7392         task_clock_event_stop(event, PERF_EF_UPDATE);
7393 }
7394
7395 static void task_clock_event_read(struct perf_event *event)
7396 {
7397         u64 now = perf_clock();
7398         u64 delta = now - event->ctx->timestamp;
7399         u64 time = event->ctx->time + delta;
7400
7401         task_clock_event_update(event, time);
7402 }
7403
7404 static int task_clock_event_init(struct perf_event *event)
7405 {
7406         if (event->attr.type != PERF_TYPE_SOFTWARE)
7407                 return -ENOENT;
7408
7409         if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
7410                 return -ENOENT;
7411
7412         /*
7413          * no branch sampling for software events
7414          */
7415         if (has_branch_stack(event))
7416                 return -EOPNOTSUPP;
7417
7418         perf_swevent_init_hrtimer(event);
7419
7420         return 0;
7421 }
7422
7423 static struct pmu perf_task_clock = {
7424         .task_ctx_nr    = perf_sw_context,
7425
7426         .capabilities   = PERF_PMU_CAP_NO_NMI,
7427
7428         .event_init     = task_clock_event_init,
7429         .add            = task_clock_event_add,
7430         .del            = task_clock_event_del,
7431         .start          = task_clock_event_start,
7432         .stop           = task_clock_event_stop,
7433         .read           = task_clock_event_read,
7434 };
7435
7436 static void perf_pmu_nop_void(struct pmu *pmu)
7437 {
7438 }
7439
7440 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
7441 {
7442 }
7443
7444 static int perf_pmu_nop_int(struct pmu *pmu)
7445 {
7446         return 0;
7447 }
7448
7449 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
7450
7451 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
7452 {
7453         __this_cpu_write(nop_txn_flags, flags);
7454
7455         if (flags & ~PERF_PMU_TXN_ADD)
7456                 return;
7457
7458         perf_pmu_disable(pmu);
7459 }
7460
7461 static int perf_pmu_commit_txn(struct pmu *pmu)
7462 {
7463         unsigned int flags = __this_cpu_read(nop_txn_flags);
7464
7465         __this_cpu_write(nop_txn_flags, 0);
7466
7467         if (flags & ~PERF_PMU_TXN_ADD)
7468                 return 0;
7469
7470         perf_pmu_enable(pmu);
7471         return 0;
7472 }
7473
7474 static void perf_pmu_cancel_txn(struct pmu *pmu)
7475 {
7476         unsigned int flags =  __this_cpu_read(nop_txn_flags);
7477
7478         __this_cpu_write(nop_txn_flags, 0);
7479
7480         if (flags & ~PERF_PMU_TXN_ADD)
7481                 return;
7482
7483         perf_pmu_enable(pmu);
7484 }
7485
7486 static int perf_event_idx_default(struct perf_event *event)
7487 {
7488         return 0;
7489 }
7490
7491 /*
7492  * Ensures all contexts with the same task_ctx_nr have the same
7493  * pmu_cpu_context too.
7494  */
7495 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
7496 {
7497         struct pmu *pmu;
7498
7499         if (ctxn < 0)
7500                 return NULL;
7501
7502         list_for_each_entry(pmu, &pmus, entry) {
7503                 if (pmu->task_ctx_nr == ctxn)
7504                         return pmu->pmu_cpu_context;
7505         }
7506
7507         return NULL;
7508 }
7509
7510 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
7511 {
7512         int cpu;
7513
7514         for_each_possible_cpu(cpu) {
7515                 struct perf_cpu_context *cpuctx;
7516
7517                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7518
7519                 if (cpuctx->unique_pmu == old_pmu)
7520                         cpuctx->unique_pmu = pmu;
7521         }
7522 }
7523
7524 static void free_pmu_context(struct pmu *pmu)
7525 {
7526         struct pmu *i;
7527
7528         mutex_lock(&pmus_lock);
7529         /*
7530          * Like a real lame refcount.
7531          */
7532         list_for_each_entry(i, &pmus, entry) {
7533                 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
7534                         update_pmu_context(i, pmu);
7535                         goto out;
7536                 }
7537         }
7538
7539         free_percpu(pmu->pmu_cpu_context);
7540 out:
7541         mutex_unlock(&pmus_lock);
7542 }
7543 static struct idr pmu_idr;
7544
7545 static ssize_t
7546 type_show(struct device *dev, struct device_attribute *attr, char *page)
7547 {
7548         struct pmu *pmu = dev_get_drvdata(dev);
7549
7550         return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
7551 }
7552 static DEVICE_ATTR_RO(type);
7553
7554 static ssize_t
7555 perf_event_mux_interval_ms_show(struct device *dev,
7556                                 struct device_attribute *attr,
7557                                 char *page)
7558 {
7559         struct pmu *pmu = dev_get_drvdata(dev);
7560
7561         return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
7562 }
7563
7564 static DEFINE_MUTEX(mux_interval_mutex);
7565
7566 static ssize_t
7567 perf_event_mux_interval_ms_store(struct device *dev,
7568                                  struct device_attribute *attr,
7569                                  const char *buf, size_t count)
7570 {
7571         struct pmu *pmu = dev_get_drvdata(dev);
7572         int timer, cpu, ret;
7573
7574         ret = kstrtoint(buf, 0, &timer);
7575         if (ret)
7576                 return ret;
7577
7578         if (timer < 1)
7579                 return -EINVAL;
7580
7581         /* same value, noting to do */
7582         if (timer == pmu->hrtimer_interval_ms)
7583                 return count;
7584
7585         mutex_lock(&mux_interval_mutex);
7586         pmu->hrtimer_interval_ms = timer;
7587
7588         /* update all cpuctx for this PMU */
7589         get_online_cpus();
7590         for_each_online_cpu(cpu) {
7591                 struct perf_cpu_context *cpuctx;
7592                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7593                 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
7594
7595                 cpu_function_call(cpu,
7596                         (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
7597         }
7598         put_online_cpus();
7599         mutex_unlock(&mux_interval_mutex);
7600
7601         return count;
7602 }
7603 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
7604
7605 static struct attribute *pmu_dev_attrs[] = {
7606         &dev_attr_type.attr,
7607         &dev_attr_perf_event_mux_interval_ms.attr,
7608         NULL,
7609 };
7610 ATTRIBUTE_GROUPS(pmu_dev);
7611
7612 static int pmu_bus_running;
7613 static struct bus_type pmu_bus = {
7614         .name           = "event_source",
7615         .dev_groups     = pmu_dev_groups,
7616 };
7617
7618 static void pmu_dev_release(struct device *dev)
7619 {
7620         kfree(dev);
7621 }
7622
7623 static int pmu_dev_alloc(struct pmu *pmu)
7624 {
7625         int ret = -ENOMEM;
7626
7627         pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
7628         if (!pmu->dev)
7629                 goto out;
7630
7631         pmu->dev->groups = pmu->attr_groups;
7632         device_initialize(pmu->dev);
7633         ret = dev_set_name(pmu->dev, "%s", pmu->name);
7634         if (ret)
7635                 goto free_dev;
7636
7637         dev_set_drvdata(pmu->dev, pmu);
7638         pmu->dev->bus = &pmu_bus;
7639         pmu->dev->release = pmu_dev_release;
7640         ret = device_add(pmu->dev);
7641         if (ret)
7642                 goto free_dev;
7643
7644 out:
7645         return ret;
7646
7647 free_dev:
7648         put_device(pmu->dev);
7649         goto out;
7650 }
7651
7652 static struct lock_class_key cpuctx_mutex;
7653 static struct lock_class_key cpuctx_lock;
7654
7655 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
7656 {
7657         int cpu, ret;
7658
7659         mutex_lock(&pmus_lock);
7660         ret = -ENOMEM;
7661         pmu->pmu_disable_count = alloc_percpu(int);
7662         if (!pmu->pmu_disable_count)
7663                 goto unlock;
7664
7665         pmu->type = -1;
7666         if (!name)
7667                 goto skip_type;
7668         pmu->name = name;
7669
7670         if (type < 0) {
7671                 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
7672                 if (type < 0) {
7673                         ret = type;
7674                         goto free_pdc;
7675                 }
7676         }
7677         pmu->type = type;
7678
7679         if (pmu_bus_running) {
7680                 ret = pmu_dev_alloc(pmu);
7681                 if (ret)
7682                         goto free_idr;
7683         }
7684
7685 skip_type:
7686         pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
7687         if (pmu->pmu_cpu_context)
7688                 goto got_cpu_context;
7689
7690         ret = -ENOMEM;
7691         pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
7692         if (!pmu->pmu_cpu_context)
7693                 goto free_dev;
7694
7695         for_each_possible_cpu(cpu) {
7696                 struct perf_cpu_context *cpuctx;
7697
7698                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7699                 __perf_event_init_context(&cpuctx->ctx);
7700                 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
7701                 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
7702                 cpuctx->ctx.pmu = pmu;
7703
7704                 __perf_mux_hrtimer_init(cpuctx, cpu);
7705
7706                 cpuctx->unique_pmu = pmu;
7707         }
7708
7709 got_cpu_context:
7710         if (!pmu->start_txn) {
7711                 if (pmu->pmu_enable) {
7712                         /*
7713                          * If we have pmu_enable/pmu_disable calls, install
7714                          * transaction stubs that use that to try and batch
7715                          * hardware accesses.
7716                          */
7717                         pmu->start_txn  = perf_pmu_start_txn;
7718                         pmu->commit_txn = perf_pmu_commit_txn;
7719                         pmu->cancel_txn = perf_pmu_cancel_txn;
7720                 } else {
7721                         pmu->start_txn  = perf_pmu_nop_txn;
7722                         pmu->commit_txn = perf_pmu_nop_int;
7723                         pmu->cancel_txn = perf_pmu_nop_void;
7724                 }
7725         }
7726
7727         if (!pmu->pmu_enable) {
7728                 pmu->pmu_enable  = perf_pmu_nop_void;
7729                 pmu->pmu_disable = perf_pmu_nop_void;
7730         }
7731
7732         if (!pmu->event_idx)
7733                 pmu->event_idx = perf_event_idx_default;
7734
7735         list_add_rcu(&pmu->entry, &pmus);
7736         atomic_set(&pmu->exclusive_cnt, 0);
7737         ret = 0;
7738 unlock:
7739         mutex_unlock(&pmus_lock);
7740
7741         return ret;
7742
7743 free_dev:
7744         device_del(pmu->dev);
7745         put_device(pmu->dev);
7746
7747 free_idr:
7748         if (pmu->type >= PERF_TYPE_MAX)
7749                 idr_remove(&pmu_idr, pmu->type);
7750
7751 free_pdc:
7752         free_percpu(pmu->pmu_disable_count);
7753         goto unlock;
7754 }
7755 EXPORT_SYMBOL_GPL(perf_pmu_register);
7756
7757 void perf_pmu_unregister(struct pmu *pmu)
7758 {
7759         mutex_lock(&pmus_lock);
7760         list_del_rcu(&pmu->entry);
7761         mutex_unlock(&pmus_lock);
7762
7763         /*
7764          * We dereference the pmu list under both SRCU and regular RCU, so
7765          * synchronize against both of those.
7766          */
7767         synchronize_srcu(&pmus_srcu);
7768         synchronize_rcu();
7769
7770         free_percpu(pmu->pmu_disable_count);
7771         if (pmu->type >= PERF_TYPE_MAX)
7772                 idr_remove(&pmu_idr, pmu->type);
7773         device_del(pmu->dev);
7774         put_device(pmu->dev);
7775         free_pmu_context(pmu);
7776 }
7777 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
7778
7779 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
7780 {
7781         struct perf_event_context *ctx = NULL;
7782         int ret;
7783
7784         if (!try_module_get(pmu->module))
7785                 return -ENODEV;
7786
7787         if (event->group_leader != event) {
7788                 /*
7789                  * This ctx->mutex can nest when we're called through
7790                  * inheritance. See the perf_event_ctx_lock_nested() comment.
7791                  */
7792                 ctx = perf_event_ctx_lock_nested(event->group_leader,
7793                                                  SINGLE_DEPTH_NESTING);
7794                 BUG_ON(!ctx);
7795         }
7796
7797         event->pmu = pmu;
7798         ret = pmu->event_init(event);
7799
7800         if (ctx)
7801                 perf_event_ctx_unlock(event->group_leader, ctx);
7802
7803         if (ret)
7804                 module_put(pmu->module);
7805
7806         return ret;
7807 }
7808
7809 static struct pmu *perf_init_event(struct perf_event *event)
7810 {
7811         struct pmu *pmu = NULL;
7812         int idx;
7813         int ret;
7814
7815         idx = srcu_read_lock(&pmus_srcu);
7816
7817         rcu_read_lock();
7818         pmu = idr_find(&pmu_idr, event->attr.type);
7819         rcu_read_unlock();
7820         if (pmu) {
7821                 ret = perf_try_init_event(pmu, event);
7822                 if (ret)
7823                         pmu = ERR_PTR(ret);
7824                 goto unlock;
7825         }
7826
7827         list_for_each_entry_rcu(pmu, &pmus, entry) {
7828                 ret = perf_try_init_event(pmu, event);
7829                 if (!ret)
7830                         goto unlock;
7831
7832                 if (ret != -ENOENT) {
7833                         pmu = ERR_PTR(ret);
7834                         goto unlock;
7835                 }
7836         }
7837         pmu = ERR_PTR(-ENOENT);
7838 unlock:
7839         srcu_read_unlock(&pmus_srcu, idx);
7840
7841         return pmu;
7842 }
7843
7844 static void account_event_cpu(struct perf_event *event, int cpu)
7845 {
7846         if (event->parent)
7847                 return;
7848
7849         if (is_cgroup_event(event))
7850                 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
7851 }
7852
7853 static void account_event(struct perf_event *event)
7854 {
7855         if (event->parent)
7856                 return;
7857
7858         if (event->attach_state & PERF_ATTACH_TASK)
7859                 static_key_slow_inc(&perf_sched_events.key);
7860         if (event->attr.mmap || event->attr.mmap_data)
7861                 atomic_inc(&nr_mmap_events);
7862         if (event->attr.comm)
7863                 atomic_inc(&nr_comm_events);
7864         if (event->attr.task)
7865                 atomic_inc(&nr_task_events);
7866         if (event->attr.freq) {
7867                 if (atomic_inc_return(&nr_freq_events) == 1)
7868                         tick_nohz_full_kick_all();
7869         }
7870         if (event->attr.context_switch) {
7871                 atomic_inc(&nr_switch_events);
7872                 static_key_slow_inc(&perf_sched_events.key);
7873         }
7874         if (has_branch_stack(event))
7875                 static_key_slow_inc(&perf_sched_events.key);
7876         if (is_cgroup_event(event))
7877                 static_key_slow_inc(&perf_sched_events.key);
7878
7879         account_event_cpu(event, event->cpu);
7880 }
7881
7882 /*
7883  * Allocate and initialize a event structure
7884  */
7885 static struct perf_event *
7886 perf_event_alloc(struct perf_event_attr *attr, int cpu,
7887                  struct task_struct *task,
7888                  struct perf_event *group_leader,
7889                  struct perf_event *parent_event,
7890                  perf_overflow_handler_t overflow_handler,
7891                  void *context, int cgroup_fd)
7892 {
7893         struct pmu *pmu;
7894         struct perf_event *event;
7895         struct hw_perf_event *hwc;
7896         long err = -EINVAL;
7897
7898         if ((unsigned)cpu >= nr_cpu_ids) {
7899                 if (!task || cpu != -1)
7900                         return ERR_PTR(-EINVAL);
7901         }
7902
7903         event = kzalloc(sizeof(*event), GFP_KERNEL);
7904         if (!event)
7905                 return ERR_PTR(-ENOMEM);
7906
7907         /*
7908          * Single events are their own group leaders, with an
7909          * empty sibling list:
7910          */
7911         if (!group_leader)
7912                 group_leader = event;
7913
7914         mutex_init(&event->child_mutex);
7915         INIT_LIST_HEAD(&event->child_list);
7916
7917         INIT_LIST_HEAD(&event->group_entry);
7918         INIT_LIST_HEAD(&event->event_entry);
7919         INIT_LIST_HEAD(&event->sibling_list);
7920         INIT_LIST_HEAD(&event->rb_entry);
7921         INIT_LIST_HEAD(&event->active_entry);
7922         INIT_HLIST_NODE(&event->hlist_entry);
7923
7924
7925         init_waitqueue_head(&event->waitq);
7926         init_irq_work(&event->pending, perf_pending_event);
7927
7928         mutex_init(&event->mmap_mutex);
7929
7930         atomic_long_set(&event->refcount, 1);
7931         event->cpu              = cpu;
7932         event->attr             = *attr;
7933         event->group_leader     = group_leader;
7934         event->pmu              = NULL;
7935         event->oncpu            = -1;
7936
7937         event->parent           = parent_event;
7938
7939         event->ns               = get_pid_ns(task_active_pid_ns(current));
7940         event->id               = atomic64_inc_return(&perf_event_id);
7941
7942         event->state            = PERF_EVENT_STATE_INACTIVE;
7943
7944         if (task) {
7945                 event->attach_state = PERF_ATTACH_TASK;
7946                 /*
7947                  * XXX pmu::event_init needs to know what task to account to
7948                  * and we cannot use the ctx information because we need the
7949                  * pmu before we get a ctx.
7950                  */
7951                 event->hw.target = task;
7952         }
7953
7954         event->clock = &local_clock;
7955         if (parent_event)
7956                 event->clock = parent_event->clock;
7957
7958         if (!overflow_handler && parent_event) {
7959                 overflow_handler = parent_event->overflow_handler;
7960                 context = parent_event->overflow_handler_context;
7961         }
7962
7963         event->overflow_handler = overflow_handler;
7964         event->overflow_handler_context = context;
7965
7966         perf_event__state_init(event);
7967
7968         pmu = NULL;
7969
7970         hwc = &event->hw;
7971         hwc->sample_period = attr->sample_period;
7972         if (attr->freq && attr->sample_freq)
7973                 hwc->sample_period = 1;
7974         hwc->last_period = hwc->sample_period;
7975
7976         local64_set(&hwc->period_left, hwc->sample_period);
7977
7978         /*
7979          * We currently do not support PERF_SAMPLE_READ on inherited events.
7980          * See perf_output_read().
7981          */
7982         if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
7983                 goto err_ns;
7984
7985         if (!has_branch_stack(event))
7986                 event->attr.branch_sample_type = 0;
7987
7988         if (cgroup_fd != -1) {
7989                 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
7990                 if (err)
7991                         goto err_ns;
7992         }
7993
7994         pmu = perf_init_event(event);
7995         if (!pmu)
7996                 goto err_ns;
7997         else if (IS_ERR(pmu)) {
7998                 err = PTR_ERR(pmu);
7999                 goto err_ns;
8000         }
8001
8002         err = exclusive_event_init(event);
8003         if (err)
8004                 goto err_pmu;
8005
8006         if (!event->parent) {
8007                 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
8008                         err = get_callchain_buffers();
8009                         if (err)
8010                                 goto err_per_task;
8011                 }
8012         }
8013
8014         /* symmetric to unaccount_event() in _free_event() */
8015         account_event(event);
8016
8017         return event;
8018
8019 err_per_task:
8020         exclusive_event_destroy(event);
8021
8022 err_pmu:
8023         if (event->destroy)
8024                 event->destroy(event);
8025         module_put(pmu->module);
8026 err_ns:
8027         if (is_cgroup_event(event))
8028                 perf_detach_cgroup(event);
8029         if (event->ns)
8030                 put_pid_ns(event->ns);
8031         kfree(event);
8032
8033         return ERR_PTR(err);
8034 }
8035
8036 static int perf_copy_attr(struct perf_event_attr __user *uattr,
8037                           struct perf_event_attr *attr)
8038 {
8039         u32 size;
8040         int ret;
8041
8042         if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
8043                 return -EFAULT;
8044
8045         /*
8046          * zero the full structure, so that a short copy will be nice.
8047          */
8048         memset(attr, 0, sizeof(*attr));
8049
8050         ret = get_user(size, &uattr->size);
8051         if (ret)
8052                 return ret;
8053
8054         if (size > PAGE_SIZE)   /* silly large */
8055                 goto err_size;
8056
8057         if (!size)              /* abi compat */
8058                 size = PERF_ATTR_SIZE_VER0;
8059
8060         if (size < PERF_ATTR_SIZE_VER0)
8061                 goto err_size;
8062
8063         /*
8064          * If we're handed a bigger struct than we know of,
8065          * ensure all the unknown bits are 0 - i.e. new
8066          * user-space does not rely on any kernel feature
8067          * extensions we dont know about yet.
8068          */
8069         if (size > sizeof(*attr)) {
8070                 unsigned char __user *addr;
8071                 unsigned char __user *end;
8072                 unsigned char val;
8073
8074                 addr = (void __user *)uattr + sizeof(*attr);
8075                 end  = (void __user *)uattr + size;
8076
8077                 for (; addr < end; addr++) {
8078                         ret = get_user(val, addr);
8079                         if (ret)
8080                                 return ret;
8081                         if (val)
8082                                 goto err_size;
8083                 }
8084                 size = sizeof(*attr);
8085         }
8086
8087         ret = copy_from_user(attr, uattr, size);
8088         if (ret)
8089                 return -EFAULT;
8090
8091         if (attr->__reserved_1)
8092                 return -EINVAL;
8093
8094         if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
8095                 return -EINVAL;
8096
8097         if (attr->read_format & ~(PERF_FORMAT_MAX-1))
8098                 return -EINVAL;
8099
8100         if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
8101                 u64 mask = attr->branch_sample_type;
8102
8103                 /* only using defined bits */
8104                 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
8105                         return -EINVAL;
8106
8107                 /* at least one branch bit must be set */
8108                 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
8109                         return -EINVAL;
8110
8111                 /* propagate priv level, when not set for branch */
8112                 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
8113
8114                         /* exclude_kernel checked on syscall entry */
8115                         if (!attr->exclude_kernel)
8116                                 mask |= PERF_SAMPLE_BRANCH_KERNEL;
8117
8118                         if (!attr->exclude_user)
8119                                 mask |= PERF_SAMPLE_BRANCH_USER;
8120
8121                         if (!attr->exclude_hv)
8122                                 mask |= PERF_SAMPLE_BRANCH_HV;
8123                         /*
8124                          * adjust user setting (for HW filter setup)
8125                          */
8126                         attr->branch_sample_type = mask;
8127                 }
8128                 /* privileged levels capture (kernel, hv): check permissions */
8129                 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
8130                     && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8131                         return -EACCES;
8132         }
8133
8134         if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
8135                 ret = perf_reg_validate(attr->sample_regs_user);
8136                 if (ret)
8137                         return ret;
8138         }
8139
8140         if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
8141                 if (!arch_perf_have_user_stack_dump())
8142                         return -ENOSYS;
8143
8144                 /*
8145                  * We have __u32 type for the size, but so far
8146                  * we can only use __u16 as maximum due to the
8147                  * __u16 sample size limit.
8148                  */
8149                 if (attr->sample_stack_user >= USHRT_MAX)
8150                         return -EINVAL;
8151                 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
8152                         return -EINVAL;
8153         }
8154
8155         if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
8156                 ret = perf_reg_validate(attr->sample_regs_intr);
8157 out:
8158         return ret;
8159
8160 err_size:
8161         put_user(sizeof(*attr), &uattr->size);
8162         ret = -E2BIG;
8163         goto out;
8164 }
8165
8166 static int
8167 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
8168 {
8169         struct ring_buffer *rb = NULL;
8170         int ret = -EINVAL;
8171
8172         if (!output_event)
8173                 goto set;
8174
8175         /* don't allow circular references */
8176         if (event == output_event)
8177                 goto out;
8178
8179         /*
8180          * Don't allow cross-cpu buffers
8181          */
8182         if (output_event->cpu != event->cpu)
8183                 goto out;
8184
8185         /*
8186          * If its not a per-cpu rb, it must be the same task.
8187          */
8188         if (output_event->cpu == -1 && output_event->ctx != event->ctx)
8189                 goto out;
8190
8191         /*
8192          * Mixing clocks in the same buffer is trouble you don't need.
8193          */
8194         if (output_event->clock != event->clock)
8195                 goto out;
8196
8197         /*
8198          * If both events generate aux data, they must be on the same PMU
8199          */
8200         if (has_aux(event) && has_aux(output_event) &&
8201             event->pmu != output_event->pmu)
8202                 goto out;
8203
8204 set:
8205         mutex_lock(&event->mmap_mutex);
8206         /* Can't redirect output if we've got an active mmap() */
8207         if (atomic_read(&event->mmap_count))
8208                 goto unlock;
8209
8210         if (output_event) {
8211                 /* get the rb we want to redirect to */
8212                 rb = ring_buffer_get(output_event);
8213                 if (!rb)
8214                         goto unlock;
8215         }
8216
8217         ring_buffer_attach(event, rb);
8218
8219         ret = 0;
8220 unlock:
8221         mutex_unlock(&event->mmap_mutex);
8222
8223 out:
8224         return ret;
8225 }
8226
8227 static void mutex_lock_double(struct mutex *a, struct mutex *b)
8228 {
8229         if (b < a)
8230                 swap(a, b);
8231
8232         mutex_lock(a);
8233         mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
8234 }
8235
8236 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
8237 {
8238         bool nmi_safe = false;
8239
8240         switch (clk_id) {
8241         case CLOCK_MONOTONIC:
8242                 event->clock = &ktime_get_mono_fast_ns;
8243                 nmi_safe = true;
8244                 break;
8245
8246         case CLOCK_MONOTONIC_RAW:
8247                 event->clock = &ktime_get_raw_fast_ns;
8248                 nmi_safe = true;
8249                 break;
8250
8251         case CLOCK_REALTIME:
8252                 event->clock = &ktime_get_real_ns;
8253                 break;
8254
8255         case CLOCK_BOOTTIME:
8256                 event->clock = &ktime_get_boot_ns;
8257                 break;
8258
8259         case CLOCK_TAI:
8260                 event->clock = &ktime_get_tai_ns;
8261                 break;
8262
8263         default:
8264                 return -EINVAL;
8265         }
8266
8267         if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
8268                 return -EINVAL;
8269
8270         return 0;
8271 }
8272
8273 /*
8274  * Variation on perf_event_ctx_lock_nested(), except we take two context
8275  * mutexes.
8276  */
8277 static struct perf_event_context *
8278 __perf_event_ctx_lock_double(struct perf_event *group_leader,
8279                              struct perf_event_context *ctx)
8280 {
8281         struct perf_event_context *gctx;
8282
8283 again:
8284         rcu_read_lock();
8285         gctx = READ_ONCE(group_leader->ctx);
8286         if (!atomic_inc_not_zero(&gctx->refcount)) {
8287                 rcu_read_unlock();
8288                 goto again;
8289         }
8290         rcu_read_unlock();
8291
8292         mutex_lock_double(&gctx->mutex, &ctx->mutex);
8293
8294         if (group_leader->ctx != gctx) {
8295                 mutex_unlock(&ctx->mutex);
8296                 mutex_unlock(&gctx->mutex);
8297                 put_ctx(gctx);
8298                 goto again;
8299         }
8300
8301         return gctx;
8302 }
8303
8304 /**
8305  * sys_perf_event_open - open a performance event, associate it to a task/cpu
8306  *
8307  * @attr_uptr:  event_id type attributes for monitoring/sampling
8308  * @pid:                target pid
8309  * @cpu:                target cpu
8310  * @group_fd:           group leader event fd
8311  */
8312 SYSCALL_DEFINE5(perf_event_open,
8313                 struct perf_event_attr __user *, attr_uptr,
8314                 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
8315 {
8316         struct perf_event *group_leader = NULL, *output_event = NULL;
8317         struct perf_event *event, *sibling;
8318         struct perf_event_attr attr;
8319         struct perf_event_context *ctx, *uninitialized_var(gctx);
8320         struct file *event_file = NULL;
8321         struct fd group = {NULL, 0};
8322         struct task_struct *task = NULL;
8323         struct pmu *pmu;
8324         int event_fd;
8325         int move_group = 0;
8326         int err;
8327         int f_flags = O_RDWR;
8328         int cgroup_fd = -1;
8329
8330         /* for future expandability... */
8331         if (flags & ~PERF_FLAG_ALL)
8332                 return -EINVAL;
8333
8334         err = perf_copy_attr(attr_uptr, &attr);
8335         if (err)
8336                 return err;
8337
8338         if (!attr.exclude_kernel) {
8339                 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8340                         return -EACCES;
8341         }
8342
8343         if (attr.freq) {
8344                 if (attr.sample_freq > sysctl_perf_event_sample_rate)
8345                         return -EINVAL;
8346         } else {
8347                 if (attr.sample_period & (1ULL << 63))
8348                         return -EINVAL;
8349         }
8350
8351         /*
8352          * In cgroup mode, the pid argument is used to pass the fd
8353          * opened to the cgroup directory in cgroupfs. The cpu argument
8354          * designates the cpu on which to monitor threads from that
8355          * cgroup.
8356          */
8357         if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
8358                 return -EINVAL;
8359
8360         if (flags & PERF_FLAG_FD_CLOEXEC)
8361                 f_flags |= O_CLOEXEC;
8362
8363         event_fd = get_unused_fd_flags(f_flags);
8364         if (event_fd < 0)
8365                 return event_fd;
8366
8367         if (group_fd != -1) {
8368                 err = perf_fget_light(group_fd, &group);
8369                 if (err)
8370                         goto err_fd;
8371                 group_leader = group.file->private_data;
8372                 if (flags & PERF_FLAG_FD_OUTPUT)
8373                         output_event = group_leader;
8374                 if (flags & PERF_FLAG_FD_NO_GROUP)
8375                         group_leader = NULL;
8376         }
8377
8378         if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
8379                 task = find_lively_task_by_vpid(pid);
8380                 if (IS_ERR(task)) {
8381                         err = PTR_ERR(task);
8382                         goto err_group_fd;
8383                 }
8384         }
8385
8386         if (task && group_leader &&
8387             group_leader->attr.inherit != attr.inherit) {
8388                 err = -EINVAL;
8389                 goto err_task;
8390         }
8391
8392         get_online_cpus();
8393
8394         if (task) {
8395                 err = mutex_lock_interruptible(&task->signal->cred_guard_mutex);
8396                 if (err)
8397                         goto err_cpus;
8398
8399                 /*
8400                  * Reuse ptrace permission checks for now.
8401                  *
8402                  * We must hold cred_guard_mutex across this and any potential
8403                  * perf_install_in_context() call for this new event to
8404                  * serialize against exec() altering our credentials (and the
8405                  * perf_event_exit_task() that could imply).
8406                  */
8407                 err = -EACCES;
8408                 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
8409                         goto err_cred;
8410         }
8411
8412         if (flags & PERF_FLAG_PID_CGROUP)
8413                 cgroup_fd = pid;
8414
8415         event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
8416                                  NULL, NULL, cgroup_fd);
8417         if (IS_ERR(event)) {
8418                 err = PTR_ERR(event);
8419                 goto err_cred;
8420         }
8421
8422         if (is_sampling_event(event)) {
8423                 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
8424                         err = -ENOTSUPP;
8425                         goto err_alloc;
8426                 }
8427         }
8428
8429         /*
8430          * Special case software events and allow them to be part of
8431          * any hardware group.
8432          */
8433         pmu = event->pmu;
8434
8435         if (attr.use_clockid) {
8436                 err = perf_event_set_clock(event, attr.clockid);
8437                 if (err)
8438                         goto err_alloc;
8439         }
8440
8441         if (group_leader &&
8442             (is_software_event(event) != is_software_event(group_leader))) {
8443                 if (is_software_event(event)) {
8444                         /*
8445                          * If event and group_leader are not both a software
8446                          * event, and event is, then group leader is not.
8447                          *
8448                          * Allow the addition of software events to !software
8449                          * groups, this is safe because software events never
8450                          * fail to schedule.
8451                          */
8452                         pmu = group_leader->pmu;
8453                 } else if (is_software_event(group_leader) &&
8454                            (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
8455                         /*
8456                          * In case the group is a pure software group, and we
8457                          * try to add a hardware event, move the whole group to
8458                          * the hardware context.
8459                          */
8460                         move_group = 1;
8461                 }
8462         }
8463
8464         /*
8465          * Get the target context (task or percpu):
8466          */
8467         ctx = find_get_context(pmu, task, event);
8468         if (IS_ERR(ctx)) {
8469                 err = PTR_ERR(ctx);
8470                 goto err_alloc;
8471         }
8472
8473         if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
8474                 err = -EBUSY;
8475                 goto err_context;
8476         }
8477
8478         /*
8479          * Look up the group leader (we will attach this event to it):
8480          */
8481         if (group_leader) {
8482                 err = -EINVAL;
8483
8484                 /*
8485                  * Do not allow a recursive hierarchy (this new sibling
8486                  * becoming part of another group-sibling):
8487                  */
8488                 if (group_leader->group_leader != group_leader)
8489                         goto err_context;
8490
8491                 /* All events in a group should have the same clock */
8492                 if (group_leader->clock != event->clock)
8493                         goto err_context;
8494
8495                 /*
8496                  * Make sure we're both events for the same CPU;
8497                  * grouping events for different CPUs is broken; since
8498                  * you can never concurrently schedule them anyhow.
8499                  */
8500                 if (group_leader->cpu != event->cpu)
8501                         goto err_context;
8502
8503                 /*
8504                  * Make sure we're both on the same task, or both
8505                  * per-CPU events.
8506                  */
8507                 if (group_leader->ctx->task != ctx->task)
8508                         goto err_context;
8509
8510                 /*
8511                  * Do not allow to attach to a group in a different task
8512                  * or CPU context. If we're moving SW events, we'll fix
8513                  * this up later, so allow that.
8514                  */
8515                 if (!move_group && group_leader->ctx != ctx)
8516                         goto err_context;
8517
8518                 /*
8519                  * Only a group leader can be exclusive or pinned
8520                  */
8521                 if (attr.exclusive || attr.pinned)
8522                         goto err_context;
8523         }
8524
8525         if (output_event) {
8526                 err = perf_event_set_output(event, output_event);
8527                 if (err)
8528                         goto err_context;
8529         }
8530
8531         event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
8532                                         f_flags);
8533         if (IS_ERR(event_file)) {
8534                 err = PTR_ERR(event_file);
8535                 event_file = NULL;
8536                 goto err_context;
8537         }
8538
8539         if (move_group) {
8540                 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
8541
8542                 /*
8543                  * Check if we raced against another sys_perf_event_open() call
8544                  * moving the software group underneath us.
8545                  */
8546                 if (!(group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
8547                         /*
8548                          * If someone moved the group out from under us, check
8549                          * if this new event wound up on the same ctx, if so
8550                          * its the regular !move_group case, otherwise fail.
8551                          */
8552                         if (gctx != ctx) {
8553                                 err = -EINVAL;
8554                                 goto err_locked;
8555                         } else {
8556                                 perf_event_ctx_unlock(group_leader, gctx);
8557                                 move_group = 0;
8558                         }
8559                 }
8560         } else {
8561                 mutex_lock(&ctx->mutex);
8562         }
8563
8564         if (!perf_event_validate_size(event)) {
8565                 err = -E2BIG;
8566                 goto err_locked;
8567         }
8568
8569         /*
8570          * Must be under the same ctx::mutex as perf_install_in_context(),
8571          * because we need to serialize with concurrent event creation.
8572          */
8573         if (!exclusive_event_installable(event, ctx)) {
8574                 /* exclusive and group stuff are assumed mutually exclusive */
8575                 WARN_ON_ONCE(move_group);
8576
8577                 err = -EBUSY;
8578                 goto err_locked;
8579         }
8580
8581         WARN_ON_ONCE(ctx->parent_ctx);
8582
8583         /*
8584          * This is the point on no return; we cannot fail hereafter. This is
8585          * where we start modifying current state.
8586          */
8587
8588         if (move_group) {
8589                 /*
8590                  * See perf_event_ctx_lock() for comments on the details
8591                  * of swizzling perf_event::ctx.
8592                  */
8593                 perf_remove_from_context(group_leader, false);
8594
8595                 list_for_each_entry(sibling, &group_leader->sibling_list,
8596                                     group_entry) {
8597                         perf_remove_from_context(sibling, false);
8598                         put_ctx(gctx);
8599                 }
8600
8601                 /*
8602                  * Wait for everybody to stop referencing the events through
8603                  * the old lists, before installing it on new lists.
8604                  */
8605                 synchronize_rcu();
8606
8607                 /*
8608                  * Install the group siblings before the group leader.
8609                  *
8610                  * Because a group leader will try and install the entire group
8611                  * (through the sibling list, which is still in-tact), we can
8612                  * end up with siblings installed in the wrong context.
8613                  *
8614                  * By installing siblings first we NO-OP because they're not
8615                  * reachable through the group lists.
8616                  */
8617                 list_for_each_entry(sibling, &group_leader->sibling_list,
8618                                     group_entry) {
8619                         perf_event__state_init(sibling);
8620                         perf_install_in_context(ctx, sibling, sibling->cpu);
8621                         get_ctx(ctx);
8622                 }
8623
8624                 /*
8625                  * Removing from the context ends up with disabled
8626                  * event. What we want here is event in the initial
8627                  * startup state, ready to be add into new context.
8628                  */
8629                 perf_event__state_init(group_leader);
8630                 perf_install_in_context(ctx, group_leader, group_leader->cpu);
8631                 get_ctx(ctx);
8632
8633                 /*
8634                  * Now that all events are installed in @ctx, nothing
8635                  * references @gctx anymore, so drop the last reference we have
8636                  * on it.
8637                  */
8638                 put_ctx(gctx);
8639         }
8640
8641         /*
8642          * Precalculate sample_data sizes; do while holding ctx::mutex such
8643          * that we're serialized against further additions and before
8644          * perf_install_in_context() which is the point the event is active and
8645          * can use these values.
8646          */
8647         perf_event__header_size(event);
8648         perf_event__id_header_size(event);
8649
8650         perf_install_in_context(ctx, event, event->cpu);
8651         perf_unpin_context(ctx);
8652
8653         if (move_group)
8654                 perf_event_ctx_unlock(group_leader, gctx);
8655         mutex_unlock(&ctx->mutex);
8656
8657         if (task) {
8658                 mutex_unlock(&task->signal->cred_guard_mutex);
8659                 put_task_struct(task);
8660         }
8661
8662         put_online_cpus();
8663
8664         event->owner = current;
8665
8666         mutex_lock(&current->perf_event_mutex);
8667         list_add_tail(&event->owner_entry, &current->perf_event_list);
8668         mutex_unlock(&current->perf_event_mutex);
8669
8670         /*
8671          * Drop the reference on the group_event after placing the
8672          * new event on the sibling_list. This ensures destruction
8673          * of the group leader will find the pointer to itself in
8674          * perf_group_detach().
8675          */
8676         fdput(group);
8677         fd_install(event_fd, event_file);
8678         return event_fd;
8679
8680 err_locked:
8681         if (move_group)
8682                 perf_event_ctx_unlock(group_leader, gctx);
8683         mutex_unlock(&ctx->mutex);
8684 /* err_file: */
8685         fput(event_file);
8686 err_context:
8687         perf_unpin_context(ctx);
8688         put_ctx(ctx);
8689 err_alloc:
8690         /*
8691          * If event_file is set, the fput() above will have called ->release()
8692          * and that will take care of freeing the event.
8693          */
8694         if (!event_file)
8695                 free_event(event);
8696 err_cred:
8697         if (task)
8698                 mutex_unlock(&task->signal->cred_guard_mutex);
8699 err_cpus:
8700         put_online_cpus();
8701 err_task:
8702         if (task)
8703                 put_task_struct(task);
8704 err_group_fd:
8705         fdput(group);
8706 err_fd:
8707         put_unused_fd(event_fd);
8708         return err;
8709 }
8710
8711 /**
8712  * perf_event_create_kernel_counter
8713  *
8714  * @attr: attributes of the counter to create
8715  * @cpu: cpu in which the counter is bound
8716  * @task: task to profile (NULL for percpu)
8717  */
8718 struct perf_event *
8719 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
8720                                  struct task_struct *task,
8721                                  perf_overflow_handler_t overflow_handler,
8722                                  void *context)
8723 {
8724         struct perf_event_context *ctx;
8725         struct perf_event *event;
8726         int err;
8727
8728         /*
8729          * Get the target context (task or percpu):
8730          */
8731
8732         event = perf_event_alloc(attr, cpu, task, NULL, NULL,
8733                                  overflow_handler, context, -1);
8734         if (IS_ERR(event)) {
8735                 err = PTR_ERR(event);
8736                 goto err;
8737         }
8738
8739         /* Mark owner so we could distinguish it from user events. */
8740         event->owner = EVENT_OWNER_KERNEL;
8741
8742         ctx = find_get_context(event->pmu, task, event);
8743         if (IS_ERR(ctx)) {
8744                 err = PTR_ERR(ctx);
8745                 goto err_free;
8746         }
8747
8748         WARN_ON_ONCE(ctx->parent_ctx);
8749         mutex_lock(&ctx->mutex);
8750         if (!exclusive_event_installable(event, ctx)) {
8751                 mutex_unlock(&ctx->mutex);
8752                 perf_unpin_context(ctx);
8753                 put_ctx(ctx);
8754                 err = -EBUSY;
8755                 goto err_free;
8756         }
8757
8758         perf_install_in_context(ctx, event, cpu);
8759         perf_unpin_context(ctx);
8760         mutex_unlock(&ctx->mutex);
8761
8762         return event;
8763
8764 err_free:
8765         free_event(event);
8766 err:
8767         return ERR_PTR(err);
8768 }
8769 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
8770
8771 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
8772 {
8773         struct perf_event_context *src_ctx;
8774         struct perf_event_context *dst_ctx;
8775         struct perf_event *event, *tmp;
8776         LIST_HEAD(events);
8777
8778         src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
8779         dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
8780
8781         /*
8782          * See perf_event_ctx_lock() for comments on the details
8783          * of swizzling perf_event::ctx.
8784          */
8785         mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
8786         list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
8787                                  event_entry) {
8788                 perf_remove_from_context(event, false);
8789                 unaccount_event_cpu(event, src_cpu);
8790                 put_ctx(src_ctx);
8791                 list_add(&event->migrate_entry, &events);
8792         }
8793
8794         /*
8795          * Wait for the events to quiesce before re-instating them.
8796          */
8797         synchronize_rcu();
8798
8799         /*
8800          * Re-instate events in 2 passes.
8801          *
8802          * Skip over group leaders and only install siblings on this first
8803          * pass, siblings will not get enabled without a leader, however a
8804          * leader will enable its siblings, even if those are still on the old
8805          * context.
8806          */
8807         list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
8808                 if (event->group_leader == event)
8809                         continue;
8810
8811                 list_del(&event->migrate_entry);
8812                 if (event->state >= PERF_EVENT_STATE_OFF)
8813                         event->state = PERF_EVENT_STATE_INACTIVE;
8814                 account_event_cpu(event, dst_cpu);
8815                 perf_install_in_context(dst_ctx, event, dst_cpu);
8816                 get_ctx(dst_ctx);
8817         }
8818
8819         /*
8820          * Once all the siblings are setup properly, install the group leaders
8821          * to make it go.
8822          */
8823         list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
8824                 list_del(&event->migrate_entry);
8825                 if (event->state >= PERF_EVENT_STATE_OFF)
8826                         event->state = PERF_EVENT_STATE_INACTIVE;
8827                 account_event_cpu(event, dst_cpu);
8828                 perf_install_in_context(dst_ctx, event, dst_cpu);
8829                 get_ctx(dst_ctx);
8830         }
8831         mutex_unlock(&dst_ctx->mutex);
8832         mutex_unlock(&src_ctx->mutex);
8833 }
8834 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
8835
8836 static void sync_child_event(struct perf_event *child_event,
8837                                struct task_struct *child)
8838 {
8839         struct perf_event *parent_event = child_event->parent;
8840         u64 child_val;
8841
8842         if (child_event->attr.inherit_stat)
8843                 perf_event_read_event(child_event, child);
8844
8845         child_val = perf_event_count(child_event);
8846
8847         /*
8848          * Add back the child's count to the parent's count:
8849          */
8850         atomic64_add(child_val, &parent_event->child_count);
8851         atomic64_add(child_event->total_time_enabled,
8852                      &parent_event->child_total_time_enabled);
8853         atomic64_add(child_event->total_time_running,
8854                      &parent_event->child_total_time_running);
8855
8856         /*
8857          * Remove this event from the parent's list
8858          */
8859         WARN_ON_ONCE(parent_event->ctx->parent_ctx);
8860         mutex_lock(&parent_event->child_mutex);
8861         list_del_init(&child_event->child_list);
8862         mutex_unlock(&parent_event->child_mutex);
8863
8864         /*
8865          * Make sure user/parent get notified, that we just
8866          * lost one event.
8867          */
8868         perf_event_wakeup(parent_event);
8869
8870         /*
8871          * Release the parent event, if this was the last
8872          * reference to it.
8873          */
8874         put_event(parent_event);
8875 }
8876
8877 static void
8878 __perf_event_exit_task(struct perf_event *child_event,
8879                          struct perf_event_context *child_ctx,
8880                          struct task_struct *child)
8881 {
8882         /*
8883          * Do not destroy the 'original' grouping; because of the context
8884          * switch optimization the original events could've ended up in a
8885          * random child task.
8886          *
8887          * If we were to destroy the original group, all group related
8888          * operations would cease to function properly after this random
8889          * child dies.
8890          *
8891          * Do destroy all inherited groups, we don't care about those
8892          * and being thorough is better.
8893          */
8894         perf_remove_from_context(child_event, !!child_event->parent);
8895
8896         /*
8897          * It can happen that the parent exits first, and has events
8898          * that are still around due to the child reference. These
8899          * events need to be zapped.
8900          */
8901         if (child_event->parent) {
8902                 sync_child_event(child_event, child);
8903                 free_event(child_event);
8904         } else {
8905                 child_event->state = PERF_EVENT_STATE_EXIT;
8906                 perf_event_wakeup(child_event);
8907         }
8908 }
8909
8910 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
8911 {
8912         struct perf_event *child_event, *next;
8913         struct perf_event_context *child_ctx, *clone_ctx = NULL;
8914         unsigned long flags;
8915
8916         if (likely(!child->perf_event_ctxp[ctxn]))
8917                 return;
8918
8919         local_irq_save(flags);
8920         /*
8921          * We can't reschedule here because interrupts are disabled,
8922          * and either child is current or it is a task that can't be
8923          * scheduled, so we are now safe from rescheduling changing
8924          * our context.
8925          */
8926         child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
8927
8928         /*
8929          * Take the context lock here so that if find_get_context is
8930          * reading child->perf_event_ctxp, we wait until it has
8931          * incremented the context's refcount before we do put_ctx below.
8932          */
8933         raw_spin_lock(&child_ctx->lock);
8934         task_ctx_sched_out(child_ctx);
8935         child->perf_event_ctxp[ctxn] = NULL;
8936
8937         /*
8938          * If this context is a clone; unclone it so it can't get
8939          * swapped to another process while we're removing all
8940          * the events from it.
8941          */
8942         clone_ctx = unclone_ctx(child_ctx);
8943         update_context_time(child_ctx);
8944         raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
8945
8946         if (clone_ctx)
8947                 put_ctx(clone_ctx);
8948
8949         /*
8950          * Report the task dead after unscheduling the events so that we
8951          * won't get any samples after PERF_RECORD_EXIT. We can however still
8952          * get a few PERF_RECORD_READ events.
8953          */
8954         perf_event_task(child, child_ctx, 0);
8955
8956         /*
8957          * We can recurse on the same lock type through:
8958          *
8959          *   __perf_event_exit_task()
8960          *     sync_child_event()
8961          *       put_event()
8962          *         mutex_lock(&ctx->mutex)
8963          *
8964          * But since its the parent context it won't be the same instance.
8965          */
8966         mutex_lock(&child_ctx->mutex);
8967
8968         list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
8969                 __perf_event_exit_task(child_event, child_ctx, child);
8970
8971         mutex_unlock(&child_ctx->mutex);
8972
8973         put_ctx(child_ctx);
8974 }
8975
8976 /*
8977  * When a child task exits, feed back event values to parent events.
8978  *
8979  * Can be called with cred_guard_mutex held when called from
8980  * install_exec_creds().
8981  */
8982 void perf_event_exit_task(struct task_struct *child)
8983 {
8984         struct perf_event *event, *tmp;
8985         int ctxn;
8986
8987         mutex_lock(&child->perf_event_mutex);
8988         list_for_each_entry_safe(event, tmp, &child->perf_event_list,
8989                                  owner_entry) {
8990                 list_del_init(&event->owner_entry);
8991
8992                 /*
8993                  * Ensure the list deletion is visible before we clear
8994                  * the owner, closes a race against perf_release() where
8995                  * we need to serialize on the owner->perf_event_mutex.
8996                  */
8997                 smp_wmb();
8998                 event->owner = NULL;
8999         }
9000         mutex_unlock(&child->perf_event_mutex);
9001
9002         for_each_task_context_nr(ctxn)
9003                 perf_event_exit_task_context(child, ctxn);
9004
9005         /*
9006          * The perf_event_exit_task_context calls perf_event_task
9007          * with child's task_ctx, which generates EXIT events for
9008          * child contexts and sets child->perf_event_ctxp[] to NULL.
9009          * At this point we need to send EXIT events to cpu contexts.
9010          */
9011         perf_event_task(child, NULL, 0);
9012 }
9013
9014 static void perf_free_event(struct perf_event *event,
9015                             struct perf_event_context *ctx)
9016 {
9017         struct perf_event *parent = event->parent;
9018
9019         if (WARN_ON_ONCE(!parent))
9020                 return;
9021
9022         mutex_lock(&parent->child_mutex);
9023         list_del_init(&event->child_list);
9024         mutex_unlock(&parent->child_mutex);
9025
9026         put_event(parent);
9027
9028         raw_spin_lock_irq(&ctx->lock);
9029         perf_group_detach(event);
9030         list_del_event(event, ctx);
9031         raw_spin_unlock_irq(&ctx->lock);
9032         free_event(event);
9033 }
9034
9035 /*
9036  * Free an unexposed, unused context as created by inheritance by
9037  * perf_event_init_task below, used by fork() in case of fail.
9038  *
9039  * Not all locks are strictly required, but take them anyway to be nice and
9040  * help out with the lockdep assertions.
9041  */
9042 void perf_event_free_task(struct task_struct *task)
9043 {
9044         struct perf_event_context *ctx;
9045         struct perf_event *event, *tmp;
9046         int ctxn;
9047
9048         for_each_task_context_nr(ctxn) {
9049                 ctx = task->perf_event_ctxp[ctxn];
9050                 if (!ctx)
9051                         continue;
9052
9053                 mutex_lock(&ctx->mutex);
9054 again:
9055                 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
9056                                 group_entry)
9057                         perf_free_event(event, ctx);
9058
9059                 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
9060                                 group_entry)
9061                         perf_free_event(event, ctx);
9062
9063                 if (!list_empty(&ctx->pinned_groups) ||
9064                                 !list_empty(&ctx->flexible_groups))
9065                         goto again;
9066
9067                 mutex_unlock(&ctx->mutex);
9068
9069                 put_ctx(ctx);
9070         }
9071 }
9072
9073 void perf_event_delayed_put(struct task_struct *task)
9074 {
9075         int ctxn;
9076
9077         for_each_task_context_nr(ctxn)
9078                 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
9079 }
9080
9081 struct perf_event *perf_event_get(unsigned int fd)
9082 {
9083         int err;
9084         struct fd f;
9085         struct perf_event *event;
9086
9087         err = perf_fget_light(fd, &f);
9088         if (err)
9089                 return ERR_PTR(err);
9090
9091         event = f.file->private_data;
9092         atomic_long_inc(&event->refcount);
9093         fdput(f);
9094
9095         return event;
9096 }
9097
9098 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
9099 {
9100         if (!event)
9101                 return ERR_PTR(-EINVAL);
9102
9103         return &event->attr;
9104 }
9105
9106 /*
9107  * inherit a event from parent task to child task:
9108  */
9109 static struct perf_event *
9110 inherit_event(struct perf_event *parent_event,
9111               struct task_struct *parent,
9112               struct perf_event_context *parent_ctx,
9113               struct task_struct *child,
9114               struct perf_event *group_leader,
9115               struct perf_event_context *child_ctx)
9116 {
9117         enum perf_event_active_state parent_state = parent_event->state;
9118         struct perf_event *child_event;
9119         unsigned long flags;
9120
9121         /*
9122          * Instead of creating recursive hierarchies of events,
9123          * we link inherited events back to the original parent,
9124          * which has a filp for sure, which we use as the reference
9125          * count:
9126          */
9127         if (parent_event->parent)
9128                 parent_event = parent_event->parent;
9129
9130         child_event = perf_event_alloc(&parent_event->attr,
9131                                            parent_event->cpu,
9132                                            child,
9133                                            group_leader, parent_event,
9134                                            NULL, NULL, -1);
9135         if (IS_ERR(child_event))
9136                 return child_event;
9137
9138         if (is_orphaned_event(parent_event) ||
9139             !atomic_long_inc_not_zero(&parent_event->refcount)) {
9140                 free_event(child_event);
9141                 return NULL;
9142         }
9143
9144         get_ctx(child_ctx);
9145
9146         /*
9147          * Make the child state follow the state of the parent event,
9148          * not its attr.disabled bit.  We hold the parent's mutex,
9149          * so we won't race with perf_event_{en, dis}able_family.
9150          */
9151         if (parent_state >= PERF_EVENT_STATE_INACTIVE)
9152                 child_event->state = PERF_EVENT_STATE_INACTIVE;
9153         else
9154                 child_event->state = PERF_EVENT_STATE_OFF;
9155
9156         if (parent_event->attr.freq) {
9157                 u64 sample_period = parent_event->hw.sample_period;
9158                 struct hw_perf_event *hwc = &child_event->hw;
9159
9160                 hwc->sample_period = sample_period;
9161                 hwc->last_period   = sample_period;
9162
9163                 local64_set(&hwc->period_left, sample_period);
9164         }
9165
9166         child_event->ctx = child_ctx;
9167         child_event->overflow_handler = parent_event->overflow_handler;
9168         child_event->overflow_handler_context
9169                 = parent_event->overflow_handler_context;
9170
9171         /*
9172          * Precalculate sample_data sizes
9173          */
9174         perf_event__header_size(child_event);
9175         perf_event__id_header_size(child_event);
9176
9177         /*
9178          * Link it up in the child's context:
9179          */
9180         raw_spin_lock_irqsave(&child_ctx->lock, flags);
9181         add_event_to_ctx(child_event, child_ctx);
9182         raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
9183
9184         /*
9185          * Link this into the parent event's child list
9186          */
9187         WARN_ON_ONCE(parent_event->ctx->parent_ctx);
9188         mutex_lock(&parent_event->child_mutex);
9189         list_add_tail(&child_event->child_list, &parent_event->child_list);
9190         mutex_unlock(&parent_event->child_mutex);
9191
9192         return child_event;
9193 }
9194
9195 static int inherit_group(struct perf_event *parent_event,
9196               struct task_struct *parent,
9197               struct perf_event_context *parent_ctx,
9198               struct task_struct *child,
9199               struct perf_event_context *child_ctx)
9200 {
9201         struct perf_event *leader;
9202         struct perf_event *sub;
9203         struct perf_event *child_ctr;
9204
9205         leader = inherit_event(parent_event, parent, parent_ctx,
9206                                  child, NULL, child_ctx);
9207         if (IS_ERR(leader))
9208                 return PTR_ERR(leader);
9209         list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
9210                 child_ctr = inherit_event(sub, parent, parent_ctx,
9211                                             child, leader, child_ctx);
9212                 if (IS_ERR(child_ctr))
9213                         return PTR_ERR(child_ctr);
9214         }
9215         return 0;
9216 }
9217
9218 static int
9219 inherit_task_group(struct perf_event *event, struct task_struct *parent,
9220                    struct perf_event_context *parent_ctx,
9221                    struct task_struct *child, int ctxn,
9222                    int *inherited_all)
9223 {
9224         int ret;
9225         struct perf_event_context *child_ctx;
9226
9227         if (!event->attr.inherit) {
9228                 *inherited_all = 0;
9229                 return 0;
9230         }
9231
9232         child_ctx = child->perf_event_ctxp[ctxn];
9233         if (!child_ctx) {
9234                 /*
9235                  * This is executed from the parent task context, so
9236                  * inherit events that have been marked for cloning.
9237                  * First allocate and initialize a context for the
9238                  * child.
9239                  */
9240
9241                 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
9242                 if (!child_ctx)
9243                         return -ENOMEM;
9244
9245                 child->perf_event_ctxp[ctxn] = child_ctx;
9246         }
9247
9248         ret = inherit_group(event, parent, parent_ctx,
9249                             child, child_ctx);
9250
9251         if (ret)
9252                 *inherited_all = 0;
9253
9254         return ret;
9255 }
9256
9257 /*
9258  * Initialize the perf_event context in task_struct
9259  */
9260 static int perf_event_init_context(struct task_struct *child, int ctxn)
9261 {
9262         struct perf_event_context *child_ctx, *parent_ctx;
9263         struct perf_event_context *cloned_ctx;
9264         struct perf_event *event;
9265         struct task_struct *parent = current;
9266         int inherited_all = 1;
9267         unsigned long flags;
9268         int ret = 0;
9269
9270         if (likely(!parent->perf_event_ctxp[ctxn]))
9271                 return 0;
9272
9273         /*
9274          * If the parent's context is a clone, pin it so it won't get
9275          * swapped under us.
9276          */
9277         parent_ctx = perf_pin_task_context(parent, ctxn);
9278         if (!parent_ctx)
9279                 return 0;
9280
9281         /*
9282          * No need to check if parent_ctx != NULL here; since we saw
9283          * it non-NULL earlier, the only reason for it to become NULL
9284          * is if we exit, and since we're currently in the middle of
9285          * a fork we can't be exiting at the same time.
9286          */
9287
9288         /*
9289          * Lock the parent list. No need to lock the child - not PID
9290          * hashed yet and not running, so nobody can access it.
9291          */
9292         mutex_lock(&parent_ctx->mutex);
9293
9294         /*
9295          * We dont have to disable NMIs - we are only looking at
9296          * the list, not manipulating it:
9297          */
9298         list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
9299                 ret = inherit_task_group(event, parent, parent_ctx,
9300                                          child, ctxn, &inherited_all);
9301                 if (ret)
9302                         goto out_unlock;
9303         }
9304
9305         /*
9306          * We can't hold ctx->lock when iterating the ->flexible_group list due
9307          * to allocations, but we need to prevent rotation because
9308          * rotate_ctx() will change the list from interrupt context.
9309          */
9310         raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9311         parent_ctx->rotate_disable = 1;
9312         raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
9313
9314         list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
9315                 ret = inherit_task_group(event, parent, parent_ctx,
9316                                          child, ctxn, &inherited_all);
9317                 if (ret)
9318                         goto out_unlock;
9319         }
9320
9321         raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9322         parent_ctx->rotate_disable = 0;
9323
9324         child_ctx = child->perf_event_ctxp[ctxn];
9325
9326         if (child_ctx && inherited_all) {
9327                 /*
9328                  * Mark the child context as a clone of the parent
9329                  * context, or of whatever the parent is a clone of.
9330                  *
9331                  * Note that if the parent is a clone, the holding of
9332                  * parent_ctx->lock avoids it from being uncloned.
9333                  */
9334                 cloned_ctx = parent_ctx->parent_ctx;
9335                 if (cloned_ctx) {
9336                         child_ctx->parent_ctx = cloned_ctx;
9337                         child_ctx->parent_gen = parent_ctx->parent_gen;
9338                 } else {
9339                         child_ctx->parent_ctx = parent_ctx;
9340                         child_ctx->parent_gen = parent_ctx->generation;
9341                 }
9342                 get_ctx(child_ctx->parent_ctx);
9343         }
9344
9345         raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
9346 out_unlock:
9347         mutex_unlock(&parent_ctx->mutex);
9348
9349         perf_unpin_context(parent_ctx);
9350         put_ctx(parent_ctx);
9351
9352         return ret;
9353 }
9354
9355 /*
9356  * Initialize the perf_event context in task_struct
9357  */
9358 int perf_event_init_task(struct task_struct *child)
9359 {
9360         int ctxn, ret;
9361
9362         memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
9363         mutex_init(&child->perf_event_mutex);
9364         INIT_LIST_HEAD(&child->perf_event_list);
9365
9366         for_each_task_context_nr(ctxn) {
9367                 ret = perf_event_init_context(child, ctxn);
9368                 if (ret) {
9369                         perf_event_free_task(child);
9370                         return ret;
9371                 }
9372         }
9373
9374         return 0;
9375 }
9376
9377 static void __init perf_event_init_all_cpus(void)
9378 {
9379         struct swevent_htable *swhash;
9380         int cpu;
9381
9382         for_each_possible_cpu(cpu) {
9383                 swhash = &per_cpu(swevent_htable, cpu);
9384                 mutex_init(&swhash->hlist_mutex);
9385                 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
9386         }
9387 }
9388
9389 static void perf_event_init_cpu(int cpu)
9390 {
9391         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9392
9393         mutex_lock(&swhash->hlist_mutex);
9394         if (swhash->hlist_refcount > 0) {
9395                 struct swevent_hlist *hlist;
9396
9397                 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
9398                 WARN_ON(!hlist);
9399                 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9400         }
9401         mutex_unlock(&swhash->hlist_mutex);
9402 }
9403
9404 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
9405 static void __perf_event_exit_context(void *__info)
9406 {
9407         struct remove_event re = { .detach_group = true };
9408         struct perf_event_context *ctx = __info;
9409
9410         rcu_read_lock();
9411         list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
9412                 __perf_remove_from_context(&re);
9413         rcu_read_unlock();
9414 }
9415
9416 static void perf_event_exit_cpu_context(int cpu)
9417 {
9418         struct perf_event_context *ctx;
9419         struct pmu *pmu;
9420         int idx;
9421
9422         idx = srcu_read_lock(&pmus_srcu);
9423         list_for_each_entry_rcu(pmu, &pmus, entry) {
9424                 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
9425
9426                 mutex_lock(&ctx->mutex);
9427                 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
9428                 mutex_unlock(&ctx->mutex);
9429         }
9430         srcu_read_unlock(&pmus_srcu, idx);
9431 }
9432
9433 static void perf_event_exit_cpu(int cpu)
9434 {
9435         perf_event_exit_cpu_context(cpu);
9436 }
9437 #else
9438 static inline void perf_event_exit_cpu(int cpu) { }
9439 #endif
9440
9441 static int
9442 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
9443 {
9444         int cpu;
9445
9446         for_each_online_cpu(cpu)
9447                 perf_event_exit_cpu(cpu);
9448
9449         return NOTIFY_OK;
9450 }
9451
9452 /*
9453  * Run the perf reboot notifier at the very last possible moment so that
9454  * the generic watchdog code runs as long as possible.
9455  */
9456 static struct notifier_block perf_reboot_notifier = {
9457         .notifier_call = perf_reboot,
9458         .priority = INT_MIN,
9459 };
9460
9461 static int
9462 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
9463 {
9464         unsigned int cpu = (long)hcpu;
9465
9466         switch (action & ~CPU_TASKS_FROZEN) {
9467
9468         case CPU_UP_PREPARE:
9469         case CPU_DOWN_FAILED:
9470                 perf_event_init_cpu(cpu);
9471                 break;
9472
9473         case CPU_UP_CANCELED:
9474         case CPU_DOWN_PREPARE:
9475                 perf_event_exit_cpu(cpu);
9476                 break;
9477         default:
9478                 break;
9479         }
9480
9481         return NOTIFY_OK;
9482 }
9483
9484 void __init perf_event_init(void)
9485 {
9486         int ret;
9487
9488         idr_init(&pmu_idr);
9489
9490         perf_event_init_all_cpus();
9491         init_srcu_struct(&pmus_srcu);
9492         perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
9493         perf_pmu_register(&perf_cpu_clock, NULL, -1);
9494         perf_pmu_register(&perf_task_clock, NULL, -1);
9495         perf_tp_register();
9496         perf_cpu_notifier(perf_cpu_notify);
9497         register_reboot_notifier(&perf_reboot_notifier);
9498
9499         ret = init_hw_breakpoint();
9500         WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
9501
9502         /* do not patch jump label more than once per second */
9503         jump_label_rate_limit(&perf_sched_events, HZ);
9504
9505         /*
9506          * Build time assertion that we keep the data_head at the intended
9507          * location.  IOW, validation we got the __reserved[] size right.
9508          */
9509         BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
9510                      != 1024);
9511 }
9512
9513 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
9514                               char *page)
9515 {
9516         struct perf_pmu_events_attr *pmu_attr =
9517                 container_of(attr, struct perf_pmu_events_attr, attr);
9518
9519         if (pmu_attr->event_str)
9520                 return sprintf(page, "%s\n", pmu_attr->event_str);
9521
9522         return 0;
9523 }
9524
9525 static int __init perf_event_sysfs_init(void)
9526 {
9527         struct pmu *pmu;
9528         int ret;
9529
9530         mutex_lock(&pmus_lock);
9531
9532         ret = bus_register(&pmu_bus);
9533         if (ret)
9534                 goto unlock;
9535
9536         list_for_each_entry(pmu, &pmus, entry) {
9537                 if (!pmu->name || pmu->type < 0)
9538                         continue;
9539
9540                 ret = pmu_dev_alloc(pmu);
9541                 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
9542         }
9543         pmu_bus_running = 1;
9544         ret = 0;
9545
9546 unlock:
9547         mutex_unlock(&pmus_lock);
9548
9549         return ret;
9550 }
9551 device_initcall(perf_event_sysfs_init);
9552
9553 #ifdef CONFIG_CGROUP_PERF
9554 static struct cgroup_subsys_state *
9555 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
9556 {
9557         struct perf_cgroup *jc;
9558
9559         jc = kzalloc(sizeof(*jc), GFP_KERNEL);
9560         if (!jc)
9561                 return ERR_PTR(-ENOMEM);
9562
9563         jc->info = alloc_percpu(struct perf_cgroup_info);
9564         if (!jc->info) {
9565                 kfree(jc);
9566                 return ERR_PTR(-ENOMEM);
9567         }
9568
9569         return &jc->css;
9570 }
9571
9572 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
9573 {
9574         struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
9575
9576         free_percpu(jc->info);
9577         kfree(jc);
9578 }
9579
9580 static int __perf_cgroup_move(void *info)
9581 {
9582         struct task_struct *task = info;
9583         rcu_read_lock();
9584         perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
9585         rcu_read_unlock();
9586         return 0;
9587 }
9588
9589 static void perf_cgroup_attach(struct cgroup_taskset *tset)
9590 {
9591         struct task_struct *task;
9592         struct cgroup_subsys_state *css;
9593
9594         cgroup_taskset_for_each(task, css, tset)
9595                 task_function_call(task, __perf_cgroup_move, task);
9596 }
9597
9598 struct cgroup_subsys perf_event_cgrp_subsys = {
9599         .css_alloc      = perf_cgroup_css_alloc,
9600         .css_free       = perf_cgroup_css_free,
9601         .attach         = perf_cgroup_attach,
9602 };
9603 #endif /* CONFIG_CGROUP_PERF */