OSDN Git Service

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