OSDN Git Service

Merge android-4.4-p.205 (5169787) into msm-4.4
[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) + user_extra;
5007
5008         if (user_locked > user_lock_limit)
5009                 extra = user_locked - user_lock_limit;
5010
5011         lock_limit = rlimit(RLIMIT_MEMLOCK);
5012         lock_limit >>= PAGE_SHIFT;
5013         locked = vma->vm_mm->pinned_vm + extra;
5014
5015         if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
5016                 !capable(CAP_IPC_LOCK)) {
5017                 ret = -EPERM;
5018                 goto unlock;
5019         }
5020
5021         WARN_ON(!rb && event->rb);
5022
5023         if (vma->vm_flags & VM_WRITE)
5024                 flags |= RING_BUFFER_WRITABLE;
5025
5026         if (!rb) {
5027                 rb = rb_alloc(nr_pages,
5028                               event->attr.watermark ? event->attr.wakeup_watermark : 0,
5029                               event->cpu, flags);
5030
5031                 if (!rb) {
5032                         ret = -ENOMEM;
5033                         goto unlock;
5034                 }
5035
5036                 atomic_set(&rb->mmap_count, 1);
5037                 rb->mmap_user = get_current_user();
5038                 rb->mmap_locked = extra;
5039
5040                 ring_buffer_attach(event, rb);
5041
5042                 perf_event_init_userpage(event);
5043                 perf_event_update_userpage(event);
5044         } else {
5045                 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
5046                                    event->attr.aux_watermark, flags);
5047                 if (!ret)
5048                         rb->aux_mmap_locked = extra;
5049         }
5050
5051 unlock:
5052         if (!ret) {
5053                 atomic_long_add(user_extra, &user->locked_vm);
5054                 vma->vm_mm->pinned_vm += extra;
5055
5056                 atomic_inc(&event->mmap_count);
5057         } else if (rb) {
5058                 atomic_dec(&rb->mmap_count);
5059         }
5060 aux_unlock:
5061         mutex_unlock(&event->mmap_mutex);
5062
5063         /*
5064          * Since pinned accounting is per vm we cannot allow fork() to copy our
5065          * vma.
5066          */
5067         vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
5068         vma->vm_ops = &perf_mmap_vmops;
5069
5070         if (event->pmu->event_mapped)
5071                 event->pmu->event_mapped(event);
5072
5073         return ret;
5074 }
5075
5076 static int perf_fasync(int fd, struct file *filp, int on)
5077 {
5078         struct inode *inode = file_inode(filp);
5079         struct perf_event *event = filp->private_data;
5080         int retval;
5081
5082         mutex_lock(&inode->i_mutex);
5083         retval = fasync_helper(fd, filp, on, &event->fasync);
5084         mutex_unlock(&inode->i_mutex);
5085
5086         if (retval < 0)
5087                 return retval;
5088
5089         return 0;
5090 }
5091
5092 static const struct file_operations perf_fops = {
5093         .llseek                 = no_llseek,
5094         .release                = perf_release,
5095         .read                   = perf_read,
5096         .poll                   = perf_poll,
5097         .unlocked_ioctl         = perf_ioctl,
5098         .compat_ioctl           = perf_compat_ioctl,
5099         .mmap                   = perf_mmap,
5100         .fasync                 = perf_fasync,
5101 };
5102
5103 /*
5104  * Perf event wakeup
5105  *
5106  * If there's data, ensure we set the poll() state and publish everything
5107  * to user-space before waking everybody up.
5108  */
5109
5110 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
5111 {
5112         /* only the parent has fasync state */
5113         if (event->parent)
5114                 event = event->parent;
5115         return &event->fasync;
5116 }
5117
5118 void perf_event_wakeup(struct perf_event *event)
5119 {
5120         ring_buffer_wakeup(event);
5121
5122         if (event->pending_kill) {
5123                 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
5124                 event->pending_kill = 0;
5125         }
5126 }
5127
5128 static void perf_pending_event(struct irq_work *entry)
5129 {
5130         struct perf_event *event = container_of(entry,
5131                         struct perf_event, pending);
5132         int rctx;
5133
5134         rctx = perf_swevent_get_recursion_context();
5135         /*
5136          * If we 'fail' here, that's OK, it means recursion is already disabled
5137          * and we won't recurse 'further'.
5138          */
5139
5140         if (event->pending_disable) {
5141                 event->pending_disable = 0;
5142                 __perf_event_disable(event);
5143         }
5144
5145         if (event->pending_wakeup) {
5146                 event->pending_wakeup = 0;
5147                 perf_event_wakeup(event);
5148         }
5149
5150         if (rctx >= 0)
5151                 perf_swevent_put_recursion_context(rctx);
5152 }
5153
5154 /*
5155  * We assume there is only KVM supporting the callbacks.
5156  * Later on, we might change it to a list if there is
5157  * another virtualization implementation supporting the callbacks.
5158  */
5159 struct perf_guest_info_callbacks *perf_guest_cbs;
5160
5161 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5162 {
5163         perf_guest_cbs = cbs;
5164         return 0;
5165 }
5166 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
5167
5168 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
5169 {
5170         perf_guest_cbs = NULL;
5171         return 0;
5172 }
5173 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
5174
5175 static void
5176 perf_output_sample_regs(struct perf_output_handle *handle,
5177                         struct pt_regs *regs, u64 mask)
5178 {
5179         int bit;
5180
5181         for_each_set_bit(bit, (const unsigned long *) &mask,
5182                          sizeof(mask) * BITS_PER_BYTE) {
5183                 u64 val;
5184
5185                 val = perf_reg_value(regs, bit);
5186                 perf_output_put(handle, val);
5187         }
5188 }
5189
5190 static void perf_sample_regs_user(struct perf_regs *regs_user,
5191                                   struct pt_regs *regs,
5192                                   struct pt_regs *regs_user_copy)
5193 {
5194         if (user_mode(regs)) {
5195                 regs_user->abi = perf_reg_abi(current);
5196                 regs_user->regs = regs;
5197         } else if (!(current->flags & PF_KTHREAD)) {
5198                 perf_get_regs_user(regs_user, regs, regs_user_copy);
5199         } else {
5200                 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
5201                 regs_user->regs = NULL;
5202         }
5203 }
5204
5205 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
5206                                   struct pt_regs *regs)
5207 {
5208         regs_intr->regs = regs;
5209         regs_intr->abi  = perf_reg_abi(current);
5210 }
5211
5212
5213 /*
5214  * Get remaining task size from user stack pointer.
5215  *
5216  * It'd be better to take stack vma map and limit this more
5217  * precisly, but there's no way to get it safely under interrupt,
5218  * so using TASK_SIZE as limit.
5219  */
5220 static u64 perf_ustack_task_size(struct pt_regs *regs)
5221 {
5222         unsigned long addr = perf_user_stack_pointer(regs);
5223
5224         if (!addr || addr >= TASK_SIZE)
5225                 return 0;
5226
5227         return TASK_SIZE - addr;
5228 }
5229
5230 static u16
5231 perf_sample_ustack_size(u16 stack_size, u16 header_size,
5232                         struct pt_regs *regs)
5233 {
5234         u64 task_size;
5235
5236         /* No regs, no stack pointer, no dump. */
5237         if (!regs)
5238                 return 0;
5239
5240         /*
5241          * Check if we fit in with the requested stack size into the:
5242          * - TASK_SIZE
5243          *   If we don't, we limit the size to the TASK_SIZE.
5244          *
5245          * - remaining sample size
5246          *   If we don't, we customize the stack size to
5247          *   fit in to the remaining sample size.
5248          */
5249
5250         task_size  = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
5251         stack_size = min(stack_size, (u16) task_size);
5252
5253         /* Current header size plus static size and dynamic size. */
5254         header_size += 2 * sizeof(u64);
5255
5256         /* Do we fit in with the current stack dump size? */
5257         if ((u16) (header_size + stack_size) < header_size) {
5258                 /*
5259                  * If we overflow the maximum size for the sample,
5260                  * we customize the stack dump size to fit in.
5261                  */
5262                 stack_size = USHRT_MAX - header_size - sizeof(u64);
5263                 stack_size = round_up(stack_size, sizeof(u64));
5264         }
5265
5266         return stack_size;
5267 }
5268
5269 static void
5270 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
5271                           struct pt_regs *regs)
5272 {
5273         /* Case of a kernel thread, nothing to dump */
5274         if (!regs) {
5275                 u64 size = 0;
5276                 perf_output_put(handle, size);
5277         } else {
5278                 unsigned long sp;
5279                 unsigned int rem;
5280                 u64 dyn_size;
5281
5282                 /*
5283                  * We dump:
5284                  * static size
5285                  *   - the size requested by user or the best one we can fit
5286                  *     in to the sample max size
5287                  * data
5288                  *   - user stack dump data
5289                  * dynamic size
5290                  *   - the actual dumped size
5291                  */
5292
5293                 /* Static size. */
5294                 perf_output_put(handle, dump_size);
5295
5296                 /* Data. */
5297                 sp = perf_user_stack_pointer(regs);
5298                 rem = __output_copy_user(handle, (void *) sp, dump_size);
5299                 dyn_size = dump_size - rem;
5300
5301                 perf_output_skip(handle, rem);
5302
5303                 /* Dynamic size. */
5304                 perf_output_put(handle, dyn_size);
5305         }
5306 }
5307
5308 static void __perf_event_header__init_id(struct perf_event_header *header,
5309                                          struct perf_sample_data *data,
5310                                          struct perf_event *event)
5311 {
5312         u64 sample_type = event->attr.sample_type;
5313
5314         data->type = sample_type;
5315         header->size += event->id_header_size;
5316
5317         if (sample_type & PERF_SAMPLE_TID) {
5318                 /* namespace issues */
5319                 data->tid_entry.pid = perf_event_pid(event, current);
5320                 data->tid_entry.tid = perf_event_tid(event, current);
5321         }
5322
5323         if (sample_type & PERF_SAMPLE_TIME)
5324                 data->time = perf_event_clock(event);
5325
5326         if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
5327                 data->id = primary_event_id(event);
5328
5329         if (sample_type & PERF_SAMPLE_STREAM_ID)
5330                 data->stream_id = event->id;
5331
5332         if (sample_type & PERF_SAMPLE_CPU) {
5333                 data->cpu_entry.cpu      = raw_smp_processor_id();
5334                 data->cpu_entry.reserved = 0;
5335         }
5336 }
5337
5338 void perf_event_header__init_id(struct perf_event_header *header,
5339                                 struct perf_sample_data *data,
5340                                 struct perf_event *event)
5341 {
5342         if (event->attr.sample_id_all)
5343                 __perf_event_header__init_id(header, data, event);
5344 }
5345
5346 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
5347                                            struct perf_sample_data *data)
5348 {
5349         u64 sample_type = data->type;
5350
5351         if (sample_type & PERF_SAMPLE_TID)
5352                 perf_output_put(handle, data->tid_entry);
5353
5354         if (sample_type & PERF_SAMPLE_TIME)
5355                 perf_output_put(handle, data->time);
5356
5357         if (sample_type & PERF_SAMPLE_ID)
5358                 perf_output_put(handle, data->id);
5359
5360         if (sample_type & PERF_SAMPLE_STREAM_ID)
5361                 perf_output_put(handle, data->stream_id);
5362
5363         if (sample_type & PERF_SAMPLE_CPU)
5364                 perf_output_put(handle, data->cpu_entry);
5365
5366         if (sample_type & PERF_SAMPLE_IDENTIFIER)
5367                 perf_output_put(handle, data->id);
5368 }
5369
5370 void perf_event__output_id_sample(struct perf_event *event,
5371                                   struct perf_output_handle *handle,
5372                                   struct perf_sample_data *sample)
5373 {
5374         if (event->attr.sample_id_all)
5375                 __perf_event__output_id_sample(handle, sample);
5376 }
5377
5378 static void perf_output_read_one(struct perf_output_handle *handle,
5379                                  struct perf_event *event,
5380                                  u64 enabled, u64 running)
5381 {
5382         u64 read_format = event->attr.read_format;
5383         u64 values[4];
5384         int n = 0;
5385
5386         values[n++] = perf_event_count(event);
5387         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5388                 values[n++] = enabled +
5389                         atomic64_read(&event->child_total_time_enabled);
5390         }
5391         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5392                 values[n++] = running +
5393                         atomic64_read(&event->child_total_time_running);
5394         }
5395         if (read_format & PERF_FORMAT_ID)
5396                 values[n++] = primary_event_id(event);
5397
5398         __output_copy(handle, values, n * sizeof(u64));
5399 }
5400
5401 static void perf_output_read_group(struct perf_output_handle *handle,
5402                             struct perf_event *event,
5403                             u64 enabled, u64 running)
5404 {
5405         struct perf_event *leader = event->group_leader, *sub;
5406         u64 read_format = event->attr.read_format;
5407         u64 values[5];
5408         int n = 0;
5409
5410         values[n++] = 1 + leader->nr_siblings;
5411
5412         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5413                 values[n++] = enabled;
5414
5415         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5416                 values[n++] = running;
5417
5418         if ((leader != event) &&
5419             (leader->state == PERF_EVENT_STATE_ACTIVE))
5420                 leader->pmu->read(leader);
5421
5422         values[n++] = perf_event_count(leader);
5423         if (read_format & PERF_FORMAT_ID)
5424                 values[n++] = primary_event_id(leader);
5425
5426         __output_copy(handle, values, n * sizeof(u64));
5427
5428         list_for_each_entry(sub, &leader->sibling_list, group_entry) {
5429                 n = 0;
5430
5431                 if ((sub != event) &&
5432                     (sub->state == PERF_EVENT_STATE_ACTIVE))
5433                         sub->pmu->read(sub);
5434
5435                 values[n++] = perf_event_count(sub);
5436                 if (read_format & PERF_FORMAT_ID)
5437                         values[n++] = primary_event_id(sub);
5438
5439                 __output_copy(handle, values, n * sizeof(u64));
5440         }
5441 }
5442
5443 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
5444                                  PERF_FORMAT_TOTAL_TIME_RUNNING)
5445
5446 /*
5447  * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
5448  *
5449  * The problem is that its both hard and excessively expensive to iterate the
5450  * child list, not to mention that its impossible to IPI the children running
5451  * on another CPU, from interrupt/NMI context.
5452  */
5453 static void perf_output_read(struct perf_output_handle *handle,
5454                              struct perf_event *event)
5455 {
5456         u64 enabled = 0, running = 0, now;
5457         u64 read_format = event->attr.read_format;
5458
5459         /*
5460          * compute total_time_enabled, total_time_running
5461          * based on snapshot values taken when the event
5462          * was last scheduled in.
5463          *
5464          * we cannot simply called update_context_time()
5465          * because of locking issue as we are called in
5466          * NMI context
5467          */
5468         if (read_format & PERF_FORMAT_TOTAL_TIMES)
5469                 calc_timer_values(event, &now, &enabled, &running);
5470
5471         if (event->attr.read_format & PERF_FORMAT_GROUP)
5472                 perf_output_read_group(handle, event, enabled, running);
5473         else
5474                 perf_output_read_one(handle, event, enabled, running);
5475 }
5476
5477 void perf_output_sample(struct perf_output_handle *handle,
5478                         struct perf_event_header *header,
5479                         struct perf_sample_data *data,
5480                         struct perf_event *event)
5481 {
5482         u64 sample_type = data->type;
5483
5484         perf_output_put(handle, *header);
5485
5486         if (sample_type & PERF_SAMPLE_IDENTIFIER)
5487                 perf_output_put(handle, data->id);
5488
5489         if (sample_type & PERF_SAMPLE_IP)
5490                 perf_output_put(handle, data->ip);
5491
5492         if (sample_type & PERF_SAMPLE_TID)
5493                 perf_output_put(handle, data->tid_entry);
5494
5495         if (sample_type & PERF_SAMPLE_TIME)
5496                 perf_output_put(handle, data->time);
5497
5498         if (sample_type & PERF_SAMPLE_ADDR)
5499                 perf_output_put(handle, data->addr);
5500
5501         if (sample_type & PERF_SAMPLE_ID)
5502                 perf_output_put(handle, data->id);
5503
5504         if (sample_type & PERF_SAMPLE_STREAM_ID)
5505                 perf_output_put(handle, data->stream_id);
5506
5507         if (sample_type & PERF_SAMPLE_CPU)
5508                 perf_output_put(handle, data->cpu_entry);
5509
5510         if (sample_type & PERF_SAMPLE_PERIOD)
5511                 perf_output_put(handle, data->period);
5512
5513         if (sample_type & PERF_SAMPLE_READ)
5514                 perf_output_read(handle, event);
5515
5516         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5517                 if (data->callchain) {
5518                         int size = 1;
5519
5520                         if (data->callchain)
5521                                 size += data->callchain->nr;
5522
5523                         size *= sizeof(u64);
5524
5525                         __output_copy(handle, data->callchain, size);
5526                 } else {
5527                         u64 nr = 0;
5528                         perf_output_put(handle, nr);
5529                 }
5530         }
5531
5532         if (sample_type & PERF_SAMPLE_RAW) {
5533                 if (data->raw) {
5534                         u32 raw_size = data->raw->size;
5535                         u32 real_size = round_up(raw_size + sizeof(u32),
5536                                                  sizeof(u64)) - sizeof(u32);
5537                         u64 zero = 0;
5538
5539                         perf_output_put(handle, real_size);
5540                         __output_copy(handle, data->raw->data, raw_size);
5541                         if (real_size - raw_size)
5542                                 __output_copy(handle, &zero, real_size - raw_size);
5543                 } else {
5544                         struct {
5545                                 u32     size;
5546                                 u32     data;
5547                         } raw = {
5548                                 .size = sizeof(u32),
5549                                 .data = 0,
5550                         };
5551                         perf_output_put(handle, raw);
5552                 }
5553         }
5554
5555         if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5556                 if (data->br_stack) {
5557                         size_t size;
5558
5559                         size = data->br_stack->nr
5560                              * sizeof(struct perf_branch_entry);
5561
5562                         perf_output_put(handle, data->br_stack->nr);
5563                         perf_output_copy(handle, data->br_stack->entries, size);
5564                 } else {
5565                         /*
5566                          * we always store at least the value of nr
5567                          */
5568                         u64 nr = 0;
5569                         perf_output_put(handle, nr);
5570                 }
5571         }
5572
5573         if (sample_type & PERF_SAMPLE_REGS_USER) {
5574                 u64 abi = data->regs_user.abi;
5575
5576                 /*
5577                  * If there are no regs to dump, notice it through
5578                  * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5579                  */
5580                 perf_output_put(handle, abi);
5581
5582                 if (abi) {
5583                         u64 mask = event->attr.sample_regs_user;
5584                         perf_output_sample_regs(handle,
5585                                                 data->regs_user.regs,
5586                                                 mask);
5587                 }
5588         }
5589
5590         if (sample_type & PERF_SAMPLE_STACK_USER) {
5591                 perf_output_sample_ustack(handle,
5592                                           data->stack_user_size,
5593                                           data->regs_user.regs);
5594         }
5595
5596         if (sample_type & PERF_SAMPLE_WEIGHT)
5597                 perf_output_put(handle, data->weight);
5598
5599         if (sample_type & PERF_SAMPLE_DATA_SRC)
5600                 perf_output_put(handle, data->data_src.val);
5601
5602         if (sample_type & PERF_SAMPLE_TRANSACTION)
5603                 perf_output_put(handle, data->txn);
5604
5605         if (sample_type & PERF_SAMPLE_REGS_INTR) {
5606                 u64 abi = data->regs_intr.abi;
5607                 /*
5608                  * If there are no regs to dump, notice it through
5609                  * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5610                  */
5611                 perf_output_put(handle, abi);
5612
5613                 if (abi) {
5614                         u64 mask = event->attr.sample_regs_intr;
5615
5616                         perf_output_sample_regs(handle,
5617                                                 data->regs_intr.regs,
5618                                                 mask);
5619                 }
5620         }
5621
5622         if (!event->attr.watermark) {
5623                 int wakeup_events = event->attr.wakeup_events;
5624
5625                 if (wakeup_events) {
5626                         struct ring_buffer *rb = handle->rb;
5627                         int events = local_inc_return(&rb->events);
5628
5629                         if (events >= wakeup_events) {
5630                                 local_sub(wakeup_events, &rb->events);
5631                                 local_inc(&rb->wakeup);
5632                         }
5633                 }
5634         }
5635 }
5636
5637 void perf_prepare_sample(struct perf_event_header *header,
5638                          struct perf_sample_data *data,
5639                          struct perf_event *event,
5640                          struct pt_regs *regs)
5641 {
5642         u64 sample_type = event->attr.sample_type;
5643
5644         header->type = PERF_RECORD_SAMPLE;
5645         header->size = sizeof(*header) + event->header_size;
5646
5647         header->misc = 0;
5648         header->misc |= perf_misc_flags(regs);
5649
5650         __perf_event_header__init_id(header, data, event);
5651
5652         if (sample_type & PERF_SAMPLE_IP)
5653                 data->ip = perf_instruction_pointer(regs);
5654
5655         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5656                 int size = 1;
5657
5658                 data->callchain = perf_callchain(event, regs);
5659
5660                 if (data->callchain)
5661                         size += data->callchain->nr;
5662
5663                 header->size += size * sizeof(u64);
5664         }
5665
5666         if (sample_type & PERF_SAMPLE_RAW) {
5667                 int size = sizeof(u32);
5668
5669                 if (data->raw)
5670                         size += data->raw->size;
5671                 else
5672                         size += sizeof(u32);
5673
5674                 header->size += round_up(size, sizeof(u64));
5675         }
5676
5677         if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5678                 int size = sizeof(u64); /* nr */
5679                 if (data->br_stack) {
5680                         size += data->br_stack->nr
5681                               * sizeof(struct perf_branch_entry);
5682                 }
5683                 header->size += size;
5684         }
5685
5686         if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
5687                 perf_sample_regs_user(&data->regs_user, regs,
5688                                       &data->regs_user_copy);
5689
5690         if (sample_type & PERF_SAMPLE_REGS_USER) {
5691                 /* regs dump ABI info */
5692                 int size = sizeof(u64);
5693
5694                 if (data->regs_user.regs) {
5695                         u64 mask = event->attr.sample_regs_user;
5696                         size += hweight64(mask) * sizeof(u64);
5697                 }
5698
5699                 header->size += size;
5700         }
5701
5702         if (sample_type & PERF_SAMPLE_STACK_USER) {
5703                 /*
5704                  * Either we need PERF_SAMPLE_STACK_USER bit to be allways
5705                  * processed as the last one or have additional check added
5706                  * in case new sample type is added, because we could eat
5707                  * up the rest of the sample size.
5708                  */
5709                 u16 stack_size = event->attr.sample_stack_user;
5710                 u16 size = sizeof(u64);
5711
5712                 stack_size = perf_sample_ustack_size(stack_size, header->size,
5713                                                      data->regs_user.regs);
5714
5715                 /*
5716                  * If there is something to dump, add space for the dump
5717                  * itself and for the field that tells the dynamic size,
5718                  * which is how many have been actually dumped.
5719                  */
5720                 if (stack_size)
5721                         size += sizeof(u64) + stack_size;
5722
5723                 data->stack_user_size = stack_size;
5724                 header->size += size;
5725         }
5726
5727         if (sample_type & PERF_SAMPLE_REGS_INTR) {
5728                 /* regs dump ABI info */
5729                 int size = sizeof(u64);
5730
5731                 perf_sample_regs_intr(&data->regs_intr, regs);
5732
5733                 if (data->regs_intr.regs) {
5734                         u64 mask = event->attr.sample_regs_intr;
5735
5736                         size += hweight64(mask) * sizeof(u64);
5737                 }
5738
5739                 header->size += size;
5740         }
5741 }
5742
5743 void perf_event_output(struct perf_event *event,
5744                         struct perf_sample_data *data,
5745                         struct pt_regs *regs)
5746 {
5747         struct perf_output_handle handle;
5748         struct perf_event_header header;
5749
5750         /* protect the callchain buffers */
5751         rcu_read_lock();
5752
5753         perf_prepare_sample(&header, data, event, regs);
5754
5755         if (perf_output_begin(&handle, event, header.size))
5756                 goto exit;
5757
5758         perf_output_sample(&handle, &header, data, event);
5759
5760         perf_output_end(&handle);
5761
5762 exit:
5763         rcu_read_unlock();
5764 }
5765
5766 /*
5767  * read event_id
5768  */
5769
5770 struct perf_read_event {
5771         struct perf_event_header        header;
5772
5773         u32                             pid;
5774         u32                             tid;
5775 };
5776
5777 static void
5778 perf_event_read_event(struct perf_event *event,
5779                         struct task_struct *task)
5780 {
5781         struct perf_output_handle handle;
5782         struct perf_sample_data sample;
5783         struct perf_read_event read_event = {
5784                 .header = {
5785                         .type = PERF_RECORD_READ,
5786                         .misc = 0,
5787                         .size = sizeof(read_event) + event->read_size,
5788                 },
5789                 .pid = perf_event_pid(event, task),
5790                 .tid = perf_event_tid(event, task),
5791         };
5792         int ret;
5793
5794         perf_event_header__init_id(&read_event.header, &sample, event);
5795         ret = perf_output_begin(&handle, event, read_event.header.size);
5796         if (ret)
5797                 return;
5798
5799         perf_output_put(&handle, read_event);
5800         perf_output_read(&handle, event);
5801         perf_event__output_id_sample(event, &handle, &sample);
5802
5803         perf_output_end(&handle);
5804 }
5805
5806 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
5807
5808 static void
5809 perf_event_aux_ctx(struct perf_event_context *ctx,
5810                    perf_event_aux_output_cb output,
5811                    void *data)
5812 {
5813         struct perf_event *event;
5814
5815         list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5816                 if (event->state < PERF_EVENT_STATE_INACTIVE)
5817                         continue;
5818                 if (!event_filter_match(event))
5819                         continue;
5820                 output(event, data);
5821         }
5822 }
5823
5824 static void
5825 perf_event_aux_task_ctx(perf_event_aux_output_cb output, void *data,
5826                         struct perf_event_context *task_ctx)
5827 {
5828         rcu_read_lock();
5829         preempt_disable();
5830         perf_event_aux_ctx(task_ctx, output, data);
5831         preempt_enable();
5832         rcu_read_unlock();
5833 }
5834
5835 static void
5836 perf_event_aux(perf_event_aux_output_cb output, void *data,
5837                struct perf_event_context *task_ctx)
5838 {
5839         struct perf_cpu_context *cpuctx;
5840         struct perf_event_context *ctx;
5841         struct pmu *pmu;
5842         int ctxn;
5843
5844         /*
5845          * If we have task_ctx != NULL we only notify
5846          * the task context itself. The task_ctx is set
5847          * only for EXIT events before releasing task
5848          * context.
5849          */
5850         if (task_ctx) {
5851                 perf_event_aux_task_ctx(output, data, task_ctx);
5852                 return;
5853         }
5854
5855         rcu_read_lock();
5856         list_for_each_entry_rcu(pmu, &pmus, entry) {
5857                 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
5858                 if (cpuctx->unique_pmu != pmu)
5859                         goto next;
5860                 perf_event_aux_ctx(&cpuctx->ctx, output, data);
5861                 ctxn = pmu->task_ctx_nr;
5862                 if (ctxn < 0)
5863                         goto next;
5864                 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
5865                 if (ctx)
5866                         perf_event_aux_ctx(ctx, output, data);
5867 next:
5868                 put_cpu_ptr(pmu->pmu_cpu_context);
5869         }
5870         rcu_read_unlock();
5871 }
5872
5873 struct remote_output {
5874         struct ring_buffer      *rb;
5875         int                     err;
5876 };
5877
5878 static void __perf_event_output_stop(struct perf_event *event, void *data)
5879 {
5880         struct perf_event *parent = event->parent;
5881         struct remote_output *ro = data;
5882         struct ring_buffer *rb = ro->rb;
5883
5884         if (!has_aux(event))
5885                 return;
5886
5887         if (!parent)
5888                 parent = event;
5889
5890         /*
5891          * In case of inheritance, it will be the parent that links to the
5892          * ring-buffer, but it will be the child that's actually using it:
5893          */
5894         if (rcu_dereference(parent->rb) == rb)
5895                 ro->err = __perf_event_stop(event);
5896 }
5897
5898 static int __perf_pmu_output_stop(void *info)
5899 {
5900         struct perf_event *event = info;
5901         struct pmu *pmu = event->pmu;
5902         struct perf_cpu_context *cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
5903         struct remote_output ro = {
5904                 .rb     = event->rb,
5905         };
5906
5907         rcu_read_lock();
5908         perf_event_aux_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro);
5909         if (cpuctx->task_ctx)
5910                 perf_event_aux_ctx(cpuctx->task_ctx, __perf_event_output_stop,
5911                                    &ro);
5912         rcu_read_unlock();
5913
5914         return ro.err;
5915 }
5916
5917 static void perf_pmu_output_stop(struct perf_event *event)
5918 {
5919         struct perf_event *iter;
5920         int err, cpu;
5921
5922 restart:
5923         rcu_read_lock();
5924         list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
5925                 /*
5926                  * For per-CPU events, we need to make sure that neither they
5927                  * nor their children are running; for cpu==-1 events it's
5928                  * sufficient to stop the event itself if it's active, since
5929                  * it can't have children.
5930                  */
5931                 cpu = iter->cpu;
5932                 if (cpu == -1)
5933                         cpu = READ_ONCE(iter->oncpu);
5934
5935                 if (cpu == -1)
5936                         continue;
5937
5938                 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
5939                 if (err == -EAGAIN) {
5940                         rcu_read_unlock();
5941                         goto restart;
5942                 }
5943         }
5944         rcu_read_unlock();
5945 }
5946
5947 /*
5948  * task tracking -- fork/exit
5949  *
5950  * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
5951  */
5952
5953 struct perf_task_event {
5954         struct task_struct              *task;
5955         struct perf_event_context       *task_ctx;
5956
5957         struct {
5958                 struct perf_event_header        header;
5959
5960                 u32                             pid;
5961                 u32                             ppid;
5962                 u32                             tid;
5963                 u32                             ptid;
5964                 u64                             time;
5965         } event_id;
5966 };
5967
5968 static int perf_event_task_match(struct perf_event *event)
5969 {
5970         return event->attr.comm  || event->attr.mmap ||
5971                event->attr.mmap2 || event->attr.mmap_data ||
5972                event->attr.task;
5973 }
5974
5975 static void perf_event_task_output(struct perf_event *event,
5976                                    void *data)
5977 {
5978         struct perf_task_event *task_event = data;
5979         struct perf_output_handle handle;
5980         struct perf_sample_data sample;
5981         struct task_struct *task = task_event->task;
5982         int ret, size = task_event->event_id.header.size;
5983
5984         if (!perf_event_task_match(event))
5985                 return;
5986
5987         perf_event_header__init_id(&task_event->event_id.header, &sample, event);
5988
5989         ret = perf_output_begin(&handle, event,
5990                                 task_event->event_id.header.size);
5991         if (ret)
5992                 goto out;
5993
5994         task_event->event_id.pid = perf_event_pid(event, task);
5995         task_event->event_id.ppid = perf_event_pid(event, current);
5996
5997         task_event->event_id.tid = perf_event_tid(event, task);
5998         task_event->event_id.ptid = perf_event_tid(event, current);
5999
6000         task_event->event_id.time = perf_event_clock(event);
6001
6002         perf_output_put(&handle, task_event->event_id);
6003
6004         perf_event__output_id_sample(event, &handle, &sample);
6005
6006         perf_output_end(&handle);
6007 out:
6008         task_event->event_id.header.size = size;
6009 }
6010
6011 static void perf_event_task(struct task_struct *task,
6012                               struct perf_event_context *task_ctx,
6013                               int new)
6014 {
6015         struct perf_task_event task_event;
6016
6017         if (!atomic_read(&nr_comm_events) &&
6018             !atomic_read(&nr_mmap_events) &&
6019             !atomic_read(&nr_task_events))
6020                 return;
6021
6022         task_event = (struct perf_task_event){
6023                 .task     = task,
6024                 .task_ctx = task_ctx,
6025                 .event_id    = {
6026                         .header = {
6027                                 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
6028                                 .misc = 0,
6029                                 .size = sizeof(task_event.event_id),
6030                         },
6031                         /* .pid  */
6032                         /* .ppid */
6033                         /* .tid  */
6034                         /* .ptid */
6035                         /* .time */
6036                 },
6037         };
6038
6039         perf_event_aux(perf_event_task_output,
6040                        &task_event,
6041                        task_ctx);
6042 }
6043
6044 void perf_event_fork(struct task_struct *task)
6045 {
6046         perf_event_task(task, NULL, 1);
6047 }
6048
6049 /*
6050  * comm tracking
6051  */
6052
6053 struct perf_comm_event {
6054         struct task_struct      *task;
6055         char                    *comm;
6056         int                     comm_size;
6057
6058         struct {
6059                 struct perf_event_header        header;
6060
6061                 u32                             pid;
6062                 u32                             tid;
6063         } event_id;
6064 };
6065
6066 static int perf_event_comm_match(struct perf_event *event)
6067 {
6068         return event->attr.comm;
6069 }
6070
6071 static void perf_event_comm_output(struct perf_event *event,
6072                                    void *data)
6073 {
6074         struct perf_comm_event *comm_event = data;
6075         struct perf_output_handle handle;
6076         struct perf_sample_data sample;
6077         int size = comm_event->event_id.header.size;
6078         int ret;
6079
6080         if (!perf_event_comm_match(event))
6081                 return;
6082
6083         perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
6084         ret = perf_output_begin(&handle, event,
6085                                 comm_event->event_id.header.size);
6086
6087         if (ret)
6088                 goto out;
6089
6090         comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
6091         comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
6092
6093         perf_output_put(&handle, comm_event->event_id);
6094         __output_copy(&handle, comm_event->comm,
6095                                    comm_event->comm_size);
6096
6097         perf_event__output_id_sample(event, &handle, &sample);
6098
6099         perf_output_end(&handle);
6100 out:
6101         comm_event->event_id.header.size = size;
6102 }
6103
6104 static void perf_event_comm_event(struct perf_comm_event *comm_event)
6105 {
6106         char comm[TASK_COMM_LEN];
6107         unsigned int size;
6108
6109         memset(comm, 0, sizeof(comm));
6110         strlcpy(comm, comm_event->task->comm, sizeof(comm));
6111         size = ALIGN(strlen(comm)+1, sizeof(u64));
6112
6113         comm_event->comm = comm;
6114         comm_event->comm_size = size;
6115
6116         comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
6117
6118         perf_event_aux(perf_event_comm_output,
6119                        comm_event,
6120                        NULL);
6121 }
6122
6123 void perf_event_comm(struct task_struct *task, bool exec)
6124 {
6125         struct perf_comm_event comm_event;
6126
6127         if (!atomic_read(&nr_comm_events))
6128                 return;
6129
6130         comm_event = (struct perf_comm_event){
6131                 .task   = task,
6132                 /* .comm      */
6133                 /* .comm_size */
6134                 .event_id  = {
6135                         .header = {
6136                                 .type = PERF_RECORD_COMM,
6137                                 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
6138                                 /* .size */
6139                         },
6140                         /* .pid */
6141                         /* .tid */
6142                 },
6143         };
6144
6145         perf_event_comm_event(&comm_event);
6146 }
6147
6148 /*
6149  * mmap tracking
6150  */
6151
6152 struct perf_mmap_event {
6153         struct vm_area_struct   *vma;
6154
6155         const char              *file_name;
6156         int                     file_size;
6157         int                     maj, min;
6158         u64                     ino;
6159         u64                     ino_generation;
6160         u32                     prot, flags;
6161
6162         struct {
6163                 struct perf_event_header        header;
6164
6165                 u32                             pid;
6166                 u32                             tid;
6167                 u64                             start;
6168                 u64                             len;
6169                 u64                             pgoff;
6170         } event_id;
6171 };
6172
6173 static int perf_event_mmap_match(struct perf_event *event,
6174                                  void *data)
6175 {
6176         struct perf_mmap_event *mmap_event = data;
6177         struct vm_area_struct *vma = mmap_event->vma;
6178         int executable = vma->vm_flags & VM_EXEC;
6179
6180         return (!executable && event->attr.mmap_data) ||
6181                (executable && (event->attr.mmap || event->attr.mmap2));
6182 }
6183
6184 static void perf_event_mmap_output(struct perf_event *event,
6185                                    void *data)
6186 {
6187         struct perf_mmap_event *mmap_event = data;
6188         struct perf_output_handle handle;
6189         struct perf_sample_data sample;
6190         int size = mmap_event->event_id.header.size;
6191         u32 type = mmap_event->event_id.header.type;
6192         int ret;
6193
6194         if (!perf_event_mmap_match(event, data))
6195                 return;
6196
6197         if (event->attr.mmap2) {
6198                 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
6199                 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
6200                 mmap_event->event_id.header.size += sizeof(mmap_event->min);
6201                 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
6202                 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
6203                 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
6204                 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
6205         }
6206
6207         perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
6208         ret = perf_output_begin(&handle, event,
6209                                 mmap_event->event_id.header.size);
6210         if (ret)
6211                 goto out;
6212
6213         mmap_event->event_id.pid = perf_event_pid(event, current);
6214         mmap_event->event_id.tid = perf_event_tid(event, current);
6215
6216         perf_output_put(&handle, mmap_event->event_id);
6217
6218         if (event->attr.mmap2) {
6219                 perf_output_put(&handle, mmap_event->maj);
6220                 perf_output_put(&handle, mmap_event->min);
6221                 perf_output_put(&handle, mmap_event->ino);
6222                 perf_output_put(&handle, mmap_event->ino_generation);
6223                 perf_output_put(&handle, mmap_event->prot);
6224                 perf_output_put(&handle, mmap_event->flags);
6225         }
6226
6227         __output_copy(&handle, mmap_event->file_name,
6228                                    mmap_event->file_size);
6229
6230         perf_event__output_id_sample(event, &handle, &sample);
6231
6232         perf_output_end(&handle);
6233 out:
6234         mmap_event->event_id.header.size = size;
6235         mmap_event->event_id.header.type = type;
6236 }
6237
6238 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
6239 {
6240         struct vm_area_struct *vma = mmap_event->vma;
6241         struct file *file = vma->vm_file;
6242         int maj = 0, min = 0;
6243         u64 ino = 0, gen = 0;
6244         u32 prot = 0, flags = 0;
6245         unsigned int size;
6246         char tmp[16];
6247         char *buf = NULL;
6248         char *name;
6249
6250         if (vma->vm_flags & VM_READ)
6251                 prot |= PROT_READ;
6252         if (vma->vm_flags & VM_WRITE)
6253                 prot |= PROT_WRITE;
6254         if (vma->vm_flags & VM_EXEC)
6255                 prot |= PROT_EXEC;
6256
6257         if (vma->vm_flags & VM_MAYSHARE)
6258                 flags = MAP_SHARED;
6259         else
6260                 flags = MAP_PRIVATE;
6261
6262         if (vma->vm_flags & VM_DENYWRITE)
6263                 flags |= MAP_DENYWRITE;
6264         if (vma->vm_flags & VM_MAYEXEC)
6265                 flags |= MAP_EXECUTABLE;
6266         if (vma->vm_flags & VM_LOCKED)
6267                 flags |= MAP_LOCKED;
6268         if (vma->vm_flags & VM_HUGETLB)
6269                 flags |= MAP_HUGETLB;
6270
6271         if (file) {
6272                 struct inode *inode;
6273                 dev_t dev;
6274
6275                 buf = kmalloc(PATH_MAX, GFP_KERNEL);
6276                 if (!buf) {
6277                         name = "//enomem";
6278                         goto cpy_name;
6279                 }
6280                 /*
6281                  * d_path() works from the end of the rb backwards, so we
6282                  * need to add enough zero bytes after the string to handle
6283                  * the 64bit alignment we do later.
6284                  */
6285                 name = file_path(file, buf, PATH_MAX - sizeof(u64));
6286                 if (IS_ERR(name)) {
6287                         name = "//toolong";
6288                         goto cpy_name;
6289                 }
6290                 inode = file_inode(vma->vm_file);
6291                 dev = inode->i_sb->s_dev;
6292                 ino = inode->i_ino;
6293                 gen = inode->i_generation;
6294                 maj = MAJOR(dev);
6295                 min = MINOR(dev);
6296
6297                 goto got_name;
6298         } else {
6299                 if (vma->vm_ops && vma->vm_ops->name) {
6300                         name = (char *) vma->vm_ops->name(vma);
6301                         if (name)
6302                                 goto cpy_name;
6303                 }
6304
6305                 name = (char *)arch_vma_name(vma);
6306                 if (name)
6307                         goto cpy_name;
6308
6309                 if (vma->vm_start <= vma->vm_mm->start_brk &&
6310                                 vma->vm_end >= vma->vm_mm->brk) {
6311                         name = "[heap]";
6312                         goto cpy_name;
6313                 }
6314                 if (vma->vm_start <= vma->vm_mm->start_stack &&
6315                                 vma->vm_end >= vma->vm_mm->start_stack) {
6316                         name = "[stack]";
6317                         goto cpy_name;
6318                 }
6319
6320                 name = "//anon";
6321                 goto cpy_name;
6322         }
6323
6324 cpy_name:
6325         strlcpy(tmp, name, sizeof(tmp));
6326         name = tmp;
6327 got_name:
6328         /*
6329          * Since our buffer works in 8 byte units we need to align our string
6330          * size to a multiple of 8. However, we must guarantee the tail end is
6331          * zero'd out to avoid leaking random bits to userspace.
6332          */
6333         size = strlen(name)+1;
6334         while (!IS_ALIGNED(size, sizeof(u64)))
6335                 name[size++] = '\0';
6336
6337         mmap_event->file_name = name;
6338         mmap_event->file_size = size;
6339         mmap_event->maj = maj;
6340         mmap_event->min = min;
6341         mmap_event->ino = ino;
6342         mmap_event->ino_generation = gen;
6343         mmap_event->prot = prot;
6344         mmap_event->flags = flags;
6345
6346         if (!(vma->vm_flags & VM_EXEC))
6347                 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
6348
6349         mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
6350
6351         perf_event_aux(perf_event_mmap_output,
6352                        mmap_event,
6353                        NULL);
6354
6355         kfree(buf);
6356 }
6357
6358 void perf_event_mmap(struct vm_area_struct *vma)
6359 {
6360         struct perf_mmap_event mmap_event;
6361
6362         if (!atomic_read(&nr_mmap_events))
6363                 return;
6364
6365         mmap_event = (struct perf_mmap_event){
6366                 .vma    = vma,
6367                 /* .file_name */
6368                 /* .file_size */
6369                 .event_id  = {
6370                         .header = {
6371                                 .type = PERF_RECORD_MMAP,
6372                                 .misc = PERF_RECORD_MISC_USER,
6373                                 /* .size */
6374                         },
6375                         /* .pid */
6376                         /* .tid */
6377                         .start  = vma->vm_start,
6378                         .len    = vma->vm_end - vma->vm_start,
6379                         .pgoff  = (u64)vma->vm_pgoff << PAGE_SHIFT,
6380                 },
6381                 /* .maj (attr_mmap2 only) */
6382                 /* .min (attr_mmap2 only) */
6383                 /* .ino (attr_mmap2 only) */
6384                 /* .ino_generation (attr_mmap2 only) */
6385                 /* .prot (attr_mmap2 only) */
6386                 /* .flags (attr_mmap2 only) */
6387         };
6388
6389         perf_event_mmap_event(&mmap_event);
6390 }
6391
6392 void perf_event_aux_event(struct perf_event *event, unsigned long head,
6393                           unsigned long size, u64 flags)
6394 {
6395         struct perf_output_handle handle;
6396         struct perf_sample_data sample;
6397         struct perf_aux_event {
6398                 struct perf_event_header        header;
6399                 u64                             offset;
6400                 u64                             size;
6401                 u64                             flags;
6402         } rec = {
6403                 .header = {
6404                         .type = PERF_RECORD_AUX,
6405                         .misc = 0,
6406                         .size = sizeof(rec),
6407                 },
6408                 .offset         = head,
6409                 .size           = size,
6410                 .flags          = flags,
6411         };
6412         int ret;
6413
6414         perf_event_header__init_id(&rec.header, &sample, event);
6415         ret = perf_output_begin(&handle, event, rec.header.size);
6416
6417         if (ret)
6418                 return;
6419
6420         perf_output_put(&handle, rec);
6421         perf_event__output_id_sample(event, &handle, &sample);
6422
6423         perf_output_end(&handle);
6424 }
6425
6426 /*
6427  * Lost/dropped samples logging
6428  */
6429 void perf_log_lost_samples(struct perf_event *event, u64 lost)
6430 {
6431         struct perf_output_handle handle;
6432         struct perf_sample_data sample;
6433         int ret;
6434
6435         struct {
6436                 struct perf_event_header        header;
6437                 u64                             lost;
6438         } lost_samples_event = {
6439                 .header = {
6440                         .type = PERF_RECORD_LOST_SAMPLES,
6441                         .misc = 0,
6442                         .size = sizeof(lost_samples_event),
6443                 },
6444                 .lost           = lost,
6445         };
6446
6447         perf_event_header__init_id(&lost_samples_event.header, &sample, event);
6448
6449         ret = perf_output_begin(&handle, event,
6450                                 lost_samples_event.header.size);
6451         if (ret)
6452                 return;
6453
6454         perf_output_put(&handle, lost_samples_event);
6455         perf_event__output_id_sample(event, &handle, &sample);
6456         perf_output_end(&handle);
6457 }
6458
6459 /*
6460  * context_switch tracking
6461  */
6462
6463 struct perf_switch_event {
6464         struct task_struct      *task;
6465         struct task_struct      *next_prev;
6466
6467         struct {
6468                 struct perf_event_header        header;
6469                 u32                             next_prev_pid;
6470                 u32                             next_prev_tid;
6471         } event_id;
6472 };
6473
6474 static int perf_event_switch_match(struct perf_event *event)
6475 {
6476         return event->attr.context_switch;
6477 }
6478
6479 static void perf_event_switch_output(struct perf_event *event, void *data)
6480 {
6481         struct perf_switch_event *se = data;
6482         struct perf_output_handle handle;
6483         struct perf_sample_data sample;
6484         int ret;
6485
6486         if (!perf_event_switch_match(event))
6487                 return;
6488
6489         /* Only CPU-wide events are allowed to see next/prev pid/tid */
6490         if (event->ctx->task) {
6491                 se->event_id.header.type = PERF_RECORD_SWITCH;
6492                 se->event_id.header.size = sizeof(se->event_id.header);
6493         } else {
6494                 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
6495                 se->event_id.header.size = sizeof(se->event_id);
6496                 se->event_id.next_prev_pid =
6497                                         perf_event_pid(event, se->next_prev);
6498                 se->event_id.next_prev_tid =
6499                                         perf_event_tid(event, se->next_prev);
6500         }
6501
6502         perf_event_header__init_id(&se->event_id.header, &sample, event);
6503
6504         ret = perf_output_begin(&handle, event, se->event_id.header.size);
6505         if (ret)
6506                 return;
6507
6508         if (event->ctx->task)
6509                 perf_output_put(&handle, se->event_id.header);
6510         else
6511                 perf_output_put(&handle, se->event_id);
6512
6513         perf_event__output_id_sample(event, &handle, &sample);
6514
6515         perf_output_end(&handle);
6516 }
6517
6518 static void perf_event_switch(struct task_struct *task,
6519                               struct task_struct *next_prev, bool sched_in)
6520 {
6521         struct perf_switch_event switch_event;
6522
6523         /* N.B. caller checks nr_switch_events != 0 */
6524
6525         switch_event = (struct perf_switch_event){
6526                 .task           = task,
6527                 .next_prev      = next_prev,
6528                 .event_id       = {
6529                         .header = {
6530                                 /* .type */
6531                                 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
6532                                 /* .size */
6533                         },
6534                         /* .next_prev_pid */
6535                         /* .next_prev_tid */
6536                 },
6537         };
6538
6539         perf_event_aux(perf_event_switch_output,
6540                        &switch_event,
6541                        NULL);
6542 }
6543
6544 /*
6545  * IRQ throttle logging
6546  */
6547
6548 static void perf_log_throttle(struct perf_event *event, int enable)
6549 {
6550         struct perf_output_handle handle;
6551         struct perf_sample_data sample;
6552         int ret;
6553
6554         struct {
6555                 struct perf_event_header        header;
6556                 u64                             time;
6557                 u64                             id;
6558                 u64                             stream_id;
6559         } throttle_event = {
6560                 .header = {
6561                         .type = PERF_RECORD_THROTTLE,
6562                         .misc = 0,
6563                         .size = sizeof(throttle_event),
6564                 },
6565                 .time           = perf_event_clock(event),
6566                 .id             = primary_event_id(event),
6567                 .stream_id      = event->id,
6568         };
6569
6570         if (enable)
6571                 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
6572
6573         perf_event_header__init_id(&throttle_event.header, &sample, event);
6574
6575         ret = perf_output_begin(&handle, event,
6576                                 throttle_event.header.size);
6577         if (ret)
6578                 return;
6579
6580         perf_output_put(&handle, throttle_event);
6581         perf_event__output_id_sample(event, &handle, &sample);
6582         perf_output_end(&handle);
6583 }
6584
6585 static void perf_log_itrace_start(struct perf_event *event)
6586 {
6587         struct perf_output_handle handle;
6588         struct perf_sample_data sample;
6589         struct perf_aux_event {
6590                 struct perf_event_header        header;
6591                 u32                             pid;
6592                 u32                             tid;
6593         } rec;
6594         int ret;
6595
6596         if (event->parent)
6597                 event = event->parent;
6598
6599         if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
6600             event->hw.itrace_started)
6601                 return;
6602
6603         rec.header.type = PERF_RECORD_ITRACE_START;
6604         rec.header.misc = 0;
6605         rec.header.size = sizeof(rec);
6606         rec.pid = perf_event_pid(event, current);
6607         rec.tid = perf_event_tid(event, current);
6608
6609         perf_event_header__init_id(&rec.header, &sample, event);
6610         ret = perf_output_begin(&handle, event, rec.header.size);
6611
6612         if (ret)
6613                 return;
6614
6615         perf_output_put(&handle, rec);
6616         perf_event__output_id_sample(event, &handle, &sample);
6617
6618         perf_output_end(&handle);
6619 }
6620
6621 /*
6622  * Generic event overflow handling, sampling.
6623  */
6624
6625 static int __perf_event_overflow(struct perf_event *event,
6626                                    int throttle, struct perf_sample_data *data,
6627                                    struct pt_regs *regs)
6628 {
6629         int events = atomic_read(&event->event_limit);
6630         struct hw_perf_event *hwc = &event->hw;
6631         u64 seq;
6632         int ret = 0;
6633
6634         /*
6635          * Non-sampling counters might still use the PMI to fold short
6636          * hardware counters, ignore those.
6637          */
6638         if (unlikely(!is_sampling_event(event)))
6639                 return 0;
6640
6641         seq = __this_cpu_read(perf_throttled_seq);
6642         if (seq != hwc->interrupts_seq) {
6643                 hwc->interrupts_seq = seq;
6644                 hwc->interrupts = 1;
6645         } else {
6646                 hwc->interrupts++;
6647                 if (unlikely(throttle
6648                              && hwc->interrupts >= max_samples_per_tick)) {
6649                         __this_cpu_inc(perf_throttled_count);
6650                         hwc->interrupts = MAX_INTERRUPTS;
6651                         perf_log_throttle(event, 0);
6652                         tick_nohz_full_kick();
6653                         ret = 1;
6654                 }
6655         }
6656
6657         if (event->attr.freq) {
6658                 u64 now = perf_clock();
6659                 s64 delta = now - hwc->freq_time_stamp;
6660
6661                 hwc->freq_time_stamp = now;
6662
6663                 if (delta > 0 && delta < 2*TICK_NSEC)
6664                         perf_adjust_period(event, delta, hwc->last_period, true);
6665         }
6666
6667         /*
6668          * XXX event_limit might not quite work as expected on inherited
6669          * events
6670          */
6671
6672         event->pending_kill = POLL_IN;
6673         if (events && atomic_dec_and_test(&event->event_limit)) {
6674                 ret = 1;
6675                 event->pending_kill = POLL_HUP;
6676                 event->pending_disable = 1;
6677                 irq_work_queue(&event->pending);
6678         }
6679
6680         if (event->overflow_handler)
6681                 event->overflow_handler(event, data, regs);
6682         else
6683                 perf_event_output(event, data, regs);
6684
6685         if (*perf_event_fasync(event) && event->pending_kill) {
6686                 event->pending_wakeup = 1;
6687                 irq_work_queue(&event->pending);
6688         }
6689
6690         return ret;
6691 }
6692
6693 int perf_event_overflow(struct perf_event *event,
6694                           struct perf_sample_data *data,
6695                           struct pt_regs *regs)
6696 {
6697         return __perf_event_overflow(event, 1, data, regs);
6698 }
6699
6700 /*
6701  * Generic software event infrastructure
6702  */
6703
6704 struct swevent_htable {
6705         struct swevent_hlist            *swevent_hlist;
6706         struct mutex                    hlist_mutex;
6707         int                             hlist_refcount;
6708
6709         /* Recursion avoidance in each contexts */
6710         int                             recursion[PERF_NR_CONTEXTS];
6711 };
6712
6713 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
6714
6715 /*
6716  * We directly increment event->count and keep a second value in
6717  * event->hw.period_left to count intervals. This period event
6718  * is kept in the range [-sample_period, 0] so that we can use the
6719  * sign as trigger.
6720  */
6721
6722 u64 perf_swevent_set_period(struct perf_event *event)
6723 {
6724         struct hw_perf_event *hwc = &event->hw;
6725         u64 period = hwc->last_period;
6726         u64 nr, offset;
6727         s64 old, val;
6728
6729         hwc->last_period = hwc->sample_period;
6730
6731 again:
6732         old = val = local64_read(&hwc->period_left);
6733         if (val < 0)
6734                 return 0;
6735
6736         nr = div64_u64(period + val, period);
6737         offset = nr * period;
6738         val -= offset;
6739         if (local64_cmpxchg(&hwc->period_left, old, val) != old)
6740                 goto again;
6741
6742         return nr;
6743 }
6744
6745 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
6746                                     struct perf_sample_data *data,
6747                                     struct pt_regs *regs)
6748 {
6749         struct hw_perf_event *hwc = &event->hw;
6750         int throttle = 0;
6751
6752         if (!overflow)
6753                 overflow = perf_swevent_set_period(event);
6754
6755         if (hwc->interrupts == MAX_INTERRUPTS)
6756                 return;
6757
6758         for (; overflow; overflow--) {
6759                 if (__perf_event_overflow(event, throttle,
6760                                             data, regs)) {
6761                         /*
6762                          * We inhibit the overflow from happening when
6763                          * hwc->interrupts == MAX_INTERRUPTS.
6764                          */
6765                         break;
6766                 }
6767                 throttle = 1;
6768         }
6769 }
6770
6771 static void perf_swevent_event(struct perf_event *event, u64 nr,
6772                                struct perf_sample_data *data,
6773                                struct pt_regs *regs)
6774 {
6775         struct hw_perf_event *hwc = &event->hw;
6776
6777         local64_add(nr, &event->count);
6778
6779         if (!regs)
6780                 return;
6781
6782         if (!is_sampling_event(event))
6783                 return;
6784
6785         if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
6786                 data->period = nr;
6787                 return perf_swevent_overflow(event, 1, data, regs);
6788         } else
6789                 data->period = event->hw.last_period;
6790
6791         if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
6792                 return perf_swevent_overflow(event, 1, data, regs);
6793
6794         if (local64_add_negative(nr, &hwc->period_left))
6795                 return;
6796
6797         perf_swevent_overflow(event, 0, data, regs);
6798 }
6799
6800 static int perf_exclude_event(struct perf_event *event,
6801                               struct pt_regs *regs)
6802 {
6803         if (event->hw.state & PERF_HES_STOPPED)
6804                 return 1;
6805
6806         if (regs) {
6807                 if (event->attr.exclude_user && user_mode(regs))
6808                         return 1;
6809
6810                 if (event->attr.exclude_kernel && !user_mode(regs))
6811                         return 1;
6812         }
6813
6814         return 0;
6815 }
6816
6817 static int perf_swevent_match(struct perf_event *event,
6818                                 enum perf_type_id type,
6819                                 u32 event_id,
6820                                 struct perf_sample_data *data,
6821                                 struct pt_regs *regs)
6822 {
6823         if (event->attr.type != type)
6824                 return 0;
6825
6826         if (event->attr.config != event_id)
6827                 return 0;
6828
6829         if (perf_exclude_event(event, regs))
6830                 return 0;
6831
6832         return 1;
6833 }
6834
6835 static inline u64 swevent_hash(u64 type, u32 event_id)
6836 {
6837         u64 val = event_id | (type << 32);
6838
6839         return hash_64(val, SWEVENT_HLIST_BITS);
6840 }
6841
6842 static inline struct hlist_head *
6843 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
6844 {
6845         u64 hash = swevent_hash(type, event_id);
6846
6847         return &hlist->heads[hash];
6848 }
6849
6850 /* For the read side: events when they trigger */
6851 static inline struct hlist_head *
6852 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
6853 {
6854         struct swevent_hlist *hlist;
6855
6856         hlist = rcu_dereference(swhash->swevent_hlist);
6857         if (!hlist)
6858                 return NULL;
6859
6860         return __find_swevent_head(hlist, type, event_id);
6861 }
6862
6863 /* For the event head insertion and removal in the hlist */
6864 static inline struct hlist_head *
6865 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
6866 {
6867         struct swevent_hlist *hlist;
6868         u32 event_id = event->attr.config;
6869         u64 type = event->attr.type;
6870
6871         /*
6872          * Event scheduling is always serialized against hlist allocation
6873          * and release. Which makes the protected version suitable here.
6874          * The context lock guarantees that.
6875          */
6876         hlist = rcu_dereference_protected(swhash->swevent_hlist,
6877                                           lockdep_is_held(&event->ctx->lock));
6878         if (!hlist)
6879                 return NULL;
6880
6881         return __find_swevent_head(hlist, type, event_id);
6882 }
6883
6884 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
6885                                     u64 nr,
6886                                     struct perf_sample_data *data,
6887                                     struct pt_regs *regs)
6888 {
6889         struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6890         struct perf_event *event;
6891         struct hlist_head *head;
6892
6893         rcu_read_lock();
6894         head = find_swevent_head_rcu(swhash, type, event_id);
6895         if (!head)
6896                 goto end;
6897
6898         hlist_for_each_entry_rcu(event, head, hlist_entry) {
6899                 if (perf_swevent_match(event, type, event_id, data, regs))
6900                         perf_swevent_event(event, nr, data, regs);
6901         }
6902 end:
6903         rcu_read_unlock();
6904 }
6905
6906 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
6907
6908 int perf_swevent_get_recursion_context(void)
6909 {
6910         struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6911
6912         return get_recursion_context(swhash->recursion);
6913 }
6914 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
6915
6916 inline void perf_swevent_put_recursion_context(int rctx)
6917 {
6918         struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6919
6920         put_recursion_context(swhash->recursion, rctx);
6921 }
6922
6923 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6924 {
6925         struct perf_sample_data data;
6926
6927         if (WARN_ON_ONCE(!regs))
6928                 return;
6929
6930         perf_sample_data_init(&data, addr, 0);
6931         do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
6932 }
6933
6934 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6935 {
6936         int rctx;
6937
6938         preempt_disable_notrace();
6939         rctx = perf_swevent_get_recursion_context();
6940         if (unlikely(rctx < 0))
6941                 goto fail;
6942
6943         ___perf_sw_event(event_id, nr, regs, addr);
6944
6945         perf_swevent_put_recursion_context(rctx);
6946 fail:
6947         preempt_enable_notrace();
6948 }
6949
6950 static void perf_swevent_read(struct perf_event *event)
6951 {
6952 }
6953
6954 static int perf_swevent_add(struct perf_event *event, int flags)
6955 {
6956         struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6957         struct hw_perf_event *hwc = &event->hw;
6958         struct hlist_head *head;
6959
6960         if (is_sampling_event(event)) {
6961                 hwc->last_period = hwc->sample_period;
6962                 perf_swevent_set_period(event);
6963         }
6964
6965         hwc->state = !(flags & PERF_EF_START);
6966
6967         head = find_swevent_head(swhash, event);
6968         if (WARN_ON_ONCE(!head))
6969                 return -EINVAL;
6970
6971         hlist_add_head_rcu(&event->hlist_entry, head);
6972         perf_event_update_userpage(event);
6973
6974         return 0;
6975 }
6976
6977 static void perf_swevent_del(struct perf_event *event, int flags)
6978 {
6979         hlist_del_rcu(&event->hlist_entry);
6980 }
6981
6982 static void perf_swevent_start(struct perf_event *event, int flags)
6983 {
6984         event->hw.state = 0;
6985 }
6986
6987 static void perf_swevent_stop(struct perf_event *event, int flags)
6988 {
6989         event->hw.state = PERF_HES_STOPPED;
6990 }
6991
6992 /* Deref the hlist from the update side */
6993 static inline struct swevent_hlist *
6994 swevent_hlist_deref(struct swevent_htable *swhash)
6995 {
6996         return rcu_dereference_protected(swhash->swevent_hlist,
6997                                          lockdep_is_held(&swhash->hlist_mutex));
6998 }
6999
7000 static void swevent_hlist_release(struct swevent_htable *swhash)
7001 {
7002         struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
7003
7004         if (!hlist)
7005                 return;
7006
7007         RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
7008         kfree_rcu(hlist, rcu_head);
7009 }
7010
7011 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
7012 {
7013         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7014
7015         mutex_lock(&swhash->hlist_mutex);
7016
7017         if (!--swhash->hlist_refcount)
7018                 swevent_hlist_release(swhash);
7019
7020         mutex_unlock(&swhash->hlist_mutex);
7021 }
7022
7023 static void swevent_hlist_put(struct perf_event *event)
7024 {
7025         int cpu;
7026
7027         for_each_possible_cpu(cpu)
7028                 swevent_hlist_put_cpu(event, cpu);
7029 }
7030
7031 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
7032 {
7033         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
7034         int err = 0;
7035
7036         mutex_lock(&swhash->hlist_mutex);
7037         if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
7038                 struct swevent_hlist *hlist;
7039
7040                 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
7041                 if (!hlist) {
7042                         err = -ENOMEM;
7043                         goto exit;
7044                 }
7045                 rcu_assign_pointer(swhash->swevent_hlist, hlist);
7046         }
7047         swhash->hlist_refcount++;
7048 exit:
7049         mutex_unlock(&swhash->hlist_mutex);
7050
7051         return err;
7052 }
7053
7054 static int swevent_hlist_get(struct perf_event *event)
7055 {
7056         int err;
7057         int cpu, failed_cpu;
7058
7059         get_online_cpus();
7060         for_each_possible_cpu(cpu) {
7061                 err = swevent_hlist_get_cpu(event, cpu);
7062                 if (err) {
7063                         failed_cpu = cpu;
7064                         goto fail;
7065                 }
7066         }
7067         put_online_cpus();
7068
7069         return 0;
7070 fail:
7071         for_each_possible_cpu(cpu) {
7072                 if (cpu == failed_cpu)
7073                         break;
7074                 swevent_hlist_put_cpu(event, cpu);
7075         }
7076
7077         put_online_cpus();
7078         return err;
7079 }
7080
7081 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
7082
7083 static void sw_perf_event_destroy(struct perf_event *event)
7084 {
7085         u64 event_id = event->attr.config;
7086
7087         WARN_ON(event->parent);
7088
7089         static_key_slow_dec(&perf_swevent_enabled[event_id]);
7090         swevent_hlist_put(event);
7091 }
7092
7093 static int perf_swevent_init(struct perf_event *event)
7094 {
7095         u64 event_id = event->attr.config;
7096
7097         if (event->attr.type != PERF_TYPE_SOFTWARE)
7098                 return -ENOENT;
7099
7100         /*
7101          * no branch sampling for software events
7102          */
7103         if (has_branch_stack(event))
7104                 return -EOPNOTSUPP;
7105
7106         switch (event_id) {
7107         case PERF_COUNT_SW_CPU_CLOCK:
7108         case PERF_COUNT_SW_TASK_CLOCK:
7109                 return -ENOENT;
7110
7111         default:
7112                 break;
7113         }
7114
7115         if (event_id >= PERF_COUNT_SW_MAX)
7116                 return -ENOENT;
7117
7118         if (!event->parent) {
7119                 int err;
7120
7121                 err = swevent_hlist_get(event);
7122                 if (err)
7123                         return err;
7124
7125                 static_key_slow_inc(&perf_swevent_enabled[event_id]);
7126                 event->destroy = sw_perf_event_destroy;
7127         }
7128
7129         return 0;
7130 }
7131
7132 static struct pmu perf_swevent = {
7133         .task_ctx_nr    = perf_sw_context,
7134
7135         .capabilities   = PERF_PMU_CAP_NO_NMI,
7136
7137         .event_init     = perf_swevent_init,
7138         .add            = perf_swevent_add,
7139         .del            = perf_swevent_del,
7140         .start          = perf_swevent_start,
7141         .stop           = perf_swevent_stop,
7142         .read           = perf_swevent_read,
7143
7144         .events_across_hotplug = 1,
7145 };
7146
7147 #ifdef CONFIG_EVENT_TRACING
7148
7149 static int perf_tp_filter_match(struct perf_event *event,
7150                                 struct perf_sample_data *data)
7151 {
7152         void *record = data->raw->data;
7153
7154         /* only top level events have filters set */
7155         if (event->parent)
7156                 event = event->parent;
7157
7158         if (likely(!event->filter) || filter_match_preds(event->filter, record))
7159                 return 1;
7160         return 0;
7161 }
7162
7163 static int perf_tp_event_match(struct perf_event *event,
7164                                 struct perf_sample_data *data,
7165                                 struct pt_regs *regs)
7166 {
7167         if (event->hw.state & PERF_HES_STOPPED)
7168                 return 0;
7169         /*
7170          * All tracepoints are from kernel-space.
7171          */
7172         if (event->attr.exclude_kernel)
7173                 return 0;
7174
7175         if (!perf_tp_filter_match(event, data))
7176                 return 0;
7177
7178         return 1;
7179 }
7180
7181 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
7182                    struct pt_regs *regs, struct hlist_head *head, int rctx,
7183                    struct task_struct *task)
7184 {
7185         struct perf_sample_data data;
7186         struct perf_event *event;
7187
7188         struct perf_raw_record raw = {
7189                 .size = entry_size,
7190                 .data = record,
7191         };
7192
7193         perf_sample_data_init(&data, addr, 0);
7194         data.raw = &raw;
7195
7196         hlist_for_each_entry_rcu(event, head, hlist_entry) {
7197                 if (perf_tp_event_match(event, &data, regs))
7198                         perf_swevent_event(event, count, &data, regs);
7199         }
7200
7201         /*
7202          * If we got specified a target task, also iterate its context and
7203          * deliver this event there too.
7204          */
7205         if (task && task != current) {
7206                 struct perf_event_context *ctx;
7207                 struct trace_entry *entry = record;
7208
7209                 rcu_read_lock();
7210                 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
7211                 if (!ctx)
7212                         goto unlock;
7213
7214                 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7215                         if (event->cpu != smp_processor_id())
7216                                 continue;
7217                         if (event->attr.type != PERF_TYPE_TRACEPOINT)
7218                                 continue;
7219                         if (event->attr.config != entry->type)
7220                                 continue;
7221                         if (perf_tp_event_match(event, &data, regs))
7222                                 perf_swevent_event(event, count, &data, regs);
7223                 }
7224 unlock:
7225                 rcu_read_unlock();
7226         }
7227
7228         perf_swevent_put_recursion_context(rctx);
7229 }
7230 EXPORT_SYMBOL_GPL(perf_tp_event);
7231
7232 static void tp_perf_event_destroy(struct perf_event *event)
7233 {
7234         perf_trace_destroy(event);
7235 }
7236
7237 static int perf_tp_event_init(struct perf_event *event)
7238 {
7239         int err;
7240
7241         if (event->attr.type != PERF_TYPE_TRACEPOINT)
7242                 return -ENOENT;
7243
7244         /*
7245          * no branch sampling for tracepoint events
7246          */
7247         if (has_branch_stack(event))
7248                 return -EOPNOTSUPP;
7249
7250         err = perf_trace_init(event);
7251         if (err)
7252                 return err;
7253
7254         event->destroy = tp_perf_event_destroy;
7255
7256         return 0;
7257 }
7258
7259 static struct pmu perf_tracepoint = {
7260         .task_ctx_nr    = perf_sw_context,
7261
7262         .event_init     = perf_tp_event_init,
7263         .add            = perf_trace_add,
7264         .del            = perf_trace_del,
7265         .start          = perf_swevent_start,
7266         .stop           = perf_swevent_stop,
7267         .read           = perf_swevent_read,
7268
7269         .events_across_hotplug = 1,
7270 };
7271
7272 static inline void perf_tp_register(void)
7273 {
7274         perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
7275 }
7276
7277 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7278 {
7279         char *filter_str;
7280         int ret;
7281
7282         if (event->attr.type != PERF_TYPE_TRACEPOINT)
7283                 return -EINVAL;
7284
7285         filter_str = strndup_user(arg, PAGE_SIZE);
7286         if (IS_ERR(filter_str))
7287                 return PTR_ERR(filter_str);
7288
7289         ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
7290
7291         kfree(filter_str);
7292         return ret;
7293 }
7294
7295 static void perf_event_free_filter(struct perf_event *event)
7296 {
7297         ftrace_profile_free_filter(event);
7298 }
7299
7300 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7301 {
7302         struct bpf_prog *prog;
7303
7304         if (event->attr.type != PERF_TYPE_TRACEPOINT)
7305                 return -EINVAL;
7306
7307         if (event->tp_event->prog)
7308                 return -EEXIST;
7309
7310         if (!(event->tp_event->flags & TRACE_EVENT_FL_UKPROBE))
7311                 /* bpf programs can only be attached to u/kprobes */
7312                 return -EINVAL;
7313
7314         prog = bpf_prog_get(prog_fd);
7315         if (IS_ERR(prog))
7316                 return PTR_ERR(prog);
7317
7318         if (prog->type != BPF_PROG_TYPE_KPROBE) {
7319                 /* valid fd, but invalid bpf program type */
7320                 bpf_prog_put(prog);
7321                 return -EINVAL;
7322         }
7323
7324         event->tp_event->prog = prog;
7325         event->tp_event->bpf_prog_owner = event;
7326
7327         return 0;
7328 }
7329
7330 static void perf_event_free_bpf_prog(struct perf_event *event)
7331 {
7332         struct bpf_prog *prog;
7333
7334         if (!event->tp_event)
7335                 return;
7336
7337         prog = event->tp_event->prog;
7338         if (prog && event->tp_event->bpf_prog_owner == event) {
7339                 event->tp_event->prog = NULL;
7340                 bpf_prog_put(prog);
7341         }
7342 }
7343
7344 #else
7345
7346 static inline void perf_tp_register(void)
7347 {
7348 }
7349
7350 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7351 {
7352         return -ENOENT;
7353 }
7354
7355 static void perf_event_free_filter(struct perf_event *event)
7356 {
7357 }
7358
7359 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7360 {
7361         return -ENOENT;
7362 }
7363
7364 static void perf_event_free_bpf_prog(struct perf_event *event)
7365 {
7366 }
7367 #endif /* CONFIG_EVENT_TRACING */
7368
7369 #ifdef CONFIG_HAVE_HW_BREAKPOINT
7370 void perf_bp_event(struct perf_event *bp, void *data)
7371 {
7372         struct perf_sample_data sample;
7373         struct pt_regs *regs = data;
7374
7375         perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
7376
7377         if (!bp->hw.state && !perf_exclude_event(bp, regs))
7378                 perf_swevent_event(bp, 1, &sample, regs);
7379 }
7380 #endif
7381
7382 static int perf_event_drv_configs(struct perf_event *event,
7383                                   void __user *arg)
7384 {
7385         if (!event->pmu->get_drv_configs)
7386                 return -EINVAL;
7387
7388         return event->pmu->get_drv_configs(event, arg);
7389 }
7390
7391 /*
7392  * hrtimer based swevent callback
7393  */
7394
7395 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
7396 {
7397         enum hrtimer_restart ret = HRTIMER_RESTART;
7398         struct perf_sample_data data;
7399         struct pt_regs *regs;
7400         struct perf_event *event;
7401         u64 period;
7402
7403         event = container_of(hrtimer, struct perf_event, hw.hrtimer);
7404
7405         if (event->state != PERF_EVENT_STATE_ACTIVE)
7406                 return HRTIMER_NORESTART;
7407
7408         event->pmu->read(event);
7409
7410         perf_sample_data_init(&data, 0, event->hw.last_period);
7411         regs = get_irq_regs();
7412
7413         if (regs && !perf_exclude_event(event, regs)) {
7414                 if (!(event->attr.exclude_idle && is_idle_task(current)))
7415                         if (__perf_event_overflow(event, 1, &data, regs))
7416                                 ret = HRTIMER_NORESTART;
7417         }
7418
7419         period = max_t(u64, 10000, event->hw.sample_period);
7420         hrtimer_forward_now(hrtimer, ns_to_ktime(period));
7421
7422         return ret;
7423 }
7424
7425 static void perf_swevent_start_hrtimer(struct perf_event *event)
7426 {
7427         struct hw_perf_event *hwc = &event->hw;
7428         s64 period;
7429
7430         if (!is_sampling_event(event))
7431                 return;
7432
7433         period = local64_read(&hwc->period_left);
7434         if (period) {
7435                 if (period < 0)
7436                         period = 10000;
7437
7438                 local64_set(&hwc->period_left, 0);
7439         } else {
7440                 period = max_t(u64, 10000, hwc->sample_period);
7441         }
7442         hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
7443                       HRTIMER_MODE_REL_PINNED);
7444 }
7445
7446 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
7447 {
7448         struct hw_perf_event *hwc = &event->hw;
7449
7450         if (is_sampling_event(event)) {
7451                 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
7452                 local64_set(&hwc->period_left, ktime_to_ns(remaining));
7453
7454                 hrtimer_cancel(&hwc->hrtimer);
7455         }
7456 }
7457
7458 static void perf_swevent_init_hrtimer(struct perf_event *event)
7459 {
7460         struct hw_perf_event *hwc = &event->hw;
7461
7462         if (!is_sampling_event(event))
7463                 return;
7464
7465         hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7466         hwc->hrtimer.function = perf_swevent_hrtimer;
7467
7468         /*
7469          * Since hrtimers have a fixed rate, we can do a static freq->period
7470          * mapping and avoid the whole period adjust feedback stuff.
7471          */
7472         if (event->attr.freq) {
7473                 long freq = event->attr.sample_freq;
7474
7475                 event->attr.sample_period = NSEC_PER_SEC / freq;
7476                 hwc->sample_period = event->attr.sample_period;
7477                 local64_set(&hwc->period_left, hwc->sample_period);
7478                 hwc->last_period = hwc->sample_period;
7479                 event->attr.freq = 0;
7480         }
7481 }
7482
7483 /*
7484  * Software event: cpu wall time clock
7485  */
7486
7487 static void cpu_clock_event_update(struct perf_event *event)
7488 {
7489         s64 prev;
7490         u64 now;
7491
7492         now = local_clock();
7493         prev = local64_xchg(&event->hw.prev_count, now);
7494         local64_add(now - prev, &event->count);
7495 }
7496
7497 static void cpu_clock_event_start(struct perf_event *event, int flags)
7498 {
7499         local64_set(&event->hw.prev_count, local_clock());
7500         perf_swevent_start_hrtimer(event);
7501 }
7502
7503 static void cpu_clock_event_stop(struct perf_event *event, int flags)
7504 {
7505         perf_swevent_cancel_hrtimer(event);
7506         cpu_clock_event_update(event);
7507 }
7508
7509 static int cpu_clock_event_add(struct perf_event *event, int flags)
7510 {
7511         if (flags & PERF_EF_START)
7512                 cpu_clock_event_start(event, flags);
7513         perf_event_update_userpage(event);
7514
7515         return 0;
7516 }
7517
7518 static void cpu_clock_event_del(struct perf_event *event, int flags)
7519 {
7520         cpu_clock_event_stop(event, flags);
7521 }
7522
7523 static void cpu_clock_event_read(struct perf_event *event)
7524 {
7525         cpu_clock_event_update(event);
7526 }
7527
7528 static int cpu_clock_event_init(struct perf_event *event)
7529 {
7530         if (event->attr.type != PERF_TYPE_SOFTWARE)
7531                 return -ENOENT;
7532
7533         if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
7534                 return -ENOENT;
7535
7536         /*
7537          * no branch sampling for software events
7538          */
7539         if (has_branch_stack(event))
7540                 return -EOPNOTSUPP;
7541
7542         perf_swevent_init_hrtimer(event);
7543
7544         return 0;
7545 }
7546
7547 static struct pmu perf_cpu_clock = {
7548         .task_ctx_nr    = perf_sw_context,
7549
7550         .capabilities   = PERF_PMU_CAP_NO_NMI,
7551
7552         .event_init     = cpu_clock_event_init,
7553         .add            = cpu_clock_event_add,
7554         .del            = cpu_clock_event_del,
7555         .start          = cpu_clock_event_start,
7556         .stop           = cpu_clock_event_stop,
7557         .read           = cpu_clock_event_read,
7558
7559         .events_across_hotplug = 1,
7560 };
7561
7562 /*
7563  * Software event: task time clock
7564  */
7565
7566 static void task_clock_event_update(struct perf_event *event, u64 now)
7567 {
7568         u64 prev;
7569         s64 delta;
7570
7571         prev = local64_xchg(&event->hw.prev_count, now);
7572         delta = now - prev;
7573         local64_add(delta, &event->count);
7574 }
7575
7576 static void task_clock_event_start(struct perf_event *event, int flags)
7577 {
7578         local64_set(&event->hw.prev_count, event->ctx->time);
7579         perf_swevent_start_hrtimer(event);
7580 }
7581
7582 static void task_clock_event_stop(struct perf_event *event, int flags)
7583 {
7584         perf_swevent_cancel_hrtimer(event);
7585         task_clock_event_update(event, event->ctx->time);
7586 }
7587
7588 static int task_clock_event_add(struct perf_event *event, int flags)
7589 {
7590         if (flags & PERF_EF_START)
7591                 task_clock_event_start(event, flags);
7592         perf_event_update_userpage(event);
7593
7594         return 0;
7595 }
7596
7597 static void task_clock_event_del(struct perf_event *event, int flags)
7598 {
7599         task_clock_event_stop(event, PERF_EF_UPDATE);
7600 }
7601
7602 static void task_clock_event_read(struct perf_event *event)
7603 {
7604         u64 now = perf_clock();
7605         u64 delta = now - event->ctx->timestamp;
7606         u64 time = event->ctx->time + delta;
7607
7608         task_clock_event_update(event, time);
7609 }
7610
7611 static int task_clock_event_init(struct perf_event *event)
7612 {
7613         if (event->attr.type != PERF_TYPE_SOFTWARE)
7614                 return -ENOENT;
7615
7616         if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
7617                 return -ENOENT;
7618
7619         /*
7620          * no branch sampling for software events
7621          */
7622         if (has_branch_stack(event))
7623                 return -EOPNOTSUPP;
7624
7625         perf_swevent_init_hrtimer(event);
7626
7627         return 0;
7628 }
7629
7630 static struct pmu perf_task_clock = {
7631         .task_ctx_nr    = perf_sw_context,
7632
7633         .capabilities   = PERF_PMU_CAP_NO_NMI,
7634
7635         .event_init     = task_clock_event_init,
7636         .add            = task_clock_event_add,
7637         .del            = task_clock_event_del,
7638         .start          = task_clock_event_start,
7639         .stop           = task_clock_event_stop,
7640         .read           = task_clock_event_read,
7641
7642         .events_across_hotplug = 1,
7643 };
7644
7645 static void perf_pmu_nop_void(struct pmu *pmu)
7646 {
7647 }
7648
7649 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
7650 {
7651 }
7652
7653 static int perf_pmu_nop_int(struct pmu *pmu)
7654 {
7655         return 0;
7656 }
7657
7658 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
7659
7660 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
7661 {
7662         __this_cpu_write(nop_txn_flags, flags);
7663
7664         if (flags & ~PERF_PMU_TXN_ADD)
7665                 return;
7666
7667         perf_pmu_disable(pmu);
7668 }
7669
7670 static int perf_pmu_commit_txn(struct pmu *pmu)
7671 {
7672         unsigned int flags = __this_cpu_read(nop_txn_flags);
7673
7674         __this_cpu_write(nop_txn_flags, 0);
7675
7676         if (flags & ~PERF_PMU_TXN_ADD)
7677                 return 0;
7678
7679         perf_pmu_enable(pmu);
7680         return 0;
7681 }
7682
7683 static void perf_pmu_cancel_txn(struct pmu *pmu)
7684 {
7685         unsigned int flags =  __this_cpu_read(nop_txn_flags);
7686
7687         __this_cpu_write(nop_txn_flags, 0);
7688
7689         if (flags & ~PERF_PMU_TXN_ADD)
7690                 return;
7691
7692         perf_pmu_enable(pmu);
7693 }
7694
7695 static int perf_event_idx_default(struct perf_event *event)
7696 {
7697         return 0;
7698 }
7699
7700 /*
7701  * Ensures all contexts with the same task_ctx_nr have the same
7702  * pmu_cpu_context too.
7703  */
7704 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
7705 {
7706         struct pmu *pmu;
7707
7708         if (ctxn < 0)
7709                 return NULL;
7710
7711         list_for_each_entry(pmu, &pmus, entry) {
7712                 if (pmu->task_ctx_nr == ctxn)
7713                         return pmu->pmu_cpu_context;
7714         }
7715
7716         return NULL;
7717 }
7718
7719 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
7720 {
7721         int cpu;
7722
7723         for_each_possible_cpu(cpu) {
7724                 struct perf_cpu_context *cpuctx;
7725
7726                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7727
7728                 if (cpuctx->unique_pmu == old_pmu)
7729                         cpuctx->unique_pmu = pmu;
7730         }
7731 }
7732
7733 static void free_pmu_context(struct pmu *pmu)
7734 {
7735         struct pmu *i;
7736
7737         mutex_lock(&pmus_lock);
7738         /*
7739          * Like a real lame refcount.
7740          */
7741         list_for_each_entry(i, &pmus, entry) {
7742                 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
7743                         update_pmu_context(i, pmu);
7744                         goto out;
7745                 }
7746         }
7747
7748         free_percpu(pmu->pmu_cpu_context);
7749 out:
7750         mutex_unlock(&pmus_lock);
7751 }
7752 static struct idr pmu_idr;
7753
7754 static ssize_t
7755 type_show(struct device *dev, struct device_attribute *attr, char *page)
7756 {
7757         struct pmu *pmu = dev_get_drvdata(dev);
7758
7759         return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
7760 }
7761 static DEVICE_ATTR_RO(type);
7762
7763 static ssize_t
7764 perf_event_mux_interval_ms_show(struct device *dev,
7765                                 struct device_attribute *attr,
7766                                 char *page)
7767 {
7768         struct pmu *pmu = dev_get_drvdata(dev);
7769
7770         return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
7771 }
7772
7773 static DEFINE_MUTEX(mux_interval_mutex);
7774
7775 static ssize_t
7776 perf_event_mux_interval_ms_store(struct device *dev,
7777                                  struct device_attribute *attr,
7778                                  const char *buf, size_t count)
7779 {
7780         struct pmu *pmu = dev_get_drvdata(dev);
7781         int timer, cpu, ret;
7782
7783         ret = kstrtoint(buf, 0, &timer);
7784         if (ret)
7785                 return ret;
7786
7787         if (timer < 1)
7788                 return -EINVAL;
7789
7790         /* same value, noting to do */
7791         if (timer == pmu->hrtimer_interval_ms)
7792                 return count;
7793
7794         mutex_lock(&mux_interval_mutex);
7795         pmu->hrtimer_interval_ms = timer;
7796
7797         /* update all cpuctx for this PMU */
7798         get_online_cpus();
7799         for_each_online_cpu(cpu) {
7800                 struct perf_cpu_context *cpuctx;
7801                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7802                 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
7803
7804                 cpu_function_call(cpu,
7805                         (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
7806         }
7807         put_online_cpus();
7808         mutex_unlock(&mux_interval_mutex);
7809
7810         return count;
7811 }
7812 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
7813
7814 static struct attribute *pmu_dev_attrs[] = {
7815         &dev_attr_type.attr,
7816         &dev_attr_perf_event_mux_interval_ms.attr,
7817         NULL,
7818 };
7819 ATTRIBUTE_GROUPS(pmu_dev);
7820
7821 static int pmu_bus_running;
7822 static struct bus_type pmu_bus = {
7823         .name           = "event_source",
7824         .dev_groups     = pmu_dev_groups,
7825 };
7826
7827 static void pmu_dev_release(struct device *dev)
7828 {
7829         kfree(dev);
7830 }
7831
7832 static int pmu_dev_alloc(struct pmu *pmu)
7833 {
7834         int ret = -ENOMEM;
7835
7836         pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
7837         if (!pmu->dev)
7838                 goto out;
7839
7840         pmu->dev->groups = pmu->attr_groups;
7841         device_initialize(pmu->dev);
7842         ret = dev_set_name(pmu->dev, "%s", pmu->name);
7843         if (ret)
7844                 goto free_dev;
7845
7846         dev_set_drvdata(pmu->dev, pmu);
7847         pmu->dev->bus = &pmu_bus;
7848         pmu->dev->release = pmu_dev_release;
7849         ret = device_add(pmu->dev);
7850         if (ret)
7851                 goto free_dev;
7852
7853 out:
7854         return ret;
7855
7856 free_dev:
7857         put_device(pmu->dev);
7858         goto out;
7859 }
7860
7861 static struct lock_class_key cpuctx_mutex;
7862 static struct lock_class_key cpuctx_lock;
7863
7864 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
7865 {
7866         int cpu, ret;
7867
7868         mutex_lock(&pmus_lock);
7869         ret = -ENOMEM;
7870         pmu->pmu_disable_count = alloc_percpu(int);
7871         if (!pmu->pmu_disable_count)
7872                 goto unlock;
7873
7874         pmu->type = -1;
7875         if (!name)
7876                 goto skip_type;
7877         pmu->name = name;
7878
7879         if (type < 0) {
7880                 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
7881                 if (type < 0) {
7882                         ret = type;
7883                         goto free_pdc;
7884                 }
7885         }
7886         pmu->type = type;
7887
7888         if (pmu_bus_running) {
7889                 ret = pmu_dev_alloc(pmu);
7890                 if (ret)
7891                         goto free_idr;
7892         }
7893
7894 skip_type:
7895         pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
7896         if (pmu->pmu_cpu_context)
7897                 goto got_cpu_context;
7898
7899         ret = -ENOMEM;
7900         pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
7901         if (!pmu->pmu_cpu_context)
7902                 goto free_dev;
7903
7904         for_each_possible_cpu(cpu) {
7905                 struct perf_cpu_context *cpuctx;
7906
7907                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7908                 __perf_event_init_context(&cpuctx->ctx);
7909                 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
7910                 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
7911                 cpuctx->ctx.pmu = pmu;
7912
7913                 __perf_mux_hrtimer_init(cpuctx, cpu);
7914
7915                 cpuctx->unique_pmu = pmu;
7916         }
7917
7918 got_cpu_context:
7919         if (!pmu->start_txn) {
7920                 if (pmu->pmu_enable) {
7921                         /*
7922                          * If we have pmu_enable/pmu_disable calls, install
7923                          * transaction stubs that use that to try and batch
7924                          * hardware accesses.
7925                          */
7926                         pmu->start_txn  = perf_pmu_start_txn;
7927                         pmu->commit_txn = perf_pmu_commit_txn;
7928                         pmu->cancel_txn = perf_pmu_cancel_txn;
7929                 } else {
7930                         pmu->start_txn  = perf_pmu_nop_txn;
7931                         pmu->commit_txn = perf_pmu_nop_int;
7932                         pmu->cancel_txn = perf_pmu_nop_void;
7933                 }
7934         }
7935
7936         if (!pmu->pmu_enable) {
7937                 pmu->pmu_enable  = perf_pmu_nop_void;
7938                 pmu->pmu_disable = perf_pmu_nop_void;
7939         }
7940
7941         if (!pmu->event_idx)
7942                 pmu->event_idx = perf_event_idx_default;
7943
7944         list_add_rcu(&pmu->entry, &pmus);
7945         atomic_set(&pmu->exclusive_cnt, 0);
7946         ret = 0;
7947 unlock:
7948         mutex_unlock(&pmus_lock);
7949
7950         return ret;
7951
7952 free_dev:
7953         device_del(pmu->dev);
7954         put_device(pmu->dev);
7955
7956 free_idr:
7957         if (pmu->type >= PERF_TYPE_MAX)
7958                 idr_remove(&pmu_idr, pmu->type);
7959
7960 free_pdc:
7961         free_percpu(pmu->pmu_disable_count);
7962         goto unlock;
7963 }
7964 EXPORT_SYMBOL_GPL(perf_pmu_register);
7965
7966 void perf_pmu_unregister(struct pmu *pmu)
7967 {
7968         mutex_lock(&pmus_lock);
7969         list_del_rcu(&pmu->entry);
7970         mutex_unlock(&pmus_lock);
7971
7972         /*
7973          * We dereference the pmu list under both SRCU and regular RCU, so
7974          * synchronize against both of those.
7975          */
7976         synchronize_srcu(&pmus_srcu);
7977         synchronize_rcu();
7978
7979         free_percpu(pmu->pmu_disable_count);
7980         if (pmu->type >= PERF_TYPE_MAX)
7981                 idr_remove(&pmu_idr, pmu->type);
7982         device_del(pmu->dev);
7983         put_device(pmu->dev);
7984         free_pmu_context(pmu);
7985 }
7986 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
7987
7988 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
7989 {
7990         struct perf_event_context *ctx = NULL;
7991         int ret;
7992
7993         if (!try_module_get(pmu->module))
7994                 return -ENODEV;
7995
7996         if (event->group_leader != event) {
7997                 /*
7998                  * This ctx->mutex can nest when we're called through
7999                  * inheritance. See the perf_event_ctx_lock_nested() comment.
8000                  */
8001                 ctx = perf_event_ctx_lock_nested(event->group_leader,
8002                                                  SINGLE_DEPTH_NESTING);
8003                 BUG_ON(!ctx);
8004         }
8005
8006         event->pmu = pmu;
8007         ret = pmu->event_init(event);
8008
8009         if (ctx)
8010                 perf_event_ctx_unlock(event->group_leader, ctx);
8011
8012         if (ret)
8013                 module_put(pmu->module);
8014
8015         return ret;
8016 }
8017
8018 static struct pmu *perf_init_event(struct perf_event *event)
8019 {
8020         struct pmu *pmu = NULL;
8021         int idx;
8022         int ret;
8023
8024         idx = srcu_read_lock(&pmus_srcu);
8025
8026         rcu_read_lock();
8027         pmu = idr_find(&pmu_idr, event->attr.type);
8028         rcu_read_unlock();
8029         if (pmu) {
8030                 ret = perf_try_init_event(pmu, event);
8031                 if (ret)
8032                         pmu = ERR_PTR(ret);
8033                 goto unlock;
8034         }
8035
8036         list_for_each_entry_rcu(pmu, &pmus, entry) {
8037                 ret = perf_try_init_event(pmu, event);
8038                 if (!ret)
8039                         goto unlock;
8040
8041                 if (ret != -ENOENT) {
8042                         pmu = ERR_PTR(ret);
8043                         goto unlock;
8044                 }
8045         }
8046         pmu = ERR_PTR(-ENOENT);
8047 unlock:
8048         srcu_read_unlock(&pmus_srcu, idx);
8049
8050         return pmu;
8051 }
8052
8053 static void account_event_cpu(struct perf_event *event, int cpu)
8054 {
8055         if (event->parent)
8056                 return;
8057
8058         if (is_cgroup_event(event))
8059                 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
8060 }
8061
8062 static void account_event(struct perf_event *event)
8063 {
8064         if (event->parent)
8065                 return;
8066
8067         if (event->attach_state & PERF_ATTACH_TASK)
8068                 static_key_slow_inc(&perf_sched_events.key);
8069         if (event->attr.mmap || event->attr.mmap_data)
8070                 atomic_inc(&nr_mmap_events);
8071         if (event->attr.comm)
8072                 atomic_inc(&nr_comm_events);
8073         if (event->attr.task)
8074                 atomic_inc(&nr_task_events);
8075         if (event->attr.freq) {
8076                 if (atomic_inc_return(&nr_freq_events) == 1)
8077                         tick_nohz_full_kick_all();
8078         }
8079         if (event->attr.context_switch) {
8080                 atomic_inc(&nr_switch_events);
8081                 static_key_slow_inc(&perf_sched_events.key);
8082         }
8083         if (has_branch_stack(event))
8084                 static_key_slow_inc(&perf_sched_events.key);
8085         if (is_cgroup_event(event))
8086                 static_key_slow_inc(&perf_sched_events.key);
8087
8088         account_event_cpu(event, event->cpu);
8089 }
8090
8091 /*
8092  * Allocate and initialize a event structure
8093  */
8094 static struct perf_event *
8095 perf_event_alloc(struct perf_event_attr *attr, int cpu,
8096                  struct task_struct *task,
8097                  struct perf_event *group_leader,
8098                  struct perf_event *parent_event,
8099                  perf_overflow_handler_t overflow_handler,
8100                  void *context, int cgroup_fd)
8101 {
8102         struct pmu *pmu;
8103         struct perf_event *event;
8104         struct hw_perf_event *hwc;
8105         long err = -EINVAL;
8106
8107         if ((unsigned)cpu >= nr_cpu_ids) {
8108                 if (!task || cpu != -1)
8109                         return ERR_PTR(-EINVAL);
8110         }
8111
8112         event = kzalloc(sizeof(*event), GFP_KERNEL);
8113         if (!event)
8114                 return ERR_PTR(-ENOMEM);
8115
8116         /*
8117          * Single events are their own group leaders, with an
8118          * empty sibling list:
8119          */
8120         if (!group_leader)
8121                 group_leader = event;
8122
8123         mutex_init(&event->group_leader_mutex);
8124         mutex_init(&event->child_mutex);
8125         INIT_LIST_HEAD(&event->child_list);
8126
8127         INIT_LIST_HEAD(&event->group_entry);
8128         INIT_LIST_HEAD(&event->event_entry);
8129         INIT_LIST_HEAD(&event->sibling_list);
8130         INIT_LIST_HEAD(&event->rb_entry);
8131         INIT_LIST_HEAD(&event->active_entry);
8132         INIT_LIST_HEAD(&event->drv_configs);
8133         INIT_HLIST_NODE(&event->hlist_entry);
8134
8135
8136         init_waitqueue_head(&event->waitq);
8137         init_irq_work(&event->pending, perf_pending_event);
8138
8139         mutex_init(&event->mmap_mutex);
8140
8141         atomic_long_set(&event->refcount, 1);
8142         event->cpu              = cpu;
8143         event->attr             = *attr;
8144         event->group_leader     = group_leader;
8145         event->pmu              = NULL;
8146         event->oncpu            = -1;
8147
8148         event->parent           = parent_event;
8149
8150         event->ns               = get_pid_ns(task_active_pid_ns(current));
8151         event->id               = atomic64_inc_return(&perf_event_id);
8152
8153         event->state            = PERF_EVENT_STATE_INACTIVE;
8154
8155         if (task) {
8156                 event->attach_state = PERF_ATTACH_TASK;
8157                 /*
8158                  * XXX pmu::event_init needs to know what task to account to
8159                  * and we cannot use the ctx information because we need the
8160                  * pmu before we get a ctx.
8161                  */
8162                 event->hw.target = task;
8163         }
8164
8165         event->clock = &local_clock;
8166         if (parent_event)
8167                 event->clock = parent_event->clock;
8168
8169         if (!overflow_handler && parent_event) {
8170                 overflow_handler = parent_event->overflow_handler;
8171                 context = parent_event->overflow_handler_context;
8172         }
8173
8174         event->overflow_handler = overflow_handler;
8175         event->overflow_handler_context = context;
8176
8177         perf_event__state_init(event);
8178
8179         pmu = NULL;
8180
8181         hwc = &event->hw;
8182         hwc->sample_period = attr->sample_period;
8183         if (attr->freq && attr->sample_freq)
8184                 hwc->sample_period = 1;
8185         hwc->last_period = hwc->sample_period;
8186
8187         local64_set(&hwc->period_left, hwc->sample_period);
8188
8189         /*
8190          * We currently do not support PERF_SAMPLE_READ on inherited events.
8191          * See perf_output_read().
8192          */
8193         if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
8194                 goto err_ns;
8195
8196         if (!has_branch_stack(event))
8197                 event->attr.branch_sample_type = 0;
8198
8199         if (cgroup_fd != -1) {
8200                 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
8201                 if (err)
8202                         goto err_ns;
8203         }
8204
8205         pmu = perf_init_event(event);
8206         if (!pmu)
8207                 goto err_ns;
8208         else if (IS_ERR(pmu)) {
8209                 err = PTR_ERR(pmu);
8210                 goto err_ns;
8211         }
8212
8213         err = exclusive_event_init(event);
8214         if (err)
8215                 goto err_pmu;
8216
8217         if (!event->parent) {
8218                 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
8219                         err = get_callchain_buffers();
8220                         if (err)
8221                                 goto err_per_task;
8222                 }
8223         }
8224
8225         /* symmetric to unaccount_event() in _free_event() */
8226         account_event(event);
8227
8228         return event;
8229
8230 err_per_task:
8231         exclusive_event_destroy(event);
8232
8233 err_pmu:
8234         if (event->destroy)
8235                 event->destroy(event);
8236         module_put(pmu->module);
8237 err_ns:
8238         if (is_cgroup_event(event))
8239                 perf_detach_cgroup(event);
8240         if (event->ns)
8241                 put_pid_ns(event->ns);
8242         kfree(event);
8243
8244         return ERR_PTR(err);
8245 }
8246
8247 static int perf_copy_attr(struct perf_event_attr __user *uattr,
8248                           struct perf_event_attr *attr)
8249 {
8250         u32 size;
8251         int ret;
8252
8253         if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
8254                 return -EFAULT;
8255
8256         /*
8257          * zero the full structure, so that a short copy will be nice.
8258          */
8259         memset(attr, 0, sizeof(*attr));
8260
8261         ret = get_user(size, &uattr->size);
8262         if (ret)
8263                 return ret;
8264
8265         if (size > PAGE_SIZE)   /* silly large */
8266                 goto err_size;
8267
8268         if (!size)              /* abi compat */
8269                 size = PERF_ATTR_SIZE_VER0;
8270
8271         if (size < PERF_ATTR_SIZE_VER0)
8272                 goto err_size;
8273
8274         /*
8275          * If we're handed a bigger struct than we know of,
8276          * ensure all the unknown bits are 0 - i.e. new
8277          * user-space does not rely on any kernel feature
8278          * extensions we dont know about yet.
8279          */
8280         if (size > sizeof(*attr)) {
8281                 unsigned char __user *addr;
8282                 unsigned char __user *end;
8283                 unsigned char val;
8284
8285                 addr = (void __user *)uattr + sizeof(*attr);
8286                 end  = (void __user *)uattr + size;
8287
8288                 for (; addr < end; addr++) {
8289                         ret = get_user(val, addr);
8290                         if (ret)
8291                                 return ret;
8292                         if (val)
8293                                 goto err_size;
8294                 }
8295                 size = sizeof(*attr);
8296         }
8297
8298         ret = copy_from_user(attr, uattr, size);
8299         if (ret)
8300                 return -EFAULT;
8301
8302         if (attr->__reserved_1)
8303                 return -EINVAL;
8304
8305         if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
8306                 return -EINVAL;
8307
8308         if (attr->read_format & ~(PERF_FORMAT_MAX-1))
8309                 return -EINVAL;
8310
8311         if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
8312                 u64 mask = attr->branch_sample_type;
8313
8314                 /* only using defined bits */
8315                 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
8316                         return -EINVAL;
8317
8318                 /* at least one branch bit must be set */
8319                 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
8320                         return -EINVAL;
8321
8322                 /* propagate priv level, when not set for branch */
8323                 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
8324
8325                         /* exclude_kernel checked on syscall entry */
8326                         if (!attr->exclude_kernel)
8327                                 mask |= PERF_SAMPLE_BRANCH_KERNEL;
8328
8329                         if (!attr->exclude_user)
8330                                 mask |= PERF_SAMPLE_BRANCH_USER;
8331
8332                         if (!attr->exclude_hv)
8333                                 mask |= PERF_SAMPLE_BRANCH_HV;
8334                         /*
8335                          * adjust user setting (for HW filter setup)
8336                          */
8337                         attr->branch_sample_type = mask;
8338                 }
8339                 /* privileged levels capture (kernel, hv): check permissions */
8340                 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
8341                     && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8342                         return -EACCES;
8343         }
8344
8345         if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
8346                 ret = perf_reg_validate(attr->sample_regs_user);
8347                 if (ret)
8348                         return ret;
8349         }
8350
8351         if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
8352                 if (!arch_perf_have_user_stack_dump())
8353                         return -ENOSYS;
8354
8355                 /*
8356                  * We have __u32 type for the size, but so far
8357                  * we can only use __u16 as maximum due to the
8358                  * __u16 sample size limit.
8359                  */
8360                 if (attr->sample_stack_user >= USHRT_MAX)
8361                         return -EINVAL;
8362                 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
8363                         return -EINVAL;
8364         }
8365
8366         if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
8367                 ret = perf_reg_validate(attr->sample_regs_intr);
8368 out:
8369         return ret;
8370
8371 err_size:
8372         put_user(sizeof(*attr), &uattr->size);
8373         ret = -E2BIG;
8374         goto out;
8375 }
8376
8377 static int
8378 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
8379 {
8380         struct ring_buffer *rb = NULL;
8381         int ret = -EINVAL;
8382
8383         if (!output_event)
8384                 goto set;
8385
8386         /* don't allow circular references */
8387         if (event == output_event)
8388                 goto out;
8389
8390         /*
8391          * Don't allow cross-cpu buffers
8392          */
8393         if (output_event->cpu != event->cpu)
8394                 goto out;
8395
8396         /*
8397          * If its not a per-cpu rb, it must be the same task.
8398          */
8399         if (output_event->cpu == -1 && output_event->ctx != event->ctx)
8400                 goto out;
8401
8402         /*
8403          * Mixing clocks in the same buffer is trouble you don't need.
8404          */
8405         if (output_event->clock != event->clock)
8406                 goto out;
8407
8408         /*
8409          * If both events generate aux data, they must be on the same PMU
8410          */
8411         if (has_aux(event) && has_aux(output_event) &&
8412             event->pmu != output_event->pmu)
8413                 goto out;
8414
8415 set:
8416         mutex_lock(&event->mmap_mutex);
8417         /* Can't redirect output if we've got an active mmap() */
8418         if (atomic_read(&event->mmap_count))
8419                 goto unlock;
8420
8421         if (output_event) {
8422                 /* get the rb we want to redirect to */
8423                 rb = ring_buffer_get(output_event);
8424                 if (!rb)
8425                         goto unlock;
8426         }
8427
8428         ring_buffer_attach(event, rb);
8429
8430         ret = 0;
8431 unlock:
8432         mutex_unlock(&event->mmap_mutex);
8433
8434 out:
8435         return ret;
8436 }
8437
8438 static void mutex_lock_double(struct mutex *a, struct mutex *b)
8439 {
8440         if (b < a)
8441                 swap(a, b);
8442
8443         mutex_lock(a);
8444         mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
8445 }
8446
8447 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
8448 {
8449         bool nmi_safe = false;
8450
8451         switch (clk_id) {
8452         case CLOCK_MONOTONIC:
8453                 event->clock = &ktime_get_mono_fast_ns;
8454                 nmi_safe = true;
8455                 break;
8456
8457         case CLOCK_MONOTONIC_RAW:
8458                 event->clock = &ktime_get_raw_fast_ns;
8459                 nmi_safe = true;
8460                 break;
8461
8462         case CLOCK_REALTIME:
8463                 event->clock = &ktime_get_real_ns;
8464                 break;
8465
8466         case CLOCK_BOOTTIME:
8467                 event->clock = &ktime_get_boot_ns;
8468                 break;
8469
8470         case CLOCK_TAI:
8471                 event->clock = &ktime_get_tai_ns;
8472                 break;
8473
8474         default:
8475                 return -EINVAL;
8476         }
8477
8478         if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
8479                 return -EINVAL;
8480
8481         return 0;
8482 }
8483
8484 /*
8485  * Variation on perf_event_ctx_lock_nested(), except we take two context
8486  * mutexes.
8487  */
8488 static struct perf_event_context *
8489 __perf_event_ctx_lock_double(struct perf_event *group_leader,
8490                              struct perf_event_context *ctx)
8491 {
8492         struct perf_event_context *gctx;
8493
8494 again:
8495         rcu_read_lock();
8496         gctx = READ_ONCE(group_leader->ctx);
8497         if (!atomic_inc_not_zero(&gctx->refcount)) {
8498                 rcu_read_unlock();
8499                 goto again;
8500         }
8501         rcu_read_unlock();
8502
8503         mutex_lock_double(&gctx->mutex, &ctx->mutex);
8504
8505         if (group_leader->ctx != gctx) {
8506                 mutex_unlock(&ctx->mutex);
8507                 mutex_unlock(&gctx->mutex);
8508                 put_ctx(gctx);
8509                 goto again;
8510         }
8511
8512         return gctx;
8513 }
8514
8515 /**
8516  * sys_perf_event_open - open a performance event, associate it to a task/cpu
8517  *
8518  * @attr_uptr:  event_id type attributes for monitoring/sampling
8519  * @pid:                target pid
8520  * @cpu:                target cpu
8521  * @group_fd:           group leader event fd
8522  */
8523 SYSCALL_DEFINE5(perf_event_open,
8524                 struct perf_event_attr __user *, attr_uptr,
8525                 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
8526 {
8527         struct perf_event *group_leader = NULL, *output_event = NULL;
8528         struct perf_event *event, *sibling;
8529         struct perf_event_attr attr;
8530         struct perf_event_context *ctx, *uninitialized_var(gctx);
8531         struct file *event_file = NULL;
8532         struct fd group = {NULL, 0};
8533         struct task_struct *task = NULL;
8534         struct pmu *pmu;
8535         int event_fd;
8536         int move_group = 0;
8537         int err;
8538         int f_flags = O_RDWR;
8539         int cgroup_fd = -1;
8540
8541         /* for future expandability... */
8542         if (flags & ~PERF_FLAG_ALL)
8543                 return -EINVAL;
8544
8545         if (perf_paranoid_any() && !capable(CAP_SYS_ADMIN))
8546                 return -EACCES;
8547
8548         err = perf_copy_attr(attr_uptr, &attr);
8549         if (err)
8550                 return err;
8551
8552         if (attr.constraint_duplicate || attr.__reserved_1)
8553                 return -EINVAL;
8554
8555         if (!attr.exclude_kernel) {
8556                 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8557                         return -EACCES;
8558         }
8559
8560         if (attr.freq) {
8561                 if (attr.sample_freq > sysctl_perf_event_sample_rate)
8562                         return -EINVAL;
8563         } else {
8564                 if (attr.sample_period & (1ULL << 63))
8565                         return -EINVAL;
8566         }
8567
8568         /*
8569          * In cgroup mode, the pid argument is used to pass the fd
8570          * opened to the cgroup directory in cgroupfs. The cpu argument
8571          * designates the cpu on which to monitor threads from that
8572          * cgroup.
8573          */
8574         if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
8575                 return -EINVAL;
8576
8577         if (flags & PERF_FLAG_FD_CLOEXEC)
8578                 f_flags |= O_CLOEXEC;
8579
8580         event_fd = get_unused_fd_flags(f_flags);
8581         if (event_fd < 0)
8582                 return event_fd;
8583
8584         if (group_fd != -1) {
8585                 err = perf_fget_light(group_fd, &group);
8586                 if (err)
8587                         goto err_fd;
8588                 group_leader = group.file->private_data;
8589                 if (flags & PERF_FLAG_FD_OUTPUT)
8590                         output_event = group_leader;
8591                 if (flags & PERF_FLAG_FD_NO_GROUP)
8592                         group_leader = NULL;
8593         }
8594
8595         /*
8596          * Take the group_leader's group_leader_mutex before observing
8597          * anything in the group leader that leads to changes in ctx,
8598          * many of which may be changing on another thread.
8599          * In particular, we want to take this lock before deciding
8600          * whether we need to move_group.
8601          */
8602         if (group_leader)
8603                 mutex_lock(&group_leader->group_leader_mutex);
8604
8605         if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
8606                 task = find_lively_task_by_vpid(pid);
8607                 if (IS_ERR(task)) {
8608                         err = PTR_ERR(task);
8609                         goto err_group_fd;
8610                 }
8611         }
8612
8613         if (task && group_leader &&
8614             group_leader->attr.inherit != attr.inherit) {
8615                 err = -EINVAL;
8616                 goto err_task;
8617         }
8618
8619         get_online_cpus();
8620
8621         if (task) {
8622                 err = mutex_lock_interruptible(&task->signal->cred_guard_mutex);
8623                 if (err)
8624                         goto err_cpus;
8625
8626                 /*
8627                  * Reuse ptrace permission checks for now.
8628                  *
8629                  * We must hold cred_guard_mutex across this and any potential
8630                  * perf_install_in_context() call for this new event to
8631                  * serialize against exec() altering our credentials (and the
8632                  * perf_event_exit_task() that could imply).
8633                  */
8634                 err = -EACCES;
8635                 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
8636                         goto err_cred;
8637         }
8638
8639         if (flags & PERF_FLAG_PID_CGROUP)
8640                 cgroup_fd = pid;
8641
8642         event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
8643                                  NULL, NULL, cgroup_fd);
8644         if (IS_ERR(event)) {
8645                 err = PTR_ERR(event);
8646                 goto err_cred;
8647         }
8648
8649         if (is_sampling_event(event)) {
8650                 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
8651                         err = -ENOTSUPP;
8652                         goto err_alloc;
8653                 }
8654         }
8655
8656         /*
8657          * Special case software events and allow them to be part of
8658          * any hardware group.
8659          */
8660         pmu = event->pmu;
8661
8662         if (attr.use_clockid) {
8663                 err = perf_event_set_clock(event, attr.clockid);
8664                 if (err)
8665                         goto err_alloc;
8666         }
8667
8668         if (group_leader &&
8669             (is_software_event(event) != is_software_event(group_leader))) {
8670                 if (is_software_event(event)) {
8671                         /*
8672                          * If event and group_leader are not both a software
8673                          * event, and event is, then group leader is not.
8674                          *
8675                          * Allow the addition of software events to !software
8676                          * groups, this is safe because software events never
8677                          * fail to schedule.
8678                          */
8679                         pmu = group_leader->pmu;
8680                 } else if (is_software_event(group_leader) &&
8681                            (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
8682                         /*
8683                          * In case the group is a pure software group, and we
8684                          * try to add a hardware event, move the whole group to
8685                          * the hardware context.
8686                          */
8687                         move_group = 1;
8688                 }
8689         }
8690
8691         /*
8692          * Get the target context (task or percpu):
8693          */
8694         ctx = find_get_context(pmu, task, event);
8695         if (IS_ERR(ctx)) {
8696                 err = PTR_ERR(ctx);
8697                 goto err_alloc;
8698         }
8699
8700         if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
8701                 err = -EBUSY;
8702                 goto err_context;
8703         }
8704
8705         /*
8706          * Look up the group leader (we will attach this event to it):
8707          */
8708         if (group_leader) {
8709                 err = -EINVAL;
8710
8711                 /*
8712                  * Do not allow a recursive hierarchy (this new sibling
8713                  * becoming part of another group-sibling):
8714                  */
8715                 if (group_leader->group_leader != group_leader)
8716                         goto err_context;
8717
8718                 /* All events in a group should have the same clock */
8719                 if (group_leader->clock != event->clock)
8720                         goto err_context;
8721
8722                 /*
8723                  * Make sure we're both events for the same CPU;
8724                  * grouping events for different CPUs is broken; since
8725                  * you can never concurrently schedule them anyhow.
8726                  */
8727                 if (group_leader->cpu != event->cpu)
8728                         goto err_context;
8729
8730                 /*
8731                  * Make sure we're both on the same task, or both
8732                  * per-CPU events.
8733                  */
8734                 if (group_leader->ctx->task != ctx->task)
8735                         goto err_context;
8736
8737                 /*
8738                  * Do not allow to attach to a group in a different task
8739                  * or CPU context. If we're moving SW events, we'll fix
8740                  * this up later, so allow that.
8741                  */
8742                 if (!move_group && group_leader->ctx != ctx)
8743                         goto err_context;
8744
8745                 /*
8746                  * Only a group leader can be exclusive or pinned
8747                  */
8748                 if (attr.exclusive || attr.pinned)
8749                         goto err_context;
8750         }
8751
8752         if (output_event) {
8753                 err = perf_event_set_output(event, output_event);
8754                 if (err)
8755                         goto err_context;
8756         }
8757
8758         event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
8759                                         f_flags);
8760         if (IS_ERR(event_file)) {
8761                 err = PTR_ERR(event_file);
8762                 event_file = NULL;
8763                 goto err_context;
8764         }
8765
8766         if (move_group) {
8767                 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
8768
8769                 /*
8770                  * Check if we raced against another sys_perf_event_open() call
8771                  * moving the software group underneath us.
8772                  */
8773                 if (!(group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
8774                         /*
8775                          * If someone moved the group out from under us, check
8776                          * if this new event wound up on the same ctx, if so
8777                          * its the regular !move_group case, otherwise fail.
8778                          */
8779                         if (gctx != ctx) {
8780                                 err = -EINVAL;
8781                                 goto err_locked;
8782                         } else {
8783                                 perf_event_ctx_unlock(group_leader, gctx);
8784                                 move_group = 0;
8785                         }
8786                 }
8787         } else {
8788                 mutex_lock(&ctx->mutex);
8789         }
8790
8791         if (!perf_event_validate_size(event)) {
8792                 err = -E2BIG;
8793                 goto err_locked;
8794         }
8795
8796         /*
8797          * Must be under the same ctx::mutex as perf_install_in_context(),
8798          * because we need to serialize with concurrent event creation.
8799          */
8800         if (!exclusive_event_installable(event, ctx)) {
8801                 /* exclusive and group stuff are assumed mutually exclusive */
8802                 WARN_ON_ONCE(move_group);
8803
8804                 err = -EBUSY;
8805                 goto err_locked;
8806         }
8807
8808         WARN_ON_ONCE(ctx->parent_ctx);
8809
8810         /*
8811          * This is the point on no return; we cannot fail hereafter. This is
8812          * where we start modifying current state.
8813          */
8814
8815         if (move_group) {
8816                 /*
8817                  * See perf_event_ctx_lock() for comments on the details
8818                  * of swizzling perf_event::ctx.
8819                  */
8820                 perf_remove_from_context(group_leader, false);
8821
8822                 list_for_each_entry(sibling, &group_leader->sibling_list,
8823                                     group_entry) {
8824                         perf_remove_from_context(sibling, false);
8825                         put_ctx(gctx);
8826                 }
8827
8828                 /*
8829                  * Wait for everybody to stop referencing the events through
8830                  * the old lists, before installing it on new lists.
8831                  */
8832                 synchronize_rcu();
8833
8834                 /*
8835                  * Install the group siblings before the group leader.
8836                  *
8837                  * Because a group leader will try and install the entire group
8838                  * (through the sibling list, which is still in-tact), we can
8839                  * end up with siblings installed in the wrong context.
8840                  *
8841                  * By installing siblings first we NO-OP because they're not
8842                  * reachable through the group lists.
8843                  */
8844                 list_for_each_entry(sibling, &group_leader->sibling_list,
8845                                     group_entry) {
8846                         perf_event__state_init(sibling);
8847                         perf_install_in_context(ctx, sibling, sibling->cpu);
8848                         get_ctx(ctx);
8849                 }
8850
8851                 /*
8852                  * Removing from the context ends up with disabled
8853                  * event. What we want here is event in the initial
8854                  * startup state, ready to be add into new context.
8855                  */
8856                 perf_event__state_init(group_leader);
8857                 perf_install_in_context(ctx, group_leader, group_leader->cpu);
8858                 get_ctx(ctx);
8859
8860                 /*
8861                  * Now that all events are installed in @ctx, nothing
8862                  * references @gctx anymore, so drop the last reference we have
8863                  * on it.
8864                  */
8865                 put_ctx(gctx);
8866         }
8867
8868         /*
8869          * Precalculate sample_data sizes; do while holding ctx::mutex such
8870          * that we're serialized against further additions and before
8871          * perf_install_in_context() which is the point the event is active and
8872          * can use these values.
8873          */
8874         perf_event__header_size(event);
8875         perf_event__id_header_size(event);
8876
8877         perf_install_in_context(ctx, event, event->cpu);
8878         perf_unpin_context(ctx);
8879
8880         if (move_group)
8881                 perf_event_ctx_unlock(group_leader, gctx);
8882         mutex_unlock(&ctx->mutex);
8883         if (group_leader)
8884                 mutex_unlock(&group_leader->group_leader_mutex);
8885
8886         if (task) {
8887                 mutex_unlock(&task->signal->cred_guard_mutex);
8888                 put_task_struct(task);
8889         }
8890
8891         put_online_cpus();
8892
8893         event->owner = current;
8894
8895         mutex_lock(&current->perf_event_mutex);
8896         list_add_tail(&event->owner_entry, &current->perf_event_list);
8897         mutex_unlock(&current->perf_event_mutex);
8898
8899         /*
8900          * Drop the reference on the group_event after placing the
8901          * new event on the sibling_list. This ensures destruction
8902          * of the group leader will find the pointer to itself in
8903          * perf_group_detach().
8904          */
8905         fdput(group);
8906         fd_install(event_fd, event_file);
8907         return event_fd;
8908
8909 err_locked:
8910         if (move_group)
8911                 perf_event_ctx_unlock(group_leader, gctx);
8912         mutex_unlock(&ctx->mutex);
8913 /* err_file: */
8914         fput(event_file);
8915 err_context:
8916         perf_unpin_context(ctx);
8917         put_ctx(ctx);
8918 err_alloc:
8919         /*
8920          * If event_file is set, the fput() above will have called ->release()
8921          * and that will take care of freeing the event.
8922          */
8923         if (!event_file)
8924                 free_event(event);
8925 err_cred:
8926         if (task)
8927                 mutex_unlock(&task->signal->cred_guard_mutex);
8928 err_cpus:
8929         put_online_cpus();
8930 err_task:
8931         if (task)
8932                 put_task_struct(task);
8933 err_group_fd:
8934         if (group_leader)
8935                 mutex_unlock(&group_leader->group_leader_mutex);
8936         fdput(group);
8937 err_fd:
8938         put_unused_fd(event_fd);
8939         return err;
8940 }
8941
8942 /**
8943  * perf_event_create_kernel_counter
8944  *
8945  * @attr: attributes of the counter to create
8946  * @cpu: cpu in which the counter is bound
8947  * @task: task to profile (NULL for percpu)
8948  */
8949 struct perf_event *
8950 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
8951                                  struct task_struct *task,
8952                                  perf_overflow_handler_t overflow_handler,
8953                                  void *context)
8954 {
8955         struct perf_event_context *ctx;
8956         struct perf_event *event;
8957         int err;
8958
8959         /*
8960          * Get the target context (task or percpu):
8961          */
8962
8963         event = perf_event_alloc(attr, cpu, task, NULL, NULL,
8964                                  overflow_handler, context, -1);
8965         if (IS_ERR(event)) {
8966                 err = PTR_ERR(event);
8967                 goto err;
8968         }
8969
8970         /* Mark owner so we could distinguish it from user events. */
8971         event->owner = EVENT_OWNER_KERNEL;
8972
8973         ctx = find_get_context(event->pmu, task, event);
8974         if (IS_ERR(ctx)) {
8975                 err = PTR_ERR(ctx);
8976                 goto err_free;
8977         }
8978
8979         WARN_ON_ONCE(ctx->parent_ctx);
8980         mutex_lock(&ctx->mutex);
8981         if (!exclusive_event_installable(event, ctx)) {
8982                 mutex_unlock(&ctx->mutex);
8983                 perf_unpin_context(ctx);
8984                 put_ctx(ctx);
8985                 err = -EBUSY;
8986                 goto err_free;
8987         }
8988
8989         perf_install_in_context(ctx, event, event->cpu);
8990         perf_unpin_context(ctx);
8991         mutex_unlock(&ctx->mutex);
8992
8993         return event;
8994
8995 err_free:
8996         free_event(event);
8997 err:
8998         return ERR_PTR(err);
8999 }
9000 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
9001
9002 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
9003 {
9004         struct perf_event_context *src_ctx;
9005         struct perf_event_context *dst_ctx;
9006         struct perf_event *event, *tmp;
9007         LIST_HEAD(events);
9008
9009         src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
9010         dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
9011
9012         /*
9013          * See perf_event_ctx_lock() for comments on the details
9014          * of swizzling perf_event::ctx.
9015          */
9016         mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
9017         list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
9018                                  event_entry) {
9019                 perf_remove_from_context(event, false);
9020                 unaccount_event_cpu(event, src_cpu);
9021                 put_ctx(src_ctx);
9022                 list_add(&event->migrate_entry, &events);
9023         }
9024
9025         /*
9026          * Wait for the events to quiesce before re-instating them.
9027          */
9028         synchronize_rcu();
9029
9030         /*
9031          * Re-instate events in 2 passes.
9032          *
9033          * Skip over group leaders and only install siblings on this first
9034          * pass, siblings will not get enabled without a leader, however a
9035          * leader will enable its siblings, even if those are still on the old
9036          * context.
9037          */
9038         list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
9039                 if (event->group_leader == event)
9040                         continue;
9041
9042                 list_del(&event->migrate_entry);
9043                 if (event->state >= PERF_EVENT_STATE_OFF)
9044                         event->state = PERF_EVENT_STATE_INACTIVE;
9045                 account_event_cpu(event, dst_cpu);
9046                 perf_install_in_context(dst_ctx, event, dst_cpu);
9047                 get_ctx(dst_ctx);
9048         }
9049
9050         /*
9051          * Once all the siblings are setup properly, install the group leaders
9052          * to make it go.
9053          */
9054         list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
9055                 list_del(&event->migrate_entry);
9056                 if (event->state >= PERF_EVENT_STATE_OFF)
9057                         event->state = PERF_EVENT_STATE_INACTIVE;
9058                 account_event_cpu(event, dst_cpu);
9059                 perf_install_in_context(dst_ctx, event, dst_cpu);
9060                 get_ctx(dst_ctx);
9061         }
9062         mutex_unlock(&dst_ctx->mutex);
9063         mutex_unlock(&src_ctx->mutex);
9064 }
9065 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
9066
9067 static void sync_child_event(struct perf_event *child_event,
9068                                struct task_struct *child)
9069 {
9070         struct perf_event *parent_event = child_event->parent;
9071         u64 child_val;
9072
9073         if (child_event->attr.inherit_stat)
9074                 perf_event_read_event(child_event, child);
9075
9076         child_val = perf_event_count(child_event);
9077
9078         /*
9079          * Add back the child's count to the parent's count:
9080          */
9081         atomic64_add(child_val, &parent_event->child_count);
9082         atomic64_add(child_event->total_time_enabled,
9083                      &parent_event->child_total_time_enabled);
9084         atomic64_add(child_event->total_time_running,
9085                      &parent_event->child_total_time_running);
9086
9087         /*
9088          * Remove this event from the parent's list
9089          */
9090         WARN_ON_ONCE(parent_event->ctx->parent_ctx);
9091         mutex_lock(&parent_event->child_mutex);
9092         list_del_init(&child_event->child_list);
9093         mutex_unlock(&parent_event->child_mutex);
9094
9095         /*
9096          * Make sure user/parent get notified, that we just
9097          * lost one event.
9098          */
9099         perf_event_wakeup(parent_event);
9100
9101         /*
9102          * Release the parent event, if this was the last
9103          * reference to it.
9104          */
9105         put_event(parent_event);
9106 }
9107
9108 static void
9109 __perf_event_exit_task(struct perf_event *child_event,
9110                          struct perf_event_context *child_ctx,
9111                          struct task_struct *child)
9112 {
9113         /*
9114          * Do not destroy the 'original' grouping; because of the context
9115          * switch optimization the original events could've ended up in a
9116          * random child task.
9117          *
9118          * If we were to destroy the original group, all group related
9119          * operations would cease to function properly after this random
9120          * child dies.
9121          *
9122          * Do destroy all inherited groups, we don't care about those
9123          * and being thorough is better.
9124          */
9125         perf_remove_from_context(child_event, !!child_event->parent);
9126
9127         /*
9128          * It can happen that the parent exits first, and has events
9129          * that are still around due to the child reference. These
9130          * events need to be zapped.
9131          */
9132         if (child_event->parent) {
9133                 sync_child_event(child_event, child);
9134                 free_event(child_event);
9135         } else {
9136                 child_event->state = PERF_EVENT_STATE_EXIT;
9137                 perf_event_wakeup(child_event);
9138         }
9139 }
9140
9141 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
9142 {
9143         struct perf_event *child_event, *next;
9144         struct perf_event_context *child_ctx, *clone_ctx = NULL;
9145         unsigned long flags;
9146
9147         if (likely(!child->perf_event_ctxp[ctxn]))
9148                 return;
9149
9150         local_irq_save(flags);
9151         /*
9152          * We can't reschedule here because interrupts are disabled,
9153          * and either child is current or it is a task that can't be
9154          * scheduled, so we are now safe from rescheduling changing
9155          * our context.
9156          */
9157         child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
9158
9159         /*
9160          * Take the context lock here so that if find_get_context is
9161          * reading child->perf_event_ctxp, we wait until it has
9162          * incremented the context's refcount before we do put_ctx below.
9163          */
9164         raw_spin_lock(&child_ctx->lock);
9165         task_ctx_sched_out(child_ctx);
9166         child->perf_event_ctxp[ctxn] = NULL;
9167
9168         /*
9169          * If this context is a clone; unclone it so it can't get
9170          * swapped to another process while we're removing all
9171          * the events from it.
9172          */
9173         clone_ctx = unclone_ctx(child_ctx);
9174         update_context_time(child_ctx);
9175         raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
9176
9177         if (clone_ctx)
9178                 put_ctx(clone_ctx);
9179
9180         /*
9181          * Report the task dead after unscheduling the events so that we
9182          * won't get any samples after PERF_RECORD_EXIT. We can however still
9183          * get a few PERF_RECORD_READ events.
9184          */
9185         perf_event_task(child, child_ctx, 0);
9186
9187         /*
9188          * We can recurse on the same lock type through:
9189          *
9190          *   __perf_event_exit_task()
9191          *     sync_child_event()
9192          *       put_event()
9193          *         mutex_lock(&ctx->mutex)
9194          *
9195          * But since its the parent context it won't be the same instance.
9196          */
9197         mutex_lock(&child_ctx->mutex);
9198
9199         list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
9200                 __perf_event_exit_task(child_event, child_ctx, child);
9201
9202         mutex_unlock(&child_ctx->mutex);
9203
9204         put_ctx(child_ctx);
9205 }
9206
9207 /*
9208  * When a child task exits, feed back event values to parent events.
9209  *
9210  * Can be called with cred_guard_mutex held when called from
9211  * install_exec_creds().
9212  */
9213 void perf_event_exit_task(struct task_struct *child)
9214 {
9215         struct perf_event *event, *tmp;
9216         int ctxn;
9217
9218         mutex_lock(&child->perf_event_mutex);
9219         list_for_each_entry_safe(event, tmp, &child->perf_event_list,
9220                                  owner_entry) {
9221                 list_del_init(&event->owner_entry);
9222
9223                 /*
9224                  * Ensure the list deletion is visible before we clear
9225                  * the owner, closes a race against perf_release() where
9226                  * we need to serialize on the owner->perf_event_mutex.
9227                  */
9228                 smp_wmb();
9229                 event->owner = NULL;
9230         }
9231         mutex_unlock(&child->perf_event_mutex);
9232
9233         for_each_task_context_nr(ctxn)
9234                 perf_event_exit_task_context(child, ctxn);
9235
9236         /*
9237          * The perf_event_exit_task_context calls perf_event_task
9238          * with child's task_ctx, which generates EXIT events for
9239          * child contexts and sets child->perf_event_ctxp[] to NULL.
9240          * At this point we need to send EXIT events to cpu contexts.
9241          */
9242         perf_event_task(child, NULL, 0);
9243 }
9244
9245 static void perf_free_event(struct perf_event *event,
9246                             struct perf_event_context *ctx)
9247 {
9248         struct perf_event *parent = event->parent;
9249
9250         if (WARN_ON_ONCE(!parent))
9251                 return;
9252
9253         mutex_lock(&parent->child_mutex);
9254         list_del_init(&event->child_list);
9255         mutex_unlock(&parent->child_mutex);
9256
9257         put_event(parent);
9258
9259         raw_spin_lock_irq(&ctx->lock);
9260         perf_group_detach(event);
9261         list_del_event(event, ctx);
9262         raw_spin_unlock_irq(&ctx->lock);
9263         free_event(event);
9264 }
9265
9266 /*
9267  * Free an unexposed, unused context as created by inheritance by
9268  * perf_event_init_task below, used by fork() in case of fail.
9269  *
9270  * Not all locks are strictly required, but take them anyway to be nice and
9271  * help out with the lockdep assertions.
9272  */
9273 void perf_event_free_task(struct task_struct *task)
9274 {
9275         struct perf_event_context *ctx;
9276         struct perf_event *event, *tmp;
9277         int ctxn;
9278
9279         for_each_task_context_nr(ctxn) {
9280                 ctx = task->perf_event_ctxp[ctxn];
9281                 if (!ctx)
9282                         continue;
9283
9284                 mutex_lock(&ctx->mutex);
9285 again:
9286                 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
9287                                 group_entry)
9288                         perf_free_event(event, ctx);
9289
9290                 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
9291                                 group_entry)
9292                         perf_free_event(event, ctx);
9293
9294                 if (!list_empty(&ctx->pinned_groups) ||
9295                                 !list_empty(&ctx->flexible_groups))
9296                         goto again;
9297
9298                 mutex_unlock(&ctx->mutex);
9299
9300                 put_ctx(ctx);
9301         }
9302 }
9303
9304 void perf_event_delayed_put(struct task_struct *task)
9305 {
9306         int ctxn;
9307
9308         for_each_task_context_nr(ctxn)
9309                 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
9310 }
9311
9312 struct perf_event *perf_event_get(unsigned int fd)
9313 {
9314         int err;
9315         struct fd f;
9316         struct perf_event *event;
9317
9318         err = perf_fget_light(fd, &f);
9319         if (err)
9320                 return ERR_PTR(err);
9321
9322         event = f.file->private_data;
9323         atomic_long_inc(&event->refcount);
9324         fdput(f);
9325
9326         return event;
9327 }
9328
9329 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
9330 {
9331         if (!event)
9332                 return ERR_PTR(-EINVAL);
9333
9334         return &event->attr;
9335 }
9336
9337 /*
9338  * inherit a event from parent task to child task:
9339  */
9340 static struct perf_event *
9341 inherit_event(struct perf_event *parent_event,
9342               struct task_struct *parent,
9343               struct perf_event_context *parent_ctx,
9344               struct task_struct *child,
9345               struct perf_event *group_leader,
9346               struct perf_event_context *child_ctx)
9347 {
9348         enum perf_event_active_state parent_state = parent_event->state;
9349         struct perf_event *child_event;
9350         unsigned long flags;
9351
9352         /*
9353          * Instead of creating recursive hierarchies of events,
9354          * we link inherited events back to the original parent,
9355          * which has a filp for sure, which we use as the reference
9356          * count:
9357          */
9358         if (parent_event->parent)
9359                 parent_event = parent_event->parent;
9360
9361         child_event = perf_event_alloc(&parent_event->attr,
9362                                            parent_event->cpu,
9363                                            child,
9364                                            group_leader, parent_event,
9365                                            NULL, NULL, -1);
9366         if (IS_ERR(child_event))
9367                 return child_event;
9368
9369         if (is_orphaned_event(parent_event) ||
9370             !atomic_long_inc_not_zero(&parent_event->refcount)) {
9371                 free_event(child_event);
9372                 return NULL;
9373         }
9374
9375         get_ctx(child_ctx);
9376
9377         /*
9378          * Make the child state follow the state of the parent event,
9379          * not its attr.disabled bit.  We hold the parent's mutex,
9380          * so we won't race with perf_event_{en, dis}able_family.
9381          */
9382         if (parent_state >= PERF_EVENT_STATE_INACTIVE)
9383                 child_event->state = PERF_EVENT_STATE_INACTIVE;
9384         else
9385                 child_event->state = PERF_EVENT_STATE_OFF;
9386
9387         if (parent_event->attr.freq) {
9388                 u64 sample_period = parent_event->hw.sample_period;
9389                 struct hw_perf_event *hwc = &child_event->hw;
9390
9391                 hwc->sample_period = sample_period;
9392                 hwc->last_period   = sample_period;
9393
9394                 local64_set(&hwc->period_left, sample_period);
9395         }
9396
9397         child_event->ctx = child_ctx;
9398         child_event->overflow_handler = parent_event->overflow_handler;
9399         child_event->overflow_handler_context
9400                 = parent_event->overflow_handler_context;
9401
9402         /*
9403          * Precalculate sample_data sizes
9404          */
9405         perf_event__header_size(child_event);
9406         perf_event__id_header_size(child_event);
9407
9408         /*
9409          * Link it up in the child's context:
9410          */
9411         raw_spin_lock_irqsave(&child_ctx->lock, flags);
9412         add_event_to_ctx(child_event, child_ctx);
9413         raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
9414
9415         /*
9416          * Link this into the parent event's child list
9417          */
9418         WARN_ON_ONCE(parent_event->ctx->parent_ctx);
9419         mutex_lock(&parent_event->child_mutex);
9420         list_add_tail(&child_event->child_list, &parent_event->child_list);
9421         mutex_unlock(&parent_event->child_mutex);
9422
9423         return child_event;
9424 }
9425
9426 static int inherit_group(struct perf_event *parent_event,
9427               struct task_struct *parent,
9428               struct perf_event_context *parent_ctx,
9429               struct task_struct *child,
9430               struct perf_event_context *child_ctx)
9431 {
9432         struct perf_event *leader;
9433         struct perf_event *sub;
9434         struct perf_event *child_ctr;
9435
9436         leader = inherit_event(parent_event, parent, parent_ctx,
9437                                  child, NULL, child_ctx);
9438         if (IS_ERR(leader))
9439                 return PTR_ERR(leader);
9440         list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
9441                 child_ctr = inherit_event(sub, parent, parent_ctx,
9442                                             child, leader, child_ctx);
9443                 if (IS_ERR(child_ctr))
9444                         return PTR_ERR(child_ctr);
9445         }
9446         return 0;
9447 }
9448
9449 static int
9450 inherit_task_group(struct perf_event *event, struct task_struct *parent,
9451                    struct perf_event_context *parent_ctx,
9452                    struct task_struct *child, int ctxn,
9453                    int *inherited_all)
9454 {
9455         int ret;
9456         struct perf_event_context *child_ctx;
9457
9458         if (!event->attr.inherit) {
9459                 *inherited_all = 0;
9460                 return 0;
9461         }
9462
9463         child_ctx = child->perf_event_ctxp[ctxn];
9464         if (!child_ctx) {
9465                 /*
9466                  * This is executed from the parent task context, so
9467                  * inherit events that have been marked for cloning.
9468                  * First allocate and initialize a context for the
9469                  * child.
9470                  */
9471
9472                 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
9473                 if (!child_ctx)
9474                         return -ENOMEM;
9475
9476                 child->perf_event_ctxp[ctxn] = child_ctx;
9477         }
9478
9479         ret = inherit_group(event, parent, parent_ctx,
9480                             child, child_ctx);
9481
9482         if (ret)
9483                 *inherited_all = 0;
9484
9485         return ret;
9486 }
9487
9488 /*
9489  * Initialize the perf_event context in task_struct
9490  */
9491 static int perf_event_init_context(struct task_struct *child, int ctxn)
9492 {
9493         struct perf_event_context *child_ctx, *parent_ctx;
9494         struct perf_event_context *cloned_ctx;
9495         struct perf_event *event;
9496         struct task_struct *parent = current;
9497         int inherited_all = 1;
9498         unsigned long flags;
9499         int ret = 0;
9500
9501         if (likely(!parent->perf_event_ctxp[ctxn]))
9502                 return 0;
9503
9504         /*
9505          * If the parent's context is a clone, pin it so it won't get
9506          * swapped under us.
9507          */
9508         parent_ctx = perf_pin_task_context(parent, ctxn);
9509         if (!parent_ctx)
9510                 return 0;
9511
9512         /*
9513          * No need to check if parent_ctx != NULL here; since we saw
9514          * it non-NULL earlier, the only reason for it to become NULL
9515          * is if we exit, and since we're currently in the middle of
9516          * a fork we can't be exiting at the same time.
9517          */
9518
9519         /*
9520          * Lock the parent list. No need to lock the child - not PID
9521          * hashed yet and not running, so nobody can access it.
9522          */
9523         mutex_lock(&parent_ctx->mutex);
9524
9525         /*
9526          * We dont have to disable NMIs - we are only looking at
9527          * the list, not manipulating it:
9528          */
9529         list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
9530                 ret = inherit_task_group(event, parent, parent_ctx,
9531                                          child, ctxn, &inherited_all);
9532                 if (ret)
9533                         goto out_unlock;
9534         }
9535
9536         /*
9537          * We can't hold ctx->lock when iterating the ->flexible_group list due
9538          * to allocations, but we need to prevent rotation because
9539          * rotate_ctx() will change the list from interrupt context.
9540          */
9541         raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9542         parent_ctx->rotate_disable = 1;
9543         raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
9544
9545         list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
9546                 ret = inherit_task_group(event, parent, parent_ctx,
9547                                          child, ctxn, &inherited_all);
9548                 if (ret)
9549                         goto out_unlock;
9550         }
9551
9552         raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9553         parent_ctx->rotate_disable = 0;
9554
9555         child_ctx = child->perf_event_ctxp[ctxn];
9556
9557         if (child_ctx && inherited_all) {
9558                 /*
9559                  * Mark the child context as a clone of the parent
9560                  * context, or of whatever the parent is a clone of.
9561                  *
9562                  * Note that if the parent is a clone, the holding of
9563                  * parent_ctx->lock avoids it from being uncloned.
9564                  */
9565                 cloned_ctx = parent_ctx->parent_ctx;
9566                 if (cloned_ctx) {
9567                         child_ctx->parent_ctx = cloned_ctx;
9568                         child_ctx->parent_gen = parent_ctx->parent_gen;
9569                 } else {
9570                         child_ctx->parent_ctx = parent_ctx;
9571                         child_ctx->parent_gen = parent_ctx->generation;
9572                 }
9573                 get_ctx(child_ctx->parent_ctx);
9574         }
9575
9576         raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
9577 out_unlock:
9578         mutex_unlock(&parent_ctx->mutex);
9579
9580         perf_unpin_context(parent_ctx);
9581         put_ctx(parent_ctx);
9582
9583         return ret;
9584 }
9585
9586 /*
9587  * Initialize the perf_event context in task_struct
9588  */
9589 int perf_event_init_task(struct task_struct *child)
9590 {
9591         int ctxn, ret;
9592
9593         memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
9594         mutex_init(&child->perf_event_mutex);
9595         INIT_LIST_HEAD(&child->perf_event_list);
9596
9597         for_each_task_context_nr(ctxn) {
9598                 ret = perf_event_init_context(child, ctxn);
9599                 if (ret) {
9600                         perf_event_free_task(child);
9601                         return ret;
9602                 }
9603         }
9604
9605         return 0;
9606 }
9607
9608 static void __init perf_event_init_all_cpus(void)
9609 {
9610         struct swevent_htable *swhash;
9611         int cpu;
9612
9613         for_each_possible_cpu(cpu) {
9614                 swhash = &per_cpu(swevent_htable, cpu);
9615                 mutex_init(&swhash->hlist_mutex);
9616                 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
9617         }
9618 }
9619
9620 static void perf_event_init_cpu(int cpu)
9621 {
9622         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9623
9624         mutex_lock(&swhash->hlist_mutex);
9625         if (swhash->hlist_refcount > 0) {
9626                 struct swevent_hlist *hlist;
9627
9628                 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
9629                 WARN_ON(!hlist);
9630                 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9631         }
9632         mutex_unlock(&swhash->hlist_mutex);
9633 }
9634
9635 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
9636 static void __perf_event_exit_context(void *__info)
9637 {
9638         struct remove_event re = { .detach_group = true };
9639         struct perf_event_context *ctx = __info;
9640
9641         rcu_read_lock();
9642         list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
9643                 __perf_remove_from_context(&re);
9644         rcu_read_unlock();
9645 }
9646
9647 static void __perf_event_stop_swclock(void *__info)
9648 {
9649         struct perf_event_context *ctx = __info;
9650         struct perf_event *event, *tmp;
9651
9652         list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry) {
9653                 if (event->attr.config == PERF_COUNT_SW_CPU_CLOCK &&
9654                     event->attr.type == PERF_TYPE_SOFTWARE)
9655                         cpu_clock_event_stop(event, 0);
9656         }
9657 }
9658
9659 static void perf_event_exit_cpu_context(int cpu)
9660 {
9661         struct perf_cpu_context *cpuctx;
9662         struct perf_event_context *ctx;
9663         unsigned long flags;
9664         struct pmu *pmu;
9665         int idx;
9666
9667         idx = srcu_read_lock(&pmus_srcu);
9668         list_for_each_entry_rcu(pmu, &pmus, entry) {
9669                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
9670                 ctx = &cpuctx->ctx;
9671
9672                 /* Cancel the mux hrtimer to avoid CPU migration */
9673                 if (pmu->task_ctx_nr != perf_sw_context) {
9674                         raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
9675                         hrtimer_cancel(&cpuctx->hrtimer);
9676                         cpuctx->hrtimer_active = 0;
9677                         raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock,
9678                                                         flags);
9679                 }
9680
9681                 mutex_lock(&ctx->mutex);
9682                 /*
9683                  * If keeping events across hotplugging is supported, do not
9684                  * remove the event list, but keep it alive across CPU hotplug.
9685                  * The context is exited via an fd close path when userspace
9686                  * is done and the target CPU is online. If software clock
9687                  * event is active, then stop hrtimer associated with it.
9688                  * Start the timer when the CPU comes back online.
9689                  */
9690                 if (!pmu->events_across_hotplug)
9691                         smp_call_function_single(cpu, __perf_event_exit_context,
9692                                                  ctx, 1);
9693                 else
9694                         smp_call_function_single(cpu, __perf_event_stop_swclock,
9695                                                  ctx, 1);
9696                 mutex_unlock(&ctx->mutex);
9697         }
9698         srcu_read_unlock(&pmus_srcu, idx);
9699 }
9700
9701 static void perf_event_start_swclock(int cpu)
9702 {
9703         struct perf_event_context *ctx;
9704         struct pmu *pmu;
9705         int idx;
9706         struct perf_event *event, *tmp;
9707
9708         idx = srcu_read_lock(&pmus_srcu);
9709         list_for_each_entry_rcu(pmu, &pmus, entry) {
9710                 if (pmu->events_across_hotplug) {
9711                         ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
9712                         list_for_each_entry_safe(event, tmp, &ctx->event_list,
9713                                                  event_entry) {
9714                                 if (event->attr.config ==
9715                                     PERF_COUNT_SW_CPU_CLOCK &&
9716                                     event->attr.type == PERF_TYPE_SOFTWARE)
9717                                         cpu_clock_event_start(event, 0);
9718                         }
9719                 }
9720         }
9721         srcu_read_unlock(&pmus_srcu, idx);
9722 }
9723
9724 static void perf_event_exit_cpu(int cpu)
9725 {
9726         perf_event_exit_cpu_context(cpu);
9727 }
9728 #else
9729 static inline void perf_event_exit_cpu(int cpu) { }
9730 static inline void perf_event_start_swclock(int cpu) { }
9731 #endif
9732
9733 static int
9734 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
9735 {
9736         int cpu;
9737
9738         for_each_online_cpu(cpu)
9739                 perf_event_exit_cpu(cpu);
9740
9741         return NOTIFY_OK;
9742 }
9743
9744 /*
9745  * Run the perf reboot notifier at the very last possible moment so that
9746  * the generic watchdog code runs as long as possible.
9747  */
9748 static struct notifier_block perf_reboot_notifier = {
9749         .notifier_call = perf_reboot,
9750         .priority = INT_MIN,
9751 };
9752
9753 static int
9754 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
9755 {
9756         unsigned int cpu = (long)hcpu;
9757
9758         switch (action & ~CPU_TASKS_FROZEN) {
9759
9760         case CPU_UP_PREPARE:
9761         case CPU_DOWN_FAILED:
9762                 perf_event_init_cpu(cpu);
9763                 break;
9764
9765         case CPU_UP_CANCELED:
9766         case CPU_DOWN_PREPARE:
9767                 perf_event_exit_cpu(cpu);
9768                 break;
9769
9770         case CPU_STARTING:
9771                 perf_event_start_swclock(cpu);
9772                 break;
9773
9774         default:
9775                 break;
9776         }
9777
9778         return NOTIFY_OK;
9779 }
9780
9781 static int event_idle_notif(struct notifier_block *nb, unsigned long action,
9782                                                         void *data)
9783 {
9784         switch (action) {
9785         case IDLE_START:
9786                 __this_cpu_write(is_idle, true);
9787                 break;
9788         case IDLE_END:
9789                 __this_cpu_write(is_idle, false);
9790                 break;
9791         }
9792
9793         return NOTIFY_OK;
9794 }
9795
9796 static struct notifier_block perf_event_idle_nb = {
9797         .notifier_call = event_idle_notif,
9798 };
9799
9800 void __init perf_event_init(void)
9801 {
9802         int ret;
9803
9804         idr_init(&pmu_idr);
9805
9806         perf_event_init_all_cpus();
9807         init_srcu_struct(&pmus_srcu);
9808         perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
9809         perf_pmu_register(&perf_cpu_clock, NULL, -1);
9810         perf_pmu_register(&perf_task_clock, NULL, -1);
9811         perf_tp_register();
9812         perf_cpu_notifier(perf_cpu_notify);
9813         idle_notifier_register(&perf_event_idle_nb);
9814         register_reboot_notifier(&perf_reboot_notifier);
9815
9816         ret = init_hw_breakpoint();
9817         WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
9818
9819         /* do not patch jump label more than once per second */
9820         jump_label_rate_limit(&perf_sched_events, HZ);
9821
9822         /*
9823          * Build time assertion that we keep the data_head at the intended
9824          * location.  IOW, validation we got the __reserved[] size right.
9825          */
9826         BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
9827                      != 1024);
9828 }
9829
9830 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
9831                               char *page)
9832 {
9833         struct perf_pmu_events_attr *pmu_attr =
9834                 container_of(attr, struct perf_pmu_events_attr, attr);
9835
9836         if (pmu_attr->event_str)
9837                 return sprintf(page, "%s\n", pmu_attr->event_str);
9838
9839         return 0;
9840 }
9841
9842 static int __init perf_event_sysfs_init(void)
9843 {
9844         struct pmu *pmu;
9845         int ret;
9846
9847         mutex_lock(&pmus_lock);
9848
9849         ret = bus_register(&pmu_bus);
9850         if (ret)
9851                 goto unlock;
9852
9853         list_for_each_entry(pmu, &pmus, entry) {
9854                 if (!pmu->name || pmu->type < 0)
9855                         continue;
9856
9857                 ret = pmu_dev_alloc(pmu);
9858                 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
9859         }
9860         pmu_bus_running = 1;
9861         ret = 0;
9862
9863 unlock:
9864         mutex_unlock(&pmus_lock);
9865
9866         return ret;
9867 }
9868 device_initcall(perf_event_sysfs_init);
9869
9870 #ifdef CONFIG_CGROUP_PERF
9871 static struct cgroup_subsys_state *
9872 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
9873 {
9874         struct perf_cgroup *jc;
9875
9876         jc = kzalloc(sizeof(*jc), GFP_KERNEL);
9877         if (!jc)
9878                 return ERR_PTR(-ENOMEM);
9879
9880         jc->info = alloc_percpu(struct perf_cgroup_info);
9881         if (!jc->info) {
9882                 kfree(jc);
9883                 return ERR_PTR(-ENOMEM);
9884         }
9885
9886         return &jc->css;
9887 }
9888
9889 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
9890 {
9891         struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
9892
9893         free_percpu(jc->info);
9894         kfree(jc);
9895 }
9896
9897 static int __perf_cgroup_move(void *info)
9898 {
9899         struct task_struct *task = info;
9900         rcu_read_lock();
9901         perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
9902         rcu_read_unlock();
9903         return 0;
9904 }
9905
9906 static void perf_cgroup_attach(struct cgroup_taskset *tset)
9907 {
9908         struct task_struct *task;
9909         struct cgroup_subsys_state *css;
9910
9911         cgroup_taskset_for_each(task, css, tset)
9912                 task_function_call(task, __perf_cgroup_move, task);
9913 }
9914
9915 struct cgroup_subsys perf_event_cgrp_subsys = {
9916         .css_alloc      = perf_cgroup_css_alloc,
9917         .css_free       = perf_cgroup_css_free,
9918         .attach         = perf_cgroup_attach,
9919 };
9920 #endif /* CONFIG_CGROUP_PERF */