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