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