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