perf/core: Save the dynamic parts of sample data size
[platform/kernel/linux-starfive.git] / kernel / events / core.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Performance events core code:
4  *
5  *  Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
6  *  Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
7  *  Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
8  *  Copyright  ©  2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
9  */
10
11 #include <linux/fs.h>
12 #include <linux/mm.h>
13 #include <linux/cpu.h>
14 #include <linux/smp.h>
15 #include <linux/idr.h>
16 #include <linux/file.h>
17 #include <linux/poll.h>
18 #include <linux/slab.h>
19 #include <linux/hash.h>
20 #include <linux/tick.h>
21 #include <linux/sysfs.h>
22 #include <linux/dcache.h>
23 #include <linux/percpu.h>
24 #include <linux/ptrace.h>
25 #include <linux/reboot.h>
26 #include <linux/vmstat.h>
27 #include <linux/device.h>
28 #include <linux/export.h>
29 #include <linux/vmalloc.h>
30 #include <linux/hardirq.h>
31 #include <linux/hugetlb.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 #include <linux/sched/clock.h>
50 #include <linux/sched/mm.h>
51 #include <linux/proc_ns.h>
52 #include <linux/mount.h>
53 #include <linux/min_heap.h>
54 #include <linux/highmem.h>
55 #include <linux/pgtable.h>
56 #include <linux/buildid.h>
57 #include <linux/task_work.h>
58
59 #include "internal.h"
60
61 #include <asm/irq_regs.h>
62
63 typedef int (*remote_function_f)(void *);
64
65 struct remote_function_call {
66         struct task_struct      *p;
67         remote_function_f       func;
68         void                    *info;
69         int                     ret;
70 };
71
72 static void remote_function(void *data)
73 {
74         struct remote_function_call *tfc = data;
75         struct task_struct *p = tfc->p;
76
77         if (p) {
78                 /* -EAGAIN */
79                 if (task_cpu(p) != smp_processor_id())
80                         return;
81
82                 /*
83                  * Now that we're on right CPU with IRQs disabled, we can test
84                  * if we hit the right task without races.
85                  */
86
87                 tfc->ret = -ESRCH; /* No such (running) process */
88                 if (p != current)
89                         return;
90         }
91
92         tfc->ret = tfc->func(tfc->info);
93 }
94
95 /**
96  * task_function_call - call a function on the cpu on which a task runs
97  * @p:          the task to evaluate
98  * @func:       the function to be called
99  * @info:       the function call argument
100  *
101  * Calls the function @func when the task is currently running. This might
102  * be on the current CPU, which just calls the function directly.  This will
103  * retry due to any failures in smp_call_function_single(), such as if the
104  * task_cpu() goes offline concurrently.
105  *
106  * returns @func return value or -ESRCH or -ENXIO when the process isn't running
107  */
108 static int
109 task_function_call(struct task_struct *p, remote_function_f func, void *info)
110 {
111         struct remote_function_call data = {
112                 .p      = p,
113                 .func   = func,
114                 .info   = info,
115                 .ret    = -EAGAIN,
116         };
117         int ret;
118
119         for (;;) {
120                 ret = smp_call_function_single(task_cpu(p), remote_function,
121                                                &data, 1);
122                 if (!ret)
123                         ret = data.ret;
124
125                 if (ret != -EAGAIN)
126                         break;
127
128                 cond_resched();
129         }
130
131         return ret;
132 }
133
134 /**
135  * cpu_function_call - call a function on the cpu
136  * @cpu:        target cpu to queue this function
137  * @func:       the function to be called
138  * @info:       the function call argument
139  *
140  * Calls the function @func on the remote cpu.
141  *
142  * returns: @func return value or -ENXIO when the cpu is offline
143  */
144 static int cpu_function_call(int cpu, remote_function_f func, void *info)
145 {
146         struct remote_function_call data = {
147                 .p      = NULL,
148                 .func   = func,
149                 .info   = info,
150                 .ret    = -ENXIO, /* No such CPU */
151         };
152
153         smp_call_function_single(cpu, remote_function, &data, 1);
154
155         return data.ret;
156 }
157
158 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
159                           struct perf_event_context *ctx)
160 {
161         raw_spin_lock(&cpuctx->ctx.lock);
162         if (ctx)
163                 raw_spin_lock(&ctx->lock);
164 }
165
166 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
167                             struct perf_event_context *ctx)
168 {
169         if (ctx)
170                 raw_spin_unlock(&ctx->lock);
171         raw_spin_unlock(&cpuctx->ctx.lock);
172 }
173
174 #define TASK_TOMBSTONE ((void *)-1L)
175
176 static bool is_kernel_event(struct perf_event *event)
177 {
178         return READ_ONCE(event->owner) == TASK_TOMBSTONE;
179 }
180
181 static DEFINE_PER_CPU(struct perf_cpu_context, perf_cpu_context);
182
183 struct perf_event_context *perf_cpu_task_ctx(void)
184 {
185         lockdep_assert_irqs_disabled();
186         return this_cpu_ptr(&perf_cpu_context)->task_ctx;
187 }
188
189 /*
190  * On task ctx scheduling...
191  *
192  * When !ctx->nr_events a task context will not be scheduled. This means
193  * we can disable the scheduler hooks (for performance) without leaving
194  * pending task ctx state.
195  *
196  * This however results in two special cases:
197  *
198  *  - removing the last event from a task ctx; this is relatively straight
199  *    forward and is done in __perf_remove_from_context.
200  *
201  *  - adding the first event to a task ctx; this is tricky because we cannot
202  *    rely on ctx->is_active and therefore cannot use event_function_call().
203  *    See perf_install_in_context().
204  *
205  * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
206  */
207
208 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
209                         struct perf_event_context *, void *);
210
211 struct event_function_struct {
212         struct perf_event *event;
213         event_f func;
214         void *data;
215 };
216
217 static int event_function(void *info)
218 {
219         struct event_function_struct *efs = info;
220         struct perf_event *event = efs->event;
221         struct perf_event_context *ctx = event->ctx;
222         struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
223         struct perf_event_context *task_ctx = cpuctx->task_ctx;
224         int ret = 0;
225
226         lockdep_assert_irqs_disabled();
227
228         perf_ctx_lock(cpuctx, task_ctx);
229         /*
230          * Since we do the IPI call without holding ctx->lock things can have
231          * changed, double check we hit the task we set out to hit.
232          */
233         if (ctx->task) {
234                 if (ctx->task != current) {
235                         ret = -ESRCH;
236                         goto unlock;
237                 }
238
239                 /*
240                  * We only use event_function_call() on established contexts,
241                  * and event_function() is only ever called when active (or
242                  * rather, we'll have bailed in task_function_call() or the
243                  * above ctx->task != current test), therefore we must have
244                  * ctx->is_active here.
245                  */
246                 WARN_ON_ONCE(!ctx->is_active);
247                 /*
248                  * And since we have ctx->is_active, cpuctx->task_ctx must
249                  * match.
250                  */
251                 WARN_ON_ONCE(task_ctx != ctx);
252         } else {
253                 WARN_ON_ONCE(&cpuctx->ctx != ctx);
254         }
255
256         efs->func(event, cpuctx, ctx, efs->data);
257 unlock:
258         perf_ctx_unlock(cpuctx, task_ctx);
259
260         return ret;
261 }
262
263 static void event_function_call(struct perf_event *event, event_f func, void *data)
264 {
265         struct perf_event_context *ctx = event->ctx;
266         struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
267         struct event_function_struct efs = {
268                 .event = event,
269                 .func = func,
270                 .data = data,
271         };
272
273         if (!event->parent) {
274                 /*
275                  * If this is a !child event, we must hold ctx::mutex to
276                  * stabilize the event->ctx relation. See
277                  * perf_event_ctx_lock().
278                  */
279                 lockdep_assert_held(&ctx->mutex);
280         }
281
282         if (!task) {
283                 cpu_function_call(event->cpu, event_function, &efs);
284                 return;
285         }
286
287         if (task == TASK_TOMBSTONE)
288                 return;
289
290 again:
291         if (!task_function_call(task, event_function, &efs))
292                 return;
293
294         raw_spin_lock_irq(&ctx->lock);
295         /*
296          * Reload the task pointer, it might have been changed by
297          * a concurrent perf_event_context_sched_out().
298          */
299         task = ctx->task;
300         if (task == TASK_TOMBSTONE) {
301                 raw_spin_unlock_irq(&ctx->lock);
302                 return;
303         }
304         if (ctx->is_active) {
305                 raw_spin_unlock_irq(&ctx->lock);
306                 goto again;
307         }
308         func(event, NULL, ctx, data);
309         raw_spin_unlock_irq(&ctx->lock);
310 }
311
312 /*
313  * Similar to event_function_call() + event_function(), but hard assumes IRQs
314  * are already disabled and we're on the right CPU.
315  */
316 static void event_function_local(struct perf_event *event, event_f func, void *data)
317 {
318         struct perf_event_context *ctx = event->ctx;
319         struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
320         struct task_struct *task = READ_ONCE(ctx->task);
321         struct perf_event_context *task_ctx = NULL;
322
323         lockdep_assert_irqs_disabled();
324
325         if (task) {
326                 if (task == TASK_TOMBSTONE)
327                         return;
328
329                 task_ctx = ctx;
330         }
331
332         perf_ctx_lock(cpuctx, task_ctx);
333
334         task = ctx->task;
335         if (task == TASK_TOMBSTONE)
336                 goto unlock;
337
338         if (task) {
339                 /*
340                  * We must be either inactive or active and the right task,
341                  * otherwise we're screwed, since we cannot IPI to somewhere
342                  * else.
343                  */
344                 if (ctx->is_active) {
345                         if (WARN_ON_ONCE(task != current))
346                                 goto unlock;
347
348                         if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
349                                 goto unlock;
350                 }
351         } else {
352                 WARN_ON_ONCE(&cpuctx->ctx != ctx);
353         }
354
355         func(event, cpuctx, ctx, data);
356 unlock:
357         perf_ctx_unlock(cpuctx, task_ctx);
358 }
359
360 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
361                        PERF_FLAG_FD_OUTPUT  |\
362                        PERF_FLAG_PID_CGROUP |\
363                        PERF_FLAG_FD_CLOEXEC)
364
365 /*
366  * branch priv levels that need permission checks
367  */
368 #define PERF_SAMPLE_BRANCH_PERM_PLM \
369         (PERF_SAMPLE_BRANCH_KERNEL |\
370          PERF_SAMPLE_BRANCH_HV)
371
372 enum event_type_t {
373         EVENT_FLEXIBLE = 0x1,
374         EVENT_PINNED = 0x2,
375         EVENT_TIME = 0x4,
376         /* see ctx_resched() for details */
377         EVENT_CPU = 0x8,
378         EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
379 };
380
381 /*
382  * perf_sched_events : >0 events exist
383  */
384
385 static void perf_sched_delayed(struct work_struct *work);
386 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
387 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
388 static DEFINE_MUTEX(perf_sched_mutex);
389 static atomic_t perf_sched_count;
390
391 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
392
393 static atomic_t nr_mmap_events __read_mostly;
394 static atomic_t nr_comm_events __read_mostly;
395 static atomic_t nr_namespaces_events __read_mostly;
396 static atomic_t nr_task_events __read_mostly;
397 static atomic_t nr_freq_events __read_mostly;
398 static atomic_t nr_switch_events __read_mostly;
399 static atomic_t nr_ksymbol_events __read_mostly;
400 static atomic_t nr_bpf_events __read_mostly;
401 static atomic_t nr_cgroup_events __read_mostly;
402 static atomic_t nr_text_poke_events __read_mostly;
403 static atomic_t nr_build_id_events __read_mostly;
404
405 static LIST_HEAD(pmus);
406 static DEFINE_MUTEX(pmus_lock);
407 static struct srcu_struct pmus_srcu;
408 static cpumask_var_t perf_online_mask;
409 static struct kmem_cache *perf_event_cache;
410
411 /*
412  * perf event paranoia level:
413  *  -1 - not paranoid at all
414  *   0 - disallow raw tracepoint access for unpriv
415  *   1 - disallow cpu events for unpriv
416  *   2 - disallow kernel profiling for unpriv
417  */
418 int sysctl_perf_event_paranoid __read_mostly = 2;
419
420 /* Minimum for 512 kiB + 1 user control page */
421 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
422
423 /*
424  * max perf event sample rate
425  */
426 #define DEFAULT_MAX_SAMPLE_RATE         100000
427 #define DEFAULT_SAMPLE_PERIOD_NS        (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
428 #define DEFAULT_CPU_TIME_MAX_PERCENT    25
429
430 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
431
432 static int max_samples_per_tick __read_mostly   = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
433 static int perf_sample_period_ns __read_mostly  = DEFAULT_SAMPLE_PERIOD_NS;
434
435 static int perf_sample_allowed_ns __read_mostly =
436         DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
437
438 static void update_perf_cpu_limits(void)
439 {
440         u64 tmp = perf_sample_period_ns;
441
442         tmp *= sysctl_perf_cpu_time_max_percent;
443         tmp = div_u64(tmp, 100);
444         if (!tmp)
445                 tmp = 1;
446
447         WRITE_ONCE(perf_sample_allowed_ns, tmp);
448 }
449
450 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc);
451
452 int perf_proc_update_handler(struct ctl_table *table, int write,
453                 void *buffer, size_t *lenp, loff_t *ppos)
454 {
455         int ret;
456         int perf_cpu = sysctl_perf_cpu_time_max_percent;
457         /*
458          * If throttling is disabled don't allow the write:
459          */
460         if (write && (perf_cpu == 100 || perf_cpu == 0))
461                 return -EINVAL;
462
463         ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
464         if (ret || !write)
465                 return ret;
466
467         max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
468         perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
469         update_perf_cpu_limits();
470
471         return 0;
472 }
473
474 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
475
476 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
477                 void *buffer, size_t *lenp, loff_t *ppos)
478 {
479         int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
480
481         if (ret || !write)
482                 return ret;
483
484         if (sysctl_perf_cpu_time_max_percent == 100 ||
485             sysctl_perf_cpu_time_max_percent == 0) {
486                 printk(KERN_WARNING
487                        "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
488                 WRITE_ONCE(perf_sample_allowed_ns, 0);
489         } else {
490                 update_perf_cpu_limits();
491         }
492
493         return 0;
494 }
495
496 /*
497  * perf samples are done in some very critical code paths (NMIs).
498  * If they take too much CPU time, the system can lock up and not
499  * get any real work done.  This will drop the sample rate when
500  * we detect that events are taking too long.
501  */
502 #define NR_ACCUMULATED_SAMPLES 128
503 static DEFINE_PER_CPU(u64, running_sample_length);
504
505 static u64 __report_avg;
506 static u64 __report_allowed;
507
508 static void perf_duration_warn(struct irq_work *w)
509 {
510         printk_ratelimited(KERN_INFO
511                 "perf: interrupt took too long (%lld > %lld), lowering "
512                 "kernel.perf_event_max_sample_rate to %d\n",
513                 __report_avg, __report_allowed,
514                 sysctl_perf_event_sample_rate);
515 }
516
517 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
518
519 void perf_sample_event_took(u64 sample_len_ns)
520 {
521         u64 max_len = READ_ONCE(perf_sample_allowed_ns);
522         u64 running_len;
523         u64 avg_len;
524         u32 max;
525
526         if (max_len == 0)
527                 return;
528
529         /* Decay the counter by 1 average sample. */
530         running_len = __this_cpu_read(running_sample_length);
531         running_len -= running_len/NR_ACCUMULATED_SAMPLES;
532         running_len += sample_len_ns;
533         __this_cpu_write(running_sample_length, running_len);
534
535         /*
536          * Note: this will be biased artifically low until we have
537          * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
538          * from having to maintain a count.
539          */
540         avg_len = running_len/NR_ACCUMULATED_SAMPLES;
541         if (avg_len <= max_len)
542                 return;
543
544         __report_avg = avg_len;
545         __report_allowed = max_len;
546
547         /*
548          * Compute a throttle threshold 25% below the current duration.
549          */
550         avg_len += avg_len / 4;
551         max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
552         if (avg_len < max)
553                 max /= (u32)avg_len;
554         else
555                 max = 1;
556
557         WRITE_ONCE(perf_sample_allowed_ns, avg_len);
558         WRITE_ONCE(max_samples_per_tick, max);
559
560         sysctl_perf_event_sample_rate = max * HZ;
561         perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
562
563         if (!irq_work_queue(&perf_duration_work)) {
564                 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
565                              "kernel.perf_event_max_sample_rate to %d\n",
566                              __report_avg, __report_allowed,
567                              sysctl_perf_event_sample_rate);
568         }
569 }
570
571 static atomic64_t perf_event_id;
572
573 static void update_context_time(struct perf_event_context *ctx);
574 static u64 perf_event_time(struct perf_event *event);
575
576 void __weak perf_event_print_debug(void)        { }
577
578 static inline u64 perf_clock(void)
579 {
580         return local_clock();
581 }
582
583 static inline u64 perf_event_clock(struct perf_event *event)
584 {
585         return event->clock();
586 }
587
588 /*
589  * State based event timekeeping...
590  *
591  * The basic idea is to use event->state to determine which (if any) time
592  * fields to increment with the current delta. This means we only need to
593  * update timestamps when we change state or when they are explicitly requested
594  * (read).
595  *
596  * Event groups make things a little more complicated, but not terribly so. The
597  * rules for a group are that if the group leader is OFF the entire group is
598  * OFF, irrespecive of what the group member states are. This results in
599  * __perf_effective_state().
600  *
601  * A futher ramification is that when a group leader flips between OFF and
602  * !OFF, we need to update all group member times.
603  *
604  *
605  * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
606  * need to make sure the relevant context time is updated before we try and
607  * update our timestamps.
608  */
609
610 static __always_inline enum perf_event_state
611 __perf_effective_state(struct perf_event *event)
612 {
613         struct perf_event *leader = event->group_leader;
614
615         if (leader->state <= PERF_EVENT_STATE_OFF)
616                 return leader->state;
617
618         return event->state;
619 }
620
621 static __always_inline void
622 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
623 {
624         enum perf_event_state state = __perf_effective_state(event);
625         u64 delta = now - event->tstamp;
626
627         *enabled = event->total_time_enabled;
628         if (state >= PERF_EVENT_STATE_INACTIVE)
629                 *enabled += delta;
630
631         *running = event->total_time_running;
632         if (state >= PERF_EVENT_STATE_ACTIVE)
633                 *running += delta;
634 }
635
636 static void perf_event_update_time(struct perf_event *event)
637 {
638         u64 now = perf_event_time(event);
639
640         __perf_update_times(event, now, &event->total_time_enabled,
641                                         &event->total_time_running);
642         event->tstamp = now;
643 }
644
645 static void perf_event_update_sibling_time(struct perf_event *leader)
646 {
647         struct perf_event *sibling;
648
649         for_each_sibling_event(sibling, leader)
650                 perf_event_update_time(sibling);
651 }
652
653 static void
654 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
655 {
656         if (event->state == state)
657                 return;
658
659         perf_event_update_time(event);
660         /*
661          * If a group leader gets enabled/disabled all its siblings
662          * are affected too.
663          */
664         if ((event->state < 0) ^ (state < 0))
665                 perf_event_update_sibling_time(event);
666
667         WRITE_ONCE(event->state, state);
668 }
669
670 /*
671  * UP store-release, load-acquire
672  */
673
674 #define __store_release(ptr, val)                                       \
675 do {                                                                    \
676         barrier();                                                      \
677         WRITE_ONCE(*(ptr), (val));                                      \
678 } while (0)
679
680 #define __load_acquire(ptr)                                             \
681 ({                                                                      \
682         __unqual_scalar_typeof(*(ptr)) ___p = READ_ONCE(*(ptr));        \
683         barrier();                                                      \
684         ___p;                                                           \
685 })
686
687 static void perf_ctx_disable(struct perf_event_context *ctx)
688 {
689         struct perf_event_pmu_context *pmu_ctx;
690
691         list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry)
692                 perf_pmu_disable(pmu_ctx->pmu);
693 }
694
695 static void perf_ctx_enable(struct perf_event_context *ctx)
696 {
697         struct perf_event_pmu_context *pmu_ctx;
698
699         list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry)
700                 perf_pmu_enable(pmu_ctx->pmu);
701 }
702
703 static void ctx_sched_out(struct perf_event_context *ctx, enum event_type_t event_type);
704 static void ctx_sched_in(struct perf_event_context *ctx, enum event_type_t event_type);
705
706 #ifdef CONFIG_CGROUP_PERF
707
708 static inline bool
709 perf_cgroup_match(struct perf_event *event)
710 {
711         struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
712
713         /* @event doesn't care about cgroup */
714         if (!event->cgrp)
715                 return true;
716
717         /* wants specific cgroup scope but @cpuctx isn't associated with any */
718         if (!cpuctx->cgrp)
719                 return false;
720
721         /*
722          * Cgroup scoping is recursive.  An event enabled for a cgroup is
723          * also enabled for all its descendant cgroups.  If @cpuctx's
724          * cgroup is a descendant of @event's (the test covers identity
725          * case), it's a match.
726          */
727         return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
728                                     event->cgrp->css.cgroup);
729 }
730
731 static inline void perf_detach_cgroup(struct perf_event *event)
732 {
733         css_put(&event->cgrp->css);
734         event->cgrp = NULL;
735 }
736
737 static inline int is_cgroup_event(struct perf_event *event)
738 {
739         return event->cgrp != NULL;
740 }
741
742 static inline u64 perf_cgroup_event_time(struct perf_event *event)
743 {
744         struct perf_cgroup_info *t;
745
746         t = per_cpu_ptr(event->cgrp->info, event->cpu);
747         return t->time;
748 }
749
750 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
751 {
752         struct perf_cgroup_info *t;
753
754         t = per_cpu_ptr(event->cgrp->info, event->cpu);
755         if (!__load_acquire(&t->active))
756                 return t->time;
757         now += READ_ONCE(t->timeoffset);
758         return now;
759 }
760
761 static inline void __update_cgrp_time(struct perf_cgroup_info *info, u64 now, bool adv)
762 {
763         if (adv)
764                 info->time += now - info->timestamp;
765         info->timestamp = now;
766         /*
767          * see update_context_time()
768          */
769         WRITE_ONCE(info->timeoffset, info->time - info->timestamp);
770 }
771
772 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx, bool final)
773 {
774         struct perf_cgroup *cgrp = cpuctx->cgrp;
775         struct cgroup_subsys_state *css;
776         struct perf_cgroup_info *info;
777
778         if (cgrp) {
779                 u64 now = perf_clock();
780
781                 for (css = &cgrp->css; css; css = css->parent) {
782                         cgrp = container_of(css, struct perf_cgroup, css);
783                         info = this_cpu_ptr(cgrp->info);
784
785                         __update_cgrp_time(info, now, true);
786                         if (final)
787                                 __store_release(&info->active, 0);
788                 }
789         }
790 }
791
792 static inline void update_cgrp_time_from_event(struct perf_event *event)
793 {
794         struct perf_cgroup_info *info;
795
796         /*
797          * ensure we access cgroup data only when needed and
798          * when we know the cgroup is pinned (css_get)
799          */
800         if (!is_cgroup_event(event))
801                 return;
802
803         info = this_cpu_ptr(event->cgrp->info);
804         /*
805          * Do not update time when cgroup is not active
806          */
807         if (info->active)
808                 __update_cgrp_time(info, perf_clock(), true);
809 }
810
811 static inline void
812 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx)
813 {
814         struct perf_event_context *ctx = &cpuctx->ctx;
815         struct perf_cgroup *cgrp = cpuctx->cgrp;
816         struct perf_cgroup_info *info;
817         struct cgroup_subsys_state *css;
818
819         /*
820          * ctx->lock held by caller
821          * ensure we do not access cgroup data
822          * unless we have the cgroup pinned (css_get)
823          */
824         if (!cgrp)
825                 return;
826
827         WARN_ON_ONCE(!ctx->nr_cgroups);
828
829         for (css = &cgrp->css; css; css = css->parent) {
830                 cgrp = container_of(css, struct perf_cgroup, css);
831                 info = this_cpu_ptr(cgrp->info);
832                 __update_cgrp_time(info, ctx->timestamp, false);
833                 __store_release(&info->active, 1);
834         }
835 }
836
837 /*
838  * reschedule events based on the cgroup constraint of task.
839  */
840 static void perf_cgroup_switch(struct task_struct *task)
841 {
842         struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
843         struct perf_cgroup *cgrp;
844
845         /*
846          * cpuctx->cgrp is set when the first cgroup event enabled,
847          * and is cleared when the last cgroup event disabled.
848          */
849         if (READ_ONCE(cpuctx->cgrp) == NULL)
850                 return;
851
852         WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
853
854         cgrp = perf_cgroup_from_task(task, NULL);
855         if (READ_ONCE(cpuctx->cgrp) == cgrp)
856                 return;
857
858         perf_ctx_lock(cpuctx, cpuctx->task_ctx);
859         perf_ctx_disable(&cpuctx->ctx);
860
861         ctx_sched_out(&cpuctx->ctx, EVENT_ALL);
862         /*
863          * must not be done before ctxswout due
864          * to update_cgrp_time_from_cpuctx() in
865          * ctx_sched_out()
866          */
867         cpuctx->cgrp = cgrp;
868         /*
869          * set cgrp before ctxsw in to allow
870          * perf_cgroup_set_timestamp() in ctx_sched_in()
871          * to not have to pass task around
872          */
873         ctx_sched_in(&cpuctx->ctx, EVENT_ALL);
874
875         perf_ctx_enable(&cpuctx->ctx);
876         perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
877 }
878
879 static int perf_cgroup_ensure_storage(struct perf_event *event,
880                                 struct cgroup_subsys_state *css)
881 {
882         struct perf_cpu_context *cpuctx;
883         struct perf_event **storage;
884         int cpu, heap_size, ret = 0;
885
886         /*
887          * Allow storage to have sufficent space for an iterator for each
888          * possibly nested cgroup plus an iterator for events with no cgroup.
889          */
890         for (heap_size = 1; css; css = css->parent)
891                 heap_size++;
892
893         for_each_possible_cpu(cpu) {
894                 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
895                 if (heap_size <= cpuctx->heap_size)
896                         continue;
897
898                 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
899                                        GFP_KERNEL, cpu_to_node(cpu));
900                 if (!storage) {
901                         ret = -ENOMEM;
902                         break;
903                 }
904
905                 raw_spin_lock_irq(&cpuctx->ctx.lock);
906                 if (cpuctx->heap_size < heap_size) {
907                         swap(cpuctx->heap, storage);
908                         if (storage == cpuctx->heap_default)
909                                 storage = NULL;
910                         cpuctx->heap_size = heap_size;
911                 }
912                 raw_spin_unlock_irq(&cpuctx->ctx.lock);
913
914                 kfree(storage);
915         }
916
917         return ret;
918 }
919
920 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
921                                       struct perf_event_attr *attr,
922                                       struct perf_event *group_leader)
923 {
924         struct perf_cgroup *cgrp;
925         struct cgroup_subsys_state *css;
926         struct fd f = fdget(fd);
927         int ret = 0;
928
929         if (!f.file)
930                 return -EBADF;
931
932         css = css_tryget_online_from_dir(f.file->f_path.dentry,
933                                          &perf_event_cgrp_subsys);
934         if (IS_ERR(css)) {
935                 ret = PTR_ERR(css);
936                 goto out;
937         }
938
939         ret = perf_cgroup_ensure_storage(event, css);
940         if (ret)
941                 goto out;
942
943         cgrp = container_of(css, struct perf_cgroup, css);
944         event->cgrp = cgrp;
945
946         /*
947          * all events in a group must monitor
948          * the same cgroup because a task belongs
949          * to only one perf cgroup at a time
950          */
951         if (group_leader && group_leader->cgrp != cgrp) {
952                 perf_detach_cgroup(event);
953                 ret = -EINVAL;
954         }
955 out:
956         fdput(f);
957         return ret;
958 }
959
960 static inline void
961 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
962 {
963         struct perf_cpu_context *cpuctx;
964
965         if (!is_cgroup_event(event))
966                 return;
967
968         /*
969          * Because cgroup events are always per-cpu events,
970          * @ctx == &cpuctx->ctx.
971          */
972         cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
973
974         if (ctx->nr_cgroups++)
975                 return;
976
977         cpuctx->cgrp = perf_cgroup_from_task(current, ctx);
978 }
979
980 static inline void
981 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
982 {
983         struct perf_cpu_context *cpuctx;
984
985         if (!is_cgroup_event(event))
986                 return;
987
988         /*
989          * Because cgroup events are always per-cpu events,
990          * @ctx == &cpuctx->ctx.
991          */
992         cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
993
994         if (--ctx->nr_cgroups)
995                 return;
996
997         cpuctx->cgrp = NULL;
998 }
999
1000 #else /* !CONFIG_CGROUP_PERF */
1001
1002 static inline bool
1003 perf_cgroup_match(struct perf_event *event)
1004 {
1005         return true;
1006 }
1007
1008 static inline void perf_detach_cgroup(struct perf_event *event)
1009 {}
1010
1011 static inline int is_cgroup_event(struct perf_event *event)
1012 {
1013         return 0;
1014 }
1015
1016 static inline void update_cgrp_time_from_event(struct perf_event *event)
1017 {
1018 }
1019
1020 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx,
1021                                                 bool final)
1022 {
1023 }
1024
1025 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1026                                       struct perf_event_attr *attr,
1027                                       struct perf_event *group_leader)
1028 {
1029         return -EINVAL;
1030 }
1031
1032 static inline void
1033 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx)
1034 {
1035 }
1036
1037 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1038 {
1039         return 0;
1040 }
1041
1042 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
1043 {
1044         return 0;
1045 }
1046
1047 static inline void
1048 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1049 {
1050 }
1051
1052 static inline void
1053 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1054 {
1055 }
1056
1057 static void perf_cgroup_switch(struct task_struct *task)
1058 {
1059 }
1060 #endif
1061
1062 /*
1063  * set default to be dependent on timer tick just
1064  * like original code
1065  */
1066 #define PERF_CPU_HRTIMER (1000 / HZ)
1067 /*
1068  * function must be called with interrupts disabled
1069  */
1070 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1071 {
1072         struct perf_cpu_pmu_context *cpc;
1073         bool rotations;
1074
1075         lockdep_assert_irqs_disabled();
1076
1077         cpc = container_of(hr, struct perf_cpu_pmu_context, hrtimer);
1078         rotations = perf_rotate_context(cpc);
1079
1080         raw_spin_lock(&cpc->hrtimer_lock);
1081         if (rotations)
1082                 hrtimer_forward_now(hr, cpc->hrtimer_interval);
1083         else
1084                 cpc->hrtimer_active = 0;
1085         raw_spin_unlock(&cpc->hrtimer_lock);
1086
1087         return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1088 }
1089
1090 static void __perf_mux_hrtimer_init(struct perf_cpu_pmu_context *cpc, int cpu)
1091 {
1092         struct hrtimer *timer = &cpc->hrtimer;
1093         struct pmu *pmu = cpc->epc.pmu;
1094         u64 interval;
1095
1096         /*
1097          * check default is sane, if not set then force to
1098          * default interval (1/tick)
1099          */
1100         interval = pmu->hrtimer_interval_ms;
1101         if (interval < 1)
1102                 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1103
1104         cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1105
1106         raw_spin_lock_init(&cpc->hrtimer_lock);
1107         hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
1108         timer->function = perf_mux_hrtimer_handler;
1109 }
1110
1111 static int perf_mux_hrtimer_restart(struct perf_cpu_pmu_context *cpc)
1112 {
1113         struct hrtimer *timer = &cpc->hrtimer;
1114         unsigned long flags;
1115
1116         raw_spin_lock_irqsave(&cpc->hrtimer_lock, flags);
1117         if (!cpc->hrtimer_active) {
1118                 cpc->hrtimer_active = 1;
1119                 hrtimer_forward_now(timer, cpc->hrtimer_interval);
1120                 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1121         }
1122         raw_spin_unlock_irqrestore(&cpc->hrtimer_lock, flags);
1123
1124         return 0;
1125 }
1126
1127 static int perf_mux_hrtimer_restart_ipi(void *arg)
1128 {
1129         return perf_mux_hrtimer_restart(arg);
1130 }
1131
1132 void perf_pmu_disable(struct pmu *pmu)
1133 {
1134         int *count = this_cpu_ptr(pmu->pmu_disable_count);
1135         if (!(*count)++)
1136                 pmu->pmu_disable(pmu);
1137 }
1138
1139 void perf_pmu_enable(struct pmu *pmu)
1140 {
1141         int *count = this_cpu_ptr(pmu->pmu_disable_count);
1142         if (!--(*count))
1143                 pmu->pmu_enable(pmu);
1144 }
1145
1146 static void perf_assert_pmu_disabled(struct pmu *pmu)
1147 {
1148         WARN_ON_ONCE(*this_cpu_ptr(pmu->pmu_disable_count) == 0);
1149 }
1150
1151 static void get_ctx(struct perf_event_context *ctx)
1152 {
1153         refcount_inc(&ctx->refcount);
1154 }
1155
1156 static void *alloc_task_ctx_data(struct pmu *pmu)
1157 {
1158         if (pmu->task_ctx_cache)
1159                 return kmem_cache_zalloc(pmu->task_ctx_cache, GFP_KERNEL);
1160
1161         return NULL;
1162 }
1163
1164 static void free_task_ctx_data(struct pmu *pmu, void *task_ctx_data)
1165 {
1166         if (pmu->task_ctx_cache && task_ctx_data)
1167                 kmem_cache_free(pmu->task_ctx_cache, task_ctx_data);
1168 }
1169
1170 static void free_ctx(struct rcu_head *head)
1171 {
1172         struct perf_event_context *ctx;
1173
1174         ctx = container_of(head, struct perf_event_context, rcu_head);
1175         kfree(ctx);
1176 }
1177
1178 static void put_ctx(struct perf_event_context *ctx)
1179 {
1180         if (refcount_dec_and_test(&ctx->refcount)) {
1181                 if (ctx->parent_ctx)
1182                         put_ctx(ctx->parent_ctx);
1183                 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1184                         put_task_struct(ctx->task);
1185                 call_rcu(&ctx->rcu_head, free_ctx);
1186         }
1187 }
1188
1189 /*
1190  * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1191  * perf_pmu_migrate_context() we need some magic.
1192  *
1193  * Those places that change perf_event::ctx will hold both
1194  * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1195  *
1196  * Lock ordering is by mutex address. There are two other sites where
1197  * perf_event_context::mutex nests and those are:
1198  *
1199  *  - perf_event_exit_task_context()    [ child , 0 ]
1200  *      perf_event_exit_event()
1201  *        put_event()                   [ parent, 1 ]
1202  *
1203  *  - perf_event_init_context()         [ parent, 0 ]
1204  *      inherit_task_group()
1205  *        inherit_group()
1206  *          inherit_event()
1207  *            perf_event_alloc()
1208  *              perf_init_event()
1209  *                perf_try_init_event() [ child , 1 ]
1210  *
1211  * While it appears there is an obvious deadlock here -- the parent and child
1212  * nesting levels are inverted between the two. This is in fact safe because
1213  * life-time rules separate them. That is an exiting task cannot fork, and a
1214  * spawning task cannot (yet) exit.
1215  *
1216  * But remember that these are parent<->child context relations, and
1217  * migration does not affect children, therefore these two orderings should not
1218  * interact.
1219  *
1220  * The change in perf_event::ctx does not affect children (as claimed above)
1221  * because the sys_perf_event_open() case will install a new event and break
1222  * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1223  * concerned with cpuctx and that doesn't have children.
1224  *
1225  * The places that change perf_event::ctx will issue:
1226  *
1227  *   perf_remove_from_context();
1228  *   synchronize_rcu();
1229  *   perf_install_in_context();
1230  *
1231  * to affect the change. The remove_from_context() + synchronize_rcu() should
1232  * quiesce the event, after which we can install it in the new location. This
1233  * means that only external vectors (perf_fops, prctl) can perturb the event
1234  * while in transit. Therefore all such accessors should also acquire
1235  * perf_event_context::mutex to serialize against this.
1236  *
1237  * However; because event->ctx can change while we're waiting to acquire
1238  * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1239  * function.
1240  *
1241  * Lock order:
1242  *    exec_update_lock
1243  *      task_struct::perf_event_mutex
1244  *        perf_event_context::mutex
1245  *          perf_event::child_mutex;
1246  *            perf_event_context::lock
1247  *          perf_event::mmap_mutex
1248  *          mmap_lock
1249  *            perf_addr_filters_head::lock
1250  *
1251  *    cpu_hotplug_lock
1252  *      pmus_lock
1253  *        cpuctx->mutex / perf_event_context::mutex
1254  */
1255 static struct perf_event_context *
1256 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1257 {
1258         struct perf_event_context *ctx;
1259
1260 again:
1261         rcu_read_lock();
1262         ctx = READ_ONCE(event->ctx);
1263         if (!refcount_inc_not_zero(&ctx->refcount)) {
1264                 rcu_read_unlock();
1265                 goto again;
1266         }
1267         rcu_read_unlock();
1268
1269         mutex_lock_nested(&ctx->mutex, nesting);
1270         if (event->ctx != ctx) {
1271                 mutex_unlock(&ctx->mutex);
1272                 put_ctx(ctx);
1273                 goto again;
1274         }
1275
1276         return ctx;
1277 }
1278
1279 static inline struct perf_event_context *
1280 perf_event_ctx_lock(struct perf_event *event)
1281 {
1282         return perf_event_ctx_lock_nested(event, 0);
1283 }
1284
1285 static void perf_event_ctx_unlock(struct perf_event *event,
1286                                   struct perf_event_context *ctx)
1287 {
1288         mutex_unlock(&ctx->mutex);
1289         put_ctx(ctx);
1290 }
1291
1292 /*
1293  * This must be done under the ctx->lock, such as to serialize against
1294  * context_equiv(), therefore we cannot call put_ctx() since that might end up
1295  * calling scheduler related locks and ctx->lock nests inside those.
1296  */
1297 static __must_check struct perf_event_context *
1298 unclone_ctx(struct perf_event_context *ctx)
1299 {
1300         struct perf_event_context *parent_ctx = ctx->parent_ctx;
1301
1302         lockdep_assert_held(&ctx->lock);
1303
1304         if (parent_ctx)
1305                 ctx->parent_ctx = NULL;
1306         ctx->generation++;
1307
1308         return parent_ctx;
1309 }
1310
1311 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1312                                 enum pid_type type)
1313 {
1314         u32 nr;
1315         /*
1316          * only top level events have the pid namespace they were created in
1317          */
1318         if (event->parent)
1319                 event = event->parent;
1320
1321         nr = __task_pid_nr_ns(p, type, event->ns);
1322         /* avoid -1 if it is idle thread or runs in another ns */
1323         if (!nr && !pid_alive(p))
1324                 nr = -1;
1325         return nr;
1326 }
1327
1328 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1329 {
1330         return perf_event_pid_type(event, p, PIDTYPE_TGID);
1331 }
1332
1333 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1334 {
1335         return perf_event_pid_type(event, p, PIDTYPE_PID);
1336 }
1337
1338 /*
1339  * If we inherit events we want to return the parent event id
1340  * to userspace.
1341  */
1342 static u64 primary_event_id(struct perf_event *event)
1343 {
1344         u64 id = event->id;
1345
1346         if (event->parent)
1347                 id = event->parent->id;
1348
1349         return id;
1350 }
1351
1352 /*
1353  * Get the perf_event_context for a task and lock it.
1354  *
1355  * This has to cope with the fact that until it is locked,
1356  * the context could get moved to another task.
1357  */
1358 static struct perf_event_context *
1359 perf_lock_task_context(struct task_struct *task, unsigned long *flags)
1360 {
1361         struct perf_event_context *ctx;
1362
1363 retry:
1364         /*
1365          * One of the few rules of preemptible RCU is that one cannot do
1366          * rcu_read_unlock() while holding a scheduler (or nested) lock when
1367          * part of the read side critical section was irqs-enabled -- see
1368          * rcu_read_unlock_special().
1369          *
1370          * Since ctx->lock nests under rq->lock we must ensure the entire read
1371          * side critical section has interrupts disabled.
1372          */
1373         local_irq_save(*flags);
1374         rcu_read_lock();
1375         ctx = rcu_dereference(task->perf_event_ctxp);
1376         if (ctx) {
1377                 /*
1378                  * If this context is a clone of another, it might
1379                  * get swapped for another underneath us by
1380                  * perf_event_task_sched_out, though the
1381                  * rcu_read_lock() protects us from any context
1382                  * getting freed.  Lock the context and check if it
1383                  * got swapped before we could get the lock, and retry
1384                  * if so.  If we locked the right context, then it
1385                  * can't get swapped on us any more.
1386                  */
1387                 raw_spin_lock(&ctx->lock);
1388                 if (ctx != rcu_dereference(task->perf_event_ctxp)) {
1389                         raw_spin_unlock(&ctx->lock);
1390                         rcu_read_unlock();
1391                         local_irq_restore(*flags);
1392                         goto retry;
1393                 }
1394
1395                 if (ctx->task == TASK_TOMBSTONE ||
1396                     !refcount_inc_not_zero(&ctx->refcount)) {
1397                         raw_spin_unlock(&ctx->lock);
1398                         ctx = NULL;
1399                 } else {
1400                         WARN_ON_ONCE(ctx->task != task);
1401                 }
1402         }
1403         rcu_read_unlock();
1404         if (!ctx)
1405                 local_irq_restore(*flags);
1406         return ctx;
1407 }
1408
1409 /*
1410  * Get the context for a task and increment its pin_count so it
1411  * can't get swapped to another task.  This also increments its
1412  * reference count so that the context can't get freed.
1413  */
1414 static struct perf_event_context *
1415 perf_pin_task_context(struct task_struct *task)
1416 {
1417         struct perf_event_context *ctx;
1418         unsigned long flags;
1419
1420         ctx = perf_lock_task_context(task, &flags);
1421         if (ctx) {
1422                 ++ctx->pin_count;
1423                 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1424         }
1425         return ctx;
1426 }
1427
1428 static void perf_unpin_context(struct perf_event_context *ctx)
1429 {
1430         unsigned long flags;
1431
1432         raw_spin_lock_irqsave(&ctx->lock, flags);
1433         --ctx->pin_count;
1434         raw_spin_unlock_irqrestore(&ctx->lock, flags);
1435 }
1436
1437 /*
1438  * Update the record of the current time in a context.
1439  */
1440 static void __update_context_time(struct perf_event_context *ctx, bool adv)
1441 {
1442         u64 now = perf_clock();
1443
1444         lockdep_assert_held(&ctx->lock);
1445
1446         if (adv)
1447                 ctx->time += now - ctx->timestamp;
1448         ctx->timestamp = now;
1449
1450         /*
1451          * The above: time' = time + (now - timestamp), can be re-arranged
1452          * into: time` = now + (time - timestamp), which gives a single value
1453          * offset to compute future time without locks on.
1454          *
1455          * See perf_event_time_now(), which can be used from NMI context where
1456          * it's (obviously) not possible to acquire ctx->lock in order to read
1457          * both the above values in a consistent manner.
1458          */
1459         WRITE_ONCE(ctx->timeoffset, ctx->time - ctx->timestamp);
1460 }
1461
1462 static void update_context_time(struct perf_event_context *ctx)
1463 {
1464         __update_context_time(ctx, true);
1465 }
1466
1467 static u64 perf_event_time(struct perf_event *event)
1468 {
1469         struct perf_event_context *ctx = event->ctx;
1470
1471         if (unlikely(!ctx))
1472                 return 0;
1473
1474         if (is_cgroup_event(event))
1475                 return perf_cgroup_event_time(event);
1476
1477         return ctx->time;
1478 }
1479
1480 static u64 perf_event_time_now(struct perf_event *event, u64 now)
1481 {
1482         struct perf_event_context *ctx = event->ctx;
1483
1484         if (unlikely(!ctx))
1485                 return 0;
1486
1487         if (is_cgroup_event(event))
1488                 return perf_cgroup_event_time_now(event, now);
1489
1490         if (!(__load_acquire(&ctx->is_active) & EVENT_TIME))
1491                 return ctx->time;
1492
1493         now += READ_ONCE(ctx->timeoffset);
1494         return now;
1495 }
1496
1497 static enum event_type_t get_event_type(struct perf_event *event)
1498 {
1499         struct perf_event_context *ctx = event->ctx;
1500         enum event_type_t event_type;
1501
1502         lockdep_assert_held(&ctx->lock);
1503
1504         /*
1505          * It's 'group type', really, because if our group leader is
1506          * pinned, so are we.
1507          */
1508         if (event->group_leader != event)
1509                 event = event->group_leader;
1510
1511         event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1512         if (!ctx->task)
1513                 event_type |= EVENT_CPU;
1514
1515         return event_type;
1516 }
1517
1518 /*
1519  * Helper function to initialize event group nodes.
1520  */
1521 static void init_event_group(struct perf_event *event)
1522 {
1523         RB_CLEAR_NODE(&event->group_node);
1524         event->group_index = 0;
1525 }
1526
1527 /*
1528  * Extract pinned or flexible groups from the context
1529  * based on event attrs bits.
1530  */
1531 static struct perf_event_groups *
1532 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1533 {
1534         if (event->attr.pinned)
1535                 return &ctx->pinned_groups;
1536         else
1537                 return &ctx->flexible_groups;
1538 }
1539
1540 /*
1541  * Helper function to initializes perf_event_group trees.
1542  */
1543 static void perf_event_groups_init(struct perf_event_groups *groups)
1544 {
1545         groups->tree = RB_ROOT;
1546         groups->index = 0;
1547 }
1548
1549 static inline struct cgroup *event_cgroup(const struct perf_event *event)
1550 {
1551         struct cgroup *cgroup = NULL;
1552
1553 #ifdef CONFIG_CGROUP_PERF
1554         if (event->cgrp)
1555                 cgroup = event->cgrp->css.cgroup;
1556 #endif
1557
1558         return cgroup;
1559 }
1560
1561 /*
1562  * Compare function for event groups;
1563  *
1564  * Implements complex key that first sorts by CPU and then by virtual index
1565  * which provides ordering when rotating groups for the same CPU.
1566  */
1567 static __always_inline int
1568 perf_event_groups_cmp(const int left_cpu, const struct pmu *left_pmu,
1569                       const struct cgroup *left_cgroup, const u64 left_group_index,
1570                       const struct perf_event *right)
1571 {
1572         if (left_cpu < right->cpu)
1573                 return -1;
1574         if (left_cpu > right->cpu)
1575                 return 1;
1576
1577         if (left_pmu) {
1578                 if (left_pmu < right->pmu_ctx->pmu)
1579                         return -1;
1580                 if (left_pmu > right->pmu_ctx->pmu)
1581                         return 1;
1582         }
1583
1584 #ifdef CONFIG_CGROUP_PERF
1585         {
1586                 const struct cgroup *right_cgroup = event_cgroup(right);
1587
1588                 if (left_cgroup != right_cgroup) {
1589                         if (!left_cgroup) {
1590                                 /*
1591                                  * Left has no cgroup but right does, no
1592                                  * cgroups come first.
1593                                  */
1594                                 return -1;
1595                         }
1596                         if (!right_cgroup) {
1597                                 /*
1598                                  * Right has no cgroup but left does, no
1599                                  * cgroups come first.
1600                                  */
1601                                 return 1;
1602                         }
1603                         /* Two dissimilar cgroups, order by id. */
1604                         if (cgroup_id(left_cgroup) < cgroup_id(right_cgroup))
1605                                 return -1;
1606
1607                         return 1;
1608                 }
1609         }
1610 #endif
1611
1612         if (left_group_index < right->group_index)
1613                 return -1;
1614         if (left_group_index > right->group_index)
1615                 return 1;
1616
1617         return 0;
1618 }
1619
1620 #define __node_2_pe(node) \
1621         rb_entry((node), struct perf_event, group_node)
1622
1623 static inline bool __group_less(struct rb_node *a, const struct rb_node *b)
1624 {
1625         struct perf_event *e = __node_2_pe(a);
1626         return perf_event_groups_cmp(e->cpu, e->pmu_ctx->pmu, event_cgroup(e),
1627                                      e->group_index, __node_2_pe(b)) < 0;
1628 }
1629
1630 struct __group_key {
1631         int cpu;
1632         struct pmu *pmu;
1633         struct cgroup *cgroup;
1634 };
1635
1636 static inline int __group_cmp(const void *key, const struct rb_node *node)
1637 {
1638         const struct __group_key *a = key;
1639         const struct perf_event *b = __node_2_pe(node);
1640
1641         /* partial/subtree match: @cpu, @pmu, @cgroup; ignore: @group_index */
1642         return perf_event_groups_cmp(a->cpu, a->pmu, a->cgroup, b->group_index, b);
1643 }
1644
1645 static inline int
1646 __group_cmp_ignore_cgroup(const void *key, const struct rb_node *node)
1647 {
1648         const struct __group_key *a = key;
1649         const struct perf_event *b = __node_2_pe(node);
1650
1651         /* partial/subtree match: @cpu, @pmu, ignore: @cgroup, @group_index */
1652         return perf_event_groups_cmp(a->cpu, a->pmu, event_cgroup(b),
1653                                      b->group_index, b);
1654 }
1655
1656 /*
1657  * Insert @event into @groups' tree; using
1658  *   {@event->cpu, @event->pmu_ctx->pmu, event_cgroup(@event), ++@groups->index}
1659  * as key. This places it last inside the {cpu,pmu,cgroup} subtree.
1660  */
1661 static void
1662 perf_event_groups_insert(struct perf_event_groups *groups,
1663                          struct perf_event *event)
1664 {
1665         event->group_index = ++groups->index;
1666
1667         rb_add(&event->group_node, &groups->tree, __group_less);
1668 }
1669
1670 /*
1671  * Helper function to insert event into the pinned or flexible groups.
1672  */
1673 static void
1674 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1675 {
1676         struct perf_event_groups *groups;
1677
1678         groups = get_event_groups(event, ctx);
1679         perf_event_groups_insert(groups, event);
1680 }
1681
1682 /*
1683  * Delete a group from a tree.
1684  */
1685 static void
1686 perf_event_groups_delete(struct perf_event_groups *groups,
1687                          struct perf_event *event)
1688 {
1689         WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1690                      RB_EMPTY_ROOT(&groups->tree));
1691
1692         rb_erase(&event->group_node, &groups->tree);
1693         init_event_group(event);
1694 }
1695
1696 /*
1697  * Helper function to delete event from its groups.
1698  */
1699 static void
1700 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1701 {
1702         struct perf_event_groups *groups;
1703
1704         groups = get_event_groups(event, ctx);
1705         perf_event_groups_delete(groups, event);
1706 }
1707
1708 /*
1709  * Get the leftmost event in the {cpu,pmu,cgroup} subtree.
1710  */
1711 static struct perf_event *
1712 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1713                         struct pmu *pmu, struct cgroup *cgrp)
1714 {
1715         struct __group_key key = {
1716                 .cpu = cpu,
1717                 .pmu = pmu,
1718                 .cgroup = cgrp,
1719         };
1720         struct rb_node *node;
1721
1722         node = rb_find_first(&key, &groups->tree, __group_cmp);
1723         if (node)
1724                 return __node_2_pe(node);
1725
1726         return NULL;
1727 }
1728
1729 static struct perf_event *
1730 perf_event_groups_next(struct perf_event *event, struct pmu *pmu)
1731 {
1732         struct __group_key key = {
1733                 .cpu = event->cpu,
1734                 .pmu = pmu,
1735                 .cgroup = event_cgroup(event),
1736         };
1737         struct rb_node *next;
1738
1739         next = rb_next_match(&key, &event->group_node, __group_cmp);
1740         if (next)
1741                 return __node_2_pe(next);
1742
1743         return NULL;
1744 }
1745
1746 #define perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu)          \
1747         for (event = perf_event_groups_first(groups, cpu, pmu, NULL);   \
1748              event; event = perf_event_groups_next(event, pmu))
1749
1750 /*
1751  * Iterate through the whole groups tree.
1752  */
1753 #define perf_event_groups_for_each(event, groups)                       \
1754         for (event = rb_entry_safe(rb_first(&((groups)->tree)),         \
1755                                 typeof(*event), group_node); event;     \
1756                 event = rb_entry_safe(rb_next(&event->group_node),      \
1757                                 typeof(*event), group_node))
1758
1759 /*
1760  * Add an event from the lists for its context.
1761  * Must be called with ctx->mutex and ctx->lock held.
1762  */
1763 static void
1764 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1765 {
1766         lockdep_assert_held(&ctx->lock);
1767
1768         WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1769         event->attach_state |= PERF_ATTACH_CONTEXT;
1770
1771         event->tstamp = perf_event_time(event);
1772
1773         /*
1774          * If we're a stand alone event or group leader, we go to the context
1775          * list, group events are kept attached to the group so that
1776          * perf_group_detach can, at all times, locate all siblings.
1777          */
1778         if (event->group_leader == event) {
1779                 event->group_caps = event->event_caps;
1780                 add_event_to_groups(event, ctx);
1781         }
1782
1783         list_add_rcu(&event->event_entry, &ctx->event_list);
1784         ctx->nr_events++;
1785         if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
1786                 ctx->nr_user++;
1787         if (event->attr.inherit_stat)
1788                 ctx->nr_stat++;
1789
1790         if (event->state > PERF_EVENT_STATE_OFF)
1791                 perf_cgroup_event_enable(event, ctx);
1792
1793         ctx->generation++;
1794         event->pmu_ctx->nr_events++;
1795 }
1796
1797 /*
1798  * Initialize event state based on the perf_event_attr::disabled.
1799  */
1800 static inline void perf_event__state_init(struct perf_event *event)
1801 {
1802         event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1803                                               PERF_EVENT_STATE_INACTIVE;
1804 }
1805
1806 static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
1807 {
1808         int entry = sizeof(u64); /* value */
1809         int size = 0;
1810         int nr = 1;
1811
1812         if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1813                 size += sizeof(u64);
1814
1815         if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1816                 size += sizeof(u64);
1817
1818         if (event->attr.read_format & PERF_FORMAT_ID)
1819                 entry += sizeof(u64);
1820
1821         if (event->attr.read_format & PERF_FORMAT_LOST)
1822                 entry += sizeof(u64);
1823
1824         if (event->attr.read_format & PERF_FORMAT_GROUP) {
1825                 nr += nr_siblings;
1826                 size += sizeof(u64);
1827         }
1828
1829         size += entry * nr;
1830         event->read_size = size;
1831 }
1832
1833 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1834 {
1835         struct perf_sample_data *data;
1836         u16 size = 0;
1837
1838         if (sample_type & PERF_SAMPLE_IP)
1839                 size += sizeof(data->ip);
1840
1841         if (sample_type & PERF_SAMPLE_ADDR)
1842                 size += sizeof(data->addr);
1843
1844         if (sample_type & PERF_SAMPLE_PERIOD)
1845                 size += sizeof(data->period);
1846
1847         if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
1848                 size += sizeof(data->weight.full);
1849
1850         if (sample_type & PERF_SAMPLE_READ)
1851                 size += event->read_size;
1852
1853         if (sample_type & PERF_SAMPLE_DATA_SRC)
1854                 size += sizeof(data->data_src.val);
1855
1856         if (sample_type & PERF_SAMPLE_TRANSACTION)
1857                 size += sizeof(data->txn);
1858
1859         if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1860                 size += sizeof(data->phys_addr);
1861
1862         if (sample_type & PERF_SAMPLE_CGROUP)
1863                 size += sizeof(data->cgroup);
1864
1865         if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
1866                 size += sizeof(data->data_page_size);
1867
1868         if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
1869                 size += sizeof(data->code_page_size);
1870
1871         event->header_size = size;
1872 }
1873
1874 /*
1875  * Called at perf_event creation and when events are attached/detached from a
1876  * group.
1877  */
1878 static void perf_event__header_size(struct perf_event *event)
1879 {
1880         __perf_event_read_size(event,
1881                                event->group_leader->nr_siblings);
1882         __perf_event_header_size(event, event->attr.sample_type);
1883 }
1884
1885 static void perf_event__id_header_size(struct perf_event *event)
1886 {
1887         struct perf_sample_data *data;
1888         u64 sample_type = event->attr.sample_type;
1889         u16 size = 0;
1890
1891         if (sample_type & PERF_SAMPLE_TID)
1892                 size += sizeof(data->tid_entry);
1893
1894         if (sample_type & PERF_SAMPLE_TIME)
1895                 size += sizeof(data->time);
1896
1897         if (sample_type & PERF_SAMPLE_IDENTIFIER)
1898                 size += sizeof(data->id);
1899
1900         if (sample_type & PERF_SAMPLE_ID)
1901                 size += sizeof(data->id);
1902
1903         if (sample_type & PERF_SAMPLE_STREAM_ID)
1904                 size += sizeof(data->stream_id);
1905
1906         if (sample_type & PERF_SAMPLE_CPU)
1907                 size += sizeof(data->cpu_entry);
1908
1909         event->id_header_size = size;
1910 }
1911
1912 static bool perf_event_validate_size(struct perf_event *event)
1913 {
1914         /*
1915          * The values computed here will be over-written when we actually
1916          * attach the event.
1917          */
1918         __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1919         __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1920         perf_event__id_header_size(event);
1921
1922         /*
1923          * Sum the lot; should not exceed the 64k limit we have on records.
1924          * Conservative limit to allow for callchains and other variable fields.
1925          */
1926         if (event->read_size + event->header_size +
1927             event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1928                 return false;
1929
1930         return true;
1931 }
1932
1933 static void perf_group_attach(struct perf_event *event)
1934 {
1935         struct perf_event *group_leader = event->group_leader, *pos;
1936
1937         lockdep_assert_held(&event->ctx->lock);
1938
1939         /*
1940          * We can have double attach due to group movement (move_group) in
1941          * perf_event_open().
1942          */
1943         if (event->attach_state & PERF_ATTACH_GROUP)
1944                 return;
1945
1946         event->attach_state |= PERF_ATTACH_GROUP;
1947
1948         if (group_leader == event)
1949                 return;
1950
1951         WARN_ON_ONCE(group_leader->ctx != event->ctx);
1952
1953         group_leader->group_caps &= event->event_caps;
1954
1955         list_add_tail(&event->sibling_list, &group_leader->sibling_list);
1956         group_leader->nr_siblings++;
1957
1958         perf_event__header_size(group_leader);
1959
1960         for_each_sibling_event(pos, group_leader)
1961                 perf_event__header_size(pos);
1962 }
1963
1964 /*
1965  * Remove an event from the lists for its context.
1966  * Must be called with ctx->mutex and ctx->lock held.
1967  */
1968 static void
1969 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1970 {
1971         WARN_ON_ONCE(event->ctx != ctx);
1972         lockdep_assert_held(&ctx->lock);
1973
1974         /*
1975          * We can have double detach due to exit/hot-unplug + close.
1976          */
1977         if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1978                 return;
1979
1980         event->attach_state &= ~PERF_ATTACH_CONTEXT;
1981
1982         ctx->nr_events--;
1983         if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
1984                 ctx->nr_user--;
1985         if (event->attr.inherit_stat)
1986                 ctx->nr_stat--;
1987
1988         list_del_rcu(&event->event_entry);
1989
1990         if (event->group_leader == event)
1991                 del_event_from_groups(event, ctx);
1992
1993         /*
1994          * If event was in error state, then keep it
1995          * that way, otherwise bogus counts will be
1996          * returned on read(). The only way to get out
1997          * of error state is by explicit re-enabling
1998          * of the event
1999          */
2000         if (event->state > PERF_EVENT_STATE_OFF) {
2001                 perf_cgroup_event_disable(event, ctx);
2002                 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2003         }
2004
2005         ctx->generation++;
2006         event->pmu_ctx->nr_events--;
2007 }
2008
2009 static int
2010 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2011 {
2012         if (!has_aux(aux_event))
2013                 return 0;
2014
2015         if (!event->pmu->aux_output_match)
2016                 return 0;
2017
2018         return event->pmu->aux_output_match(aux_event);
2019 }
2020
2021 static void put_event(struct perf_event *event);
2022 static void event_sched_out(struct perf_event *event,
2023                             struct perf_event_context *ctx);
2024
2025 static void perf_put_aux_event(struct perf_event *event)
2026 {
2027         struct perf_event_context *ctx = event->ctx;
2028         struct perf_event *iter;
2029
2030         /*
2031          * If event uses aux_event tear down the link
2032          */
2033         if (event->aux_event) {
2034                 iter = event->aux_event;
2035                 event->aux_event = NULL;
2036                 put_event(iter);
2037                 return;
2038         }
2039
2040         /*
2041          * If the event is an aux_event, tear down all links to
2042          * it from other events.
2043          */
2044         for_each_sibling_event(iter, event->group_leader) {
2045                 if (iter->aux_event != event)
2046                         continue;
2047
2048                 iter->aux_event = NULL;
2049                 put_event(event);
2050
2051                 /*
2052                  * If it's ACTIVE, schedule it out and put it into ERROR
2053                  * state so that we don't try to schedule it again. Note
2054                  * that perf_event_enable() will clear the ERROR status.
2055                  */
2056                 event_sched_out(iter, ctx);
2057                 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2058         }
2059 }
2060
2061 static bool perf_need_aux_event(struct perf_event *event)
2062 {
2063         return !!event->attr.aux_output || !!event->attr.aux_sample_size;
2064 }
2065
2066 static int perf_get_aux_event(struct perf_event *event,
2067                               struct perf_event *group_leader)
2068 {
2069         /*
2070          * Our group leader must be an aux event if we want to be
2071          * an aux_output. This way, the aux event will precede its
2072          * aux_output events in the group, and therefore will always
2073          * schedule first.
2074          */
2075         if (!group_leader)
2076                 return 0;
2077
2078         /*
2079          * aux_output and aux_sample_size are mutually exclusive.
2080          */
2081         if (event->attr.aux_output && event->attr.aux_sample_size)
2082                 return 0;
2083
2084         if (event->attr.aux_output &&
2085             !perf_aux_output_match(event, group_leader))
2086                 return 0;
2087
2088         if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2089                 return 0;
2090
2091         if (!atomic_long_inc_not_zero(&group_leader->refcount))
2092                 return 0;
2093
2094         /*
2095          * Link aux_outputs to their aux event; this is undone in
2096          * perf_group_detach() by perf_put_aux_event(). When the
2097          * group in torn down, the aux_output events loose their
2098          * link to the aux_event and can't schedule any more.
2099          */
2100         event->aux_event = group_leader;
2101
2102         return 1;
2103 }
2104
2105 static inline struct list_head *get_event_list(struct perf_event *event)
2106 {
2107         return event->attr.pinned ? &event->pmu_ctx->pinned_active :
2108                                     &event->pmu_ctx->flexible_active;
2109 }
2110
2111 /*
2112  * Events that have PERF_EV_CAP_SIBLING require being part of a group and
2113  * cannot exist on their own, schedule them out and move them into the ERROR
2114  * state. Also see _perf_event_enable(), it will not be able to recover
2115  * this ERROR state.
2116  */
2117 static inline void perf_remove_sibling_event(struct perf_event *event)
2118 {
2119         event_sched_out(event, event->ctx);
2120         perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2121 }
2122
2123 static void perf_group_detach(struct perf_event *event)
2124 {
2125         struct perf_event *leader = event->group_leader;
2126         struct perf_event *sibling, *tmp;
2127         struct perf_event_context *ctx = event->ctx;
2128
2129         lockdep_assert_held(&ctx->lock);
2130
2131         /*
2132          * We can have double detach due to exit/hot-unplug + close.
2133          */
2134         if (!(event->attach_state & PERF_ATTACH_GROUP))
2135                 return;
2136
2137         event->attach_state &= ~PERF_ATTACH_GROUP;
2138
2139         perf_put_aux_event(event);
2140
2141         /*
2142          * If this is a sibling, remove it from its group.
2143          */
2144         if (leader != event) {
2145                 list_del_init(&event->sibling_list);
2146                 event->group_leader->nr_siblings--;
2147                 goto out;
2148         }
2149
2150         /*
2151          * If this was a group event with sibling events then
2152          * upgrade the siblings to singleton events by adding them
2153          * to whatever list we are on.
2154          */
2155         list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2156
2157                 if (sibling->event_caps & PERF_EV_CAP_SIBLING)
2158                         perf_remove_sibling_event(sibling);
2159
2160                 sibling->group_leader = sibling;
2161                 list_del_init(&sibling->sibling_list);
2162
2163                 /* Inherit group flags from the previous leader */
2164                 sibling->group_caps = event->group_caps;
2165
2166                 if (!RB_EMPTY_NODE(&event->group_node)) {
2167                         add_event_to_groups(sibling, event->ctx);
2168
2169                         if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2170                                 list_add_tail(&sibling->active_list, get_event_list(sibling));
2171                 }
2172
2173                 WARN_ON_ONCE(sibling->ctx != event->ctx);
2174         }
2175
2176 out:
2177         for_each_sibling_event(tmp, leader)
2178                 perf_event__header_size(tmp);
2179
2180         perf_event__header_size(leader);
2181 }
2182
2183 static void sync_child_event(struct perf_event *child_event);
2184
2185 static void perf_child_detach(struct perf_event *event)
2186 {
2187         struct perf_event *parent_event = event->parent;
2188
2189         if (!(event->attach_state & PERF_ATTACH_CHILD))
2190                 return;
2191
2192         event->attach_state &= ~PERF_ATTACH_CHILD;
2193
2194         if (WARN_ON_ONCE(!parent_event))
2195                 return;
2196
2197         lockdep_assert_held(&parent_event->child_mutex);
2198
2199         sync_child_event(event);
2200         list_del_init(&event->child_list);
2201 }
2202
2203 static bool is_orphaned_event(struct perf_event *event)
2204 {
2205         return event->state == PERF_EVENT_STATE_DEAD;
2206 }
2207
2208 static inline int
2209 event_filter_match(struct perf_event *event)
2210 {
2211         return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2212                perf_cgroup_match(event);
2213 }
2214
2215 static void
2216 event_sched_out(struct perf_event *event, struct perf_event_context *ctx)
2217 {
2218         struct perf_event_pmu_context *epc = event->pmu_ctx;
2219         struct perf_cpu_pmu_context *cpc = this_cpu_ptr(epc->pmu->cpu_pmu_context);
2220         enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2221
2222         // XXX cpc serialization, probably per-cpu IRQ disabled
2223
2224         WARN_ON_ONCE(event->ctx != ctx);
2225         lockdep_assert_held(&ctx->lock);
2226
2227         if (event->state != PERF_EVENT_STATE_ACTIVE)
2228                 return;
2229
2230         /*
2231          * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2232          * we can schedule events _OUT_ individually through things like
2233          * __perf_remove_from_context().
2234          */
2235         list_del_init(&event->active_list);
2236
2237         perf_pmu_disable(event->pmu);
2238
2239         event->pmu->del(event, 0);
2240         event->oncpu = -1;
2241
2242         if (event->pending_disable) {
2243                 event->pending_disable = 0;
2244                 perf_cgroup_event_disable(event, ctx);
2245                 state = PERF_EVENT_STATE_OFF;
2246         }
2247
2248         if (event->pending_sigtrap) {
2249                 bool dec = true;
2250
2251                 event->pending_sigtrap = 0;
2252                 if (state != PERF_EVENT_STATE_OFF &&
2253                     !event->pending_work) {
2254                         event->pending_work = 1;
2255                         dec = false;
2256                         WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount));
2257                         task_work_add(current, &event->pending_task, TWA_RESUME);
2258                 }
2259                 if (dec)
2260                         local_dec(&event->ctx->nr_pending);
2261         }
2262
2263         perf_event_set_state(event, state);
2264
2265         if (!is_software_event(event))
2266                 cpc->active_oncpu--;
2267         if (event->attr.freq && event->attr.sample_freq)
2268                 ctx->nr_freq--;
2269         if (event->attr.exclusive || !cpc->active_oncpu)
2270                 cpc->exclusive = 0;
2271
2272         perf_pmu_enable(event->pmu);
2273 }
2274
2275 static void
2276 group_sched_out(struct perf_event *group_event, struct perf_event_context *ctx)
2277 {
2278         struct perf_event *event;
2279
2280         if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2281                 return;
2282
2283         perf_assert_pmu_disabled(group_event->pmu_ctx->pmu);
2284
2285         event_sched_out(group_event, ctx);
2286
2287         /*
2288          * Schedule out siblings (if any):
2289          */
2290         for_each_sibling_event(event, group_event)
2291                 event_sched_out(event, ctx);
2292 }
2293
2294 #define DETACH_GROUP    0x01UL
2295 #define DETACH_CHILD    0x02UL
2296 #define DETACH_DEAD     0x04UL
2297
2298 /*
2299  * Cross CPU call to remove a performance event
2300  *
2301  * We disable the event on the hardware level first. After that we
2302  * remove it from the context list.
2303  */
2304 static void
2305 __perf_remove_from_context(struct perf_event *event,
2306                            struct perf_cpu_context *cpuctx,
2307                            struct perf_event_context *ctx,
2308                            void *info)
2309 {
2310         struct perf_event_pmu_context *pmu_ctx = event->pmu_ctx;
2311         unsigned long flags = (unsigned long)info;
2312
2313         if (ctx->is_active & EVENT_TIME) {
2314                 update_context_time(ctx);
2315                 update_cgrp_time_from_cpuctx(cpuctx, false);
2316         }
2317
2318         /*
2319          * Ensure event_sched_out() switches to OFF, at the very least
2320          * this avoids raising perf_pending_task() at this time.
2321          */
2322         if (flags & DETACH_DEAD)
2323                 event->pending_disable = 1;
2324         event_sched_out(event, ctx);
2325         if (flags & DETACH_GROUP)
2326                 perf_group_detach(event);
2327         if (flags & DETACH_CHILD)
2328                 perf_child_detach(event);
2329         list_del_event(event, ctx);
2330         if (flags & DETACH_DEAD)
2331                 event->state = PERF_EVENT_STATE_DEAD;
2332
2333         if (!pmu_ctx->nr_events) {
2334                 pmu_ctx->rotate_necessary = 0;
2335
2336                 if (ctx->task && ctx->is_active) {
2337                         struct perf_cpu_pmu_context *cpc;
2338
2339                         cpc = this_cpu_ptr(pmu_ctx->pmu->cpu_pmu_context);
2340                         WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
2341                         cpc->task_epc = NULL;
2342                 }
2343         }
2344
2345         if (!ctx->nr_events && ctx->is_active) {
2346                 if (ctx == &cpuctx->ctx)
2347                         update_cgrp_time_from_cpuctx(cpuctx, true);
2348
2349                 ctx->is_active = 0;
2350                 if (ctx->task) {
2351                         WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2352                         cpuctx->task_ctx = NULL;
2353                 }
2354         }
2355 }
2356
2357 /*
2358  * Remove the event from a task's (or a CPU's) list of events.
2359  *
2360  * If event->ctx is a cloned context, callers must make sure that
2361  * every task struct that event->ctx->task could possibly point to
2362  * remains valid.  This is OK when called from perf_release since
2363  * that only calls us on the top-level context, which can't be a clone.
2364  * When called from perf_event_exit_task, it's OK because the
2365  * context has been detached from its task.
2366  */
2367 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2368 {
2369         struct perf_event_context *ctx = event->ctx;
2370
2371         lockdep_assert_held(&ctx->mutex);
2372
2373         /*
2374          * Because of perf_event_exit_task(), perf_remove_from_context() ought
2375          * to work in the face of TASK_TOMBSTONE, unlike every other
2376          * event_function_call() user.
2377          */
2378         raw_spin_lock_irq(&ctx->lock);
2379         if (!ctx->is_active) {
2380                 __perf_remove_from_context(event, this_cpu_ptr(&perf_cpu_context),
2381                                            ctx, (void *)flags);
2382                 raw_spin_unlock_irq(&ctx->lock);
2383                 return;
2384         }
2385         raw_spin_unlock_irq(&ctx->lock);
2386
2387         event_function_call(event, __perf_remove_from_context, (void *)flags);
2388 }
2389
2390 /*
2391  * Cross CPU call to disable a performance event
2392  */
2393 static void __perf_event_disable(struct perf_event *event,
2394                                  struct perf_cpu_context *cpuctx,
2395                                  struct perf_event_context *ctx,
2396                                  void *info)
2397 {
2398         if (event->state < PERF_EVENT_STATE_INACTIVE)
2399                 return;
2400
2401         if (ctx->is_active & EVENT_TIME) {
2402                 update_context_time(ctx);
2403                 update_cgrp_time_from_event(event);
2404         }
2405
2406         perf_pmu_disable(event->pmu_ctx->pmu);
2407
2408         if (event == event->group_leader)
2409                 group_sched_out(event, ctx);
2410         else
2411                 event_sched_out(event, ctx);
2412
2413         perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2414         perf_cgroup_event_disable(event, ctx);
2415
2416         perf_pmu_enable(event->pmu_ctx->pmu);
2417 }
2418
2419 /*
2420  * Disable an event.
2421  *
2422  * If event->ctx is a cloned context, callers must make sure that
2423  * every task struct that event->ctx->task could possibly point to
2424  * remains valid.  This condition is satisfied when called through
2425  * perf_event_for_each_child or perf_event_for_each because they
2426  * hold the top-level event's child_mutex, so any descendant that
2427  * goes to exit will block in perf_event_exit_event().
2428  *
2429  * When called from perf_pending_irq it's OK because event->ctx
2430  * is the current context on this CPU and preemption is disabled,
2431  * hence we can't get into perf_event_task_sched_out for this context.
2432  */
2433 static void _perf_event_disable(struct perf_event *event)
2434 {
2435         struct perf_event_context *ctx = event->ctx;
2436
2437         raw_spin_lock_irq(&ctx->lock);
2438         if (event->state <= PERF_EVENT_STATE_OFF) {
2439                 raw_spin_unlock_irq(&ctx->lock);
2440                 return;
2441         }
2442         raw_spin_unlock_irq(&ctx->lock);
2443
2444         event_function_call(event, __perf_event_disable, NULL);
2445 }
2446
2447 void perf_event_disable_local(struct perf_event *event)
2448 {
2449         event_function_local(event, __perf_event_disable, NULL);
2450 }
2451
2452 /*
2453  * Strictly speaking kernel users cannot create groups and therefore this
2454  * interface does not need the perf_event_ctx_lock() magic.
2455  */
2456 void perf_event_disable(struct perf_event *event)
2457 {
2458         struct perf_event_context *ctx;
2459
2460         ctx = perf_event_ctx_lock(event);
2461         _perf_event_disable(event);
2462         perf_event_ctx_unlock(event, ctx);
2463 }
2464 EXPORT_SYMBOL_GPL(perf_event_disable);
2465
2466 void perf_event_disable_inatomic(struct perf_event *event)
2467 {
2468         event->pending_disable = 1;
2469         irq_work_queue(&event->pending_irq);
2470 }
2471
2472 #define MAX_INTERRUPTS (~0ULL)
2473
2474 static void perf_log_throttle(struct perf_event *event, int enable);
2475 static void perf_log_itrace_start(struct perf_event *event);
2476
2477 static int
2478 event_sched_in(struct perf_event *event, struct perf_event_context *ctx)
2479 {
2480         struct perf_event_pmu_context *epc = event->pmu_ctx;
2481         struct perf_cpu_pmu_context *cpc = this_cpu_ptr(epc->pmu->cpu_pmu_context);
2482         int ret = 0;
2483
2484         WARN_ON_ONCE(event->ctx != ctx);
2485
2486         lockdep_assert_held(&ctx->lock);
2487
2488         if (event->state <= PERF_EVENT_STATE_OFF)
2489                 return 0;
2490
2491         WRITE_ONCE(event->oncpu, smp_processor_id());
2492         /*
2493          * Order event::oncpu write to happen before the ACTIVE state is
2494          * visible. This allows perf_event_{stop,read}() to observe the correct
2495          * ->oncpu if it sees ACTIVE.
2496          */
2497         smp_wmb();
2498         perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2499
2500         /*
2501          * Unthrottle events, since we scheduled we might have missed several
2502          * ticks already, also for a heavily scheduling task there is little
2503          * guarantee it'll get a tick in a timely manner.
2504          */
2505         if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2506                 perf_log_throttle(event, 1);
2507                 event->hw.interrupts = 0;
2508         }
2509
2510         perf_pmu_disable(event->pmu);
2511
2512         perf_log_itrace_start(event);
2513
2514         if (event->pmu->add(event, PERF_EF_START)) {
2515                 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2516                 event->oncpu = -1;
2517                 ret = -EAGAIN;
2518                 goto out;
2519         }
2520
2521         if (!is_software_event(event))
2522                 cpc->active_oncpu++;
2523         if (event->attr.freq && event->attr.sample_freq)
2524                 ctx->nr_freq++;
2525
2526         if (event->attr.exclusive)
2527                 cpc->exclusive = 1;
2528
2529 out:
2530         perf_pmu_enable(event->pmu);
2531
2532         return ret;
2533 }
2534
2535 static int
2536 group_sched_in(struct perf_event *group_event, struct perf_event_context *ctx)
2537 {
2538         struct perf_event *event, *partial_group = NULL;
2539         struct pmu *pmu = group_event->pmu_ctx->pmu;
2540
2541         if (group_event->state == PERF_EVENT_STATE_OFF)
2542                 return 0;
2543
2544         pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2545
2546         if (event_sched_in(group_event, ctx))
2547                 goto error;
2548
2549         /*
2550          * Schedule in siblings as one group (if any):
2551          */
2552         for_each_sibling_event(event, group_event) {
2553                 if (event_sched_in(event, ctx)) {
2554                         partial_group = event;
2555                         goto group_error;
2556                 }
2557         }
2558
2559         if (!pmu->commit_txn(pmu))
2560                 return 0;
2561
2562 group_error:
2563         /*
2564          * Groups can be scheduled in as one unit only, so undo any
2565          * partial group before returning:
2566          * The events up to the failed event are scheduled out normally.
2567          */
2568         for_each_sibling_event(event, group_event) {
2569                 if (event == partial_group)
2570                         break;
2571
2572                 event_sched_out(event, ctx);
2573         }
2574         event_sched_out(group_event, ctx);
2575
2576 error:
2577         pmu->cancel_txn(pmu);
2578         return -EAGAIN;
2579 }
2580
2581 /*
2582  * Work out whether we can put this event group on the CPU now.
2583  */
2584 static int group_can_go_on(struct perf_event *event, int can_add_hw)
2585 {
2586         struct perf_event_pmu_context *epc = event->pmu_ctx;
2587         struct perf_cpu_pmu_context *cpc = this_cpu_ptr(epc->pmu->cpu_pmu_context);
2588
2589         /*
2590          * Groups consisting entirely of software events can always go on.
2591          */
2592         if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2593                 return 1;
2594         /*
2595          * If an exclusive group is already on, no other hardware
2596          * events can go on.
2597          */
2598         if (cpc->exclusive)
2599                 return 0;
2600         /*
2601          * If this group is exclusive and there are already
2602          * events on the CPU, it can't go on.
2603          */
2604         if (event->attr.exclusive && !list_empty(get_event_list(event)))
2605                 return 0;
2606         /*
2607          * Otherwise, try to add it if all previous groups were able
2608          * to go on.
2609          */
2610         return can_add_hw;
2611 }
2612
2613 static void add_event_to_ctx(struct perf_event *event,
2614                                struct perf_event_context *ctx)
2615 {
2616         list_add_event(event, ctx);
2617         perf_group_attach(event);
2618 }
2619
2620 static void task_ctx_sched_out(struct perf_event_context *ctx,
2621                                 enum event_type_t event_type)
2622 {
2623         struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2624
2625         if (!cpuctx->task_ctx)
2626                 return;
2627
2628         if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2629                 return;
2630
2631         ctx_sched_out(ctx, event_type);
2632 }
2633
2634 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2635                                 struct perf_event_context *ctx)
2636 {
2637         ctx_sched_in(&cpuctx->ctx, EVENT_PINNED);
2638         if (ctx)
2639                  ctx_sched_in(ctx, EVENT_PINNED);
2640         ctx_sched_in(&cpuctx->ctx, EVENT_FLEXIBLE);
2641         if (ctx)
2642                  ctx_sched_in(ctx, EVENT_FLEXIBLE);
2643 }
2644
2645 /*
2646  * We want to maintain the following priority of scheduling:
2647  *  - CPU pinned (EVENT_CPU | EVENT_PINNED)
2648  *  - task pinned (EVENT_PINNED)
2649  *  - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2650  *  - task flexible (EVENT_FLEXIBLE).
2651  *
2652  * In order to avoid unscheduling and scheduling back in everything every
2653  * time an event is added, only do it for the groups of equal priority and
2654  * below.
2655  *
2656  * This can be called after a batch operation on task events, in which case
2657  * event_type is a bit mask of the types of events involved. For CPU events,
2658  * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2659  */
2660 /*
2661  * XXX: ctx_resched() reschedule entire perf_event_context while adding new
2662  * event to the context or enabling existing event in the context. We can
2663  * probably optimize it by rescheduling only affected pmu_ctx.
2664  */
2665 static void ctx_resched(struct perf_cpu_context *cpuctx,
2666                         struct perf_event_context *task_ctx,
2667                         enum event_type_t event_type)
2668 {
2669         bool cpu_event = !!(event_type & EVENT_CPU);
2670
2671         /*
2672          * If pinned groups are involved, flexible groups also need to be
2673          * scheduled out.
2674          */
2675         if (event_type & EVENT_PINNED)
2676                 event_type |= EVENT_FLEXIBLE;
2677
2678         event_type &= EVENT_ALL;
2679
2680         perf_ctx_disable(&cpuctx->ctx);
2681         if (task_ctx) {
2682                 perf_ctx_disable(task_ctx);
2683                 task_ctx_sched_out(task_ctx, event_type);
2684         }
2685
2686         /*
2687          * Decide which cpu ctx groups to schedule out based on the types
2688          * of events that caused rescheduling:
2689          *  - EVENT_CPU: schedule out corresponding groups;
2690          *  - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2691          *  - otherwise, do nothing more.
2692          */
2693         if (cpu_event)
2694                 ctx_sched_out(&cpuctx->ctx, event_type);
2695         else if (event_type & EVENT_PINNED)
2696                 ctx_sched_out(&cpuctx->ctx, EVENT_FLEXIBLE);
2697
2698         perf_event_sched_in(cpuctx, task_ctx);
2699
2700         perf_ctx_enable(&cpuctx->ctx);
2701         if (task_ctx)
2702                 perf_ctx_enable(task_ctx);
2703 }
2704
2705 void perf_pmu_resched(struct pmu *pmu)
2706 {
2707         struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2708         struct perf_event_context *task_ctx = cpuctx->task_ctx;
2709
2710         perf_ctx_lock(cpuctx, task_ctx);
2711         ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU);
2712         perf_ctx_unlock(cpuctx, task_ctx);
2713 }
2714
2715 /*
2716  * Cross CPU call to install and enable a performance event
2717  *
2718  * Very similar to remote_function() + event_function() but cannot assume that
2719  * things like ctx->is_active and cpuctx->task_ctx are set.
2720  */
2721 static int  __perf_install_in_context(void *info)
2722 {
2723         struct perf_event *event = info;
2724         struct perf_event_context *ctx = event->ctx;
2725         struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2726         struct perf_event_context *task_ctx = cpuctx->task_ctx;
2727         bool reprogram = true;
2728         int ret = 0;
2729
2730         raw_spin_lock(&cpuctx->ctx.lock);
2731         if (ctx->task) {
2732                 raw_spin_lock(&ctx->lock);
2733                 task_ctx = ctx;
2734
2735                 reprogram = (ctx->task == current);
2736
2737                 /*
2738                  * If the task is running, it must be running on this CPU,
2739                  * otherwise we cannot reprogram things.
2740                  *
2741                  * If its not running, we don't care, ctx->lock will
2742                  * serialize against it becoming runnable.
2743                  */
2744                 if (task_curr(ctx->task) && !reprogram) {
2745                         ret = -ESRCH;
2746                         goto unlock;
2747                 }
2748
2749                 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2750         } else if (task_ctx) {
2751                 raw_spin_lock(&task_ctx->lock);
2752         }
2753
2754 #ifdef CONFIG_CGROUP_PERF
2755         if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
2756                 /*
2757                  * If the current cgroup doesn't match the event's
2758                  * cgroup, we should not try to schedule it.
2759                  */
2760                 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2761                 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2762                                         event->cgrp->css.cgroup);
2763         }
2764 #endif
2765
2766         if (reprogram) {
2767                 ctx_sched_out(ctx, EVENT_TIME);
2768                 add_event_to_ctx(event, ctx);
2769                 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2770         } else {
2771                 add_event_to_ctx(event, ctx);
2772         }
2773
2774 unlock:
2775         perf_ctx_unlock(cpuctx, task_ctx);
2776
2777         return ret;
2778 }
2779
2780 static bool exclusive_event_installable(struct perf_event *event,
2781                                         struct perf_event_context *ctx);
2782
2783 /*
2784  * Attach a performance event to a context.
2785  *
2786  * Very similar to event_function_call, see comment there.
2787  */
2788 static void
2789 perf_install_in_context(struct perf_event_context *ctx,
2790                         struct perf_event *event,
2791                         int cpu)
2792 {
2793         struct task_struct *task = READ_ONCE(ctx->task);
2794
2795         lockdep_assert_held(&ctx->mutex);
2796
2797         WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2798
2799         if (event->cpu != -1)
2800                 WARN_ON_ONCE(event->cpu != cpu);
2801
2802         /*
2803          * Ensures that if we can observe event->ctx, both the event and ctx
2804          * will be 'complete'. See perf_iterate_sb_cpu().
2805          */
2806         smp_store_release(&event->ctx, ctx);
2807
2808         /*
2809          * perf_event_attr::disabled events will not run and can be initialized
2810          * without IPI. Except when this is the first event for the context, in
2811          * that case we need the magic of the IPI to set ctx->is_active.
2812          *
2813          * The IOC_ENABLE that is sure to follow the creation of a disabled
2814          * event will issue the IPI and reprogram the hardware.
2815          */
2816         if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF &&
2817             ctx->nr_events && !is_cgroup_event(event)) {
2818                 raw_spin_lock_irq(&ctx->lock);
2819                 if (ctx->task == TASK_TOMBSTONE) {
2820                         raw_spin_unlock_irq(&ctx->lock);
2821                         return;
2822                 }
2823                 add_event_to_ctx(event, ctx);
2824                 raw_spin_unlock_irq(&ctx->lock);
2825                 return;
2826         }
2827
2828         if (!task) {
2829                 cpu_function_call(cpu, __perf_install_in_context, event);
2830                 return;
2831         }
2832
2833         /*
2834          * Should not happen, we validate the ctx is still alive before calling.
2835          */
2836         if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2837                 return;
2838
2839         /*
2840          * Installing events is tricky because we cannot rely on ctx->is_active
2841          * to be set in case this is the nr_events 0 -> 1 transition.
2842          *
2843          * Instead we use task_curr(), which tells us if the task is running.
2844          * However, since we use task_curr() outside of rq::lock, we can race
2845          * against the actual state. This means the result can be wrong.
2846          *
2847          * If we get a false positive, we retry, this is harmless.
2848          *
2849          * If we get a false negative, things are complicated. If we are after
2850          * perf_event_context_sched_in() ctx::lock will serialize us, and the
2851          * value must be correct. If we're before, it doesn't matter since
2852          * perf_event_context_sched_in() will program the counter.
2853          *
2854          * However, this hinges on the remote context switch having observed
2855          * our task->perf_event_ctxp[] store, such that it will in fact take
2856          * ctx::lock in perf_event_context_sched_in().
2857          *
2858          * We do this by task_function_call(), if the IPI fails to hit the task
2859          * we know any future context switch of task must see the
2860          * perf_event_ctpx[] store.
2861          */
2862
2863         /*
2864          * This smp_mb() orders the task->perf_event_ctxp[] store with the
2865          * task_cpu() load, such that if the IPI then does not find the task
2866          * running, a future context switch of that task must observe the
2867          * store.
2868          */
2869         smp_mb();
2870 again:
2871         if (!task_function_call(task, __perf_install_in_context, event))
2872                 return;
2873
2874         raw_spin_lock_irq(&ctx->lock);
2875         task = ctx->task;
2876         if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2877                 /*
2878                  * Cannot happen because we already checked above (which also
2879                  * cannot happen), and we hold ctx->mutex, which serializes us
2880                  * against perf_event_exit_task_context().
2881                  */
2882                 raw_spin_unlock_irq(&ctx->lock);
2883                 return;
2884         }
2885         /*
2886          * If the task is not running, ctx->lock will avoid it becoming so,
2887          * thus we can safely install the event.
2888          */
2889         if (task_curr(task)) {
2890                 raw_spin_unlock_irq(&ctx->lock);
2891                 goto again;
2892         }
2893         add_event_to_ctx(event, ctx);
2894         raw_spin_unlock_irq(&ctx->lock);
2895 }
2896
2897 /*
2898  * Cross CPU call to enable a performance event
2899  */
2900 static void __perf_event_enable(struct perf_event *event,
2901                                 struct perf_cpu_context *cpuctx,
2902                                 struct perf_event_context *ctx,
2903                                 void *info)
2904 {
2905         struct perf_event *leader = event->group_leader;
2906         struct perf_event_context *task_ctx;
2907
2908         if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2909             event->state <= PERF_EVENT_STATE_ERROR)
2910                 return;
2911
2912         if (ctx->is_active)
2913                 ctx_sched_out(ctx, EVENT_TIME);
2914
2915         perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2916         perf_cgroup_event_enable(event, ctx);
2917
2918         if (!ctx->is_active)
2919                 return;
2920
2921         if (!event_filter_match(event)) {
2922                 ctx_sched_in(ctx, EVENT_TIME);
2923                 return;
2924         }
2925
2926         /*
2927          * If the event is in a group and isn't the group leader,
2928          * then don't put it on unless the group is on.
2929          */
2930         if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2931                 ctx_sched_in(ctx, EVENT_TIME);
2932                 return;
2933         }
2934
2935         task_ctx = cpuctx->task_ctx;
2936         if (ctx->task)
2937                 WARN_ON_ONCE(task_ctx != ctx);
2938
2939         ctx_resched(cpuctx, task_ctx, get_event_type(event));
2940 }
2941
2942 /*
2943  * Enable an event.
2944  *
2945  * If event->ctx is a cloned context, callers must make sure that
2946  * every task struct that event->ctx->task could possibly point to
2947  * remains valid.  This condition is satisfied when called through
2948  * perf_event_for_each_child or perf_event_for_each as described
2949  * for perf_event_disable.
2950  */
2951 static void _perf_event_enable(struct perf_event *event)
2952 {
2953         struct perf_event_context *ctx = event->ctx;
2954
2955         raw_spin_lock_irq(&ctx->lock);
2956         if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2957             event->state <  PERF_EVENT_STATE_ERROR) {
2958 out:
2959                 raw_spin_unlock_irq(&ctx->lock);
2960                 return;
2961         }
2962
2963         /*
2964          * If the event is in error state, clear that first.
2965          *
2966          * That way, if we see the event in error state below, we know that it
2967          * has gone back into error state, as distinct from the task having
2968          * been scheduled away before the cross-call arrived.
2969          */
2970         if (event->state == PERF_EVENT_STATE_ERROR) {
2971                 /*
2972                  * Detached SIBLING events cannot leave ERROR state.
2973                  */
2974                 if (event->event_caps & PERF_EV_CAP_SIBLING &&
2975                     event->group_leader == event)
2976                         goto out;
2977
2978                 event->state = PERF_EVENT_STATE_OFF;
2979         }
2980         raw_spin_unlock_irq(&ctx->lock);
2981
2982         event_function_call(event, __perf_event_enable, NULL);
2983 }
2984
2985 /*
2986  * See perf_event_disable();
2987  */
2988 void perf_event_enable(struct perf_event *event)
2989 {
2990         struct perf_event_context *ctx;
2991
2992         ctx = perf_event_ctx_lock(event);
2993         _perf_event_enable(event);
2994         perf_event_ctx_unlock(event, ctx);
2995 }
2996 EXPORT_SYMBOL_GPL(perf_event_enable);
2997
2998 struct stop_event_data {
2999         struct perf_event       *event;
3000         unsigned int            restart;
3001 };
3002
3003 static int __perf_event_stop(void *info)
3004 {
3005         struct stop_event_data *sd = info;
3006         struct perf_event *event = sd->event;
3007
3008         /* if it's already INACTIVE, do nothing */
3009         if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3010                 return 0;
3011
3012         /* matches smp_wmb() in event_sched_in() */
3013         smp_rmb();
3014
3015         /*
3016          * There is a window with interrupts enabled before we get here,
3017          * so we need to check again lest we try to stop another CPU's event.
3018          */
3019         if (READ_ONCE(event->oncpu) != smp_processor_id())
3020                 return -EAGAIN;
3021
3022         event->pmu->stop(event, PERF_EF_UPDATE);
3023
3024         /*
3025          * May race with the actual stop (through perf_pmu_output_stop()),
3026          * but it is only used for events with AUX ring buffer, and such
3027          * events will refuse to restart because of rb::aux_mmap_count==0,
3028          * see comments in perf_aux_output_begin().
3029          *
3030          * Since this is happening on an event-local CPU, no trace is lost
3031          * while restarting.
3032          */
3033         if (sd->restart)
3034                 event->pmu->start(event, 0);
3035
3036         return 0;
3037 }
3038
3039 static int perf_event_stop(struct perf_event *event, int restart)
3040 {
3041         struct stop_event_data sd = {
3042                 .event          = event,
3043                 .restart        = restart,
3044         };
3045         int ret = 0;
3046
3047         do {
3048                 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3049                         return 0;
3050
3051                 /* matches smp_wmb() in event_sched_in() */
3052                 smp_rmb();
3053
3054                 /*
3055                  * We only want to restart ACTIVE events, so if the event goes
3056                  * inactive here (event->oncpu==-1), there's nothing more to do;
3057                  * fall through with ret==-ENXIO.
3058                  */
3059                 ret = cpu_function_call(READ_ONCE(event->oncpu),
3060                                         __perf_event_stop, &sd);
3061         } while (ret == -EAGAIN);
3062
3063         return ret;
3064 }
3065
3066 /*
3067  * In order to contain the amount of racy and tricky in the address filter
3068  * configuration management, it is a two part process:
3069  *
3070  * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3071  *      we update the addresses of corresponding vmas in
3072  *      event::addr_filter_ranges array and bump the event::addr_filters_gen;
3073  * (p2) when an event is scheduled in (pmu::add), it calls
3074  *      perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3075  *      if the generation has changed since the previous call.
3076  *
3077  * If (p1) happens while the event is active, we restart it to force (p2).
3078  *
3079  * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3080  *     pre-existing mappings, called once when new filters arrive via SET_FILTER
3081  *     ioctl;
3082  * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3083  *     registered mapping, called for every new mmap(), with mm::mmap_lock down
3084  *     for reading;
3085  * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3086  *     of exec.
3087  */
3088 void perf_event_addr_filters_sync(struct perf_event *event)
3089 {
3090         struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3091
3092         if (!has_addr_filter(event))
3093                 return;
3094
3095         raw_spin_lock(&ifh->lock);
3096         if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3097                 event->pmu->addr_filters_sync(event);
3098                 event->hw.addr_filters_gen = event->addr_filters_gen;
3099         }
3100         raw_spin_unlock(&ifh->lock);
3101 }
3102 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3103
3104 static int _perf_event_refresh(struct perf_event *event, int refresh)
3105 {
3106         /*
3107          * not supported on inherited events
3108          */
3109         if (event->attr.inherit || !is_sampling_event(event))
3110                 return -EINVAL;
3111
3112         atomic_add(refresh, &event->event_limit);
3113         _perf_event_enable(event);
3114
3115         return 0;
3116 }
3117
3118 /*
3119  * See perf_event_disable()
3120  */
3121 int perf_event_refresh(struct perf_event *event, int refresh)
3122 {
3123         struct perf_event_context *ctx;
3124         int ret;
3125
3126         ctx = perf_event_ctx_lock(event);
3127         ret = _perf_event_refresh(event, refresh);
3128         perf_event_ctx_unlock(event, ctx);
3129
3130         return ret;
3131 }
3132 EXPORT_SYMBOL_GPL(perf_event_refresh);
3133
3134 static int perf_event_modify_breakpoint(struct perf_event *bp,
3135                                          struct perf_event_attr *attr)
3136 {
3137         int err;
3138
3139         _perf_event_disable(bp);
3140
3141         err = modify_user_hw_breakpoint_check(bp, attr, true);
3142
3143         if (!bp->attr.disabled)
3144                 _perf_event_enable(bp);
3145
3146         return err;
3147 }
3148
3149 /*
3150  * Copy event-type-independent attributes that may be modified.
3151  */
3152 static void perf_event_modify_copy_attr(struct perf_event_attr *to,
3153                                         const struct perf_event_attr *from)
3154 {
3155         to->sig_data = from->sig_data;
3156 }
3157
3158 static int perf_event_modify_attr(struct perf_event *event,
3159                                   struct perf_event_attr *attr)
3160 {
3161         int (*func)(struct perf_event *, struct perf_event_attr *);
3162         struct perf_event *child;
3163         int err;
3164
3165         if (event->attr.type != attr->type)
3166                 return -EINVAL;
3167
3168         switch (event->attr.type) {
3169         case PERF_TYPE_BREAKPOINT:
3170                 func = perf_event_modify_breakpoint;
3171                 break;
3172         default:
3173                 /* Place holder for future additions. */
3174                 return -EOPNOTSUPP;
3175         }
3176
3177         WARN_ON_ONCE(event->ctx->parent_ctx);
3178
3179         mutex_lock(&event->child_mutex);
3180         /*
3181          * Event-type-independent attributes must be copied before event-type
3182          * modification, which will validate that final attributes match the
3183          * source attributes after all relevant attributes have been copied.
3184          */
3185         perf_event_modify_copy_attr(&event->attr, attr);
3186         err = func(event, attr);
3187         if (err)
3188                 goto out;
3189         list_for_each_entry(child, &event->child_list, child_list) {
3190                 perf_event_modify_copy_attr(&child->attr, attr);
3191                 err = func(child, attr);
3192                 if (err)
3193                         goto out;
3194         }
3195 out:
3196         mutex_unlock(&event->child_mutex);
3197         return err;
3198 }
3199
3200 static void __pmu_ctx_sched_out(struct perf_event_pmu_context *pmu_ctx,
3201                                 enum event_type_t event_type)
3202 {
3203         struct perf_event_context *ctx = pmu_ctx->ctx;
3204         struct perf_event *event, *tmp;
3205         struct pmu *pmu = pmu_ctx->pmu;
3206
3207         if (ctx->task && !ctx->is_active) {
3208                 struct perf_cpu_pmu_context *cpc;
3209
3210                 cpc = this_cpu_ptr(pmu->cpu_pmu_context);
3211                 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
3212                 cpc->task_epc = NULL;
3213         }
3214
3215         if (!event_type)
3216                 return;
3217
3218         perf_pmu_disable(pmu);
3219         if (event_type & EVENT_PINNED) {
3220                 list_for_each_entry_safe(event, tmp,
3221                                          &pmu_ctx->pinned_active,
3222                                          active_list)
3223                         group_sched_out(event, ctx);
3224         }
3225
3226         if (event_type & EVENT_FLEXIBLE) {
3227                 list_for_each_entry_safe(event, tmp,
3228                                          &pmu_ctx->flexible_active,
3229                                          active_list)
3230                         group_sched_out(event, ctx);
3231                 /*
3232                  * Since we cleared EVENT_FLEXIBLE, also clear
3233                  * rotate_necessary, is will be reset by
3234                  * ctx_flexible_sched_in() when needed.
3235                  */
3236                 pmu_ctx->rotate_necessary = 0;
3237         }
3238         perf_pmu_enable(pmu);
3239 }
3240
3241 static void
3242 ctx_sched_out(struct perf_event_context *ctx, enum event_type_t event_type)
3243 {
3244         struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3245         struct perf_event_pmu_context *pmu_ctx;
3246         int is_active = ctx->is_active;
3247
3248         lockdep_assert_held(&ctx->lock);
3249
3250         if (likely(!ctx->nr_events)) {
3251                 /*
3252                  * See __perf_remove_from_context().
3253                  */
3254                 WARN_ON_ONCE(ctx->is_active);
3255                 if (ctx->task)
3256                         WARN_ON_ONCE(cpuctx->task_ctx);
3257                 return;
3258         }
3259
3260         /*
3261          * Always update time if it was set; not only when it changes.
3262          * Otherwise we can 'forget' to update time for any but the last
3263          * context we sched out. For example:
3264          *
3265          *   ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3266          *   ctx_sched_out(.event_type = EVENT_PINNED)
3267          *
3268          * would only update time for the pinned events.
3269          */
3270         if (is_active & EVENT_TIME) {
3271                 /* update (and stop) ctx time */
3272                 update_context_time(ctx);
3273                 update_cgrp_time_from_cpuctx(cpuctx, ctx == &cpuctx->ctx);
3274                 /*
3275                  * CPU-release for the below ->is_active store,
3276                  * see __load_acquire() in perf_event_time_now()
3277                  */
3278                 barrier();
3279         }
3280
3281         ctx->is_active &= ~event_type;
3282         if (!(ctx->is_active & EVENT_ALL))
3283                 ctx->is_active = 0;
3284
3285         if (ctx->task) {
3286                 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3287                 if (!ctx->is_active)
3288                         cpuctx->task_ctx = NULL;
3289         }
3290
3291         is_active ^= ctx->is_active; /* changed bits */
3292
3293         list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry)
3294                 __pmu_ctx_sched_out(pmu_ctx, is_active);
3295 }
3296
3297 /*
3298  * Test whether two contexts are equivalent, i.e. whether they have both been
3299  * cloned from the same version of the same context.
3300  *
3301  * Equivalence is measured using a generation number in the context that is
3302  * incremented on each modification to it; see unclone_ctx(), list_add_event()
3303  * and list_del_event().
3304  */
3305 static int context_equiv(struct perf_event_context *ctx1,
3306                          struct perf_event_context *ctx2)
3307 {
3308         lockdep_assert_held(&ctx1->lock);
3309         lockdep_assert_held(&ctx2->lock);
3310
3311         /* Pinning disables the swap optimization */
3312         if (ctx1->pin_count || ctx2->pin_count)
3313                 return 0;
3314
3315         /* If ctx1 is the parent of ctx2 */
3316         if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3317                 return 1;
3318
3319         /* If ctx2 is the parent of ctx1 */
3320         if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3321                 return 1;
3322
3323         /*
3324          * If ctx1 and ctx2 have the same parent; we flatten the parent
3325          * hierarchy, see perf_event_init_context().
3326          */
3327         if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3328                         ctx1->parent_gen == ctx2->parent_gen)
3329                 return 1;
3330
3331         /* Unmatched */
3332         return 0;
3333 }
3334
3335 static void __perf_event_sync_stat(struct perf_event *event,
3336                                      struct perf_event *next_event)
3337 {
3338         u64 value;
3339
3340         if (!event->attr.inherit_stat)
3341                 return;
3342
3343         /*
3344          * Update the event value, we cannot use perf_event_read()
3345          * because we're in the middle of a context switch and have IRQs
3346          * disabled, which upsets smp_call_function_single(), however
3347          * we know the event must be on the current CPU, therefore we
3348          * don't need to use it.
3349          */
3350         if (event->state == PERF_EVENT_STATE_ACTIVE)
3351                 event->pmu->read(event);
3352
3353         perf_event_update_time(event);
3354
3355         /*
3356          * In order to keep per-task stats reliable we need to flip the event
3357          * values when we flip the contexts.
3358          */
3359         value = local64_read(&next_event->count);
3360         value = local64_xchg(&event->count, value);
3361         local64_set(&next_event->count, value);
3362
3363         swap(event->total_time_enabled, next_event->total_time_enabled);
3364         swap(event->total_time_running, next_event->total_time_running);
3365
3366         /*
3367          * Since we swizzled the values, update the user visible data too.
3368          */
3369         perf_event_update_userpage(event);
3370         perf_event_update_userpage(next_event);
3371 }
3372
3373 static void perf_event_sync_stat(struct perf_event_context *ctx,
3374                                    struct perf_event_context *next_ctx)
3375 {
3376         struct perf_event *event, *next_event;
3377
3378         if (!ctx->nr_stat)
3379                 return;
3380
3381         update_context_time(ctx);
3382
3383         event = list_first_entry(&ctx->event_list,
3384                                    struct perf_event, event_entry);
3385
3386         next_event = list_first_entry(&next_ctx->event_list,
3387                                         struct perf_event, event_entry);
3388
3389         while (&event->event_entry != &ctx->event_list &&
3390                &next_event->event_entry != &next_ctx->event_list) {
3391
3392                 __perf_event_sync_stat(event, next_event);
3393
3394                 event = list_next_entry(event, event_entry);
3395                 next_event = list_next_entry(next_event, event_entry);
3396         }
3397 }
3398
3399 #define double_list_for_each_entry(pos1, pos2, head1, head2, member)    \
3400         for (pos1 = list_first_entry(head1, typeof(*pos1), member),     \
3401              pos2 = list_first_entry(head2, typeof(*pos2), member);     \
3402              !list_entry_is_head(pos1, head1, member) &&                \
3403              !list_entry_is_head(pos2, head2, member);                  \
3404              pos1 = list_next_entry(pos1, member),                      \
3405              pos2 = list_next_entry(pos2, member))
3406
3407 static void perf_event_swap_task_ctx_data(struct perf_event_context *prev_ctx,
3408                                           struct perf_event_context *next_ctx)
3409 {
3410         struct perf_event_pmu_context *prev_epc, *next_epc;
3411
3412         if (!prev_ctx->nr_task_data)
3413                 return;
3414
3415         double_list_for_each_entry(prev_epc, next_epc,
3416                                    &prev_ctx->pmu_ctx_list, &next_ctx->pmu_ctx_list,
3417                                    pmu_ctx_entry) {
3418
3419                 if (WARN_ON_ONCE(prev_epc->pmu != next_epc->pmu))
3420                         continue;
3421
3422                 /*
3423                  * PMU specific parts of task perf context can require
3424                  * additional synchronization. As an example of such
3425                  * synchronization see implementation details of Intel
3426                  * LBR call stack data profiling;
3427                  */
3428                 if (prev_epc->pmu->swap_task_ctx)
3429                         prev_epc->pmu->swap_task_ctx(prev_epc, next_epc);
3430                 else
3431                         swap(prev_epc->task_ctx_data, next_epc->task_ctx_data);
3432         }
3433 }
3434
3435 static void perf_ctx_sched_task_cb(struct perf_event_context *ctx, bool sched_in)
3436 {
3437         struct perf_event_pmu_context *pmu_ctx;
3438         struct perf_cpu_pmu_context *cpc;
3439
3440         list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
3441                 cpc = this_cpu_ptr(pmu_ctx->pmu->cpu_pmu_context);
3442
3443                 if (cpc->sched_cb_usage && pmu_ctx->pmu->sched_task)
3444                         pmu_ctx->pmu->sched_task(pmu_ctx, sched_in);
3445         }
3446 }
3447
3448 static void
3449 perf_event_context_sched_out(struct task_struct *task, struct task_struct *next)
3450 {
3451         struct perf_event_context *ctx = task->perf_event_ctxp;
3452         struct perf_event_context *next_ctx;
3453         struct perf_event_context *parent, *next_parent;
3454         int do_switch = 1;
3455
3456         if (likely(!ctx))
3457                 return;
3458
3459         rcu_read_lock();
3460         next_ctx = rcu_dereference(next->perf_event_ctxp);
3461         if (!next_ctx)
3462                 goto unlock;
3463
3464         parent = rcu_dereference(ctx->parent_ctx);
3465         next_parent = rcu_dereference(next_ctx->parent_ctx);
3466
3467         /* If neither context have a parent context; they cannot be clones. */
3468         if (!parent && !next_parent)
3469                 goto unlock;
3470
3471         if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3472                 /*
3473                  * Looks like the two contexts are clones, so we might be
3474                  * able to optimize the context switch.  We lock both
3475                  * contexts and check that they are clones under the
3476                  * lock (including re-checking that neither has been
3477                  * uncloned in the meantime).  It doesn't matter which
3478                  * order we take the locks because no other cpu could
3479                  * be trying to lock both of these tasks.
3480                  */
3481                 raw_spin_lock(&ctx->lock);
3482                 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3483                 if (context_equiv(ctx, next_ctx)) {
3484
3485                         perf_ctx_disable(ctx);
3486
3487                         /* PMIs are disabled; ctx->nr_pending is stable. */
3488                         if (local_read(&ctx->nr_pending) ||
3489                             local_read(&next_ctx->nr_pending)) {
3490                                 /*
3491                                  * Must not swap out ctx when there's pending
3492                                  * events that rely on the ctx->task relation.
3493                                  */
3494                                 raw_spin_unlock(&next_ctx->lock);
3495                                 rcu_read_unlock();
3496                                 goto inside_switch;
3497                         }
3498
3499                         WRITE_ONCE(ctx->task, next);
3500                         WRITE_ONCE(next_ctx->task, task);
3501
3502                         perf_ctx_sched_task_cb(ctx, false);
3503                         perf_event_swap_task_ctx_data(ctx, next_ctx);
3504
3505                         perf_ctx_enable(ctx);
3506
3507                         /*
3508                          * RCU_INIT_POINTER here is safe because we've not
3509                          * modified the ctx and the above modification of
3510                          * ctx->task and ctx->task_ctx_data are immaterial
3511                          * since those values are always verified under
3512                          * ctx->lock which we're now holding.
3513                          */
3514                         RCU_INIT_POINTER(task->perf_event_ctxp, next_ctx);
3515                         RCU_INIT_POINTER(next->perf_event_ctxp, ctx);
3516
3517                         do_switch = 0;
3518
3519                         perf_event_sync_stat(ctx, next_ctx);
3520                 }
3521                 raw_spin_unlock(&next_ctx->lock);
3522                 raw_spin_unlock(&ctx->lock);
3523         }
3524 unlock:
3525         rcu_read_unlock();
3526
3527         if (do_switch) {
3528                 raw_spin_lock(&ctx->lock);
3529                 perf_ctx_disable(ctx);
3530
3531 inside_switch:
3532                 perf_ctx_sched_task_cb(ctx, false);
3533                 task_ctx_sched_out(ctx, EVENT_ALL);
3534
3535                 perf_ctx_enable(ctx);
3536                 raw_spin_unlock(&ctx->lock);
3537         }
3538 }
3539
3540 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3541 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
3542
3543 void perf_sched_cb_dec(struct pmu *pmu)
3544 {
3545         struct perf_cpu_pmu_context *cpc = this_cpu_ptr(pmu->cpu_pmu_context);
3546
3547         this_cpu_dec(perf_sched_cb_usages);
3548         barrier();
3549
3550         if (!--cpc->sched_cb_usage)
3551                 list_del(&cpc->sched_cb_entry);
3552 }
3553
3554
3555 void perf_sched_cb_inc(struct pmu *pmu)
3556 {
3557         struct perf_cpu_pmu_context *cpc = this_cpu_ptr(pmu->cpu_pmu_context);
3558
3559         if (!cpc->sched_cb_usage++)
3560                 list_add(&cpc->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3561
3562         barrier();
3563         this_cpu_inc(perf_sched_cb_usages);
3564 }
3565
3566 /*
3567  * This function provides the context switch callback to the lower code
3568  * layer. It is invoked ONLY when the context switch callback is enabled.
3569  *
3570  * This callback is relevant even to per-cpu events; for example multi event
3571  * PEBS requires this to provide PID/TID information. This requires we flush
3572  * all queued PEBS records before we context switch to a new task.
3573  */
3574 static void __perf_pmu_sched_task(struct perf_cpu_pmu_context *cpc, bool sched_in)
3575 {
3576         struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3577         struct pmu *pmu;
3578
3579         pmu = cpc->epc.pmu;
3580
3581         /* software PMUs will not have sched_task */
3582         if (WARN_ON_ONCE(!pmu->sched_task))
3583                 return;
3584
3585         perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3586         perf_pmu_disable(pmu);
3587
3588         pmu->sched_task(cpc->task_epc, sched_in);
3589
3590         perf_pmu_enable(pmu);
3591         perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3592 }
3593
3594 static void perf_pmu_sched_task(struct task_struct *prev,
3595                                 struct task_struct *next,
3596                                 bool sched_in)
3597 {
3598         struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3599         struct perf_cpu_pmu_context *cpc;
3600
3601         /* cpuctx->task_ctx will be handled in perf_event_context_sched_in/out */
3602         if (prev == next || cpuctx->task_ctx)
3603                 return;
3604
3605         list_for_each_entry(cpc, this_cpu_ptr(&sched_cb_list), sched_cb_entry)
3606                 __perf_pmu_sched_task(cpc, sched_in);
3607 }
3608
3609 static void perf_event_switch(struct task_struct *task,
3610                               struct task_struct *next_prev, bool sched_in);
3611
3612 /*
3613  * Called from scheduler to remove the events of the current task,
3614  * with interrupts disabled.
3615  *
3616  * We stop each event and update the event value in event->count.
3617  *
3618  * This does not protect us against NMI, but disable()
3619  * sets the disabled bit in the control field of event _before_
3620  * accessing the event control register. If a NMI hits, then it will
3621  * not restart the event.
3622  */
3623 void __perf_event_task_sched_out(struct task_struct *task,
3624                                  struct task_struct *next)
3625 {
3626         if (__this_cpu_read(perf_sched_cb_usages))
3627                 perf_pmu_sched_task(task, next, false);
3628
3629         if (atomic_read(&nr_switch_events))
3630                 perf_event_switch(task, next, false);
3631
3632         perf_event_context_sched_out(task, next);
3633
3634         /*
3635          * if cgroup events exist on this CPU, then we need
3636          * to check if we have to switch out PMU state.
3637          * cgroup event are system-wide mode only
3638          */
3639         perf_cgroup_switch(next);
3640 }
3641
3642 static bool perf_less_group_idx(const void *l, const void *r)
3643 {
3644         const struct perf_event *le = *(const struct perf_event **)l;
3645         const struct perf_event *re = *(const struct perf_event **)r;
3646
3647         return le->group_index < re->group_index;
3648 }
3649
3650 static void swap_ptr(void *l, void *r)
3651 {
3652         void **lp = l, **rp = r;
3653
3654         swap(*lp, *rp);
3655 }
3656
3657 static const struct min_heap_callbacks perf_min_heap = {
3658         .elem_size = sizeof(struct perf_event *),
3659         .less = perf_less_group_idx,
3660         .swp = swap_ptr,
3661 };
3662
3663 static void __heap_add(struct min_heap *heap, struct perf_event *event)
3664 {
3665         struct perf_event **itrs = heap->data;
3666
3667         if (event) {
3668                 itrs[heap->nr] = event;
3669                 heap->nr++;
3670         }
3671 }
3672
3673 static void __link_epc(struct perf_event_pmu_context *pmu_ctx)
3674 {
3675         struct perf_cpu_pmu_context *cpc;
3676
3677         if (!pmu_ctx->ctx->task)
3678                 return;
3679
3680         cpc = this_cpu_ptr(pmu_ctx->pmu->cpu_pmu_context);
3681         WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
3682         cpc->task_epc = pmu_ctx;
3683 }
3684
3685 static noinline int visit_groups_merge(struct perf_event_context *ctx,
3686                                 struct perf_event_groups *groups, int cpu,
3687                                 struct pmu *pmu,
3688                                 int (*func)(struct perf_event *, void *),
3689                                 void *data)
3690 {
3691 #ifdef CONFIG_CGROUP_PERF
3692         struct cgroup_subsys_state *css = NULL;
3693 #endif
3694         struct perf_cpu_context *cpuctx = NULL;
3695         /* Space for per CPU and/or any CPU event iterators. */
3696         struct perf_event *itrs[2];
3697         struct min_heap event_heap;
3698         struct perf_event **evt;
3699         int ret;
3700
3701         if (pmu->filter && pmu->filter(pmu, cpu))
3702                 return 0;
3703
3704         if (!ctx->task) {
3705                 cpuctx = this_cpu_ptr(&perf_cpu_context);
3706                 event_heap = (struct min_heap){
3707                         .data = cpuctx->heap,
3708                         .nr = 0,
3709                         .size = cpuctx->heap_size,
3710                 };
3711
3712                 lockdep_assert_held(&cpuctx->ctx.lock);
3713
3714 #ifdef CONFIG_CGROUP_PERF
3715                 if (cpuctx->cgrp)
3716                         css = &cpuctx->cgrp->css;
3717 #endif
3718         } else {
3719                 event_heap = (struct min_heap){
3720                         .data = itrs,
3721                         .nr = 0,
3722                         .size = ARRAY_SIZE(itrs),
3723                 };
3724                 /* Events not within a CPU context may be on any CPU. */
3725                 __heap_add(&event_heap, perf_event_groups_first(groups, -1, pmu, NULL));
3726         }
3727         evt = event_heap.data;
3728
3729         __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, NULL));
3730
3731 #ifdef CONFIG_CGROUP_PERF
3732         for (; css; css = css->parent)
3733                 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, css->cgroup));
3734 #endif
3735
3736         if (event_heap.nr) {
3737                 __link_epc((*evt)->pmu_ctx);
3738                 perf_assert_pmu_disabled((*evt)->pmu_ctx->pmu);
3739         }
3740
3741         min_heapify_all(&event_heap, &perf_min_heap);
3742
3743         while (event_heap.nr) {
3744                 ret = func(*evt, data);
3745                 if (ret)
3746                         return ret;
3747
3748                 *evt = perf_event_groups_next(*evt, pmu);
3749                 if (*evt)
3750                         min_heapify(&event_heap, 0, &perf_min_heap);
3751                 else
3752                         min_heap_pop(&event_heap, &perf_min_heap);
3753         }
3754
3755         return 0;
3756 }
3757
3758 /*
3759  * Because the userpage is strictly per-event (there is no concept of context,
3760  * so there cannot be a context indirection), every userpage must be updated
3761  * when context time starts :-(
3762  *
3763  * IOW, we must not miss EVENT_TIME edges.
3764  */
3765 static inline bool event_update_userpage(struct perf_event *event)
3766 {
3767         if (likely(!atomic_read(&event->mmap_count)))
3768                 return false;
3769
3770         perf_event_update_time(event);
3771         perf_event_update_userpage(event);
3772
3773         return true;
3774 }
3775
3776 static inline void group_update_userpage(struct perf_event *group_event)
3777 {
3778         struct perf_event *event;
3779
3780         if (!event_update_userpage(group_event))
3781                 return;
3782
3783         for_each_sibling_event(event, group_event)
3784                 event_update_userpage(event);
3785 }
3786
3787 static int merge_sched_in(struct perf_event *event, void *data)
3788 {
3789         struct perf_event_context *ctx = event->ctx;
3790         int *can_add_hw = data;
3791
3792         if (event->state <= PERF_EVENT_STATE_OFF)
3793                 return 0;
3794
3795         if (!event_filter_match(event))
3796                 return 0;
3797
3798         if (group_can_go_on(event, *can_add_hw)) {
3799                 if (!group_sched_in(event, ctx))
3800                         list_add_tail(&event->active_list, get_event_list(event));
3801         }
3802
3803         if (event->state == PERF_EVENT_STATE_INACTIVE) {
3804                 *can_add_hw = 0;
3805                 if (event->attr.pinned) {
3806                         perf_cgroup_event_disable(event, ctx);
3807                         perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3808                 } else {
3809                         struct perf_cpu_pmu_context *cpc;
3810
3811                         event->pmu_ctx->rotate_necessary = 1;
3812                         cpc = this_cpu_ptr(event->pmu_ctx->pmu->cpu_pmu_context);
3813                         perf_mux_hrtimer_restart(cpc);
3814                         group_update_userpage(event);
3815                 }
3816         }
3817
3818         return 0;
3819 }
3820
3821 static void ctx_pinned_sched_in(struct perf_event_context *ctx, struct pmu *pmu)
3822 {
3823         struct perf_event_pmu_context *pmu_ctx;
3824         int can_add_hw = 1;
3825
3826         if (pmu) {
3827                 visit_groups_merge(ctx, &ctx->pinned_groups,
3828                                    smp_processor_id(), pmu,
3829                                    merge_sched_in, &can_add_hw);
3830         } else {
3831                 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
3832                         can_add_hw = 1;
3833                         visit_groups_merge(ctx, &ctx->pinned_groups,
3834                                            smp_processor_id(), pmu_ctx->pmu,
3835                                            merge_sched_in, &can_add_hw);
3836                 }
3837         }
3838 }
3839
3840 static void ctx_flexible_sched_in(struct perf_event_context *ctx, struct pmu *pmu)
3841 {
3842         struct perf_event_pmu_context *pmu_ctx;
3843         int can_add_hw = 1;
3844
3845         if (pmu) {
3846                 visit_groups_merge(ctx, &ctx->flexible_groups,
3847                                    smp_processor_id(), pmu,
3848                                    merge_sched_in, &can_add_hw);
3849         } else {
3850                 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
3851                         can_add_hw = 1;
3852                         visit_groups_merge(ctx, &ctx->flexible_groups,
3853                                            smp_processor_id(), pmu_ctx->pmu,
3854                                            merge_sched_in, &can_add_hw);
3855                 }
3856         }
3857 }
3858
3859 static void __pmu_ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu)
3860 {
3861         ctx_flexible_sched_in(ctx, pmu);
3862 }
3863
3864 static void
3865 ctx_sched_in(struct perf_event_context *ctx, enum event_type_t event_type)
3866 {
3867         struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3868         int is_active = ctx->is_active;
3869
3870         lockdep_assert_held(&ctx->lock);
3871
3872         if (likely(!ctx->nr_events))
3873                 return;
3874
3875         if (is_active ^ EVENT_TIME) {
3876                 /* start ctx time */
3877                 __update_context_time(ctx, false);
3878                 perf_cgroup_set_timestamp(cpuctx);
3879                 /*
3880                  * CPU-release for the below ->is_active store,
3881                  * see __load_acquire() in perf_event_time_now()
3882                  */
3883                 barrier();
3884         }
3885
3886         ctx->is_active |= (event_type | EVENT_TIME);
3887         if (ctx->task) {
3888                 if (!is_active)
3889                         cpuctx->task_ctx = ctx;
3890                 else
3891                         WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3892         }
3893
3894         is_active ^= ctx->is_active; /* changed bits */
3895
3896         /*
3897          * First go through the list and put on any pinned groups
3898          * in order to give them the best chance of going on.
3899          */
3900         if (is_active & EVENT_PINNED)
3901                 ctx_pinned_sched_in(ctx, NULL);
3902
3903         /* Then walk through the lower prio flexible groups */
3904         if (is_active & EVENT_FLEXIBLE)
3905                 ctx_flexible_sched_in(ctx, NULL);
3906 }
3907
3908 static void perf_event_context_sched_in(struct task_struct *task)
3909 {
3910         struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3911         struct perf_event_context *ctx;
3912
3913         rcu_read_lock();
3914         ctx = rcu_dereference(task->perf_event_ctxp);
3915         if (!ctx)
3916                 goto rcu_unlock;
3917
3918         if (cpuctx->task_ctx == ctx) {
3919                 perf_ctx_lock(cpuctx, ctx);
3920                 perf_ctx_disable(ctx);
3921
3922                 perf_ctx_sched_task_cb(ctx, true);
3923
3924                 perf_ctx_enable(ctx);
3925                 perf_ctx_unlock(cpuctx, ctx);
3926                 goto rcu_unlock;
3927         }
3928
3929         perf_ctx_lock(cpuctx, ctx);
3930         /*
3931          * We must check ctx->nr_events while holding ctx->lock, such
3932          * that we serialize against perf_install_in_context().
3933          */
3934         if (!ctx->nr_events)
3935                 goto unlock;
3936
3937         perf_ctx_disable(ctx);
3938         /*
3939          * We want to keep the following priority order:
3940          * cpu pinned (that don't need to move), task pinned,
3941          * cpu flexible, task flexible.
3942          *
3943          * However, if task's ctx is not carrying any pinned
3944          * events, no need to flip the cpuctx's events around.
3945          */
3946         if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree)) {
3947                 perf_ctx_disable(&cpuctx->ctx);
3948                 ctx_sched_out(&cpuctx->ctx, EVENT_FLEXIBLE);
3949         }
3950
3951         perf_event_sched_in(cpuctx, ctx);
3952
3953         perf_ctx_sched_task_cb(cpuctx->task_ctx, true);
3954
3955         if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3956                 perf_ctx_enable(&cpuctx->ctx);
3957
3958         perf_ctx_enable(ctx);
3959
3960 unlock:
3961         perf_ctx_unlock(cpuctx, ctx);
3962 rcu_unlock:
3963         rcu_read_unlock();
3964 }
3965
3966 /*
3967  * Called from scheduler to add the events of the current task
3968  * with interrupts disabled.
3969  *
3970  * We restore the event value and then enable it.
3971  *
3972  * This does not protect us against NMI, but enable()
3973  * sets the enabled bit in the control field of event _before_
3974  * accessing the event control register. If a NMI hits, then it will
3975  * keep the event running.
3976  */
3977 void __perf_event_task_sched_in(struct task_struct *prev,
3978                                 struct task_struct *task)
3979 {
3980         perf_event_context_sched_in(task);
3981
3982         if (atomic_read(&nr_switch_events))
3983                 perf_event_switch(task, prev, true);
3984
3985         if (__this_cpu_read(perf_sched_cb_usages))
3986                 perf_pmu_sched_task(prev, task, true);
3987 }
3988
3989 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3990 {
3991         u64 frequency = event->attr.sample_freq;
3992         u64 sec = NSEC_PER_SEC;
3993         u64 divisor, dividend;
3994
3995         int count_fls, nsec_fls, frequency_fls, sec_fls;
3996
3997         count_fls = fls64(count);
3998         nsec_fls = fls64(nsec);
3999         frequency_fls = fls64(frequency);
4000         sec_fls = 30;
4001
4002         /*
4003          * We got @count in @nsec, with a target of sample_freq HZ
4004          * the target period becomes:
4005          *
4006          *             @count * 10^9
4007          * period = -------------------
4008          *          @nsec * sample_freq
4009          *
4010          */
4011
4012         /*
4013          * Reduce accuracy by one bit such that @a and @b converge
4014          * to a similar magnitude.
4015          */
4016 #define REDUCE_FLS(a, b)                \
4017 do {                                    \
4018         if (a##_fls > b##_fls) {        \
4019                 a >>= 1;                \
4020                 a##_fls--;              \
4021         } else {                        \
4022                 b >>= 1;                \
4023                 b##_fls--;              \
4024         }                               \
4025 } while (0)
4026
4027         /*
4028          * Reduce accuracy until either term fits in a u64, then proceed with
4029          * the other, so that finally we can do a u64/u64 division.
4030          */
4031         while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
4032                 REDUCE_FLS(nsec, frequency);
4033                 REDUCE_FLS(sec, count);
4034         }
4035
4036         if (count_fls + sec_fls > 64) {
4037                 divisor = nsec * frequency;
4038
4039                 while (count_fls + sec_fls > 64) {
4040                         REDUCE_FLS(count, sec);
4041                         divisor >>= 1;
4042                 }
4043
4044                 dividend = count * sec;
4045         } else {
4046                 dividend = count * sec;
4047
4048                 while (nsec_fls + frequency_fls > 64) {
4049                         REDUCE_FLS(nsec, frequency);
4050                         dividend >>= 1;
4051                 }
4052
4053                 divisor = nsec * frequency;
4054         }
4055
4056         if (!divisor)
4057                 return dividend;
4058
4059         return div64_u64(dividend, divisor);
4060 }
4061
4062 static DEFINE_PER_CPU(int, perf_throttled_count);
4063 static DEFINE_PER_CPU(u64, perf_throttled_seq);
4064
4065 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
4066 {
4067         struct hw_perf_event *hwc = &event->hw;
4068         s64 period, sample_period;
4069         s64 delta;
4070
4071         period = perf_calculate_period(event, nsec, count);
4072
4073         delta = (s64)(period - hwc->sample_period);
4074         delta = (delta + 7) / 8; /* low pass filter */
4075
4076         sample_period = hwc->sample_period + delta;
4077
4078         if (!sample_period)
4079                 sample_period = 1;
4080
4081         hwc->sample_period = sample_period;
4082
4083         if (local64_read(&hwc->period_left) > 8*sample_period) {
4084                 if (disable)
4085                         event->pmu->stop(event, PERF_EF_UPDATE);
4086
4087                 local64_set(&hwc->period_left, 0);
4088
4089                 if (disable)
4090                         event->pmu->start(event, PERF_EF_RELOAD);
4091         }
4092 }
4093
4094 /*
4095  * combine freq adjustment with unthrottling to avoid two passes over the
4096  * events. At the same time, make sure, having freq events does not change
4097  * the rate of unthrottling as that would introduce bias.
4098  */
4099 static void
4100 perf_adjust_freq_unthr_context(struct perf_event_context *ctx, bool unthrottle)
4101 {
4102         struct perf_event *event;
4103         struct hw_perf_event *hwc;
4104         u64 now, period = TICK_NSEC;
4105         s64 delta;
4106
4107         /*
4108          * only need to iterate over all events iff:
4109          * - context have events in frequency mode (needs freq adjust)
4110          * - there are events to unthrottle on this cpu
4111          */
4112         if (!(ctx->nr_freq || unthrottle))
4113                 return;
4114
4115         raw_spin_lock(&ctx->lock);
4116
4117         list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4118                 if (event->state != PERF_EVENT_STATE_ACTIVE)
4119                         continue;
4120
4121                 // XXX use visit thingy to avoid the -1,cpu match
4122                 if (!event_filter_match(event))
4123                         continue;
4124
4125                 perf_pmu_disable(event->pmu);
4126
4127                 hwc = &event->hw;
4128
4129                 if (hwc->interrupts == MAX_INTERRUPTS) {
4130                         hwc->interrupts = 0;
4131                         perf_log_throttle(event, 1);
4132                         event->pmu->start(event, 0);
4133                 }
4134
4135                 if (!event->attr.freq || !event->attr.sample_freq)
4136                         goto next;
4137
4138                 /*
4139                  * stop the event and update event->count
4140                  */
4141                 event->pmu->stop(event, PERF_EF_UPDATE);
4142
4143                 now = local64_read(&event->count);
4144                 delta = now - hwc->freq_count_stamp;
4145                 hwc->freq_count_stamp = now;
4146
4147                 /*
4148                  * restart the event
4149                  * reload only if value has changed
4150                  * we have stopped the event so tell that
4151                  * to perf_adjust_period() to avoid stopping it
4152                  * twice.
4153                  */
4154                 if (delta > 0)
4155                         perf_adjust_period(event, period, delta, false);
4156
4157                 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
4158         next:
4159                 perf_pmu_enable(event->pmu);
4160         }
4161
4162         raw_spin_unlock(&ctx->lock);
4163 }
4164
4165 /*
4166  * Move @event to the tail of the @ctx's elegible events.
4167  */
4168 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4169 {
4170         /*
4171          * Rotate the first entry last of non-pinned groups. Rotation might be
4172          * disabled by the inheritance code.
4173          */
4174         if (ctx->rotate_disable)
4175                 return;
4176
4177         perf_event_groups_delete(&ctx->flexible_groups, event);
4178         perf_event_groups_insert(&ctx->flexible_groups, event);
4179 }
4180
4181 /* pick an event from the flexible_groups to rotate */
4182 static inline struct perf_event *
4183 ctx_event_to_rotate(struct perf_event_pmu_context *pmu_ctx)
4184 {
4185         struct perf_event *event;
4186         struct rb_node *node;
4187         struct rb_root *tree;
4188         struct __group_key key = {
4189                 .pmu = pmu_ctx->pmu,
4190         };
4191
4192         /* pick the first active flexible event */
4193         event = list_first_entry_or_null(&pmu_ctx->flexible_active,
4194                                          struct perf_event, active_list);
4195         if (event)
4196                 goto out;
4197
4198         /* if no active flexible event, pick the first event */
4199         tree = &pmu_ctx->ctx->flexible_groups.tree;
4200
4201         if (!pmu_ctx->ctx->task) {
4202                 key.cpu = smp_processor_id();
4203
4204                 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4205                 if (node)
4206                         event = __node_2_pe(node);
4207                 goto out;
4208         }
4209
4210         key.cpu = -1;
4211         node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4212         if (node) {
4213                 event = __node_2_pe(node);
4214                 goto out;
4215         }
4216
4217         key.cpu = smp_processor_id();
4218         node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4219         if (node)
4220                 event = __node_2_pe(node);
4221
4222 out:
4223         /*
4224          * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4225          * finds there are unschedulable events, it will set it again.
4226          */
4227         pmu_ctx->rotate_necessary = 0;
4228
4229         return event;
4230 }
4231
4232 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc)
4233 {
4234         struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4235         struct perf_event_pmu_context *cpu_epc, *task_epc = NULL;
4236         struct perf_event *cpu_event = NULL, *task_event = NULL;
4237         int cpu_rotate, task_rotate;
4238         struct pmu *pmu;
4239
4240         /*
4241          * Since we run this from IRQ context, nobody can install new
4242          * events, thus the event count values are stable.
4243          */
4244
4245         cpu_epc = &cpc->epc;
4246         pmu = cpu_epc->pmu;
4247         task_epc = cpc->task_epc;
4248
4249         cpu_rotate = cpu_epc->rotate_necessary;
4250         task_rotate = task_epc ? task_epc->rotate_necessary : 0;
4251
4252         if (!(cpu_rotate || task_rotate))
4253                 return false;
4254
4255         perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4256         perf_pmu_disable(pmu);
4257
4258         if (task_rotate)
4259                 task_event = ctx_event_to_rotate(task_epc);
4260         if (cpu_rotate)
4261                 cpu_event = ctx_event_to_rotate(cpu_epc);
4262
4263         /*
4264          * As per the order given at ctx_resched() first 'pop' task flexible
4265          * and then, if needed CPU flexible.
4266          */
4267         if (task_event || (task_epc && cpu_event)) {
4268                 update_context_time(task_epc->ctx);
4269                 __pmu_ctx_sched_out(task_epc, EVENT_FLEXIBLE);
4270         }
4271
4272         if (cpu_event) {
4273                 update_context_time(&cpuctx->ctx);
4274                 __pmu_ctx_sched_out(cpu_epc, EVENT_FLEXIBLE);
4275                 rotate_ctx(&cpuctx->ctx, cpu_event);
4276                 __pmu_ctx_sched_in(&cpuctx->ctx, pmu);
4277         }
4278
4279         if (task_event)
4280                 rotate_ctx(task_epc->ctx, task_event);
4281
4282         if (task_event || (task_epc && cpu_event))
4283                 __pmu_ctx_sched_in(task_epc->ctx, pmu);
4284
4285         perf_pmu_enable(pmu);
4286         perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4287
4288         return true;
4289 }
4290
4291 void perf_event_task_tick(void)
4292 {
4293         struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4294         struct perf_event_context *ctx;
4295         int throttled;
4296
4297         lockdep_assert_irqs_disabled();
4298
4299         __this_cpu_inc(perf_throttled_seq);
4300         throttled = __this_cpu_xchg(perf_throttled_count, 0);
4301         tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4302
4303         perf_adjust_freq_unthr_context(&cpuctx->ctx, !!throttled);
4304
4305         rcu_read_lock();
4306         ctx = rcu_dereference(current->perf_event_ctxp);
4307         if (ctx)
4308                 perf_adjust_freq_unthr_context(ctx, !!throttled);
4309         rcu_read_unlock();
4310 }
4311
4312 static int event_enable_on_exec(struct perf_event *event,
4313                                 struct perf_event_context *ctx)
4314 {
4315         if (!event->attr.enable_on_exec)
4316                 return 0;
4317
4318         event->attr.enable_on_exec = 0;
4319         if (event->state >= PERF_EVENT_STATE_INACTIVE)
4320                 return 0;
4321
4322         perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4323
4324         return 1;
4325 }
4326
4327 /*
4328  * Enable all of a task's events that have been marked enable-on-exec.
4329  * This expects task == current.
4330  */
4331 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
4332 {
4333         struct perf_event_context *clone_ctx = NULL;
4334         enum event_type_t event_type = 0;
4335         struct perf_cpu_context *cpuctx;
4336         struct perf_event *event;
4337         unsigned long flags;
4338         int enabled = 0;
4339
4340         local_irq_save(flags);
4341         if (WARN_ON_ONCE(current->perf_event_ctxp != ctx))
4342                 goto out;
4343
4344         if (!ctx->nr_events)
4345                 goto out;
4346
4347         cpuctx = this_cpu_ptr(&perf_cpu_context);
4348         perf_ctx_lock(cpuctx, ctx);
4349         ctx_sched_out(ctx, EVENT_TIME);
4350
4351         list_for_each_entry(event, &ctx->event_list, event_entry) {
4352                 enabled |= event_enable_on_exec(event, ctx);
4353                 event_type |= get_event_type(event);
4354         }
4355
4356         /*
4357          * Unclone and reschedule this context if we enabled any event.
4358          */
4359         if (enabled) {
4360                 clone_ctx = unclone_ctx(ctx);
4361                 ctx_resched(cpuctx, ctx, event_type);
4362         } else {
4363                 ctx_sched_in(ctx, EVENT_TIME);
4364         }
4365         perf_ctx_unlock(cpuctx, ctx);
4366
4367 out:
4368         local_irq_restore(flags);
4369
4370         if (clone_ctx)
4371                 put_ctx(clone_ctx);
4372 }
4373
4374 static void perf_remove_from_owner(struct perf_event *event);
4375 static void perf_event_exit_event(struct perf_event *event,
4376                                   struct perf_event_context *ctx);
4377
4378 /*
4379  * Removes all events from the current task that have been marked
4380  * remove-on-exec, and feeds their values back to parent events.
4381  */
4382 static void perf_event_remove_on_exec(struct perf_event_context *ctx)
4383 {
4384         struct perf_event_context *clone_ctx = NULL;
4385         struct perf_event *event, *next;
4386         unsigned long flags;
4387         bool modified = false;
4388
4389         mutex_lock(&ctx->mutex);
4390
4391         if (WARN_ON_ONCE(ctx->task != current))
4392                 goto unlock;
4393
4394         list_for_each_entry_safe(event, next, &ctx->event_list, event_entry) {
4395                 if (!event->attr.remove_on_exec)
4396                         continue;
4397
4398                 if (!is_kernel_event(event))
4399                         perf_remove_from_owner(event);
4400
4401                 modified = true;
4402
4403                 perf_event_exit_event(event, ctx);
4404         }
4405
4406         raw_spin_lock_irqsave(&ctx->lock, flags);
4407         if (modified)
4408                 clone_ctx = unclone_ctx(ctx);
4409         raw_spin_unlock_irqrestore(&ctx->lock, flags);
4410
4411 unlock:
4412         mutex_unlock(&ctx->mutex);
4413
4414         if (clone_ctx)
4415                 put_ctx(clone_ctx);
4416 }
4417
4418 struct perf_read_data {
4419         struct perf_event *event;
4420         bool group;
4421         int ret;
4422 };
4423
4424 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4425 {
4426         u16 local_pkg, event_pkg;
4427
4428         if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4429                 int local_cpu = smp_processor_id();
4430
4431                 event_pkg = topology_physical_package_id(event_cpu);
4432                 local_pkg = topology_physical_package_id(local_cpu);
4433
4434                 if (event_pkg == local_pkg)
4435                         return local_cpu;
4436         }
4437
4438         return event_cpu;
4439 }
4440
4441 /*
4442  * Cross CPU call to read the hardware event
4443  */
4444 static void __perf_event_read(void *info)
4445 {
4446         struct perf_read_data *data = info;
4447         struct perf_event *sub, *event = data->event;
4448         struct perf_event_context *ctx = event->ctx;
4449         struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4450         struct pmu *pmu = event->pmu;
4451
4452         /*
4453          * If this is a task context, we need to check whether it is
4454          * the current task context of this cpu.  If not it has been
4455          * scheduled out before the smp call arrived.  In that case
4456          * event->count would have been updated to a recent sample
4457          * when the event was scheduled out.
4458          */
4459         if (ctx->task && cpuctx->task_ctx != ctx)
4460                 return;
4461
4462         raw_spin_lock(&ctx->lock);
4463         if (ctx->is_active & EVENT_TIME) {
4464                 update_context_time(ctx);
4465                 update_cgrp_time_from_event(event);
4466         }
4467
4468         perf_event_update_time(event);
4469         if (data->group)
4470                 perf_event_update_sibling_time(event);
4471
4472         if (event->state != PERF_EVENT_STATE_ACTIVE)
4473                 goto unlock;
4474
4475         if (!data->group) {
4476                 pmu->read(event);
4477                 data->ret = 0;
4478                 goto unlock;
4479         }
4480
4481         pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4482
4483         pmu->read(event);
4484
4485         for_each_sibling_event(sub, event) {
4486                 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4487                         /*
4488                          * Use sibling's PMU rather than @event's since
4489                          * sibling could be on different (eg: software) PMU.
4490                          */
4491                         sub->pmu->read(sub);
4492                 }
4493         }
4494
4495         data->ret = pmu->commit_txn(pmu);
4496
4497 unlock:
4498         raw_spin_unlock(&ctx->lock);
4499 }
4500
4501 static inline u64 perf_event_count(struct perf_event *event)
4502 {
4503         return local64_read(&event->count) + atomic64_read(&event->child_count);
4504 }
4505
4506 static void calc_timer_values(struct perf_event *event,
4507                                 u64 *now,
4508                                 u64 *enabled,
4509                                 u64 *running)
4510 {
4511         u64 ctx_time;
4512
4513         *now = perf_clock();
4514         ctx_time = perf_event_time_now(event, *now);
4515         __perf_update_times(event, ctx_time, enabled, running);
4516 }
4517
4518 /*
4519  * NMI-safe method to read a local event, that is an event that
4520  * is:
4521  *   - either for the current task, or for this CPU
4522  *   - does not have inherit set, for inherited task events
4523  *     will not be local and we cannot read them atomically
4524  *   - must not have a pmu::count method
4525  */
4526 int perf_event_read_local(struct perf_event *event, u64 *value,
4527                           u64 *enabled, u64 *running)
4528 {
4529         unsigned long flags;
4530         int ret = 0;
4531
4532         /*
4533          * Disabling interrupts avoids all counter scheduling (context
4534          * switches, timer based rotation and IPIs).
4535          */
4536         local_irq_save(flags);
4537
4538         /*
4539          * It must not be an event with inherit set, we cannot read
4540          * all child counters from atomic context.
4541          */
4542         if (event->attr.inherit) {
4543                 ret = -EOPNOTSUPP;
4544                 goto out;
4545         }
4546
4547         /* If this is a per-task event, it must be for current */
4548         if ((event->attach_state & PERF_ATTACH_TASK) &&
4549             event->hw.target != current) {
4550                 ret = -EINVAL;
4551                 goto out;
4552         }
4553
4554         /* If this is a per-CPU event, it must be for this CPU */
4555         if (!(event->attach_state & PERF_ATTACH_TASK) &&
4556             event->cpu != smp_processor_id()) {
4557                 ret = -EINVAL;
4558                 goto out;
4559         }
4560
4561         /* If this is a pinned event it must be running on this CPU */
4562         if (event->attr.pinned && event->oncpu != smp_processor_id()) {
4563                 ret = -EBUSY;
4564                 goto out;
4565         }
4566
4567         /*
4568          * If the event is currently on this CPU, its either a per-task event,
4569          * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4570          * oncpu == -1).
4571          */
4572         if (event->oncpu == smp_processor_id())
4573                 event->pmu->read(event);
4574
4575         *value = local64_read(&event->count);
4576         if (enabled || running) {
4577                 u64 __enabled, __running, __now;
4578
4579                 calc_timer_values(event, &__now, &__enabled, &__running);
4580                 if (enabled)
4581                         *enabled = __enabled;
4582                 if (running)
4583                         *running = __running;
4584         }
4585 out:
4586         local_irq_restore(flags);
4587
4588         return ret;
4589 }
4590
4591 static int perf_event_read(struct perf_event *event, bool group)
4592 {
4593         enum perf_event_state state = READ_ONCE(event->state);
4594         int event_cpu, ret = 0;
4595
4596         /*
4597          * If event is enabled and currently active on a CPU, update the
4598          * value in the event structure:
4599          */
4600 again:
4601         if (state == PERF_EVENT_STATE_ACTIVE) {
4602                 struct perf_read_data data;
4603
4604                 /*
4605                  * Orders the ->state and ->oncpu loads such that if we see
4606                  * ACTIVE we must also see the right ->oncpu.
4607                  *
4608                  * Matches the smp_wmb() from event_sched_in().
4609                  */
4610                 smp_rmb();
4611
4612                 event_cpu = READ_ONCE(event->oncpu);
4613                 if ((unsigned)event_cpu >= nr_cpu_ids)
4614                         return 0;
4615
4616                 data = (struct perf_read_data){
4617                         .event = event,
4618                         .group = group,
4619                         .ret = 0,
4620                 };
4621
4622                 preempt_disable();
4623                 event_cpu = __perf_event_read_cpu(event, event_cpu);
4624
4625                 /*
4626                  * Purposely ignore the smp_call_function_single() return
4627                  * value.
4628                  *
4629                  * If event_cpu isn't a valid CPU it means the event got
4630                  * scheduled out and that will have updated the event count.
4631                  *
4632                  * Therefore, either way, we'll have an up-to-date event count
4633                  * after this.
4634                  */
4635                 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4636                 preempt_enable();
4637                 ret = data.ret;
4638
4639         } else if (state == PERF_EVENT_STATE_INACTIVE) {
4640                 struct perf_event_context *ctx = event->ctx;
4641                 unsigned long flags;
4642
4643                 raw_spin_lock_irqsave(&ctx->lock, flags);
4644                 state = event->state;
4645                 if (state != PERF_EVENT_STATE_INACTIVE) {
4646                         raw_spin_unlock_irqrestore(&ctx->lock, flags);
4647                         goto again;
4648                 }
4649
4650                 /*
4651                  * May read while context is not active (e.g., thread is
4652                  * blocked), in that case we cannot update context time
4653                  */
4654                 if (ctx->is_active & EVENT_TIME) {
4655                         update_context_time(ctx);
4656                         update_cgrp_time_from_event(event);
4657                 }
4658
4659                 perf_event_update_time(event);
4660                 if (group)
4661                         perf_event_update_sibling_time(event);
4662                 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4663         }
4664
4665         return ret;
4666 }
4667
4668 /*
4669  * Initialize the perf_event context in a task_struct:
4670  */
4671 static void __perf_event_init_context(struct perf_event_context *ctx)
4672 {
4673         raw_spin_lock_init(&ctx->lock);
4674         mutex_init(&ctx->mutex);
4675         INIT_LIST_HEAD(&ctx->pmu_ctx_list);
4676         perf_event_groups_init(&ctx->pinned_groups);
4677         perf_event_groups_init(&ctx->flexible_groups);
4678         INIT_LIST_HEAD(&ctx->event_list);
4679         refcount_set(&ctx->refcount, 1);
4680 }
4681
4682 static void
4683 __perf_init_event_pmu_context(struct perf_event_pmu_context *epc, struct pmu *pmu)
4684 {
4685         epc->pmu = pmu;
4686         INIT_LIST_HEAD(&epc->pmu_ctx_entry);
4687         INIT_LIST_HEAD(&epc->pinned_active);
4688         INIT_LIST_HEAD(&epc->flexible_active);
4689         atomic_set(&epc->refcount, 1);
4690 }
4691
4692 static struct perf_event_context *
4693 alloc_perf_context(struct task_struct *task)
4694 {
4695         struct perf_event_context *ctx;
4696
4697         ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4698         if (!ctx)
4699                 return NULL;
4700
4701         __perf_event_init_context(ctx);
4702         if (task)
4703                 ctx->task = get_task_struct(task);
4704
4705         return ctx;
4706 }
4707
4708 static struct task_struct *
4709 find_lively_task_by_vpid(pid_t vpid)
4710 {
4711         struct task_struct *task;
4712
4713         rcu_read_lock();
4714         if (!vpid)
4715                 task = current;
4716         else
4717                 task = find_task_by_vpid(vpid);
4718         if (task)
4719                 get_task_struct(task);
4720         rcu_read_unlock();
4721
4722         if (!task)
4723                 return ERR_PTR(-ESRCH);
4724
4725         return task;
4726 }
4727
4728 /*
4729  * Returns a matching context with refcount and pincount.
4730  */
4731 static struct perf_event_context *
4732 find_get_context(struct task_struct *task, struct perf_event *event)
4733 {
4734         struct perf_event_context *ctx, *clone_ctx = NULL;
4735         struct perf_cpu_context *cpuctx;
4736         unsigned long flags;
4737         int err;
4738
4739         if (!task) {
4740                 /* Must be root to operate on a CPU event: */
4741                 err = perf_allow_cpu(&event->attr);
4742                 if (err)
4743                         return ERR_PTR(err);
4744
4745                 cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
4746                 ctx = &cpuctx->ctx;
4747                 get_ctx(ctx);
4748                 raw_spin_lock_irqsave(&ctx->lock, flags);
4749                 ++ctx->pin_count;
4750                 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4751
4752                 return ctx;
4753         }
4754
4755         err = -EINVAL;
4756 retry:
4757         ctx = perf_lock_task_context(task, &flags);
4758         if (ctx) {
4759                 clone_ctx = unclone_ctx(ctx);
4760                 ++ctx->pin_count;
4761
4762                 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4763
4764                 if (clone_ctx)
4765                         put_ctx(clone_ctx);
4766         } else {
4767                 ctx = alloc_perf_context(task);
4768                 err = -ENOMEM;
4769                 if (!ctx)
4770                         goto errout;
4771
4772                 err = 0;
4773                 mutex_lock(&task->perf_event_mutex);
4774                 /*
4775                  * If it has already passed perf_event_exit_task().
4776                  * we must see PF_EXITING, it takes this mutex too.
4777                  */
4778                 if (task->flags & PF_EXITING)
4779                         err = -ESRCH;
4780                 else if (task->perf_event_ctxp)
4781                         err = -EAGAIN;
4782                 else {
4783                         get_ctx(ctx);
4784                         ++ctx->pin_count;
4785                         rcu_assign_pointer(task->perf_event_ctxp, ctx);
4786                 }
4787                 mutex_unlock(&task->perf_event_mutex);
4788
4789                 if (unlikely(err)) {
4790                         put_ctx(ctx);
4791
4792                         if (err == -EAGAIN)
4793                                 goto retry;
4794                         goto errout;
4795                 }
4796         }
4797
4798         return ctx;
4799
4800 errout:
4801         return ERR_PTR(err);
4802 }
4803
4804 static struct perf_event_pmu_context *
4805 find_get_pmu_context(struct pmu *pmu, struct perf_event_context *ctx,
4806                      struct perf_event *event)
4807 {
4808         struct perf_event_pmu_context *new = NULL, *epc;
4809         void *task_ctx_data = NULL;
4810
4811         if (!ctx->task) {
4812                 struct perf_cpu_pmu_context *cpc;
4813
4814                 cpc = per_cpu_ptr(pmu->cpu_pmu_context, event->cpu);
4815                 epc = &cpc->epc;
4816
4817                 if (!epc->ctx) {
4818                         atomic_set(&epc->refcount, 1);
4819                         epc->embedded = 1;
4820                         raw_spin_lock_irq(&ctx->lock);
4821                         list_add(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
4822                         epc->ctx = ctx;
4823                         raw_spin_unlock_irq(&ctx->lock);
4824                 } else {
4825                         WARN_ON_ONCE(epc->ctx != ctx);
4826                         atomic_inc(&epc->refcount);
4827                 }
4828
4829                 return epc;
4830         }
4831
4832         new = kzalloc(sizeof(*epc), GFP_KERNEL);
4833         if (!new)
4834                 return ERR_PTR(-ENOMEM);
4835
4836         if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4837                 task_ctx_data = alloc_task_ctx_data(pmu);
4838                 if (!task_ctx_data) {
4839                         kfree(new);
4840                         return ERR_PTR(-ENOMEM);
4841                 }
4842         }
4843
4844         __perf_init_event_pmu_context(new, pmu);
4845
4846         /*
4847          * XXX
4848          *
4849          * lockdep_assert_held(&ctx->mutex);
4850          *
4851          * can't because perf_event_init_task() doesn't actually hold the
4852          * child_ctx->mutex.
4853          */
4854
4855         raw_spin_lock_irq(&ctx->lock);
4856         list_for_each_entry(epc, &ctx->pmu_ctx_list, pmu_ctx_entry) {
4857                 if (epc->pmu == pmu) {
4858                         WARN_ON_ONCE(epc->ctx != ctx);
4859                         atomic_inc(&epc->refcount);
4860                         goto found_epc;
4861                 }
4862         }
4863
4864         epc = new;
4865         new = NULL;
4866
4867         list_add(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
4868         epc->ctx = ctx;
4869
4870 found_epc:
4871         if (task_ctx_data && !epc->task_ctx_data) {
4872                 epc->task_ctx_data = task_ctx_data;
4873                 task_ctx_data = NULL;
4874                 ctx->nr_task_data++;
4875         }
4876         raw_spin_unlock_irq(&ctx->lock);
4877
4878         free_task_ctx_data(pmu, task_ctx_data);
4879         kfree(new);
4880
4881         return epc;
4882 }
4883
4884 static void get_pmu_ctx(struct perf_event_pmu_context *epc)
4885 {
4886         WARN_ON_ONCE(!atomic_inc_not_zero(&epc->refcount));
4887 }
4888
4889 static void free_epc_rcu(struct rcu_head *head)
4890 {
4891         struct perf_event_pmu_context *epc = container_of(head, typeof(*epc), rcu_head);
4892
4893         kfree(epc->task_ctx_data);
4894         kfree(epc);
4895 }
4896
4897 static void put_pmu_ctx(struct perf_event_pmu_context *epc)
4898 {
4899         unsigned long flags;
4900
4901         if (!atomic_dec_and_test(&epc->refcount))
4902                 return;
4903
4904         if (epc->ctx) {
4905                 struct perf_event_context *ctx = epc->ctx;
4906
4907                 /*
4908                  * XXX
4909                  *
4910                  * lockdep_assert_held(&ctx->mutex);
4911                  *
4912                  * can't because of the call-site in _free_event()/put_event()
4913                  * which isn't always called under ctx->mutex.
4914                  */
4915
4916                 WARN_ON_ONCE(list_empty(&epc->pmu_ctx_entry));
4917                 raw_spin_lock_irqsave(&ctx->lock, flags);
4918                 list_del_init(&epc->pmu_ctx_entry);
4919                 epc->ctx = NULL;
4920                 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4921         }
4922
4923         WARN_ON_ONCE(!list_empty(&epc->pinned_active));
4924         WARN_ON_ONCE(!list_empty(&epc->flexible_active));
4925
4926         if (epc->embedded)
4927                 return;
4928
4929         call_rcu(&epc->rcu_head, free_epc_rcu);
4930 }
4931
4932 static void perf_event_free_filter(struct perf_event *event);
4933
4934 static void free_event_rcu(struct rcu_head *head)
4935 {
4936         struct perf_event *event = container_of(head, typeof(*event), rcu_head);
4937
4938         if (event->ns)
4939                 put_pid_ns(event->ns);
4940         perf_event_free_filter(event);
4941         kmem_cache_free(perf_event_cache, event);
4942 }
4943
4944 static void ring_buffer_attach(struct perf_event *event,
4945                                struct perf_buffer *rb);
4946
4947 static void detach_sb_event(struct perf_event *event)
4948 {
4949         struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4950
4951         raw_spin_lock(&pel->lock);
4952         list_del_rcu(&event->sb_list);
4953         raw_spin_unlock(&pel->lock);
4954 }
4955
4956 static bool is_sb_event(struct perf_event *event)
4957 {
4958         struct perf_event_attr *attr = &event->attr;
4959
4960         if (event->parent)
4961                 return false;
4962
4963         if (event->attach_state & PERF_ATTACH_TASK)
4964                 return false;
4965
4966         if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4967             attr->comm || attr->comm_exec ||
4968             attr->task || attr->ksymbol ||
4969             attr->context_switch || attr->text_poke ||
4970             attr->bpf_event)
4971                 return true;
4972         return false;
4973 }
4974
4975 static void unaccount_pmu_sb_event(struct perf_event *event)
4976 {
4977         if (is_sb_event(event))
4978                 detach_sb_event(event);
4979 }
4980
4981 #ifdef CONFIG_NO_HZ_FULL
4982 static DEFINE_SPINLOCK(nr_freq_lock);
4983 #endif
4984
4985 static void unaccount_freq_event_nohz(void)
4986 {
4987 #ifdef CONFIG_NO_HZ_FULL
4988         spin_lock(&nr_freq_lock);
4989         if (atomic_dec_and_test(&nr_freq_events))
4990                 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
4991         spin_unlock(&nr_freq_lock);
4992 #endif
4993 }
4994
4995 static void unaccount_freq_event(void)
4996 {
4997         if (tick_nohz_full_enabled())
4998                 unaccount_freq_event_nohz();
4999         else
5000                 atomic_dec(&nr_freq_events);
5001 }
5002
5003 static void unaccount_event(struct perf_event *event)
5004 {
5005         bool dec = false;
5006
5007         if (event->parent)
5008                 return;
5009
5010         if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
5011                 dec = true;
5012         if (event->attr.mmap || event->attr.mmap_data)
5013                 atomic_dec(&nr_mmap_events);
5014         if (event->attr.build_id)
5015                 atomic_dec(&nr_build_id_events);
5016         if (event->attr.comm)
5017                 atomic_dec(&nr_comm_events);
5018         if (event->attr.namespaces)
5019                 atomic_dec(&nr_namespaces_events);
5020         if (event->attr.cgroup)
5021                 atomic_dec(&nr_cgroup_events);
5022         if (event->attr.task)
5023                 atomic_dec(&nr_task_events);
5024         if (event->attr.freq)
5025                 unaccount_freq_event();
5026         if (event->attr.context_switch) {
5027                 dec = true;
5028                 atomic_dec(&nr_switch_events);
5029         }
5030         if (is_cgroup_event(event))
5031                 dec = true;
5032         if (has_branch_stack(event))
5033                 dec = true;
5034         if (event->attr.ksymbol)
5035                 atomic_dec(&nr_ksymbol_events);
5036         if (event->attr.bpf_event)
5037                 atomic_dec(&nr_bpf_events);
5038         if (event->attr.text_poke)
5039                 atomic_dec(&nr_text_poke_events);
5040
5041         if (dec) {
5042                 if (!atomic_add_unless(&perf_sched_count, -1, 1))
5043                         schedule_delayed_work(&perf_sched_work, HZ);
5044         }
5045
5046         unaccount_pmu_sb_event(event);
5047 }
5048
5049 static void perf_sched_delayed(struct work_struct *work)
5050 {
5051         mutex_lock(&perf_sched_mutex);
5052         if (atomic_dec_and_test(&perf_sched_count))
5053                 static_branch_disable(&perf_sched_events);
5054         mutex_unlock(&perf_sched_mutex);
5055 }
5056
5057 /*
5058  * The following implement mutual exclusion of events on "exclusive" pmus
5059  * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
5060  * at a time, so we disallow creating events that might conflict, namely:
5061  *
5062  *  1) cpu-wide events in the presence of per-task events,
5063  *  2) per-task events in the presence of cpu-wide events,
5064  *  3) two matching events on the same perf_event_context.
5065  *
5066  * The former two cases are handled in the allocation path (perf_event_alloc(),
5067  * _free_event()), the latter -- before the first perf_install_in_context().
5068  */
5069 static int exclusive_event_init(struct perf_event *event)
5070 {
5071         struct pmu *pmu = event->pmu;
5072
5073         if (!is_exclusive_pmu(pmu))
5074                 return 0;
5075
5076         /*
5077          * Prevent co-existence of per-task and cpu-wide events on the
5078          * same exclusive pmu.
5079          *
5080          * Negative pmu::exclusive_cnt means there are cpu-wide
5081          * events on this "exclusive" pmu, positive means there are
5082          * per-task events.
5083          *
5084          * Since this is called in perf_event_alloc() path, event::ctx
5085          * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
5086          * to mean "per-task event", because unlike other attach states it
5087          * never gets cleared.
5088          */
5089         if (event->attach_state & PERF_ATTACH_TASK) {
5090                 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
5091                         return -EBUSY;
5092         } else {
5093                 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
5094                         return -EBUSY;
5095         }
5096
5097         return 0;
5098 }
5099
5100 static void exclusive_event_destroy(struct perf_event *event)
5101 {
5102         struct pmu *pmu = event->pmu;
5103
5104         if (!is_exclusive_pmu(pmu))
5105                 return;
5106
5107         /* see comment in exclusive_event_init() */
5108         if (event->attach_state & PERF_ATTACH_TASK)
5109                 atomic_dec(&pmu->exclusive_cnt);
5110         else
5111                 atomic_inc(&pmu->exclusive_cnt);
5112 }
5113
5114 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
5115 {
5116         if ((e1->pmu == e2->pmu) &&
5117             (e1->cpu == e2->cpu ||
5118              e1->cpu == -1 ||
5119              e2->cpu == -1))
5120                 return true;
5121         return false;
5122 }
5123
5124 static bool exclusive_event_installable(struct perf_event *event,
5125                                         struct perf_event_context *ctx)
5126 {
5127         struct perf_event *iter_event;
5128         struct pmu *pmu = event->pmu;
5129
5130         lockdep_assert_held(&ctx->mutex);
5131
5132         if (!is_exclusive_pmu(pmu))
5133                 return true;
5134
5135         list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
5136                 if (exclusive_event_match(iter_event, event))
5137                         return false;
5138         }
5139
5140         return true;
5141 }
5142
5143 static void perf_addr_filters_splice(struct perf_event *event,
5144                                        struct list_head *head);
5145
5146 static void _free_event(struct perf_event *event)
5147 {
5148         irq_work_sync(&event->pending_irq);
5149
5150         unaccount_event(event);
5151
5152         security_perf_event_free(event);
5153
5154         if (event->rb) {
5155                 /*
5156                  * Can happen when we close an event with re-directed output.
5157                  *
5158                  * Since we have a 0 refcount, perf_mmap_close() will skip
5159                  * over us; possibly making our ring_buffer_put() the last.
5160                  */
5161                 mutex_lock(&event->mmap_mutex);
5162                 ring_buffer_attach(event, NULL);
5163                 mutex_unlock(&event->mmap_mutex);
5164         }
5165
5166         if (is_cgroup_event(event))
5167                 perf_detach_cgroup(event);
5168
5169         if (!event->parent) {
5170                 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
5171                         put_callchain_buffers();
5172         }
5173
5174         perf_event_free_bpf_prog(event);
5175         perf_addr_filters_splice(event, NULL);
5176         kfree(event->addr_filter_ranges);
5177
5178         if (event->destroy)
5179                 event->destroy(event);
5180
5181         /*
5182          * Must be after ->destroy(), due to uprobe_perf_close() using
5183          * hw.target.
5184          */
5185         if (event->hw.target)
5186                 put_task_struct(event->hw.target);
5187
5188         if (event->pmu_ctx)
5189                 put_pmu_ctx(event->pmu_ctx);
5190
5191         /*
5192          * perf_event_free_task() relies on put_ctx() being 'last', in particular
5193          * all task references must be cleaned up.
5194          */
5195         if (event->ctx)
5196                 put_ctx(event->ctx);
5197
5198         exclusive_event_destroy(event);
5199         module_put(event->pmu->module);
5200
5201         call_rcu(&event->rcu_head, free_event_rcu);
5202 }
5203
5204 /*
5205  * Used to free events which have a known refcount of 1, such as in error paths
5206  * where the event isn't exposed yet and inherited events.
5207  */
5208 static void free_event(struct perf_event *event)
5209 {
5210         if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
5211                                 "unexpected event refcount: %ld; ptr=%p\n",
5212                                 atomic_long_read(&event->refcount), event)) {
5213                 /* leak to avoid use-after-free */
5214                 return;
5215         }
5216
5217         _free_event(event);
5218 }
5219
5220 /*
5221  * Remove user event from the owner task.
5222  */
5223 static void perf_remove_from_owner(struct perf_event *event)
5224 {
5225         struct task_struct *owner;
5226
5227         rcu_read_lock();
5228         /*
5229          * Matches the smp_store_release() in perf_event_exit_task(). If we
5230          * observe !owner it means the list deletion is complete and we can
5231          * indeed free this event, otherwise we need to serialize on
5232          * owner->perf_event_mutex.
5233          */
5234         owner = READ_ONCE(event->owner);
5235         if (owner) {
5236                 /*
5237                  * Since delayed_put_task_struct() also drops the last
5238                  * task reference we can safely take a new reference
5239                  * while holding the rcu_read_lock().
5240                  */
5241                 get_task_struct(owner);
5242         }
5243         rcu_read_unlock();
5244
5245         if (owner) {
5246                 /*
5247                  * If we're here through perf_event_exit_task() we're already
5248                  * holding ctx->mutex which would be an inversion wrt. the
5249                  * normal lock order.
5250                  *
5251                  * However we can safely take this lock because its the child
5252                  * ctx->mutex.
5253                  */
5254                 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
5255
5256                 /*
5257                  * We have to re-check the event->owner field, if it is cleared
5258                  * we raced with perf_event_exit_task(), acquiring the mutex
5259                  * ensured they're done, and we can proceed with freeing the
5260                  * event.
5261                  */
5262                 if (event->owner) {
5263                         list_del_init(&event->owner_entry);
5264                         smp_store_release(&event->owner, NULL);
5265                 }
5266                 mutex_unlock(&owner->perf_event_mutex);
5267                 put_task_struct(owner);
5268         }
5269 }
5270
5271 static void put_event(struct perf_event *event)
5272 {
5273         if (!atomic_long_dec_and_test(&event->refcount))
5274                 return;
5275
5276         _free_event(event);
5277 }
5278
5279 /*
5280  * Kill an event dead; while event:refcount will preserve the event
5281  * object, it will not preserve its functionality. Once the last 'user'
5282  * gives up the object, we'll destroy the thing.
5283  */
5284 int perf_event_release_kernel(struct perf_event *event)
5285 {
5286         struct perf_event_context *ctx = event->ctx;
5287         struct perf_event *child, *tmp;
5288         LIST_HEAD(free_list);
5289
5290         /*
5291          * If we got here through err_alloc: free_event(event); we will not
5292          * have attached to a context yet.
5293          */
5294         if (!ctx) {
5295                 WARN_ON_ONCE(event->attach_state &
5296                                 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
5297                 goto no_ctx;
5298         }
5299
5300         if (!is_kernel_event(event))
5301                 perf_remove_from_owner(event);
5302
5303         ctx = perf_event_ctx_lock(event);
5304         WARN_ON_ONCE(ctx->parent_ctx);
5305
5306         /*
5307          * Mark this event as STATE_DEAD, there is no external reference to it
5308          * anymore.
5309          *
5310          * Anybody acquiring event->child_mutex after the below loop _must_
5311          * also see this, most importantly inherit_event() which will avoid
5312          * placing more children on the list.
5313          *
5314          * Thus this guarantees that we will in fact observe and kill _ALL_
5315          * child events.
5316          */
5317         perf_remove_from_context(event, DETACH_GROUP|DETACH_DEAD);
5318
5319         perf_event_ctx_unlock(event, ctx);
5320
5321 again:
5322         mutex_lock(&event->child_mutex);
5323         list_for_each_entry(child, &event->child_list, child_list) {
5324
5325                 /*
5326                  * Cannot change, child events are not migrated, see the
5327                  * comment with perf_event_ctx_lock_nested().
5328                  */
5329                 ctx = READ_ONCE(child->ctx);
5330                 /*
5331                  * Since child_mutex nests inside ctx::mutex, we must jump
5332                  * through hoops. We start by grabbing a reference on the ctx.
5333                  *
5334                  * Since the event cannot get freed while we hold the
5335                  * child_mutex, the context must also exist and have a !0
5336                  * reference count.
5337                  */
5338                 get_ctx(ctx);
5339
5340                 /*
5341                  * Now that we have a ctx ref, we can drop child_mutex, and
5342                  * acquire ctx::mutex without fear of it going away. Then we
5343                  * can re-acquire child_mutex.
5344                  */
5345                 mutex_unlock(&event->child_mutex);
5346                 mutex_lock(&ctx->mutex);
5347                 mutex_lock(&event->child_mutex);
5348
5349                 /*
5350                  * Now that we hold ctx::mutex and child_mutex, revalidate our
5351                  * state, if child is still the first entry, it didn't get freed
5352                  * and we can continue doing so.
5353                  */
5354                 tmp = list_first_entry_or_null(&event->child_list,
5355                                                struct perf_event, child_list);
5356                 if (tmp == child) {
5357                         perf_remove_from_context(child, DETACH_GROUP);
5358                         list_move(&child->child_list, &free_list);
5359                         /*
5360                          * This matches the refcount bump in inherit_event();
5361                          * this can't be the last reference.
5362                          */
5363                         put_event(event);
5364                 }
5365
5366                 mutex_unlock(&event->child_mutex);
5367                 mutex_unlock(&ctx->mutex);
5368                 put_ctx(ctx);
5369                 goto again;
5370         }
5371         mutex_unlock(&event->child_mutex);
5372
5373         list_for_each_entry_safe(child, tmp, &free_list, child_list) {
5374                 void *var = &child->ctx->refcount;
5375
5376                 list_del(&child->child_list);
5377                 free_event(child);
5378
5379                 /*
5380                  * Wake any perf_event_free_task() waiting for this event to be
5381                  * freed.
5382                  */
5383                 smp_mb(); /* pairs with wait_var_event() */
5384                 wake_up_var(var);
5385         }
5386
5387 no_ctx:
5388         put_event(event); /* Must be the 'last' reference */
5389         return 0;
5390 }
5391 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5392
5393 /*
5394  * Called when the last reference to the file is gone.
5395  */
5396 static int perf_release(struct inode *inode, struct file *file)
5397 {
5398         perf_event_release_kernel(file->private_data);
5399         return 0;
5400 }
5401
5402 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5403 {
5404         struct perf_event *child;
5405         u64 total = 0;
5406
5407         *enabled = 0;
5408         *running = 0;
5409
5410         mutex_lock(&event->child_mutex);
5411
5412         (void)perf_event_read(event, false);
5413         total += perf_event_count(event);
5414
5415         *enabled += event->total_time_enabled +
5416                         atomic64_read(&event->child_total_time_enabled);
5417         *running += event->total_time_running +
5418                         atomic64_read(&event->child_total_time_running);
5419
5420         list_for_each_entry(child, &event->child_list, child_list) {
5421                 (void)perf_event_read(child, false);
5422                 total += perf_event_count(child);
5423                 *enabled += child->total_time_enabled;
5424                 *running += child->total_time_running;
5425         }
5426         mutex_unlock(&event->child_mutex);
5427
5428         return total;
5429 }
5430
5431 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5432 {
5433         struct perf_event_context *ctx;
5434         u64 count;
5435
5436         ctx = perf_event_ctx_lock(event);
5437         count = __perf_event_read_value(event, enabled, running);
5438         perf_event_ctx_unlock(event, ctx);
5439
5440         return count;
5441 }
5442 EXPORT_SYMBOL_GPL(perf_event_read_value);
5443
5444 static int __perf_read_group_add(struct perf_event *leader,
5445                                         u64 read_format, u64 *values)
5446 {
5447         struct perf_event_context *ctx = leader->ctx;
5448         struct perf_event *sub;
5449         unsigned long flags;
5450         int n = 1; /* skip @nr */
5451         int ret;
5452
5453         ret = perf_event_read(leader, true);
5454         if (ret)
5455                 return ret;
5456
5457         raw_spin_lock_irqsave(&ctx->lock, flags);
5458
5459         /*
5460          * Since we co-schedule groups, {enabled,running} times of siblings
5461          * will be identical to those of the leader, so we only publish one
5462          * set.
5463          */
5464         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5465                 values[n++] += leader->total_time_enabled +
5466                         atomic64_read(&leader->child_total_time_enabled);
5467         }
5468
5469         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5470                 values[n++] += leader->total_time_running +
5471                         atomic64_read(&leader->child_total_time_running);
5472         }
5473
5474         /*
5475          * Write {count,id} tuples for every sibling.
5476          */
5477         values[n++] += perf_event_count(leader);
5478         if (read_format & PERF_FORMAT_ID)
5479                 values[n++] = primary_event_id(leader);
5480         if (read_format & PERF_FORMAT_LOST)
5481                 values[n++] = atomic64_read(&leader->lost_samples);
5482
5483         for_each_sibling_event(sub, leader) {
5484                 values[n++] += perf_event_count(sub);
5485                 if (read_format & PERF_FORMAT_ID)
5486                         values[n++] = primary_event_id(sub);
5487                 if (read_format & PERF_FORMAT_LOST)
5488                         values[n++] = atomic64_read(&sub->lost_samples);
5489         }
5490
5491         raw_spin_unlock_irqrestore(&ctx->lock, flags);
5492         return 0;
5493 }
5494
5495 static int perf_read_group(struct perf_event *event,
5496                                    u64 read_format, char __user *buf)
5497 {
5498         struct perf_event *leader = event->group_leader, *child;
5499         struct perf_event_context *ctx = leader->ctx;
5500         int ret;
5501         u64 *values;
5502
5503         lockdep_assert_held(&ctx->mutex);
5504
5505         values = kzalloc(event->read_size, GFP_KERNEL);
5506         if (!values)
5507                 return -ENOMEM;
5508
5509         values[0] = 1 + leader->nr_siblings;
5510
5511         /*
5512          * By locking the child_mutex of the leader we effectively
5513          * lock the child list of all siblings.. XXX explain how.
5514          */
5515         mutex_lock(&leader->child_mutex);
5516
5517         ret = __perf_read_group_add(leader, read_format, values);
5518         if (ret)
5519                 goto unlock;
5520
5521         list_for_each_entry(child, &leader->child_list, child_list) {
5522                 ret = __perf_read_group_add(child, read_format, values);
5523                 if (ret)
5524                         goto unlock;
5525         }
5526
5527         mutex_unlock(&leader->child_mutex);
5528
5529         ret = event->read_size;
5530         if (copy_to_user(buf, values, event->read_size))
5531                 ret = -EFAULT;
5532         goto out;
5533
5534 unlock:
5535         mutex_unlock(&leader->child_mutex);
5536 out:
5537         kfree(values);
5538         return ret;
5539 }
5540
5541 static int perf_read_one(struct perf_event *event,
5542                                  u64 read_format, char __user *buf)
5543 {
5544         u64 enabled, running;
5545         u64 values[5];
5546         int n = 0;
5547
5548         values[n++] = __perf_event_read_value(event, &enabled, &running);
5549         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5550                 values[n++] = enabled;
5551         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5552                 values[n++] = running;
5553         if (read_format & PERF_FORMAT_ID)
5554                 values[n++] = primary_event_id(event);
5555         if (read_format & PERF_FORMAT_LOST)
5556                 values[n++] = atomic64_read(&event->lost_samples);
5557
5558         if (copy_to_user(buf, values, n * sizeof(u64)))
5559                 return -EFAULT;
5560
5561         return n * sizeof(u64);
5562 }
5563
5564 static bool is_event_hup(struct perf_event *event)
5565 {
5566         bool no_children;
5567
5568         if (event->state > PERF_EVENT_STATE_EXIT)
5569                 return false;
5570
5571         mutex_lock(&event->child_mutex);
5572         no_children = list_empty(&event->child_list);
5573         mutex_unlock(&event->child_mutex);
5574         return no_children;
5575 }
5576
5577 /*
5578  * Read the performance event - simple non blocking version for now
5579  */
5580 static ssize_t
5581 __perf_read(struct perf_event *event, char __user *buf, size_t count)
5582 {
5583         u64 read_format = event->attr.read_format;
5584         int ret;
5585
5586         /*
5587          * Return end-of-file for a read on an event that is in
5588          * error state (i.e. because it was pinned but it couldn't be
5589          * scheduled on to the CPU at some point).
5590          */
5591         if (event->state == PERF_EVENT_STATE_ERROR)
5592                 return 0;
5593
5594         if (count < event->read_size)
5595                 return -ENOSPC;
5596
5597         WARN_ON_ONCE(event->ctx->parent_ctx);
5598         if (read_format & PERF_FORMAT_GROUP)
5599                 ret = perf_read_group(event, read_format, buf);
5600         else
5601                 ret = perf_read_one(event, read_format, buf);
5602
5603         return ret;
5604 }
5605
5606 static ssize_t
5607 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5608 {
5609         struct perf_event *event = file->private_data;
5610         struct perf_event_context *ctx;
5611         int ret;
5612
5613         ret = security_perf_event_read(event);
5614         if (ret)
5615                 return ret;
5616
5617         ctx = perf_event_ctx_lock(event);
5618         ret = __perf_read(event, buf, count);
5619         perf_event_ctx_unlock(event, ctx);
5620
5621         return ret;
5622 }
5623
5624 static __poll_t perf_poll(struct file *file, poll_table *wait)
5625 {
5626         struct perf_event *event = file->private_data;
5627         struct perf_buffer *rb;
5628         __poll_t events = EPOLLHUP;
5629
5630         poll_wait(file, &event->waitq, wait);
5631
5632         if (is_event_hup(event))
5633                 return events;
5634
5635         /*
5636          * Pin the event->rb by taking event->mmap_mutex; otherwise
5637          * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5638          */
5639         mutex_lock(&event->mmap_mutex);
5640         rb = event->rb;
5641         if (rb)
5642                 events = atomic_xchg(&rb->poll, 0);
5643         mutex_unlock(&event->mmap_mutex);
5644         return events;
5645 }
5646
5647 static void _perf_event_reset(struct perf_event *event)
5648 {
5649         (void)perf_event_read(event, false);
5650         local64_set(&event->count, 0);
5651         perf_event_update_userpage(event);
5652 }
5653
5654 /* Assume it's not an event with inherit set. */
5655 u64 perf_event_pause(struct perf_event *event, bool reset)
5656 {
5657         struct perf_event_context *ctx;
5658         u64 count;
5659
5660         ctx = perf_event_ctx_lock(event);
5661         WARN_ON_ONCE(event->attr.inherit);
5662         _perf_event_disable(event);
5663         count = local64_read(&event->count);
5664         if (reset)
5665                 local64_set(&event->count, 0);
5666         perf_event_ctx_unlock(event, ctx);
5667
5668         return count;
5669 }
5670 EXPORT_SYMBOL_GPL(perf_event_pause);
5671
5672 /*
5673  * Holding the top-level event's child_mutex means that any
5674  * descendant process that has inherited this event will block
5675  * in perf_event_exit_event() if it goes to exit, thus satisfying the
5676  * task existence requirements of perf_event_enable/disable.
5677  */
5678 static void perf_event_for_each_child(struct perf_event *event,
5679                                         void (*func)(struct perf_event *))
5680 {
5681         struct perf_event *child;
5682
5683         WARN_ON_ONCE(event->ctx->parent_ctx);
5684
5685         mutex_lock(&event->child_mutex);
5686         func(event);
5687         list_for_each_entry(child, &event->child_list, child_list)
5688                 func(child);
5689         mutex_unlock(&event->child_mutex);
5690 }
5691
5692 static void perf_event_for_each(struct perf_event *event,
5693                                   void (*func)(struct perf_event *))
5694 {
5695         struct perf_event_context *ctx = event->ctx;
5696         struct perf_event *sibling;
5697
5698         lockdep_assert_held(&ctx->mutex);
5699
5700         event = event->group_leader;
5701
5702         perf_event_for_each_child(event, func);
5703         for_each_sibling_event(sibling, event)
5704                 perf_event_for_each_child(sibling, func);
5705 }
5706
5707 static void __perf_event_period(struct perf_event *event,
5708                                 struct perf_cpu_context *cpuctx,
5709                                 struct perf_event_context *ctx,
5710                                 void *info)
5711 {
5712         u64 value = *((u64 *)info);
5713         bool active;
5714
5715         if (event->attr.freq) {
5716                 event->attr.sample_freq = value;
5717         } else {
5718                 event->attr.sample_period = value;
5719                 event->hw.sample_period = value;
5720         }
5721
5722         active = (event->state == PERF_EVENT_STATE_ACTIVE);
5723         if (active) {
5724                 perf_pmu_disable(event->pmu);
5725                 /*
5726                  * We could be throttled; unthrottle now to avoid the tick
5727                  * trying to unthrottle while we already re-started the event.
5728                  */
5729                 if (event->hw.interrupts == MAX_INTERRUPTS) {
5730                         event->hw.interrupts = 0;
5731                         perf_log_throttle(event, 1);
5732                 }
5733                 event->pmu->stop(event, PERF_EF_UPDATE);
5734         }
5735
5736         local64_set(&event->hw.period_left, 0);
5737
5738         if (active) {
5739                 event->pmu->start(event, PERF_EF_RELOAD);
5740                 perf_pmu_enable(event->pmu);
5741         }
5742 }
5743
5744 static int perf_event_check_period(struct perf_event *event, u64 value)
5745 {
5746         return event->pmu->check_period(event, value);
5747 }
5748
5749 static int _perf_event_period(struct perf_event *event, u64 value)
5750 {
5751         if (!is_sampling_event(event))
5752                 return -EINVAL;
5753
5754         if (!value)
5755                 return -EINVAL;
5756
5757         if (event->attr.freq && value > sysctl_perf_event_sample_rate)
5758                 return -EINVAL;
5759
5760         if (perf_event_check_period(event, value))
5761                 return -EINVAL;
5762
5763         if (!event->attr.freq && (value & (1ULL << 63)))
5764                 return -EINVAL;
5765
5766         event_function_call(event, __perf_event_period, &value);
5767
5768         return 0;
5769 }
5770
5771 int perf_event_period(struct perf_event *event, u64 value)
5772 {
5773         struct perf_event_context *ctx;
5774         int ret;
5775
5776         ctx = perf_event_ctx_lock(event);
5777         ret = _perf_event_period(event, value);
5778         perf_event_ctx_unlock(event, ctx);
5779
5780         return ret;
5781 }
5782 EXPORT_SYMBOL_GPL(perf_event_period);
5783
5784 static const struct file_operations perf_fops;
5785
5786 static inline int perf_fget_light(int fd, struct fd *p)
5787 {
5788         struct fd f = fdget(fd);
5789         if (!f.file)
5790                 return -EBADF;
5791
5792         if (f.file->f_op != &perf_fops) {
5793                 fdput(f);
5794                 return -EBADF;
5795         }
5796         *p = f;
5797         return 0;
5798 }
5799
5800 static int perf_event_set_output(struct perf_event *event,
5801                                  struct perf_event *output_event);
5802 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
5803 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5804                           struct perf_event_attr *attr);
5805
5806 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
5807 {
5808         void (*func)(struct perf_event *);
5809         u32 flags = arg;
5810
5811         switch (cmd) {
5812         case PERF_EVENT_IOC_ENABLE:
5813                 func = _perf_event_enable;
5814                 break;
5815         case PERF_EVENT_IOC_DISABLE:
5816                 func = _perf_event_disable;
5817                 break;
5818         case PERF_EVENT_IOC_RESET:
5819                 func = _perf_event_reset;
5820                 break;
5821
5822         case PERF_EVENT_IOC_REFRESH:
5823                 return _perf_event_refresh(event, arg);
5824
5825         case PERF_EVENT_IOC_PERIOD:
5826         {
5827                 u64 value;
5828
5829                 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
5830                         return -EFAULT;
5831
5832                 return _perf_event_period(event, value);
5833         }
5834         case PERF_EVENT_IOC_ID:
5835         {
5836                 u64 id = primary_event_id(event);
5837
5838                 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5839                         return -EFAULT;
5840                 return 0;
5841         }
5842
5843         case PERF_EVENT_IOC_SET_OUTPUT:
5844         {
5845                 int ret;
5846                 if (arg != -1) {
5847                         struct perf_event *output_event;
5848                         struct fd output;
5849                         ret = perf_fget_light(arg, &output);
5850                         if (ret)
5851                                 return ret;
5852                         output_event = output.file->private_data;
5853                         ret = perf_event_set_output(event, output_event);
5854                         fdput(output);
5855                 } else {
5856                         ret = perf_event_set_output(event, NULL);
5857                 }
5858                 return ret;
5859         }
5860
5861         case PERF_EVENT_IOC_SET_FILTER:
5862                 return perf_event_set_filter(event, (void __user *)arg);
5863
5864         case PERF_EVENT_IOC_SET_BPF:
5865         {
5866                 struct bpf_prog *prog;
5867                 int err;
5868
5869                 prog = bpf_prog_get(arg);
5870                 if (IS_ERR(prog))
5871                         return PTR_ERR(prog);
5872
5873                 err = perf_event_set_bpf_prog(event, prog, 0);
5874                 if (err) {
5875                         bpf_prog_put(prog);
5876                         return err;
5877                 }
5878
5879                 return 0;
5880         }
5881
5882         case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5883                 struct perf_buffer *rb;
5884
5885                 rcu_read_lock();
5886                 rb = rcu_dereference(event->rb);
5887                 if (!rb || !rb->nr_pages) {
5888                         rcu_read_unlock();
5889                         return -EINVAL;
5890                 }
5891                 rb_toggle_paused(rb, !!arg);
5892                 rcu_read_unlock();
5893                 return 0;
5894         }
5895
5896         case PERF_EVENT_IOC_QUERY_BPF:
5897                 return perf_event_query_prog_array(event, (void __user *)arg);
5898
5899         case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5900                 struct perf_event_attr new_attr;
5901                 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5902                                          &new_attr);
5903
5904                 if (err)
5905                         return err;
5906
5907                 return perf_event_modify_attr(event,  &new_attr);
5908         }
5909         default:
5910                 return -ENOTTY;
5911         }
5912
5913         if (flags & PERF_IOC_FLAG_GROUP)
5914                 perf_event_for_each(event, func);
5915         else
5916                 perf_event_for_each_child(event, func);
5917
5918         return 0;
5919 }
5920
5921 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5922 {
5923         struct perf_event *event = file->private_data;
5924         struct perf_event_context *ctx;
5925         long ret;
5926
5927         /* Treat ioctl like writes as it is likely a mutating operation. */
5928         ret = security_perf_event_write(event);
5929         if (ret)
5930                 return ret;
5931
5932         ctx = perf_event_ctx_lock(event);
5933         ret = _perf_ioctl(event, cmd, arg);
5934         perf_event_ctx_unlock(event, ctx);
5935
5936         return ret;
5937 }
5938
5939 #ifdef CONFIG_COMPAT
5940 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5941                                 unsigned long arg)
5942 {
5943         switch (_IOC_NR(cmd)) {
5944         case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5945         case _IOC_NR(PERF_EVENT_IOC_ID):
5946         case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
5947         case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
5948                 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5949                 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5950                         cmd &= ~IOCSIZE_MASK;
5951                         cmd |= sizeof(void *) << IOCSIZE_SHIFT;
5952                 }
5953                 break;
5954         }
5955         return perf_ioctl(file, cmd, arg);
5956 }
5957 #else
5958 # define perf_compat_ioctl NULL
5959 #endif
5960
5961 int perf_event_task_enable(void)
5962 {
5963         struct perf_event_context *ctx;
5964         struct perf_event *event;
5965
5966         mutex_lock(&current->perf_event_mutex);
5967         list_for_each_entry(event, &current->perf_event_list, owner_entry) {
5968                 ctx = perf_event_ctx_lock(event);
5969                 perf_event_for_each_child(event, _perf_event_enable);
5970                 perf_event_ctx_unlock(event, ctx);
5971         }
5972         mutex_unlock(&current->perf_event_mutex);
5973
5974         return 0;
5975 }
5976
5977 int perf_event_task_disable(void)
5978 {
5979         struct perf_event_context *ctx;
5980         struct perf_event *event;
5981
5982         mutex_lock(&current->perf_event_mutex);
5983         list_for_each_entry(event, &current->perf_event_list, owner_entry) {
5984                 ctx = perf_event_ctx_lock(event);
5985                 perf_event_for_each_child(event, _perf_event_disable);
5986                 perf_event_ctx_unlock(event, ctx);
5987         }
5988         mutex_unlock(&current->perf_event_mutex);
5989
5990         return 0;
5991 }
5992
5993 static int perf_event_index(struct perf_event *event)
5994 {
5995         if (event->hw.state & PERF_HES_STOPPED)
5996                 return 0;
5997
5998         if (event->state != PERF_EVENT_STATE_ACTIVE)
5999                 return 0;
6000
6001         return event->pmu->event_idx(event);
6002 }
6003
6004 static void perf_event_init_userpage(struct perf_event *event)
6005 {
6006         struct perf_event_mmap_page *userpg;
6007         struct perf_buffer *rb;
6008
6009         rcu_read_lock();
6010         rb = rcu_dereference(event->rb);
6011         if (!rb)
6012                 goto unlock;
6013
6014         userpg = rb->user_page;
6015
6016         /* Allow new userspace to detect that bit 0 is deprecated */
6017         userpg->cap_bit0_is_deprecated = 1;
6018         userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
6019         userpg->data_offset = PAGE_SIZE;
6020         userpg->data_size = perf_data_size(rb);
6021
6022 unlock:
6023         rcu_read_unlock();
6024 }
6025
6026 void __weak arch_perf_update_userpage(
6027         struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
6028 {
6029 }
6030
6031 /*
6032  * Callers need to ensure there can be no nesting of this function, otherwise
6033  * the seqlock logic goes bad. We can not serialize this because the arch
6034  * code calls this from NMI context.
6035  */
6036 void perf_event_update_userpage(struct perf_event *event)
6037 {
6038         struct perf_event_mmap_page *userpg;
6039         struct perf_buffer *rb;
6040         u64 enabled, running, now;
6041
6042         rcu_read_lock();
6043         rb = rcu_dereference(event->rb);
6044         if (!rb)
6045                 goto unlock;
6046
6047         /*
6048          * compute total_time_enabled, total_time_running
6049          * based on snapshot values taken when the event
6050          * was last scheduled in.
6051          *
6052          * we cannot simply called update_context_time()
6053          * because of locking issue as we can be called in
6054          * NMI context
6055          */
6056         calc_timer_values(event, &now, &enabled, &running);
6057
6058         userpg = rb->user_page;
6059         /*
6060          * Disable preemption to guarantee consistent time stamps are stored to
6061          * the user page.
6062          */
6063         preempt_disable();
6064         ++userpg->lock;
6065         barrier();
6066         userpg->index = perf_event_index(event);
6067         userpg->offset = perf_event_count(event);
6068         if (userpg->index)
6069                 userpg->offset -= local64_read(&event->hw.prev_count);
6070
6071         userpg->time_enabled = enabled +
6072                         atomic64_read(&event->child_total_time_enabled);
6073
6074         userpg->time_running = running +
6075                         atomic64_read(&event->child_total_time_running);
6076
6077         arch_perf_update_userpage(event, userpg, now);
6078
6079         barrier();
6080         ++userpg->lock;
6081         preempt_enable();
6082 unlock:
6083         rcu_read_unlock();
6084 }
6085 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
6086
6087 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
6088 {
6089         struct perf_event *event = vmf->vma->vm_file->private_data;
6090         struct perf_buffer *rb;
6091         vm_fault_t ret = VM_FAULT_SIGBUS;
6092
6093         if (vmf->flags & FAULT_FLAG_MKWRITE) {
6094                 if (vmf->pgoff == 0)
6095                         ret = 0;
6096                 return ret;
6097         }
6098
6099         rcu_read_lock();
6100         rb = rcu_dereference(event->rb);
6101         if (!rb)
6102                 goto unlock;
6103
6104         if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
6105                 goto unlock;
6106
6107         vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
6108         if (!vmf->page)
6109                 goto unlock;
6110
6111         get_page(vmf->page);
6112         vmf->page->mapping = vmf->vma->vm_file->f_mapping;
6113         vmf->page->index   = vmf->pgoff;
6114
6115         ret = 0;
6116 unlock:
6117         rcu_read_unlock();
6118
6119         return ret;
6120 }
6121
6122 static void ring_buffer_attach(struct perf_event *event,
6123                                struct perf_buffer *rb)
6124 {
6125         struct perf_buffer *old_rb = NULL;
6126         unsigned long flags;
6127
6128         WARN_ON_ONCE(event->parent);
6129
6130         if (event->rb) {
6131                 /*
6132                  * Should be impossible, we set this when removing
6133                  * event->rb_entry and wait/clear when adding event->rb_entry.
6134                  */
6135                 WARN_ON_ONCE(event->rcu_pending);
6136
6137                 old_rb = event->rb;
6138                 spin_lock_irqsave(&old_rb->event_lock, flags);
6139                 list_del_rcu(&event->rb_entry);
6140                 spin_unlock_irqrestore(&old_rb->event_lock, flags);
6141
6142                 event->rcu_batches = get_state_synchronize_rcu();
6143                 event->rcu_pending = 1;
6144         }
6145
6146         if (rb) {
6147                 if (event->rcu_pending) {
6148                         cond_synchronize_rcu(event->rcu_batches);
6149                         event->rcu_pending = 0;
6150                 }
6151
6152                 spin_lock_irqsave(&rb->event_lock, flags);
6153                 list_add_rcu(&event->rb_entry, &rb->event_list);
6154                 spin_unlock_irqrestore(&rb->event_lock, flags);
6155         }
6156
6157         /*
6158          * Avoid racing with perf_mmap_close(AUX): stop the event
6159          * before swizzling the event::rb pointer; if it's getting
6160          * unmapped, its aux_mmap_count will be 0 and it won't
6161          * restart. See the comment in __perf_pmu_output_stop().
6162          *
6163          * Data will inevitably be lost when set_output is done in
6164          * mid-air, but then again, whoever does it like this is
6165          * not in for the data anyway.
6166          */
6167         if (has_aux(event))
6168                 perf_event_stop(event, 0);
6169
6170         rcu_assign_pointer(event->rb, rb);
6171
6172         if (old_rb) {
6173                 ring_buffer_put(old_rb);
6174                 /*
6175                  * Since we detached before setting the new rb, so that we
6176                  * could attach the new rb, we could have missed a wakeup.
6177                  * Provide it now.
6178                  */
6179                 wake_up_all(&event->waitq);
6180         }
6181 }
6182
6183 static void ring_buffer_wakeup(struct perf_event *event)
6184 {
6185         struct perf_buffer *rb;
6186
6187         if (event->parent)
6188                 event = event->parent;
6189
6190         rcu_read_lock();
6191         rb = rcu_dereference(event->rb);
6192         if (rb) {
6193                 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
6194                         wake_up_all(&event->waitq);
6195         }
6196         rcu_read_unlock();
6197 }
6198
6199 struct perf_buffer *ring_buffer_get(struct perf_event *event)
6200 {
6201         struct perf_buffer *rb;
6202
6203         if (event->parent)
6204                 event = event->parent;
6205
6206         rcu_read_lock();
6207         rb = rcu_dereference(event->rb);
6208         if (rb) {
6209                 if (!refcount_inc_not_zero(&rb->refcount))
6210                         rb = NULL;
6211         }
6212         rcu_read_unlock();
6213
6214         return rb;
6215 }
6216
6217 void ring_buffer_put(struct perf_buffer *rb)
6218 {
6219         if (!refcount_dec_and_test(&rb->refcount))
6220                 return;
6221
6222         WARN_ON_ONCE(!list_empty(&rb->event_list));
6223
6224         call_rcu(&rb->rcu_head, rb_free_rcu);
6225 }
6226
6227 static void perf_mmap_open(struct vm_area_struct *vma)
6228 {
6229         struct perf_event *event = vma->vm_file->private_data;
6230
6231         atomic_inc(&event->mmap_count);
6232         atomic_inc(&event->rb->mmap_count);
6233
6234         if (vma->vm_pgoff)
6235                 atomic_inc(&event->rb->aux_mmap_count);
6236
6237         if (event->pmu->event_mapped)
6238                 event->pmu->event_mapped(event, vma->vm_mm);
6239 }
6240
6241 static void perf_pmu_output_stop(struct perf_event *event);
6242
6243 /*
6244  * A buffer can be mmap()ed multiple times; either directly through the same
6245  * event, or through other events by use of perf_event_set_output().
6246  *
6247  * In order to undo the VM accounting done by perf_mmap() we need to destroy
6248  * the buffer here, where we still have a VM context. This means we need
6249  * to detach all events redirecting to us.
6250  */
6251 static void perf_mmap_close(struct vm_area_struct *vma)
6252 {
6253         struct perf_event *event = vma->vm_file->private_data;
6254         struct perf_buffer *rb = ring_buffer_get(event);
6255         struct user_struct *mmap_user = rb->mmap_user;
6256         int mmap_locked = rb->mmap_locked;
6257         unsigned long size = perf_data_size(rb);
6258         bool detach_rest = false;
6259
6260         if (event->pmu->event_unmapped)
6261                 event->pmu->event_unmapped(event, vma->vm_mm);
6262
6263         /*
6264          * rb->aux_mmap_count will always drop before rb->mmap_count and
6265          * event->mmap_count, so it is ok to use event->mmap_mutex to
6266          * serialize with perf_mmap here.
6267          */
6268         if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
6269             atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
6270                 /*
6271                  * Stop all AUX events that are writing to this buffer,
6272                  * so that we can free its AUX pages and corresponding PMU
6273                  * data. Note that after rb::aux_mmap_count dropped to zero,
6274                  * they won't start any more (see perf_aux_output_begin()).
6275                  */
6276                 perf_pmu_output_stop(event);
6277
6278                 /* now it's safe to free the pages */
6279                 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
6280                 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
6281
6282                 /* this has to be the last one */
6283                 rb_free_aux(rb);
6284                 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
6285
6286                 mutex_unlock(&event->mmap_mutex);
6287         }
6288
6289         if (atomic_dec_and_test(&rb->mmap_count))
6290                 detach_rest = true;
6291
6292         if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
6293                 goto out_put;
6294
6295         ring_buffer_attach(event, NULL);
6296         mutex_unlock(&event->mmap_mutex);
6297
6298         /* If there's still other mmap()s of this buffer, we're done. */
6299         if (!detach_rest)
6300                 goto out_put;
6301
6302         /*
6303          * No other mmap()s, detach from all other events that might redirect
6304          * into the now unreachable buffer. Somewhat complicated by the
6305          * fact that rb::event_lock otherwise nests inside mmap_mutex.
6306          */
6307 again:
6308         rcu_read_lock();
6309         list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
6310                 if (!atomic_long_inc_not_zero(&event->refcount)) {
6311                         /*
6312                          * This event is en-route to free_event() which will
6313                          * detach it and remove it from the list.
6314                          */
6315                         continue;
6316                 }
6317                 rcu_read_unlock();
6318
6319                 mutex_lock(&event->mmap_mutex);
6320                 /*
6321                  * Check we didn't race with perf_event_set_output() which can
6322                  * swizzle the rb from under us while we were waiting to
6323                  * acquire mmap_mutex.
6324                  *
6325                  * If we find a different rb; ignore this event, a next
6326                  * iteration will no longer find it on the list. We have to
6327                  * still restart the iteration to make sure we're not now
6328                  * iterating the wrong list.
6329                  */
6330                 if (event->rb == rb)
6331                         ring_buffer_attach(event, NULL);
6332
6333                 mutex_unlock(&event->mmap_mutex);
6334                 put_event(event);
6335
6336                 /*
6337                  * Restart the iteration; either we're on the wrong list or
6338                  * destroyed its integrity by doing a deletion.
6339                  */
6340                 goto again;
6341         }
6342         rcu_read_unlock();
6343
6344         /*
6345          * It could be there's still a few 0-ref events on the list; they'll
6346          * get cleaned up by free_event() -- they'll also still have their
6347          * ref on the rb and will free it whenever they are done with it.
6348          *
6349          * Aside from that, this buffer is 'fully' detached and unmapped,
6350          * undo the VM accounting.
6351          */
6352
6353         atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
6354                         &mmap_user->locked_vm);
6355         atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
6356         free_uid(mmap_user);
6357
6358 out_put:
6359         ring_buffer_put(rb); /* could be last */
6360 }
6361
6362 static const struct vm_operations_struct perf_mmap_vmops = {
6363         .open           = perf_mmap_open,
6364         .close          = perf_mmap_close, /* non mergeable */
6365         .fault          = perf_mmap_fault,
6366         .page_mkwrite   = perf_mmap_fault,
6367 };
6368
6369 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
6370 {
6371         struct perf_event *event = file->private_data;
6372         unsigned long user_locked, user_lock_limit;
6373         struct user_struct *user = current_user();
6374         struct perf_buffer *rb = NULL;
6375         unsigned long locked, lock_limit;
6376         unsigned long vma_size;
6377         unsigned long nr_pages;
6378         long user_extra = 0, extra = 0;
6379         int ret = 0, flags = 0;
6380
6381         /*
6382          * Don't allow mmap() of inherited per-task counters. This would
6383          * create a performance issue due to all children writing to the
6384          * same rb.
6385          */
6386         if (event->cpu == -1 && event->attr.inherit)
6387                 return -EINVAL;
6388
6389         if (!(vma->vm_flags & VM_SHARED))
6390                 return -EINVAL;
6391
6392         ret = security_perf_event_read(event);
6393         if (ret)
6394                 return ret;
6395
6396         vma_size = vma->vm_end - vma->vm_start;
6397
6398         if (vma->vm_pgoff == 0) {
6399                 nr_pages = (vma_size / PAGE_SIZE) - 1;
6400         } else {
6401                 /*
6402                  * AUX area mapping: if rb->aux_nr_pages != 0, it's already
6403                  * mapped, all subsequent mappings should have the same size
6404                  * and offset. Must be above the normal perf buffer.
6405                  */
6406                 u64 aux_offset, aux_size;
6407
6408                 if (!event->rb)
6409                         return -EINVAL;
6410
6411                 nr_pages = vma_size / PAGE_SIZE;
6412
6413                 mutex_lock(&event->mmap_mutex);
6414                 ret = -EINVAL;
6415
6416                 rb = event->rb;
6417                 if (!rb)
6418                         goto aux_unlock;
6419
6420                 aux_offset = READ_ONCE(rb->user_page->aux_offset);
6421                 aux_size = READ_ONCE(rb->user_page->aux_size);
6422
6423                 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6424                         goto aux_unlock;
6425
6426                 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6427                         goto aux_unlock;
6428
6429                 /* already mapped with a different offset */
6430                 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6431                         goto aux_unlock;
6432
6433                 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6434                         goto aux_unlock;
6435
6436                 /* already mapped with a different size */
6437                 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6438                         goto aux_unlock;
6439
6440                 if (!is_power_of_2(nr_pages))
6441                         goto aux_unlock;
6442
6443                 if (!atomic_inc_not_zero(&rb->mmap_count))
6444                         goto aux_unlock;
6445
6446                 if (rb_has_aux(rb)) {
6447                         atomic_inc(&rb->aux_mmap_count);
6448                         ret = 0;
6449                         goto unlock;
6450                 }
6451
6452                 atomic_set(&rb->aux_mmap_count, 1);
6453                 user_extra = nr_pages;
6454
6455                 goto accounting;
6456         }
6457
6458         /*
6459          * If we have rb pages ensure they're a power-of-two number, so we
6460          * can do bitmasks instead of modulo.
6461          */
6462         if (nr_pages != 0 && !is_power_of_2(nr_pages))
6463                 return -EINVAL;
6464
6465         if (vma_size != PAGE_SIZE * (1 + nr_pages))
6466                 return -EINVAL;
6467
6468         WARN_ON_ONCE(event->ctx->parent_ctx);
6469 again:
6470         mutex_lock(&event->mmap_mutex);
6471         if (event->rb) {
6472                 if (data_page_nr(event->rb) != nr_pages) {
6473                         ret = -EINVAL;
6474                         goto unlock;
6475                 }
6476
6477                 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
6478                         /*
6479                          * Raced against perf_mmap_close(); remove the
6480                          * event and try again.
6481                          */
6482                         ring_buffer_attach(event, NULL);
6483                         mutex_unlock(&event->mmap_mutex);
6484                         goto again;
6485                 }
6486
6487                 goto unlock;
6488         }
6489
6490         user_extra = nr_pages + 1;
6491
6492 accounting:
6493         user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
6494
6495         /*
6496          * Increase the limit linearly with more CPUs:
6497          */
6498         user_lock_limit *= num_online_cpus();
6499
6500         user_locked = atomic_long_read(&user->locked_vm);
6501
6502         /*
6503          * sysctl_perf_event_mlock may have changed, so that
6504          *     user->locked_vm > user_lock_limit
6505          */
6506         if (user_locked > user_lock_limit)
6507                 user_locked = user_lock_limit;
6508         user_locked += user_extra;
6509
6510         if (user_locked > user_lock_limit) {
6511                 /*
6512                  * charge locked_vm until it hits user_lock_limit;
6513                  * charge the rest from pinned_vm
6514                  */
6515                 extra = user_locked - user_lock_limit;
6516                 user_extra -= extra;
6517         }
6518
6519         lock_limit = rlimit(RLIMIT_MEMLOCK);
6520         lock_limit >>= PAGE_SHIFT;
6521         locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
6522
6523         if ((locked > lock_limit) && perf_is_paranoid() &&
6524                 !capable(CAP_IPC_LOCK)) {
6525                 ret = -EPERM;
6526                 goto unlock;
6527         }
6528
6529         WARN_ON(!rb && event->rb);
6530
6531         if (vma->vm_flags & VM_WRITE)
6532                 flags |= RING_BUFFER_WRITABLE;
6533
6534         if (!rb) {
6535                 rb = rb_alloc(nr_pages,
6536                               event->attr.watermark ? event->attr.wakeup_watermark : 0,
6537                               event->cpu, flags);
6538
6539                 if (!rb) {
6540                         ret = -ENOMEM;
6541                         goto unlock;
6542                 }
6543
6544                 atomic_set(&rb->mmap_count, 1);
6545                 rb->mmap_user = get_current_user();
6546                 rb->mmap_locked = extra;
6547
6548                 ring_buffer_attach(event, rb);
6549
6550                 perf_event_update_time(event);
6551                 perf_event_init_userpage(event);
6552                 perf_event_update_userpage(event);
6553         } else {
6554                 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
6555                                    event->attr.aux_watermark, flags);
6556                 if (!ret)
6557                         rb->aux_mmap_locked = extra;
6558         }
6559
6560 unlock:
6561         if (!ret) {
6562                 atomic_long_add(user_extra, &user->locked_vm);
6563                 atomic64_add(extra, &vma->vm_mm->pinned_vm);
6564
6565                 atomic_inc(&event->mmap_count);
6566         } else if (rb) {
6567                 atomic_dec(&rb->mmap_count);
6568         }
6569 aux_unlock:
6570         mutex_unlock(&event->mmap_mutex);
6571
6572         /*
6573          * Since pinned accounting is per vm we cannot allow fork() to copy our
6574          * vma.
6575          */
6576         vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
6577         vma->vm_ops = &perf_mmap_vmops;
6578
6579         if (event->pmu->event_mapped)
6580                 event->pmu->event_mapped(event, vma->vm_mm);
6581
6582         return ret;
6583 }
6584
6585 static int perf_fasync(int fd, struct file *filp, int on)
6586 {
6587         struct inode *inode = file_inode(filp);
6588         struct perf_event *event = filp->private_data;
6589         int retval;
6590
6591         inode_lock(inode);
6592         retval = fasync_helper(fd, filp, on, &event->fasync);
6593         inode_unlock(inode);
6594
6595         if (retval < 0)
6596                 return retval;
6597
6598         return 0;
6599 }
6600
6601 static const struct file_operations perf_fops = {
6602         .llseek                 = no_llseek,
6603         .release                = perf_release,
6604         .read                   = perf_read,
6605         .poll                   = perf_poll,
6606         .unlocked_ioctl         = perf_ioctl,
6607         .compat_ioctl           = perf_compat_ioctl,
6608         .mmap                   = perf_mmap,
6609         .fasync                 = perf_fasync,
6610 };
6611
6612 /*
6613  * Perf event wakeup
6614  *
6615  * If there's data, ensure we set the poll() state and publish everything
6616  * to user-space before waking everybody up.
6617  */
6618
6619 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
6620 {
6621         /* only the parent has fasync state */
6622         if (event->parent)
6623                 event = event->parent;
6624         return &event->fasync;
6625 }
6626
6627 void perf_event_wakeup(struct perf_event *event)
6628 {
6629         ring_buffer_wakeup(event);
6630
6631         if (event->pending_kill) {
6632                 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
6633                 event->pending_kill = 0;
6634         }
6635 }
6636
6637 static void perf_sigtrap(struct perf_event *event)
6638 {
6639         /*
6640          * We'd expect this to only occur if the irq_work is delayed and either
6641          * ctx->task or current has changed in the meantime. This can be the
6642          * case on architectures that do not implement arch_irq_work_raise().
6643          */
6644         if (WARN_ON_ONCE(event->ctx->task != current))
6645                 return;
6646
6647         /*
6648          * Both perf_pending_task() and perf_pending_irq() can race with the
6649          * task exiting.
6650          */
6651         if (current->flags & PF_EXITING)
6652                 return;
6653
6654         send_sig_perf((void __user *)event->pending_addr,
6655                       event->attr.type, event->attr.sig_data);
6656 }
6657
6658 /*
6659  * Deliver the pending work in-event-context or follow the context.
6660  */
6661 static void __perf_pending_irq(struct perf_event *event)
6662 {
6663         int cpu = READ_ONCE(event->oncpu);
6664
6665         /*
6666          * If the event isn't running; we done. event_sched_out() will have
6667          * taken care of things.
6668          */
6669         if (cpu < 0)
6670                 return;
6671
6672         /*
6673          * Yay, we hit home and are in the context of the event.
6674          */
6675         if (cpu == smp_processor_id()) {
6676                 if (event->pending_sigtrap) {
6677                         event->pending_sigtrap = 0;
6678                         perf_sigtrap(event);
6679                         local_dec(&event->ctx->nr_pending);
6680                 }
6681                 if (event->pending_disable) {
6682                         event->pending_disable = 0;
6683                         perf_event_disable_local(event);
6684                 }
6685                 return;
6686         }
6687
6688         /*
6689          *  CPU-A                       CPU-B
6690          *
6691          *  perf_event_disable_inatomic()
6692          *    @pending_disable = CPU-A;
6693          *    irq_work_queue();
6694          *
6695          *  sched-out
6696          *    @pending_disable = -1;
6697          *
6698          *                              sched-in
6699          *                              perf_event_disable_inatomic()
6700          *                                @pending_disable = CPU-B;
6701          *                                irq_work_queue(); // FAILS
6702          *
6703          *  irq_work_run()
6704          *    perf_pending_irq()
6705          *
6706          * But the event runs on CPU-B and wants disabling there.
6707          */
6708         irq_work_queue_on(&event->pending_irq, cpu);
6709 }
6710
6711 static void perf_pending_irq(struct irq_work *entry)
6712 {
6713         struct perf_event *event = container_of(entry, struct perf_event, pending_irq);
6714         int rctx;
6715
6716         /*
6717          * If we 'fail' here, that's OK, it means recursion is already disabled
6718          * and we won't recurse 'further'.
6719          */
6720         rctx = perf_swevent_get_recursion_context();
6721
6722         /*
6723          * The wakeup isn't bound to the context of the event -- it can happen
6724          * irrespective of where the event is.
6725          */
6726         if (event->pending_wakeup) {
6727                 event->pending_wakeup = 0;
6728                 perf_event_wakeup(event);
6729         }
6730
6731         __perf_pending_irq(event);
6732
6733         if (rctx >= 0)
6734                 perf_swevent_put_recursion_context(rctx);
6735 }
6736
6737 static void perf_pending_task(struct callback_head *head)
6738 {
6739         struct perf_event *event = container_of(head, struct perf_event, pending_task);
6740         int rctx;
6741
6742         /*
6743          * If we 'fail' here, that's OK, it means recursion is already disabled
6744          * and we won't recurse 'further'.
6745          */
6746         preempt_disable_notrace();
6747         rctx = perf_swevent_get_recursion_context();
6748
6749         if (event->pending_work) {
6750                 event->pending_work = 0;
6751                 perf_sigtrap(event);
6752                 local_dec(&event->ctx->nr_pending);
6753         }
6754
6755         if (rctx >= 0)
6756                 perf_swevent_put_recursion_context(rctx);
6757         preempt_enable_notrace();
6758
6759         put_event(event);
6760 }
6761
6762 #ifdef CONFIG_GUEST_PERF_EVENTS
6763 struct perf_guest_info_callbacks __rcu *perf_guest_cbs;
6764
6765 DEFINE_STATIC_CALL_RET0(__perf_guest_state, *perf_guest_cbs->state);
6766 DEFINE_STATIC_CALL_RET0(__perf_guest_get_ip, *perf_guest_cbs->get_ip);
6767 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr);
6768
6769 void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6770 {
6771         if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs)))
6772                 return;
6773
6774         rcu_assign_pointer(perf_guest_cbs, cbs);
6775         static_call_update(__perf_guest_state, cbs->state);
6776         static_call_update(__perf_guest_get_ip, cbs->get_ip);
6777
6778         /* Implementing ->handle_intel_pt_intr is optional. */
6779         if (cbs->handle_intel_pt_intr)
6780                 static_call_update(__perf_guest_handle_intel_pt_intr,
6781                                    cbs->handle_intel_pt_intr);
6782 }
6783 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
6784
6785 void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6786 {
6787         if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs) != cbs))
6788                 return;
6789
6790         rcu_assign_pointer(perf_guest_cbs, NULL);
6791         static_call_update(__perf_guest_state, (void *)&__static_call_return0);
6792         static_call_update(__perf_guest_get_ip, (void *)&__static_call_return0);
6793         static_call_update(__perf_guest_handle_intel_pt_intr,
6794                            (void *)&__static_call_return0);
6795         synchronize_rcu();
6796 }
6797 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
6798 #endif
6799
6800 static void
6801 perf_output_sample_regs(struct perf_output_handle *handle,
6802                         struct pt_regs *regs, u64 mask)
6803 {
6804         int bit;
6805         DECLARE_BITMAP(_mask, 64);
6806
6807         bitmap_from_u64(_mask, mask);
6808         for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
6809                 u64 val;
6810
6811                 val = perf_reg_value(regs, bit);
6812                 perf_output_put(handle, val);
6813         }
6814 }
6815
6816 static void perf_sample_regs_user(struct perf_regs *regs_user,
6817                                   struct pt_regs *regs)
6818 {
6819         if (user_mode(regs)) {
6820                 regs_user->abi = perf_reg_abi(current);
6821                 regs_user->regs = regs;
6822         } else if (!(current->flags & PF_KTHREAD)) {
6823                 perf_get_regs_user(regs_user, regs);
6824         } else {
6825                 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
6826                 regs_user->regs = NULL;
6827         }
6828 }
6829
6830 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
6831                                   struct pt_regs *regs)
6832 {
6833         regs_intr->regs = regs;
6834         regs_intr->abi  = perf_reg_abi(current);
6835 }
6836
6837
6838 /*
6839  * Get remaining task size from user stack pointer.
6840  *
6841  * It'd be better to take stack vma map and limit this more
6842  * precisely, but there's no way to get it safely under interrupt,
6843  * so using TASK_SIZE as limit.
6844  */
6845 static u64 perf_ustack_task_size(struct pt_regs *regs)
6846 {
6847         unsigned long addr = perf_user_stack_pointer(regs);
6848
6849         if (!addr || addr >= TASK_SIZE)
6850                 return 0;
6851
6852         return TASK_SIZE - addr;
6853 }
6854
6855 static u16
6856 perf_sample_ustack_size(u16 stack_size, u16 header_size,
6857                         struct pt_regs *regs)
6858 {
6859         u64 task_size;
6860
6861         /* No regs, no stack pointer, no dump. */
6862         if (!regs)
6863                 return 0;
6864
6865         /*
6866          * Check if we fit in with the requested stack size into the:
6867          * - TASK_SIZE
6868          *   If we don't, we limit the size to the TASK_SIZE.
6869          *
6870          * - remaining sample size
6871          *   If we don't, we customize the stack size to
6872          *   fit in to the remaining sample size.
6873          */
6874
6875         task_size  = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
6876         stack_size = min(stack_size, (u16) task_size);
6877
6878         /* Current header size plus static size and dynamic size. */
6879         header_size += 2 * sizeof(u64);
6880
6881         /* Do we fit in with the current stack dump size? */
6882         if ((u16) (header_size + stack_size) < header_size) {
6883                 /*
6884                  * If we overflow the maximum size for the sample,
6885                  * we customize the stack dump size to fit in.
6886                  */
6887                 stack_size = USHRT_MAX - header_size - sizeof(u64);
6888                 stack_size = round_up(stack_size, sizeof(u64));
6889         }
6890
6891         return stack_size;
6892 }
6893
6894 static void
6895 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
6896                           struct pt_regs *regs)
6897 {
6898         /* Case of a kernel thread, nothing to dump */
6899         if (!regs) {
6900                 u64 size = 0;
6901                 perf_output_put(handle, size);
6902         } else {
6903                 unsigned long sp;
6904                 unsigned int rem;
6905                 u64 dyn_size;
6906
6907                 /*
6908                  * We dump:
6909                  * static size
6910                  *   - the size requested by user or the best one we can fit
6911                  *     in to the sample max size
6912                  * data
6913                  *   - user stack dump data
6914                  * dynamic size
6915                  *   - the actual dumped size
6916                  */
6917
6918                 /* Static size. */
6919                 perf_output_put(handle, dump_size);
6920
6921                 /* Data. */
6922                 sp = perf_user_stack_pointer(regs);
6923                 rem = __output_copy_user(handle, (void *) sp, dump_size);
6924                 dyn_size = dump_size - rem;
6925
6926                 perf_output_skip(handle, rem);
6927
6928                 /* Dynamic size. */
6929                 perf_output_put(handle, dyn_size);
6930         }
6931 }
6932
6933 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
6934                                           struct perf_sample_data *data,
6935                                           size_t size)
6936 {
6937         struct perf_event *sampler = event->aux_event;
6938         struct perf_buffer *rb;
6939
6940         data->aux_size = 0;
6941
6942         if (!sampler)
6943                 goto out;
6944
6945         if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
6946                 goto out;
6947
6948         if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
6949                 goto out;
6950
6951         rb = ring_buffer_get(sampler);
6952         if (!rb)
6953                 goto out;
6954
6955         /*
6956          * If this is an NMI hit inside sampling code, don't take
6957          * the sample. See also perf_aux_sample_output().
6958          */
6959         if (READ_ONCE(rb->aux_in_sampling)) {
6960                 data->aux_size = 0;
6961         } else {
6962                 size = min_t(size_t, size, perf_aux_size(rb));
6963                 data->aux_size = ALIGN(size, sizeof(u64));
6964         }
6965         ring_buffer_put(rb);
6966
6967 out:
6968         return data->aux_size;
6969 }
6970
6971 static long perf_pmu_snapshot_aux(struct perf_buffer *rb,
6972                                  struct perf_event *event,
6973                                  struct perf_output_handle *handle,
6974                                  unsigned long size)
6975 {
6976         unsigned long flags;
6977         long ret;
6978
6979         /*
6980          * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
6981          * paths. If we start calling them in NMI context, they may race with
6982          * the IRQ ones, that is, for example, re-starting an event that's just
6983          * been stopped, which is why we're using a separate callback that
6984          * doesn't change the event state.
6985          *
6986          * IRQs need to be disabled to prevent IPIs from racing with us.
6987          */
6988         local_irq_save(flags);
6989         /*
6990          * Guard against NMI hits inside the critical section;
6991          * see also perf_prepare_sample_aux().
6992          */
6993         WRITE_ONCE(rb->aux_in_sampling, 1);
6994         barrier();
6995
6996         ret = event->pmu->snapshot_aux(event, handle, size);
6997
6998         barrier();
6999         WRITE_ONCE(rb->aux_in_sampling, 0);
7000         local_irq_restore(flags);
7001
7002         return ret;
7003 }
7004
7005 static void perf_aux_sample_output(struct perf_event *event,
7006                                    struct perf_output_handle *handle,
7007                                    struct perf_sample_data *data)
7008 {
7009         struct perf_event *sampler = event->aux_event;
7010         struct perf_buffer *rb;
7011         unsigned long pad;
7012         long size;
7013
7014         if (WARN_ON_ONCE(!sampler || !data->aux_size))
7015                 return;
7016
7017         rb = ring_buffer_get(sampler);
7018         if (!rb)
7019                 return;
7020
7021         size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
7022
7023         /*
7024          * An error here means that perf_output_copy() failed (returned a
7025          * non-zero surplus that it didn't copy), which in its current
7026          * enlightened implementation is not possible. If that changes, we'd
7027          * like to know.
7028          */
7029         if (WARN_ON_ONCE(size < 0))
7030                 goto out_put;
7031
7032         /*
7033          * The pad comes from ALIGN()ing data->aux_size up to u64 in
7034          * perf_prepare_sample_aux(), so should not be more than that.
7035          */
7036         pad = data->aux_size - size;
7037         if (WARN_ON_ONCE(pad >= sizeof(u64)))
7038                 pad = 8;
7039
7040         if (pad) {
7041                 u64 zero = 0;
7042                 perf_output_copy(handle, &zero, pad);
7043         }
7044
7045 out_put:
7046         ring_buffer_put(rb);
7047 }
7048
7049 static void __perf_event_header__init_id(struct perf_event_header *header,
7050                                          struct perf_sample_data *data,
7051                                          struct perf_event *event,
7052                                          u64 sample_type)
7053 {
7054         data->type = event->attr.sample_type;
7055         header->size += event->id_header_size;
7056
7057         if (sample_type & PERF_SAMPLE_TID) {
7058                 /* namespace issues */
7059                 data->tid_entry.pid = perf_event_pid(event, current);
7060                 data->tid_entry.tid = perf_event_tid(event, current);
7061         }
7062
7063         if (sample_type & PERF_SAMPLE_TIME)
7064                 data->time = perf_event_clock(event);
7065
7066         if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
7067                 data->id = primary_event_id(event);
7068
7069         if (sample_type & PERF_SAMPLE_STREAM_ID)
7070                 data->stream_id = event->id;
7071
7072         if (sample_type & PERF_SAMPLE_CPU) {
7073                 data->cpu_entry.cpu      = raw_smp_processor_id();
7074                 data->cpu_entry.reserved = 0;
7075         }
7076 }
7077
7078 void perf_event_header__init_id(struct perf_event_header *header,
7079                                 struct perf_sample_data *data,
7080                                 struct perf_event *event)
7081 {
7082         if (event->attr.sample_id_all)
7083                 __perf_event_header__init_id(header, data, event, event->attr.sample_type);
7084 }
7085
7086 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
7087                                            struct perf_sample_data *data)
7088 {
7089         u64 sample_type = data->type;
7090
7091         if (sample_type & PERF_SAMPLE_TID)
7092                 perf_output_put(handle, data->tid_entry);
7093
7094         if (sample_type & PERF_SAMPLE_TIME)
7095                 perf_output_put(handle, data->time);
7096
7097         if (sample_type & PERF_SAMPLE_ID)
7098                 perf_output_put(handle, data->id);
7099
7100         if (sample_type & PERF_SAMPLE_STREAM_ID)
7101                 perf_output_put(handle, data->stream_id);
7102
7103         if (sample_type & PERF_SAMPLE_CPU)
7104                 perf_output_put(handle, data->cpu_entry);
7105
7106         if (sample_type & PERF_SAMPLE_IDENTIFIER)
7107                 perf_output_put(handle, data->id);
7108 }
7109
7110 void perf_event__output_id_sample(struct perf_event *event,
7111                                   struct perf_output_handle *handle,
7112                                   struct perf_sample_data *sample)
7113 {
7114         if (event->attr.sample_id_all)
7115                 __perf_event__output_id_sample(handle, sample);
7116 }
7117
7118 static void perf_output_read_one(struct perf_output_handle *handle,
7119                                  struct perf_event *event,
7120                                  u64 enabled, u64 running)
7121 {
7122         u64 read_format = event->attr.read_format;
7123         u64 values[5];
7124         int n = 0;
7125
7126         values[n++] = perf_event_count(event);
7127         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
7128                 values[n++] = enabled +
7129                         atomic64_read(&event->child_total_time_enabled);
7130         }
7131         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
7132                 values[n++] = running +
7133                         atomic64_read(&event->child_total_time_running);
7134         }
7135         if (read_format & PERF_FORMAT_ID)
7136                 values[n++] = primary_event_id(event);
7137         if (read_format & PERF_FORMAT_LOST)
7138                 values[n++] = atomic64_read(&event->lost_samples);
7139
7140         __output_copy(handle, values, n * sizeof(u64));
7141 }
7142
7143 static void perf_output_read_group(struct perf_output_handle *handle,
7144                             struct perf_event *event,
7145                             u64 enabled, u64 running)
7146 {
7147         struct perf_event *leader = event->group_leader, *sub;
7148         u64 read_format = event->attr.read_format;
7149         unsigned long flags;
7150         u64 values[6];
7151         int n = 0;
7152
7153         /*
7154          * Disabling interrupts avoids all counter scheduling
7155          * (context switches, timer based rotation and IPIs).
7156          */
7157         local_irq_save(flags);
7158
7159         values[n++] = 1 + leader->nr_siblings;
7160
7161         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
7162                 values[n++] = enabled;
7163
7164         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
7165                 values[n++] = running;
7166
7167         if ((leader != event) &&
7168             (leader->state == PERF_EVENT_STATE_ACTIVE))
7169                 leader->pmu->read(leader);
7170
7171         values[n++] = perf_event_count(leader);
7172         if (read_format & PERF_FORMAT_ID)
7173                 values[n++] = primary_event_id(leader);
7174         if (read_format & PERF_FORMAT_LOST)
7175                 values[n++] = atomic64_read(&leader->lost_samples);
7176
7177         __output_copy(handle, values, n * sizeof(u64));
7178
7179         for_each_sibling_event(sub, leader) {
7180                 n = 0;
7181
7182                 if ((sub != event) &&
7183                     (sub->state == PERF_EVENT_STATE_ACTIVE))
7184                         sub->pmu->read(sub);
7185
7186                 values[n++] = perf_event_count(sub);
7187                 if (read_format & PERF_FORMAT_ID)
7188                         values[n++] = primary_event_id(sub);
7189                 if (read_format & PERF_FORMAT_LOST)
7190                         values[n++] = atomic64_read(&sub->lost_samples);
7191
7192                 __output_copy(handle, values, n * sizeof(u64));
7193         }
7194
7195         local_irq_restore(flags);
7196 }
7197
7198 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
7199                                  PERF_FORMAT_TOTAL_TIME_RUNNING)
7200
7201 /*
7202  * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
7203  *
7204  * The problem is that its both hard and excessively expensive to iterate the
7205  * child list, not to mention that its impossible to IPI the children running
7206  * on another CPU, from interrupt/NMI context.
7207  */
7208 static void perf_output_read(struct perf_output_handle *handle,
7209                              struct perf_event *event)
7210 {
7211         u64 enabled = 0, running = 0, now;
7212         u64 read_format = event->attr.read_format;
7213
7214         /*
7215          * compute total_time_enabled, total_time_running
7216          * based on snapshot values taken when the event
7217          * was last scheduled in.
7218          *
7219          * we cannot simply called update_context_time()
7220          * because of locking issue as we are called in
7221          * NMI context
7222          */
7223         if (read_format & PERF_FORMAT_TOTAL_TIMES)
7224                 calc_timer_values(event, &now, &enabled, &running);
7225
7226         if (event->attr.read_format & PERF_FORMAT_GROUP)
7227                 perf_output_read_group(handle, event, enabled, running);
7228         else
7229                 perf_output_read_one(handle, event, enabled, running);
7230 }
7231
7232 void perf_output_sample(struct perf_output_handle *handle,
7233                         struct perf_event_header *header,
7234                         struct perf_sample_data *data,
7235                         struct perf_event *event)
7236 {
7237         u64 sample_type = data->type;
7238
7239         perf_output_put(handle, *header);
7240
7241         if (sample_type & PERF_SAMPLE_IDENTIFIER)
7242                 perf_output_put(handle, data->id);
7243
7244         if (sample_type & PERF_SAMPLE_IP)
7245                 perf_output_put(handle, data->ip);
7246
7247         if (sample_type & PERF_SAMPLE_TID)
7248                 perf_output_put(handle, data->tid_entry);
7249
7250         if (sample_type & PERF_SAMPLE_TIME)
7251                 perf_output_put(handle, data->time);
7252
7253         if (sample_type & PERF_SAMPLE_ADDR)
7254                 perf_output_put(handle, data->addr);
7255
7256         if (sample_type & PERF_SAMPLE_ID)
7257                 perf_output_put(handle, data->id);
7258
7259         if (sample_type & PERF_SAMPLE_STREAM_ID)
7260                 perf_output_put(handle, data->stream_id);
7261
7262         if (sample_type & PERF_SAMPLE_CPU)
7263                 perf_output_put(handle, data->cpu_entry);
7264
7265         if (sample_type & PERF_SAMPLE_PERIOD)
7266                 perf_output_put(handle, data->period);
7267
7268         if (sample_type & PERF_SAMPLE_READ)
7269                 perf_output_read(handle, event);
7270
7271         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7272                 int size = 1;
7273
7274                 size += data->callchain->nr;
7275                 size *= sizeof(u64);
7276                 __output_copy(handle, data->callchain, size);
7277         }
7278
7279         if (sample_type & PERF_SAMPLE_RAW) {
7280                 struct perf_raw_record *raw = data->raw;
7281
7282                 if (raw) {
7283                         struct perf_raw_frag *frag = &raw->frag;
7284
7285                         perf_output_put(handle, raw->size);
7286                         do {
7287                                 if (frag->copy) {
7288                                         __output_custom(handle, frag->copy,
7289                                                         frag->data, frag->size);
7290                                 } else {
7291                                         __output_copy(handle, frag->data,
7292                                                       frag->size);
7293                                 }
7294                                 if (perf_raw_frag_last(frag))
7295                                         break;
7296                                 frag = frag->next;
7297                         } while (1);
7298                         if (frag->pad)
7299                                 __output_skip(handle, NULL, frag->pad);
7300                 } else {
7301                         struct {
7302                                 u32     size;
7303                                 u32     data;
7304                         } raw = {
7305                                 .size = sizeof(u32),
7306                                 .data = 0,
7307                         };
7308                         perf_output_put(handle, raw);
7309                 }
7310         }
7311
7312         if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7313                 if (data->sample_flags & PERF_SAMPLE_BRANCH_STACK) {
7314                         size_t size;
7315
7316                         size = data->br_stack->nr
7317                              * sizeof(struct perf_branch_entry);
7318
7319                         perf_output_put(handle, data->br_stack->nr);
7320                         if (branch_sample_hw_index(event))
7321                                 perf_output_put(handle, data->br_stack->hw_idx);
7322                         perf_output_copy(handle, data->br_stack->entries, size);
7323                 } else {
7324                         /*
7325                          * we always store at least the value of nr
7326                          */
7327                         u64 nr = 0;
7328                         perf_output_put(handle, nr);
7329                 }
7330         }
7331
7332         if (sample_type & PERF_SAMPLE_REGS_USER) {
7333                 u64 abi = data->regs_user.abi;
7334
7335                 /*
7336                  * If there are no regs to dump, notice it through
7337                  * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7338                  */
7339                 perf_output_put(handle, abi);
7340
7341                 if (abi) {
7342                         u64 mask = event->attr.sample_regs_user;
7343                         perf_output_sample_regs(handle,
7344                                                 data->regs_user.regs,
7345                                                 mask);
7346                 }
7347         }
7348
7349         if (sample_type & PERF_SAMPLE_STACK_USER) {
7350                 perf_output_sample_ustack(handle,
7351                                           data->stack_user_size,
7352                                           data->regs_user.regs);
7353         }
7354
7355         if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
7356                 perf_output_put(handle, data->weight.full);
7357
7358         if (sample_type & PERF_SAMPLE_DATA_SRC)
7359                 perf_output_put(handle, data->data_src.val);
7360
7361         if (sample_type & PERF_SAMPLE_TRANSACTION)
7362                 perf_output_put(handle, data->txn);
7363
7364         if (sample_type & PERF_SAMPLE_REGS_INTR) {
7365                 u64 abi = data->regs_intr.abi;
7366                 /*
7367                  * If there are no regs to dump, notice it through
7368                  * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7369                  */
7370                 perf_output_put(handle, abi);
7371
7372                 if (abi) {
7373                         u64 mask = event->attr.sample_regs_intr;
7374
7375                         perf_output_sample_regs(handle,
7376                                                 data->regs_intr.regs,
7377                                                 mask);
7378                 }
7379         }
7380
7381         if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7382                 perf_output_put(handle, data->phys_addr);
7383
7384         if (sample_type & PERF_SAMPLE_CGROUP)
7385                 perf_output_put(handle, data->cgroup);
7386
7387         if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
7388                 perf_output_put(handle, data->data_page_size);
7389
7390         if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
7391                 perf_output_put(handle, data->code_page_size);
7392
7393         if (sample_type & PERF_SAMPLE_AUX) {
7394                 perf_output_put(handle, data->aux_size);
7395
7396                 if (data->aux_size)
7397                         perf_aux_sample_output(event, handle, data);
7398         }
7399
7400         if (!event->attr.watermark) {
7401                 int wakeup_events = event->attr.wakeup_events;
7402
7403                 if (wakeup_events) {
7404                         struct perf_buffer *rb = handle->rb;
7405                         int events = local_inc_return(&rb->events);
7406
7407                         if (events >= wakeup_events) {
7408                                 local_sub(wakeup_events, &rb->events);
7409                                 local_inc(&rb->wakeup);
7410                         }
7411                 }
7412         }
7413 }
7414
7415 static u64 perf_virt_to_phys(u64 virt)
7416 {
7417         u64 phys_addr = 0;
7418
7419         if (!virt)
7420                 return 0;
7421
7422         if (virt >= TASK_SIZE) {
7423                 /* If it's vmalloc()d memory, leave phys_addr as 0 */
7424                 if (virt_addr_valid((void *)(uintptr_t)virt) &&
7425                     !(virt >= VMALLOC_START && virt < VMALLOC_END))
7426                         phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
7427         } else {
7428                 /*
7429                  * Walking the pages tables for user address.
7430                  * Interrupts are disabled, so it prevents any tear down
7431                  * of the page tables.
7432                  * Try IRQ-safe get_user_page_fast_only first.
7433                  * If failed, leave phys_addr as 0.
7434                  */
7435                 if (current->mm != NULL) {
7436                         struct page *p;
7437
7438                         pagefault_disable();
7439                         if (get_user_page_fast_only(virt, 0, &p)) {
7440                                 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
7441                                 put_page(p);
7442                         }
7443                         pagefault_enable();
7444                 }
7445         }
7446
7447         return phys_addr;
7448 }
7449
7450 /*
7451  * Return the pagetable size of a given virtual address.
7452  */
7453 static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
7454 {
7455         u64 size = 0;
7456
7457 #ifdef CONFIG_HAVE_FAST_GUP
7458         pgd_t *pgdp, pgd;
7459         p4d_t *p4dp, p4d;
7460         pud_t *pudp, pud;
7461         pmd_t *pmdp, pmd;
7462         pte_t *ptep, pte;
7463
7464         pgdp = pgd_offset(mm, addr);
7465         pgd = READ_ONCE(*pgdp);
7466         if (pgd_none(pgd))
7467                 return 0;
7468
7469         if (pgd_leaf(pgd))
7470                 return pgd_leaf_size(pgd);
7471
7472         p4dp = p4d_offset_lockless(pgdp, pgd, addr);
7473         p4d = READ_ONCE(*p4dp);
7474         if (!p4d_present(p4d))
7475                 return 0;
7476
7477         if (p4d_leaf(p4d))
7478                 return p4d_leaf_size(p4d);
7479
7480         pudp = pud_offset_lockless(p4dp, p4d, addr);
7481         pud = READ_ONCE(*pudp);
7482         if (!pud_present(pud))
7483                 return 0;
7484
7485         if (pud_leaf(pud))
7486                 return pud_leaf_size(pud);
7487
7488         pmdp = pmd_offset_lockless(pudp, pud, addr);
7489         pmd = pmdp_get_lockless(pmdp);
7490         if (!pmd_present(pmd))
7491                 return 0;
7492
7493         if (pmd_leaf(pmd))
7494                 return pmd_leaf_size(pmd);
7495
7496         ptep = pte_offset_map(&pmd, addr);
7497         pte = ptep_get_lockless(ptep);
7498         if (pte_present(pte))
7499                 size = pte_leaf_size(pte);
7500         pte_unmap(ptep);
7501 #endif /* CONFIG_HAVE_FAST_GUP */
7502
7503         return size;
7504 }
7505
7506 static u64 perf_get_page_size(unsigned long addr)
7507 {
7508         struct mm_struct *mm;
7509         unsigned long flags;
7510         u64 size;
7511
7512         if (!addr)
7513                 return 0;
7514
7515         /*
7516          * Software page-table walkers must disable IRQs,
7517          * which prevents any tear down of the page tables.
7518          */
7519         local_irq_save(flags);
7520
7521         mm = current->mm;
7522         if (!mm) {
7523                 /*
7524                  * For kernel threads and the like, use init_mm so that
7525                  * we can find kernel memory.
7526                  */
7527                 mm = &init_mm;
7528         }
7529
7530         size = perf_get_pgtable_size(mm, addr);
7531
7532         local_irq_restore(flags);
7533
7534         return size;
7535 }
7536
7537 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
7538
7539 struct perf_callchain_entry *
7540 perf_callchain(struct perf_event *event, struct pt_regs *regs)
7541 {
7542         bool kernel = !event->attr.exclude_callchain_kernel;
7543         bool user   = !event->attr.exclude_callchain_user;
7544         /* Disallow cross-task user callchains. */
7545         bool crosstask = event->ctx->task && event->ctx->task != current;
7546         const u32 max_stack = event->attr.sample_max_stack;
7547         struct perf_callchain_entry *callchain;
7548
7549         if (!kernel && !user)
7550                 return &__empty_callchain;
7551
7552         callchain = get_perf_callchain(regs, 0, kernel, user,
7553                                        max_stack, crosstask, true);
7554         return callchain ?: &__empty_callchain;
7555 }
7556
7557 void perf_prepare_sample(struct perf_event_header *header,
7558                          struct perf_sample_data *data,
7559                          struct perf_event *event,
7560                          struct pt_regs *regs)
7561 {
7562         u64 sample_type = event->attr.sample_type;
7563         u64 filtered_sample_type;
7564
7565         header->type = PERF_RECORD_SAMPLE;
7566         header->size = sizeof(*header) + event->header_size;
7567
7568         header->misc = 0;
7569         header->misc |= perf_misc_flags(regs);
7570
7571         /*
7572          * Clear the sample flags that have already been done by the
7573          * PMU driver.
7574          */
7575         filtered_sample_type = sample_type & ~data->sample_flags;
7576         __perf_event_header__init_id(header, data, event, filtered_sample_type);
7577
7578         if (sample_type & (PERF_SAMPLE_IP | PERF_SAMPLE_CODE_PAGE_SIZE))
7579                 data->ip = perf_instruction_pointer(regs);
7580
7581         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7582                 int size = 1;
7583
7584                 if (filtered_sample_type & PERF_SAMPLE_CALLCHAIN)
7585                         data->callchain = perf_callchain(event, regs);
7586
7587                 size += data->callchain->nr;
7588
7589                 data->dyn_size += size * sizeof(u64);
7590         }
7591
7592         if (sample_type & PERF_SAMPLE_RAW) {
7593                 struct perf_raw_record *raw = data->raw;
7594                 int size;
7595
7596                 if (raw && (data->sample_flags & PERF_SAMPLE_RAW)) {
7597                         struct perf_raw_frag *frag = &raw->frag;
7598                         u32 sum = 0;
7599
7600                         do {
7601                                 sum += frag->size;
7602                                 if (perf_raw_frag_last(frag))
7603                                         break;
7604                                 frag = frag->next;
7605                         } while (1);
7606
7607                         size = round_up(sum + sizeof(u32), sizeof(u64));
7608                         raw->size = size - sizeof(u32);
7609                         frag->pad = raw->size - sum;
7610                 } else {
7611                         size = sizeof(u64);
7612                         data->raw = NULL;
7613                 }
7614
7615                 data->dyn_size += size;
7616         }
7617
7618         if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7619                 int size = sizeof(u64); /* nr */
7620                 if (data->sample_flags & PERF_SAMPLE_BRANCH_STACK) {
7621                         if (branch_sample_hw_index(event))
7622                                 size += sizeof(u64);
7623
7624                         size += data->br_stack->nr
7625                               * sizeof(struct perf_branch_entry);
7626                 }
7627                 data->dyn_size += size;
7628         }
7629
7630         if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
7631                 perf_sample_regs_user(&data->regs_user, regs);
7632
7633         if (sample_type & PERF_SAMPLE_REGS_USER) {
7634                 /* regs dump ABI info */
7635                 int size = sizeof(u64);
7636
7637                 if (data->regs_user.regs) {
7638                         u64 mask = event->attr.sample_regs_user;
7639                         size += hweight64(mask) * sizeof(u64);
7640                 }
7641
7642                 data->dyn_size += size;
7643         }
7644
7645         if (sample_type & PERF_SAMPLE_STACK_USER) {
7646                 /*
7647                  * Either we need PERF_SAMPLE_STACK_USER bit to be always
7648                  * processed as the last one or have additional check added
7649                  * in case new sample type is added, because we could eat
7650                  * up the rest of the sample size.
7651                  */
7652                 u16 stack_size = event->attr.sample_stack_user;
7653                 u16 size = sizeof(u64);
7654
7655                 stack_size = perf_sample_ustack_size(stack_size, header->size,
7656                                                      data->regs_user.regs);
7657
7658                 /*
7659                  * If there is something to dump, add space for the dump
7660                  * itself and for the field that tells the dynamic size,
7661                  * which is how many have been actually dumped.
7662                  */
7663                 if (stack_size)
7664                         size += sizeof(u64) + stack_size;
7665
7666                 data->stack_user_size = stack_size;
7667                 data->dyn_size += size;
7668         }
7669
7670         if (filtered_sample_type & PERF_SAMPLE_WEIGHT_TYPE)
7671                 data->weight.full = 0;
7672
7673         if (filtered_sample_type & PERF_SAMPLE_DATA_SRC)
7674                 data->data_src.val = PERF_MEM_NA;
7675
7676         if (filtered_sample_type & PERF_SAMPLE_TRANSACTION)
7677                 data->txn = 0;
7678
7679         if (sample_type & (PERF_SAMPLE_ADDR | PERF_SAMPLE_PHYS_ADDR | PERF_SAMPLE_DATA_PAGE_SIZE)) {
7680                 if (filtered_sample_type & PERF_SAMPLE_ADDR)
7681                         data->addr = 0;
7682         }
7683
7684         if (sample_type & PERF_SAMPLE_REGS_INTR) {
7685                 /* regs dump ABI info */
7686                 int size = sizeof(u64);
7687
7688                 perf_sample_regs_intr(&data->regs_intr, regs);
7689
7690                 if (data->regs_intr.regs) {
7691                         u64 mask = event->attr.sample_regs_intr;
7692
7693                         size += hweight64(mask) * sizeof(u64);
7694                 }
7695
7696                 data->dyn_size += size;
7697         }
7698
7699         if (sample_type & PERF_SAMPLE_PHYS_ADDR &&
7700             filtered_sample_type & PERF_SAMPLE_PHYS_ADDR)
7701                 data->phys_addr = perf_virt_to_phys(data->addr);
7702
7703 #ifdef CONFIG_CGROUP_PERF
7704         if (sample_type & PERF_SAMPLE_CGROUP) {
7705                 struct cgroup *cgrp;
7706
7707                 /* protected by RCU */
7708                 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
7709                 data->cgroup = cgroup_id(cgrp);
7710         }
7711 #endif
7712
7713         /*
7714          * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't
7715          * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr,
7716          * but the value will not dump to the userspace.
7717          */
7718         if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
7719                 data->data_page_size = perf_get_page_size(data->addr);
7720
7721         if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
7722                 data->code_page_size = perf_get_page_size(data->ip);
7723
7724         if (sample_type & PERF_SAMPLE_AUX) {
7725                 u64 size;
7726
7727                 header->size += sizeof(u64); /* size */
7728
7729                 /*
7730                  * Given the 16bit nature of header::size, an AUX sample can
7731                  * easily overflow it, what with all the preceding sample bits.
7732                  * Make sure this doesn't happen by using up to U16_MAX bytes
7733                  * per sample in total (rounded down to 8 byte boundary).
7734                  */
7735                 size = min_t(size_t, U16_MAX - header->size,
7736                              event->attr.aux_sample_size);
7737                 size = rounddown(size, 8);
7738                 size = perf_prepare_sample_aux(event, data, size);
7739
7740                 WARN_ON_ONCE(size + header->size > U16_MAX);
7741                 data->dyn_size += size + sizeof(u64); /* size above */
7742         }
7743
7744         header->size += data->dyn_size;
7745
7746         /*
7747          * If you're adding more sample types here, you likely need to do
7748          * something about the overflowing header::size, like repurpose the
7749          * lowest 3 bits of size, which should be always zero at the moment.
7750          * This raises a more important question, do we really need 512k sized
7751          * samples and why, so good argumentation is in order for whatever you
7752          * do here next.
7753          */
7754         WARN_ON_ONCE(header->size & 7);
7755 }
7756
7757 static __always_inline int
7758 __perf_event_output(struct perf_event *event,
7759                     struct perf_sample_data *data,
7760                     struct pt_regs *regs,
7761                     int (*output_begin)(struct perf_output_handle *,
7762                                         struct perf_sample_data *,
7763                                         struct perf_event *,
7764                                         unsigned int))
7765 {
7766         struct perf_output_handle handle;
7767         struct perf_event_header header;
7768         int err;
7769
7770         /* protect the callchain buffers */
7771         rcu_read_lock();
7772
7773         perf_prepare_sample(&header, data, event, regs);
7774
7775         err = output_begin(&handle, data, event, header.size);
7776         if (err)
7777                 goto exit;
7778
7779         perf_output_sample(&handle, &header, data, event);
7780
7781         perf_output_end(&handle);
7782
7783 exit:
7784         rcu_read_unlock();
7785         return err;
7786 }
7787
7788 void
7789 perf_event_output_forward(struct perf_event *event,
7790                          struct perf_sample_data *data,
7791                          struct pt_regs *regs)
7792 {
7793         __perf_event_output(event, data, regs, perf_output_begin_forward);
7794 }
7795
7796 void
7797 perf_event_output_backward(struct perf_event *event,
7798                            struct perf_sample_data *data,
7799                            struct pt_regs *regs)
7800 {
7801         __perf_event_output(event, data, regs, perf_output_begin_backward);
7802 }
7803
7804 int
7805 perf_event_output(struct perf_event *event,
7806                   struct perf_sample_data *data,
7807                   struct pt_regs *regs)
7808 {
7809         return __perf_event_output(event, data, regs, perf_output_begin);
7810 }
7811
7812 /*
7813  * read event_id
7814  */
7815
7816 struct perf_read_event {
7817         struct perf_event_header        header;
7818
7819         u32                             pid;
7820         u32                             tid;
7821 };
7822
7823 static void
7824 perf_event_read_event(struct perf_event *event,
7825                         struct task_struct *task)
7826 {
7827         struct perf_output_handle handle;
7828         struct perf_sample_data sample;
7829         struct perf_read_event read_event = {
7830                 .header = {
7831                         .type = PERF_RECORD_READ,
7832                         .misc = 0,
7833                         .size = sizeof(read_event) + event->read_size,
7834                 },
7835                 .pid = perf_event_pid(event, task),
7836                 .tid = perf_event_tid(event, task),
7837         };
7838         int ret;
7839
7840         perf_event_header__init_id(&read_event.header, &sample, event);
7841         ret = perf_output_begin(&handle, &sample, event, read_event.header.size);
7842         if (ret)
7843                 return;
7844
7845         perf_output_put(&handle, read_event);
7846         perf_output_read(&handle, event);
7847         perf_event__output_id_sample(event, &handle, &sample);
7848
7849         perf_output_end(&handle);
7850 }
7851
7852 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
7853
7854 static void
7855 perf_iterate_ctx(struct perf_event_context *ctx,
7856                    perf_iterate_f output,
7857                    void *data, bool all)
7858 {
7859         struct perf_event *event;
7860
7861         list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7862                 if (!all) {
7863                         if (event->state < PERF_EVENT_STATE_INACTIVE)
7864                                 continue;
7865                         if (!event_filter_match(event))
7866                                 continue;
7867                 }
7868
7869                 output(event, data);
7870         }
7871 }
7872
7873 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
7874 {
7875         struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
7876         struct perf_event *event;
7877
7878         list_for_each_entry_rcu(event, &pel->list, sb_list) {
7879                 /*
7880                  * Skip events that are not fully formed yet; ensure that
7881                  * if we observe event->ctx, both event and ctx will be
7882                  * complete enough. See perf_install_in_context().
7883                  */
7884                 if (!smp_load_acquire(&event->ctx))
7885                         continue;
7886
7887                 if (event->state < PERF_EVENT_STATE_INACTIVE)
7888                         continue;
7889                 if (!event_filter_match(event))
7890                         continue;
7891                 output(event, data);
7892         }
7893 }
7894
7895 /*
7896  * Iterate all events that need to receive side-band events.
7897  *
7898  * For new callers; ensure that account_pmu_sb_event() includes
7899  * your event, otherwise it might not get delivered.
7900  */
7901 static void
7902 perf_iterate_sb(perf_iterate_f output, void *data,
7903                struct perf_event_context *task_ctx)
7904 {
7905         struct perf_event_context *ctx;
7906
7907         rcu_read_lock();
7908         preempt_disable();
7909
7910         /*
7911          * If we have task_ctx != NULL we only notify the task context itself.
7912          * The task_ctx is set only for EXIT events before releasing task
7913          * context.
7914          */
7915         if (task_ctx) {
7916                 perf_iterate_ctx(task_ctx, output, data, false);
7917                 goto done;
7918         }
7919
7920         perf_iterate_sb_cpu(output, data);
7921
7922         ctx = rcu_dereference(current->perf_event_ctxp);
7923         if (ctx)
7924                 perf_iterate_ctx(ctx, output, data, false);
7925 done:
7926         preempt_enable();
7927         rcu_read_unlock();
7928 }
7929
7930 /*
7931  * Clear all file-based filters at exec, they'll have to be
7932  * re-instated when/if these objects are mmapped again.
7933  */
7934 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
7935 {
7936         struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7937         struct perf_addr_filter *filter;
7938         unsigned int restart = 0, count = 0;
7939         unsigned long flags;
7940
7941         if (!has_addr_filter(event))
7942                 return;
7943
7944         raw_spin_lock_irqsave(&ifh->lock, flags);
7945         list_for_each_entry(filter, &ifh->list, entry) {
7946                 if (filter->path.dentry) {
7947                         event->addr_filter_ranges[count].start = 0;
7948                         event->addr_filter_ranges[count].size = 0;
7949                         restart++;
7950                 }
7951
7952                 count++;
7953         }
7954
7955         if (restart)
7956                 event->addr_filters_gen++;
7957         raw_spin_unlock_irqrestore(&ifh->lock, flags);
7958
7959         if (restart)
7960                 perf_event_stop(event, 1);
7961 }
7962
7963 void perf_event_exec(void)
7964 {
7965         struct perf_event_context *ctx;
7966
7967         ctx = perf_pin_task_context(current);
7968         if (!ctx)
7969                 return;
7970
7971         perf_event_enable_on_exec(ctx);
7972         perf_event_remove_on_exec(ctx);
7973         perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL, true);
7974
7975         perf_unpin_context(ctx);
7976         put_ctx(ctx);
7977 }
7978
7979 struct remote_output {
7980         struct perf_buffer      *rb;
7981         int                     err;
7982 };
7983
7984 static void __perf_event_output_stop(struct perf_event *event, void *data)
7985 {
7986         struct perf_event *parent = event->parent;
7987         struct remote_output *ro = data;
7988         struct perf_buffer *rb = ro->rb;
7989         struct stop_event_data sd = {
7990                 .event  = event,
7991         };
7992
7993         if (!has_aux(event))
7994                 return;
7995
7996         if (!parent)
7997                 parent = event;
7998
7999         /*
8000          * In case of inheritance, it will be the parent that links to the
8001          * ring-buffer, but it will be the child that's actually using it.
8002          *
8003          * We are using event::rb to determine if the event should be stopped,
8004          * however this may race with ring_buffer_attach() (through set_output),
8005          * which will make us skip the event that actually needs to be stopped.
8006          * So ring_buffer_attach() has to stop an aux event before re-assigning
8007          * its rb pointer.
8008          */
8009         if (rcu_dereference(parent->rb) == rb)
8010                 ro->err = __perf_event_stop(&sd);
8011 }
8012
8013 static int __perf_pmu_output_stop(void *info)
8014 {
8015         struct perf_event *event = info;
8016         struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
8017         struct remote_output ro = {
8018                 .rb     = event->rb,
8019         };
8020
8021         rcu_read_lock();
8022         perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
8023         if (cpuctx->task_ctx)
8024                 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
8025                                    &ro, false);
8026         rcu_read_unlock();
8027
8028         return ro.err;
8029 }
8030
8031 static void perf_pmu_output_stop(struct perf_event *event)
8032 {
8033         struct perf_event *iter;
8034         int err, cpu;
8035
8036 restart:
8037         rcu_read_lock();
8038         list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
8039                 /*
8040                  * For per-CPU events, we need to make sure that neither they
8041                  * nor their children are running; for cpu==-1 events it's
8042                  * sufficient to stop the event itself if it's active, since
8043                  * it can't have children.
8044                  */
8045                 cpu = iter->cpu;
8046                 if (cpu == -1)
8047                         cpu = READ_ONCE(iter->oncpu);
8048
8049                 if (cpu == -1)
8050                         continue;
8051
8052                 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
8053                 if (err == -EAGAIN) {
8054                         rcu_read_unlock();
8055                         goto restart;
8056                 }
8057         }
8058         rcu_read_unlock();
8059 }
8060
8061 /*
8062  * task tracking -- fork/exit
8063  *
8064  * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
8065  */
8066
8067 struct perf_task_event {
8068         struct task_struct              *task;
8069         struct perf_event_context       *task_ctx;
8070
8071         struct {
8072                 struct perf_event_header        header;
8073
8074                 u32                             pid;
8075                 u32                             ppid;
8076                 u32                             tid;
8077                 u32                             ptid;
8078                 u64                             time;
8079         } event_id;
8080 };
8081
8082 static int perf_event_task_match(struct perf_event *event)
8083 {
8084         return event->attr.comm  || event->attr.mmap ||
8085                event->attr.mmap2 || event->attr.mmap_data ||
8086                event->attr.task;
8087 }
8088
8089 static void perf_event_task_output(struct perf_event *event,
8090                                    void *data)
8091 {
8092         struct perf_task_event *task_event = data;
8093         struct perf_output_handle handle;
8094         struct perf_sample_data sample;
8095         struct task_struct *task = task_event->task;
8096         int ret, size = task_event->event_id.header.size;
8097
8098         if (!perf_event_task_match(event))
8099                 return;
8100
8101         perf_event_header__init_id(&task_event->event_id.header, &sample, event);
8102
8103         ret = perf_output_begin(&handle, &sample, event,
8104                                 task_event->event_id.header.size);
8105         if (ret)
8106                 goto out;
8107
8108         task_event->event_id.pid = perf_event_pid(event, task);
8109         task_event->event_id.tid = perf_event_tid(event, task);
8110
8111         if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
8112                 task_event->event_id.ppid = perf_event_pid(event,
8113                                                         task->real_parent);
8114                 task_event->event_id.ptid = perf_event_pid(event,
8115                                                         task->real_parent);
8116         } else {  /* PERF_RECORD_FORK */
8117                 task_event->event_id.ppid = perf_event_pid(event, current);
8118                 task_event->event_id.ptid = perf_event_tid(event, current);
8119         }
8120
8121         task_event->event_id.time = perf_event_clock(event);
8122
8123         perf_output_put(&handle, task_event->event_id);
8124
8125         perf_event__output_id_sample(event, &handle, &sample);
8126
8127         perf_output_end(&handle);
8128 out:
8129         task_event->event_id.header.size = size;
8130 }
8131
8132 static void perf_event_task(struct task_struct *task,
8133                               struct perf_event_context *task_ctx,
8134                               int new)
8135 {
8136         struct perf_task_event task_event;
8137
8138         if (!atomic_read(&nr_comm_events) &&
8139             !atomic_read(&nr_mmap_events) &&
8140             !atomic_read(&nr_task_events))
8141                 return;
8142
8143         task_event = (struct perf_task_event){
8144                 .task     = task,
8145                 .task_ctx = task_ctx,
8146                 .event_id    = {
8147                         .header = {
8148                                 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
8149                                 .misc = 0,
8150                                 .size = sizeof(task_event.event_id),
8151                         },
8152                         /* .pid  */
8153                         /* .ppid */
8154                         /* .tid  */
8155                         /* .ptid */
8156                         /* .time */
8157                 },
8158         };
8159
8160         perf_iterate_sb(perf_event_task_output,
8161                        &task_event,
8162                        task_ctx);
8163 }
8164
8165 void perf_event_fork(struct task_struct *task)
8166 {
8167         perf_event_task(task, NULL, 1);
8168         perf_event_namespaces(task);
8169 }
8170
8171 /*
8172  * comm tracking
8173  */
8174
8175 struct perf_comm_event {
8176         struct task_struct      *task;
8177         char                    *comm;
8178         int                     comm_size;
8179
8180         struct {
8181                 struct perf_event_header        header;
8182
8183                 u32                             pid;
8184                 u32                             tid;
8185         } event_id;
8186 };
8187
8188 static int perf_event_comm_match(struct perf_event *event)
8189 {
8190         return event->attr.comm;
8191 }
8192
8193 static void perf_event_comm_output(struct perf_event *event,
8194                                    void *data)
8195 {
8196         struct perf_comm_event *comm_event = data;
8197         struct perf_output_handle handle;
8198         struct perf_sample_data sample;
8199         int size = comm_event->event_id.header.size;
8200         int ret;
8201
8202         if (!perf_event_comm_match(event))
8203                 return;
8204
8205         perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
8206         ret = perf_output_begin(&handle, &sample, event,
8207                                 comm_event->event_id.header.size);
8208
8209         if (ret)
8210                 goto out;
8211
8212         comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
8213         comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
8214
8215         perf_output_put(&handle, comm_event->event_id);
8216         __output_copy(&handle, comm_event->comm,
8217                                    comm_event->comm_size);
8218
8219         perf_event__output_id_sample(event, &handle, &sample);
8220
8221         perf_output_end(&handle);
8222 out:
8223         comm_event->event_id.header.size = size;
8224 }
8225
8226 static void perf_event_comm_event(struct perf_comm_event *comm_event)
8227 {
8228         char comm[TASK_COMM_LEN];
8229         unsigned int size;
8230
8231         memset(comm, 0, sizeof(comm));
8232         strlcpy(comm, comm_event->task->comm, sizeof(comm));
8233         size = ALIGN(strlen(comm)+1, sizeof(u64));
8234
8235         comm_event->comm = comm;
8236         comm_event->comm_size = size;
8237
8238         comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
8239
8240         perf_iterate_sb(perf_event_comm_output,
8241                        comm_event,
8242                        NULL);
8243 }
8244
8245 void perf_event_comm(struct task_struct *task, bool exec)
8246 {
8247         struct perf_comm_event comm_event;
8248
8249         if (!atomic_read(&nr_comm_events))
8250                 return;
8251
8252         comm_event = (struct perf_comm_event){
8253                 .task   = task,
8254                 /* .comm      */
8255                 /* .comm_size */
8256                 .event_id  = {
8257                         .header = {
8258                                 .type = PERF_RECORD_COMM,
8259                                 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
8260                                 /* .size */
8261                         },
8262                         /* .pid */
8263                         /* .tid */
8264                 },
8265         };
8266
8267         perf_event_comm_event(&comm_event);
8268 }
8269
8270 /*
8271  * namespaces tracking
8272  */
8273
8274 struct perf_namespaces_event {
8275         struct task_struct              *task;
8276
8277         struct {
8278                 struct perf_event_header        header;
8279
8280                 u32                             pid;
8281                 u32                             tid;
8282                 u64                             nr_namespaces;
8283                 struct perf_ns_link_info        link_info[NR_NAMESPACES];
8284         } event_id;
8285 };
8286
8287 static int perf_event_namespaces_match(struct perf_event *event)
8288 {
8289         return event->attr.namespaces;
8290 }
8291
8292 static void perf_event_namespaces_output(struct perf_event *event,
8293                                          void *data)
8294 {
8295         struct perf_namespaces_event *namespaces_event = data;
8296         struct perf_output_handle handle;
8297         struct perf_sample_data sample;
8298         u16 header_size = namespaces_event->event_id.header.size;
8299         int ret;
8300
8301         if (!perf_event_namespaces_match(event))
8302                 return;
8303
8304         perf_event_header__init_id(&namespaces_event->event_id.header,
8305                                    &sample, event);
8306         ret = perf_output_begin(&handle, &sample, event,
8307                                 namespaces_event->event_id.header.size);
8308         if (ret)
8309                 goto out;
8310
8311         namespaces_event->event_id.pid = perf_event_pid(event,
8312                                                         namespaces_event->task);
8313         namespaces_event->event_id.tid = perf_event_tid(event,
8314                                                         namespaces_event->task);
8315
8316         perf_output_put(&handle, namespaces_event->event_id);
8317
8318         perf_event__output_id_sample(event, &handle, &sample);
8319
8320         perf_output_end(&handle);
8321 out:
8322         namespaces_event->event_id.header.size = header_size;
8323 }
8324
8325 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
8326                                    struct task_struct *task,
8327                                    const struct proc_ns_operations *ns_ops)
8328 {
8329         struct path ns_path;
8330         struct inode *ns_inode;
8331         int error;
8332
8333         error = ns_get_path(&ns_path, task, ns_ops);
8334         if (!error) {
8335                 ns_inode = ns_path.dentry->d_inode;
8336                 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
8337                 ns_link_info->ino = ns_inode->i_ino;
8338                 path_put(&ns_path);
8339         }
8340 }
8341
8342 void perf_event_namespaces(struct task_struct *task)
8343 {
8344         struct perf_namespaces_event namespaces_event;
8345         struct perf_ns_link_info *ns_link_info;
8346
8347         if (!atomic_read(&nr_namespaces_events))
8348                 return;
8349
8350         namespaces_event = (struct perf_namespaces_event){
8351                 .task   = task,
8352                 .event_id  = {
8353                         .header = {
8354                                 .type = PERF_RECORD_NAMESPACES,
8355                                 .misc = 0,
8356                                 .size = sizeof(namespaces_event.event_id),
8357                         },
8358                         /* .pid */
8359                         /* .tid */
8360                         .nr_namespaces = NR_NAMESPACES,
8361                         /* .link_info[NR_NAMESPACES] */
8362                 },
8363         };
8364
8365         ns_link_info = namespaces_event.event_id.link_info;
8366
8367         perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
8368                                task, &mntns_operations);
8369
8370 #ifdef CONFIG_USER_NS
8371         perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
8372                                task, &userns_operations);
8373 #endif
8374 #ifdef CONFIG_NET_NS
8375         perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
8376                                task, &netns_operations);
8377 #endif
8378 #ifdef CONFIG_UTS_NS
8379         perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
8380                                task, &utsns_operations);
8381 #endif
8382 #ifdef CONFIG_IPC_NS
8383         perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
8384                                task, &ipcns_operations);
8385 #endif
8386 #ifdef CONFIG_PID_NS
8387         perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
8388                                task, &pidns_operations);
8389 #endif
8390 #ifdef CONFIG_CGROUPS
8391         perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
8392                                task, &cgroupns_operations);
8393 #endif
8394
8395         perf_iterate_sb(perf_event_namespaces_output,
8396                         &namespaces_event,
8397                         NULL);
8398 }
8399
8400 /*
8401  * cgroup tracking
8402  */
8403 #ifdef CONFIG_CGROUP_PERF
8404
8405 struct perf_cgroup_event {
8406         char                            *path;
8407         int                             path_size;
8408         struct {
8409                 struct perf_event_header        header;
8410                 u64                             id;
8411                 char                            path[];
8412         } event_id;
8413 };
8414
8415 static int perf_event_cgroup_match(struct perf_event *event)
8416 {
8417         return event->attr.cgroup;
8418 }
8419
8420 static void perf_event_cgroup_output(struct perf_event *event, void *data)
8421 {
8422         struct perf_cgroup_event *cgroup_event = data;
8423         struct perf_output_handle handle;
8424         struct perf_sample_data sample;
8425         u16 header_size = cgroup_event->event_id.header.size;
8426         int ret;
8427
8428         if (!perf_event_cgroup_match(event))
8429                 return;
8430
8431         perf_event_header__init_id(&cgroup_event->event_id.header,
8432                                    &sample, event);
8433         ret = perf_output_begin(&handle, &sample, event,
8434                                 cgroup_event->event_id.header.size);
8435         if (ret)
8436                 goto out;
8437
8438         perf_output_put(&handle, cgroup_event->event_id);
8439         __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
8440
8441         perf_event__output_id_sample(event, &handle, &sample);
8442
8443         perf_output_end(&handle);
8444 out:
8445         cgroup_event->event_id.header.size = header_size;
8446 }
8447
8448 static void perf_event_cgroup(struct cgroup *cgrp)
8449 {
8450         struct perf_cgroup_event cgroup_event;
8451         char path_enomem[16] = "//enomem";
8452         char *pathname;
8453         size_t size;
8454
8455         if (!atomic_read(&nr_cgroup_events))
8456                 return;
8457
8458         cgroup_event = (struct perf_cgroup_event){
8459                 .event_id  = {
8460                         .header = {
8461                                 .type = PERF_RECORD_CGROUP,
8462                                 .misc = 0,
8463                                 .size = sizeof(cgroup_event.event_id),
8464                         },
8465                         .id = cgroup_id(cgrp),
8466                 },
8467         };
8468
8469         pathname = kmalloc(PATH_MAX, GFP_KERNEL);
8470         if (pathname == NULL) {
8471                 cgroup_event.path = path_enomem;
8472         } else {
8473                 /* just to be sure to have enough space for alignment */
8474                 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
8475                 cgroup_event.path = pathname;
8476         }
8477
8478         /*
8479          * Since our buffer works in 8 byte units we need to align our string
8480          * size to a multiple of 8. However, we must guarantee the tail end is
8481          * zero'd out to avoid leaking random bits to userspace.
8482          */
8483         size = strlen(cgroup_event.path) + 1;
8484         while (!IS_ALIGNED(size, sizeof(u64)))
8485                 cgroup_event.path[size++] = '\0';
8486
8487         cgroup_event.event_id.header.size += size;
8488         cgroup_event.path_size = size;
8489
8490         perf_iterate_sb(perf_event_cgroup_output,
8491                         &cgroup_event,
8492                         NULL);
8493
8494         kfree(pathname);
8495 }
8496
8497 #endif
8498
8499 /*
8500  * mmap tracking
8501  */
8502
8503 struct perf_mmap_event {
8504         struct vm_area_struct   *vma;
8505
8506         const char              *file_name;
8507         int                     file_size;
8508         int                     maj, min;
8509         u64                     ino;
8510         u64                     ino_generation;
8511         u32                     prot, flags;
8512         u8                      build_id[BUILD_ID_SIZE_MAX];
8513         u32                     build_id_size;
8514
8515         struct {
8516                 struct perf_event_header        header;
8517
8518                 u32                             pid;
8519                 u32                             tid;
8520                 u64                             start;
8521                 u64                             len;
8522                 u64                             pgoff;
8523         } event_id;
8524 };
8525
8526 static int perf_event_mmap_match(struct perf_event *event,
8527                                  void *data)
8528 {
8529         struct perf_mmap_event *mmap_event = data;
8530         struct vm_area_struct *vma = mmap_event->vma;
8531         int executable = vma->vm_flags & VM_EXEC;
8532
8533         return (!executable && event->attr.mmap_data) ||
8534                (executable && (event->attr.mmap || event->attr.mmap2));
8535 }
8536
8537 static void perf_event_mmap_output(struct perf_event *event,
8538                                    void *data)
8539 {
8540         struct perf_mmap_event *mmap_event = data;
8541         struct perf_output_handle handle;
8542         struct perf_sample_data sample;
8543         int size = mmap_event->event_id.header.size;
8544         u32 type = mmap_event->event_id.header.type;
8545         bool use_build_id;
8546         int ret;
8547
8548         if (!perf_event_mmap_match(event, data))
8549                 return;
8550
8551         if (event->attr.mmap2) {
8552                 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
8553                 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
8554                 mmap_event->event_id.header.size += sizeof(mmap_event->min);
8555                 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
8556                 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
8557                 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
8558                 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
8559         }
8560
8561         perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
8562         ret = perf_output_begin(&handle, &sample, event,
8563                                 mmap_event->event_id.header.size);
8564         if (ret)
8565                 goto out;
8566
8567         mmap_event->event_id.pid = perf_event_pid(event, current);
8568         mmap_event->event_id.tid = perf_event_tid(event, current);
8569
8570         use_build_id = event->attr.build_id && mmap_event->build_id_size;
8571
8572         if (event->attr.mmap2 && use_build_id)
8573                 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID;
8574
8575         perf_output_put(&handle, mmap_event->event_id);
8576
8577         if (event->attr.mmap2) {
8578                 if (use_build_id) {
8579                         u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 };
8580
8581                         __output_copy(&handle, size, 4);
8582                         __output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX);
8583                 } else {
8584                         perf_output_put(&handle, mmap_event->maj);
8585                         perf_output_put(&handle, mmap_event->min);
8586                         perf_output_put(&handle, mmap_event->ino);
8587                         perf_output_put(&handle, mmap_event->ino_generation);
8588                 }
8589                 perf_output_put(&handle, mmap_event->prot);
8590                 perf_output_put(&handle, mmap_event->flags);
8591         }
8592
8593         __output_copy(&handle, mmap_event->file_name,
8594                                    mmap_event->file_size);
8595
8596         perf_event__output_id_sample(event, &handle, &sample);
8597
8598         perf_output_end(&handle);
8599 out:
8600         mmap_event->event_id.header.size = size;
8601         mmap_event->event_id.header.type = type;
8602 }
8603
8604 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
8605 {
8606         struct vm_area_struct *vma = mmap_event->vma;
8607         struct file *file = vma->vm_file;
8608         int maj = 0, min = 0;
8609         u64 ino = 0, gen = 0;
8610         u32 prot = 0, flags = 0;
8611         unsigned int size;
8612         char tmp[16];
8613         char *buf = NULL;
8614         char *name;
8615
8616         if (vma->vm_flags & VM_READ)
8617                 prot |= PROT_READ;
8618         if (vma->vm_flags & VM_WRITE)
8619                 prot |= PROT_WRITE;
8620         if (vma->vm_flags & VM_EXEC)
8621                 prot |= PROT_EXEC;
8622
8623         if (vma->vm_flags & VM_MAYSHARE)
8624                 flags = MAP_SHARED;
8625         else
8626                 flags = MAP_PRIVATE;
8627
8628         if (vma->vm_flags & VM_LOCKED)
8629                 flags |= MAP_LOCKED;
8630         if (is_vm_hugetlb_page(vma))
8631                 flags |= MAP_HUGETLB;
8632
8633         if (file) {
8634                 struct inode *inode;
8635                 dev_t dev;
8636
8637                 buf = kmalloc(PATH_MAX, GFP_KERNEL);
8638                 if (!buf) {
8639                         name = "//enomem";
8640                         goto cpy_name;
8641                 }
8642                 /*
8643                  * d_path() works from the end of the rb backwards, so we
8644                  * need to add enough zero bytes after the string to handle
8645                  * the 64bit alignment we do later.
8646                  */
8647                 name = file_path(file, buf, PATH_MAX - sizeof(u64));
8648                 if (IS_ERR(name)) {
8649                         name = "//toolong";
8650                         goto cpy_name;
8651                 }
8652                 inode = file_inode(vma->vm_file);
8653                 dev = inode->i_sb->s_dev;
8654                 ino = inode->i_ino;
8655                 gen = inode->i_generation;
8656                 maj = MAJOR(dev);
8657                 min = MINOR(dev);
8658
8659                 goto got_name;
8660         } else {
8661                 if (vma->vm_ops && vma->vm_ops->name) {
8662                         name = (char *) vma->vm_ops->name(vma);
8663                         if (name)
8664                                 goto cpy_name;
8665                 }
8666
8667                 name = (char *)arch_vma_name(vma);
8668                 if (name)
8669                         goto cpy_name;
8670
8671                 if (vma->vm_start <= vma->vm_mm->start_brk &&
8672                                 vma->vm_end >= vma->vm_mm->brk) {
8673                         name = "[heap]";
8674                         goto cpy_name;
8675                 }
8676                 if (vma->vm_start <= vma->vm_mm->start_stack &&
8677                                 vma->vm_end >= vma->vm_mm->start_stack) {
8678                         name = "[stack]";
8679                         goto cpy_name;
8680                 }
8681
8682                 name = "//anon";
8683                 goto cpy_name;
8684         }
8685
8686 cpy_name:
8687         strlcpy(tmp, name, sizeof(tmp));
8688         name = tmp;
8689 got_name:
8690         /*
8691          * Since our buffer works in 8 byte units we need to align our string
8692          * size to a multiple of 8. However, we must guarantee the tail end is
8693          * zero'd out to avoid leaking random bits to userspace.
8694          */
8695         size = strlen(name)+1;
8696         while (!IS_ALIGNED(size, sizeof(u64)))
8697                 name[size++] = '\0';
8698
8699         mmap_event->file_name = name;
8700         mmap_event->file_size = size;
8701         mmap_event->maj = maj;
8702         mmap_event->min = min;
8703         mmap_event->ino = ino;
8704         mmap_event->ino_generation = gen;
8705         mmap_event->prot = prot;
8706         mmap_event->flags = flags;
8707
8708         if (!(vma->vm_flags & VM_EXEC))
8709                 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
8710
8711         mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
8712
8713         if (atomic_read(&nr_build_id_events))
8714                 build_id_parse(vma, mmap_event->build_id, &mmap_event->build_id_size);
8715
8716         perf_iterate_sb(perf_event_mmap_output,
8717                        mmap_event,
8718                        NULL);
8719
8720         kfree(buf);
8721 }
8722
8723 /*
8724  * Check whether inode and address range match filter criteria.
8725  */
8726 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
8727                                      struct file *file, unsigned long offset,
8728                                      unsigned long size)
8729 {
8730         /* d_inode(NULL) won't be equal to any mapped user-space file */
8731         if (!filter->path.dentry)
8732                 return false;
8733
8734         if (d_inode(filter->path.dentry) != file_inode(file))
8735                 return false;
8736
8737         if (filter->offset > offset + size)
8738                 return false;
8739
8740         if (filter->offset + filter->size < offset)
8741                 return false;
8742
8743         return true;
8744 }
8745
8746 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
8747                                         struct vm_area_struct *vma,
8748                                         struct perf_addr_filter_range *fr)
8749 {
8750         unsigned long vma_size = vma->vm_end - vma->vm_start;
8751         unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8752         struct file *file = vma->vm_file;
8753
8754         if (!perf_addr_filter_match(filter, file, off, vma_size))
8755                 return false;
8756
8757         if (filter->offset < off) {
8758                 fr->start = vma->vm_start;
8759                 fr->size = min(vma_size, filter->size - (off - filter->offset));
8760         } else {
8761                 fr->start = vma->vm_start + filter->offset - off;
8762                 fr->size = min(vma->vm_end - fr->start, filter->size);
8763         }
8764
8765         return true;
8766 }
8767
8768 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
8769 {
8770         struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8771         struct vm_area_struct *vma = data;
8772         struct perf_addr_filter *filter;
8773         unsigned int restart = 0, count = 0;
8774         unsigned long flags;
8775
8776         if (!has_addr_filter(event))
8777                 return;
8778
8779         if (!vma->vm_file)
8780                 return;
8781
8782         raw_spin_lock_irqsave(&ifh->lock, flags);
8783         list_for_each_entry(filter, &ifh->list, entry) {
8784                 if (perf_addr_filter_vma_adjust(filter, vma,
8785                                                 &event->addr_filter_ranges[count]))
8786                         restart++;
8787
8788                 count++;
8789         }
8790
8791         if (restart)
8792                 event->addr_filters_gen++;
8793         raw_spin_unlock_irqrestore(&ifh->lock, flags);
8794
8795         if (restart)
8796                 perf_event_stop(event, 1);
8797 }
8798
8799 /*
8800  * Adjust all task's events' filters to the new vma
8801  */
8802 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
8803 {
8804         struct perf_event_context *ctx;
8805
8806         /*
8807          * Data tracing isn't supported yet and as such there is no need
8808          * to keep track of anything that isn't related to executable code:
8809          */
8810         if (!(vma->vm_flags & VM_EXEC))
8811                 return;
8812
8813         rcu_read_lock();
8814         ctx = rcu_dereference(current->perf_event_ctxp);
8815         if (ctx)
8816                 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
8817         rcu_read_unlock();
8818 }
8819
8820 void perf_event_mmap(struct vm_area_struct *vma)
8821 {
8822         struct perf_mmap_event mmap_event;
8823
8824         if (!atomic_read(&nr_mmap_events))
8825                 return;
8826
8827         mmap_event = (struct perf_mmap_event){
8828                 .vma    = vma,
8829                 /* .file_name */
8830                 /* .file_size */
8831                 .event_id  = {
8832                         .header = {
8833                                 .type = PERF_RECORD_MMAP,
8834                                 .misc = PERF_RECORD_MISC_USER,
8835                                 /* .size */
8836                         },
8837                         /* .pid */
8838                         /* .tid */
8839                         .start  = vma->vm_start,
8840                         .len    = vma->vm_end - vma->vm_start,
8841                         .pgoff  = (u64)vma->vm_pgoff << PAGE_SHIFT,
8842                 },
8843                 /* .maj (attr_mmap2 only) */
8844                 /* .min (attr_mmap2 only) */
8845                 /* .ino (attr_mmap2 only) */
8846                 /* .ino_generation (attr_mmap2 only) */
8847                 /* .prot (attr_mmap2 only) */
8848                 /* .flags (attr_mmap2 only) */
8849         };
8850
8851         perf_addr_filters_adjust(vma);
8852         perf_event_mmap_event(&mmap_event);
8853 }
8854
8855 void perf_event_aux_event(struct perf_event *event, unsigned long head,
8856                           unsigned long size, u64 flags)
8857 {
8858         struct perf_output_handle handle;
8859         struct perf_sample_data sample;
8860         struct perf_aux_event {
8861                 struct perf_event_header        header;
8862                 u64                             offset;
8863                 u64                             size;
8864                 u64                             flags;
8865         } rec = {
8866                 .header = {
8867                         .type = PERF_RECORD_AUX,
8868                         .misc = 0,
8869                         .size = sizeof(rec),
8870                 },
8871                 .offset         = head,
8872                 .size           = size,
8873                 .flags          = flags,
8874         };
8875         int ret;
8876
8877         perf_event_header__init_id(&rec.header, &sample, event);
8878         ret = perf_output_begin(&handle, &sample, event, rec.header.size);
8879
8880         if (ret)
8881                 return;
8882
8883         perf_output_put(&handle, rec);
8884         perf_event__output_id_sample(event, &handle, &sample);
8885
8886         perf_output_end(&handle);
8887 }
8888
8889 /*
8890  * Lost/dropped samples logging
8891  */
8892 void perf_log_lost_samples(struct perf_event *event, u64 lost)
8893 {
8894         struct perf_output_handle handle;
8895         struct perf_sample_data sample;
8896         int ret;
8897
8898         struct {
8899                 struct perf_event_header        header;
8900                 u64                             lost;
8901         } lost_samples_event = {
8902                 .header = {
8903                         .type = PERF_RECORD_LOST_SAMPLES,
8904                         .misc = 0,
8905                         .size = sizeof(lost_samples_event),
8906                 },
8907                 .lost           = lost,
8908         };
8909
8910         perf_event_header__init_id(&lost_samples_event.header, &sample, event);
8911
8912         ret = perf_output_begin(&handle, &sample, event,
8913                                 lost_samples_event.header.size);
8914         if (ret)
8915                 return;
8916
8917         perf_output_put(&handle, lost_samples_event);
8918         perf_event__output_id_sample(event, &handle, &sample);
8919         perf_output_end(&handle);
8920 }
8921
8922 /*
8923  * context_switch tracking
8924  */
8925
8926 struct perf_switch_event {
8927         struct task_struct      *task;
8928         struct task_struct      *next_prev;
8929
8930         struct {
8931                 struct perf_event_header        header;
8932                 u32                             next_prev_pid;
8933                 u32                             next_prev_tid;
8934         } event_id;
8935 };
8936
8937 static int perf_event_switch_match(struct perf_event *event)
8938 {
8939         return event->attr.context_switch;
8940 }
8941
8942 static void perf_event_switch_output(struct perf_event *event, void *data)
8943 {
8944         struct perf_switch_event *se = data;
8945         struct perf_output_handle handle;
8946         struct perf_sample_data sample;
8947         int ret;
8948
8949         if (!perf_event_switch_match(event))
8950                 return;
8951
8952         /* Only CPU-wide events are allowed to see next/prev pid/tid */
8953         if (event->ctx->task) {
8954                 se->event_id.header.type = PERF_RECORD_SWITCH;
8955                 se->event_id.header.size = sizeof(se->event_id.header);
8956         } else {
8957                 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
8958                 se->event_id.header.size = sizeof(se->event_id);
8959                 se->event_id.next_prev_pid =
8960                                         perf_event_pid(event, se->next_prev);
8961                 se->event_id.next_prev_tid =
8962                                         perf_event_tid(event, se->next_prev);
8963         }
8964
8965         perf_event_header__init_id(&se->event_id.header, &sample, event);
8966
8967         ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size);
8968         if (ret)
8969                 return;
8970
8971         if (event->ctx->task)
8972                 perf_output_put(&handle, se->event_id.header);
8973         else
8974                 perf_output_put(&handle, se->event_id);
8975
8976         perf_event__output_id_sample(event, &handle, &sample);
8977
8978         perf_output_end(&handle);
8979 }
8980
8981 static void perf_event_switch(struct task_struct *task,
8982                               struct task_struct *next_prev, bool sched_in)
8983 {
8984         struct perf_switch_event switch_event;
8985
8986         /* N.B. caller checks nr_switch_events != 0 */
8987
8988         switch_event = (struct perf_switch_event){
8989                 .task           = task,
8990                 .next_prev      = next_prev,
8991                 .event_id       = {
8992                         .header = {
8993                                 /* .type */
8994                                 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
8995                                 /* .size */
8996                         },
8997                         /* .next_prev_pid */
8998                         /* .next_prev_tid */
8999                 },
9000         };
9001
9002         if (!sched_in && task->on_rq) {
9003                 switch_event.event_id.header.misc |=
9004                                 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
9005         }
9006
9007         perf_iterate_sb(perf_event_switch_output, &switch_event, NULL);
9008 }
9009
9010 /*
9011  * IRQ throttle logging
9012  */
9013
9014 static void perf_log_throttle(struct perf_event *event, int enable)
9015 {
9016         struct perf_output_handle handle;
9017         struct perf_sample_data sample;
9018         int ret;
9019
9020         struct {
9021                 struct perf_event_header        header;
9022                 u64                             time;
9023                 u64                             id;
9024                 u64                             stream_id;
9025         } throttle_event = {
9026                 .header = {
9027                         .type = PERF_RECORD_THROTTLE,
9028                         .misc = 0,
9029                         .size = sizeof(throttle_event),
9030                 },
9031                 .time           = perf_event_clock(event),
9032                 .id             = primary_event_id(event),
9033                 .stream_id      = event->id,
9034         };
9035
9036         if (enable)
9037                 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
9038
9039         perf_event_header__init_id(&throttle_event.header, &sample, event);
9040
9041         ret = perf_output_begin(&handle, &sample, event,
9042                                 throttle_event.header.size);
9043         if (ret)
9044                 return;
9045
9046         perf_output_put(&handle, throttle_event);
9047         perf_event__output_id_sample(event, &handle, &sample);
9048         perf_output_end(&handle);
9049 }
9050
9051 /*
9052  * ksymbol register/unregister tracking
9053  */
9054
9055 struct perf_ksymbol_event {
9056         const char      *name;
9057         int             name_len;
9058         struct {
9059                 struct perf_event_header        header;
9060                 u64                             addr;
9061                 u32                             len;
9062                 u16                             ksym_type;
9063                 u16                             flags;
9064         } event_id;
9065 };
9066
9067 static int perf_event_ksymbol_match(struct perf_event *event)
9068 {
9069         return event->attr.ksymbol;
9070 }
9071
9072 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
9073 {
9074         struct perf_ksymbol_event *ksymbol_event = data;
9075         struct perf_output_handle handle;
9076         struct perf_sample_data sample;
9077         int ret;
9078
9079         if (!perf_event_ksymbol_match(event))
9080                 return;
9081
9082         perf_event_header__init_id(&ksymbol_event->event_id.header,
9083                                    &sample, event);
9084         ret = perf_output_begin(&handle, &sample, event,
9085                                 ksymbol_event->event_id.header.size);
9086         if (ret)
9087                 return;
9088
9089         perf_output_put(&handle, ksymbol_event->event_id);
9090         __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
9091         perf_event__output_id_sample(event, &handle, &sample);
9092
9093         perf_output_end(&handle);
9094 }
9095
9096 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
9097                         const char *sym)
9098 {
9099         struct perf_ksymbol_event ksymbol_event;
9100         char name[KSYM_NAME_LEN];
9101         u16 flags = 0;
9102         int name_len;
9103
9104         if (!atomic_read(&nr_ksymbol_events))
9105                 return;
9106
9107         if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
9108             ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
9109                 goto err;
9110
9111         strlcpy(name, sym, KSYM_NAME_LEN);
9112         name_len = strlen(name) + 1;
9113         while (!IS_ALIGNED(name_len, sizeof(u64)))
9114                 name[name_len++] = '\0';
9115         BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
9116
9117         if (unregister)
9118                 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
9119
9120         ksymbol_event = (struct perf_ksymbol_event){
9121                 .name = name,
9122                 .name_len = name_len,
9123                 .event_id = {
9124                         .header = {
9125                                 .type = PERF_RECORD_KSYMBOL,
9126                                 .size = sizeof(ksymbol_event.event_id) +
9127                                         name_len,
9128                         },
9129                         .addr = addr,
9130                         .len = len,
9131                         .ksym_type = ksym_type,
9132                         .flags = flags,
9133                 },
9134         };
9135
9136         perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
9137         return;
9138 err:
9139         WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
9140 }
9141
9142 /*
9143  * bpf program load/unload tracking
9144  */
9145
9146 struct perf_bpf_event {
9147         struct bpf_prog *prog;
9148         struct {
9149                 struct perf_event_header        header;
9150                 u16                             type;
9151                 u16                             flags;
9152                 u32                             id;
9153                 u8                              tag[BPF_TAG_SIZE];
9154         } event_id;
9155 };
9156
9157 static int perf_event_bpf_match(struct perf_event *event)
9158 {
9159         return event->attr.bpf_event;
9160 }
9161
9162 static void perf_event_bpf_output(struct perf_event *event, void *data)
9163 {
9164         struct perf_bpf_event *bpf_event = data;
9165         struct perf_output_handle handle;
9166         struct perf_sample_data sample;
9167         int ret;
9168
9169         if (!perf_event_bpf_match(event))
9170                 return;
9171
9172         perf_event_header__init_id(&bpf_event->event_id.header,
9173                                    &sample, event);
9174         ret = perf_output_begin(&handle, data, event,
9175                                 bpf_event->event_id.header.size);
9176         if (ret)
9177                 return;
9178
9179         perf_output_put(&handle, bpf_event->event_id);
9180         perf_event__output_id_sample(event, &handle, &sample);
9181
9182         perf_output_end(&handle);
9183 }
9184
9185 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
9186                                          enum perf_bpf_event_type type)
9187 {
9188         bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
9189         int i;
9190
9191         if (prog->aux->func_cnt == 0) {
9192                 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
9193                                    (u64)(unsigned long)prog->bpf_func,
9194                                    prog->jited_len, unregister,
9195                                    prog->aux->ksym.name);
9196         } else {
9197                 for (i = 0; i < prog->aux->func_cnt; i++) {
9198                         struct bpf_prog *subprog = prog->aux->func[i];
9199
9200                         perf_event_ksymbol(
9201                                 PERF_RECORD_KSYMBOL_TYPE_BPF,
9202                                 (u64)(unsigned long)subprog->bpf_func,
9203                                 subprog->jited_len, unregister,
9204                                 subprog->aux->ksym.name);
9205                 }
9206         }
9207 }
9208
9209 void perf_event_bpf_event(struct bpf_prog *prog,
9210                           enum perf_bpf_event_type type,
9211                           u16 flags)
9212 {
9213         struct perf_bpf_event bpf_event;
9214
9215         if (type <= PERF_BPF_EVENT_UNKNOWN ||
9216             type >= PERF_BPF_EVENT_MAX)
9217                 return;
9218
9219         switch (type) {
9220         case PERF_BPF_EVENT_PROG_LOAD:
9221         case PERF_BPF_EVENT_PROG_UNLOAD:
9222                 if (atomic_read(&nr_ksymbol_events))
9223                         perf_event_bpf_emit_ksymbols(prog, type);
9224                 break;
9225         default:
9226                 break;
9227         }
9228
9229         if (!atomic_read(&nr_bpf_events))
9230                 return;
9231
9232         bpf_event = (struct perf_bpf_event){
9233                 .prog = prog,
9234                 .event_id = {
9235                         .header = {
9236                                 .type = PERF_RECORD_BPF_EVENT,
9237                                 .size = sizeof(bpf_event.event_id),
9238                         },
9239                         .type = type,
9240                         .flags = flags,
9241                         .id = prog->aux->id,
9242                 },
9243         };
9244
9245         BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
9246
9247         memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
9248         perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
9249 }
9250
9251 struct perf_text_poke_event {
9252         const void              *old_bytes;
9253         const void              *new_bytes;
9254         size_t                  pad;
9255         u16                     old_len;
9256         u16                     new_len;
9257
9258         struct {
9259                 struct perf_event_header        header;
9260
9261                 u64                             addr;
9262         } event_id;
9263 };
9264
9265 static int perf_event_text_poke_match(struct perf_event *event)
9266 {
9267         return event->attr.text_poke;
9268 }
9269
9270 static void perf_event_text_poke_output(struct perf_event *event, void *data)
9271 {
9272         struct perf_text_poke_event *text_poke_event = data;
9273         struct perf_output_handle handle;
9274         struct perf_sample_data sample;
9275         u64 padding = 0;
9276         int ret;
9277
9278         if (!perf_event_text_poke_match(event))
9279                 return;
9280
9281         perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
9282
9283         ret = perf_output_begin(&handle, &sample, event,
9284                                 text_poke_event->event_id.header.size);
9285         if (ret)
9286                 return;
9287
9288         perf_output_put(&handle, text_poke_event->event_id);
9289         perf_output_put(&handle, text_poke_event->old_len);
9290         perf_output_put(&handle, text_poke_event->new_len);
9291
9292         __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
9293         __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
9294
9295         if (text_poke_event->pad)
9296                 __output_copy(&handle, &padding, text_poke_event->pad);
9297
9298         perf_event__output_id_sample(event, &handle, &sample);
9299
9300         perf_output_end(&handle);
9301 }
9302
9303 void perf_event_text_poke(const void *addr, const void *old_bytes,
9304                           size_t old_len, const void *new_bytes, size_t new_len)
9305 {
9306         struct perf_text_poke_event text_poke_event;
9307         size_t tot, pad;
9308
9309         if (!atomic_read(&nr_text_poke_events))
9310                 return;
9311
9312         tot  = sizeof(text_poke_event.old_len) + old_len;
9313         tot += sizeof(text_poke_event.new_len) + new_len;
9314         pad  = ALIGN(tot, sizeof(u64)) - tot;
9315
9316         text_poke_event = (struct perf_text_poke_event){
9317                 .old_bytes    = old_bytes,
9318                 .new_bytes    = new_bytes,
9319                 .pad          = pad,
9320                 .old_len      = old_len,
9321                 .new_len      = new_len,
9322                 .event_id  = {
9323                         .header = {
9324                                 .type = PERF_RECORD_TEXT_POKE,
9325                                 .misc = PERF_RECORD_MISC_KERNEL,
9326                                 .size = sizeof(text_poke_event.event_id) + tot + pad,
9327                         },
9328                         .addr = (unsigned long)addr,
9329                 },
9330         };
9331
9332         perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
9333 }
9334
9335 void perf_event_itrace_started(struct perf_event *event)
9336 {
9337         event->attach_state |= PERF_ATTACH_ITRACE;
9338 }
9339
9340 static void perf_log_itrace_start(struct perf_event *event)
9341 {
9342         struct perf_output_handle handle;
9343         struct perf_sample_data sample;
9344         struct perf_aux_event {
9345                 struct perf_event_header        header;
9346                 u32                             pid;
9347                 u32                             tid;
9348         } rec;
9349         int ret;
9350
9351         if (event->parent)
9352                 event = event->parent;
9353
9354         if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
9355             event->attach_state & PERF_ATTACH_ITRACE)
9356                 return;
9357
9358         rec.header.type = PERF_RECORD_ITRACE_START;
9359         rec.header.misc = 0;
9360         rec.header.size = sizeof(rec);
9361         rec.pid = perf_event_pid(event, current);
9362         rec.tid = perf_event_tid(event, current);
9363
9364         perf_event_header__init_id(&rec.header, &sample, event);
9365         ret = perf_output_begin(&handle, &sample, event, rec.header.size);
9366
9367         if (ret)
9368                 return;
9369
9370         perf_output_put(&handle, rec);
9371         perf_event__output_id_sample(event, &handle, &sample);
9372
9373         perf_output_end(&handle);
9374 }
9375
9376 void perf_report_aux_output_id(struct perf_event *event, u64 hw_id)
9377 {
9378         struct perf_output_handle handle;
9379         struct perf_sample_data sample;
9380         struct perf_aux_event {
9381                 struct perf_event_header        header;
9382                 u64                             hw_id;
9383         } rec;
9384         int ret;
9385
9386         if (event->parent)
9387                 event = event->parent;
9388
9389         rec.header.type = PERF_RECORD_AUX_OUTPUT_HW_ID;
9390         rec.header.misc = 0;
9391         rec.header.size = sizeof(rec);
9392         rec.hw_id       = hw_id;
9393
9394         perf_event_header__init_id(&rec.header, &sample, event);
9395         ret = perf_output_begin(&handle, &sample, event, rec.header.size);
9396
9397         if (ret)
9398                 return;
9399
9400         perf_output_put(&handle, rec);
9401         perf_event__output_id_sample(event, &handle, &sample);
9402
9403         perf_output_end(&handle);
9404 }
9405
9406 static int
9407 __perf_event_account_interrupt(struct perf_event *event, int throttle)
9408 {
9409         struct hw_perf_event *hwc = &event->hw;
9410         int ret = 0;
9411         u64 seq;
9412
9413         seq = __this_cpu_read(perf_throttled_seq);
9414         if (seq != hwc->interrupts_seq) {
9415                 hwc->interrupts_seq = seq;
9416                 hwc->interrupts = 1;
9417         } else {
9418                 hwc->interrupts++;
9419                 if (unlikely(throttle
9420                              && hwc->interrupts >= max_samples_per_tick)) {
9421                         __this_cpu_inc(perf_throttled_count);
9422                         tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
9423                         hwc->interrupts = MAX_INTERRUPTS;
9424                         perf_log_throttle(event, 0);
9425                         ret = 1;
9426                 }
9427         }
9428
9429         if (event->attr.freq) {
9430                 u64 now = perf_clock();
9431                 s64 delta = now - hwc->freq_time_stamp;
9432
9433                 hwc->freq_time_stamp = now;
9434
9435                 if (delta > 0 && delta < 2*TICK_NSEC)
9436                         perf_adjust_period(event, delta, hwc->last_period, true);
9437         }
9438
9439         return ret;
9440 }
9441
9442 int perf_event_account_interrupt(struct perf_event *event)
9443 {
9444         return __perf_event_account_interrupt(event, 1);
9445 }
9446
9447 static inline bool sample_is_allowed(struct perf_event *event, struct pt_regs *regs)
9448 {
9449         /*
9450          * Due to interrupt latency (AKA "skid"), we may enter the
9451          * kernel before taking an overflow, even if the PMU is only
9452          * counting user events.
9453          */
9454         if (event->attr.exclude_kernel && !user_mode(regs))
9455                 return false;
9456
9457         return true;
9458 }
9459
9460 /*
9461  * Generic event overflow handling, sampling.
9462  */
9463
9464 static int __perf_event_overflow(struct perf_event *event,
9465                                  int throttle, struct perf_sample_data *data,
9466                                  struct pt_regs *regs)
9467 {
9468         int events = atomic_read(&event->event_limit);
9469         int ret = 0;
9470
9471         /*
9472          * Non-sampling counters might still use the PMI to fold short
9473          * hardware counters, ignore those.
9474          */
9475         if (unlikely(!is_sampling_event(event)))
9476                 return 0;
9477
9478         ret = __perf_event_account_interrupt(event, throttle);
9479
9480         /*
9481          * XXX event_limit might not quite work as expected on inherited
9482          * events
9483          */
9484
9485         event->pending_kill = POLL_IN;
9486         if (events && atomic_dec_and_test(&event->event_limit)) {
9487                 ret = 1;
9488                 event->pending_kill = POLL_HUP;
9489                 perf_event_disable_inatomic(event);
9490         }
9491
9492         if (event->attr.sigtrap) {
9493                 /*
9494                  * The desired behaviour of sigtrap vs invalid samples is a bit
9495                  * tricky; on the one hand, one should not loose the SIGTRAP if
9496                  * it is the first event, on the other hand, we should also not
9497                  * trigger the WARN or override the data address.
9498                  */
9499                 bool valid_sample = sample_is_allowed(event, regs);
9500                 unsigned int pending_id = 1;
9501
9502                 if (regs)
9503                         pending_id = hash32_ptr((void *)instruction_pointer(regs)) ?: 1;
9504                 if (!event->pending_sigtrap) {
9505                         event->pending_sigtrap = pending_id;
9506                         local_inc(&event->ctx->nr_pending);
9507                 } else if (event->attr.exclude_kernel && valid_sample) {
9508                         /*
9509                          * Should not be able to return to user space without
9510                          * consuming pending_sigtrap; with exceptions:
9511                          *
9512                          *  1. Where !exclude_kernel, events can overflow again
9513                          *     in the kernel without returning to user space.
9514                          *
9515                          *  2. Events that can overflow again before the IRQ-
9516                          *     work without user space progress (e.g. hrtimer).
9517                          *     To approximate progress (with false negatives),
9518                          *     check 32-bit hash of the current IP.
9519                          */
9520                         WARN_ON_ONCE(event->pending_sigtrap != pending_id);
9521                 }
9522
9523                 event->pending_addr = 0;
9524                 if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR))
9525                         event->pending_addr = data->addr;
9526                 irq_work_queue(&event->pending_irq);
9527         }
9528
9529         READ_ONCE(event->overflow_handler)(event, data, regs);
9530
9531         if (*perf_event_fasync(event) && event->pending_kill) {
9532                 event->pending_wakeup = 1;
9533                 irq_work_queue(&event->pending_irq);
9534         }
9535
9536         return ret;
9537 }
9538
9539 int perf_event_overflow(struct perf_event *event,
9540                         struct perf_sample_data *data,
9541                         struct pt_regs *regs)
9542 {
9543         return __perf_event_overflow(event, 1, data, regs);
9544 }
9545
9546 /*
9547  * Generic software event infrastructure
9548  */
9549
9550 struct swevent_htable {
9551         struct swevent_hlist            *swevent_hlist;
9552         struct mutex                    hlist_mutex;
9553         int                             hlist_refcount;
9554
9555         /* Recursion avoidance in each contexts */
9556         int                             recursion[PERF_NR_CONTEXTS];
9557 };
9558
9559 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
9560
9561 /*
9562  * We directly increment event->count and keep a second value in
9563  * event->hw.period_left to count intervals. This period event
9564  * is kept in the range [-sample_period, 0] so that we can use the
9565  * sign as trigger.
9566  */
9567
9568 u64 perf_swevent_set_period(struct perf_event *event)
9569 {
9570         struct hw_perf_event *hwc = &event->hw;
9571         u64 period = hwc->last_period;
9572         u64 nr, offset;
9573         s64 old, val;
9574
9575         hwc->last_period = hwc->sample_period;
9576
9577 again:
9578         old = val = local64_read(&hwc->period_left);
9579         if (val < 0)
9580                 return 0;
9581
9582         nr = div64_u64(period + val, period);
9583         offset = nr * period;
9584         val -= offset;
9585         if (local64_cmpxchg(&hwc->period_left, old, val) != old)
9586                 goto again;
9587
9588         return nr;
9589 }
9590
9591 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
9592                                     struct perf_sample_data *data,
9593                                     struct pt_regs *regs)
9594 {
9595         struct hw_perf_event *hwc = &event->hw;
9596         int throttle = 0;
9597
9598         if (!overflow)
9599                 overflow = perf_swevent_set_period(event);
9600
9601         if (hwc->interrupts == MAX_INTERRUPTS)
9602                 return;
9603
9604         for (; overflow; overflow--) {
9605                 if (__perf_event_overflow(event, throttle,
9606                                             data, regs)) {
9607                         /*
9608                          * We inhibit the overflow from happening when
9609                          * hwc->interrupts == MAX_INTERRUPTS.
9610                          */
9611                         break;
9612                 }
9613                 throttle = 1;
9614         }
9615 }
9616
9617 static void perf_swevent_event(struct perf_event *event, u64 nr,
9618                                struct perf_sample_data *data,
9619                                struct pt_regs *regs)
9620 {
9621         struct hw_perf_event *hwc = &event->hw;
9622
9623         local64_add(nr, &event->count);
9624
9625         if (!regs)
9626                 return;
9627
9628         if (!is_sampling_event(event))
9629                 return;
9630
9631         if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
9632                 data->period = nr;
9633                 return perf_swevent_overflow(event, 1, data, regs);
9634         } else
9635                 data->period = event->hw.last_period;
9636
9637         if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
9638                 return perf_swevent_overflow(event, 1, data, regs);
9639
9640         if (local64_add_negative(nr, &hwc->period_left))
9641                 return;
9642
9643         perf_swevent_overflow(event, 0, data, regs);
9644 }
9645
9646 static int perf_exclude_event(struct perf_event *event,
9647                               struct pt_regs *regs)
9648 {
9649         if (event->hw.state & PERF_HES_STOPPED)
9650                 return 1;
9651
9652         if (regs) {
9653                 if (event->attr.exclude_user && user_mode(regs))
9654                         return 1;
9655
9656                 if (event->attr.exclude_kernel && !user_mode(regs))
9657                         return 1;
9658         }
9659
9660         return 0;
9661 }
9662
9663 static int perf_swevent_match(struct perf_event *event,
9664                                 enum perf_type_id type,
9665                                 u32 event_id,
9666                                 struct perf_sample_data *data,
9667                                 struct pt_regs *regs)
9668 {
9669         if (event->attr.type != type)
9670                 return 0;
9671
9672         if (event->attr.config != event_id)
9673                 return 0;
9674
9675         if (perf_exclude_event(event, regs))
9676                 return 0;
9677
9678         return 1;
9679 }
9680
9681 static inline u64 swevent_hash(u64 type, u32 event_id)
9682 {
9683         u64 val = event_id | (type << 32);
9684
9685         return hash_64(val, SWEVENT_HLIST_BITS);
9686 }
9687
9688 static inline struct hlist_head *
9689 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
9690 {
9691         u64 hash = swevent_hash(type, event_id);
9692
9693         return &hlist->heads[hash];
9694 }
9695
9696 /* For the read side: events when they trigger */
9697 static inline struct hlist_head *
9698 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
9699 {
9700         struct swevent_hlist *hlist;
9701
9702         hlist = rcu_dereference(swhash->swevent_hlist);
9703         if (!hlist)
9704                 return NULL;
9705
9706         return __find_swevent_head(hlist, type, event_id);
9707 }
9708
9709 /* For the event head insertion and removal in the hlist */
9710 static inline struct hlist_head *
9711 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
9712 {
9713         struct swevent_hlist *hlist;
9714         u32 event_id = event->attr.config;
9715         u64 type = event->attr.type;
9716
9717         /*
9718          * Event scheduling is always serialized against hlist allocation
9719          * and release. Which makes the protected version suitable here.
9720          * The context lock guarantees that.
9721          */
9722         hlist = rcu_dereference_protected(swhash->swevent_hlist,
9723                                           lockdep_is_held(&event->ctx->lock));
9724         if (!hlist)
9725                 return NULL;
9726
9727         return __find_swevent_head(hlist, type, event_id);
9728 }
9729
9730 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
9731                                     u64 nr,
9732                                     struct perf_sample_data *data,
9733                                     struct pt_regs *regs)
9734 {
9735         struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9736         struct perf_event *event;
9737         struct hlist_head *head;
9738
9739         rcu_read_lock();
9740         head = find_swevent_head_rcu(swhash, type, event_id);
9741         if (!head)
9742                 goto end;
9743
9744         hlist_for_each_entry_rcu(event, head, hlist_entry) {
9745                 if (perf_swevent_match(event, type, event_id, data, regs))
9746                         perf_swevent_event(event, nr, data, regs);
9747         }
9748 end:
9749         rcu_read_unlock();
9750 }
9751
9752 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
9753
9754 int perf_swevent_get_recursion_context(void)
9755 {
9756         struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9757
9758         return get_recursion_context(swhash->recursion);
9759 }
9760 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
9761
9762 void perf_swevent_put_recursion_context(int rctx)
9763 {
9764         struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9765
9766         put_recursion_context(swhash->recursion, rctx);
9767 }
9768
9769 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9770 {
9771         struct perf_sample_data data;
9772
9773         if (WARN_ON_ONCE(!regs))
9774                 return;
9775
9776         perf_sample_data_init(&data, addr, 0);
9777         do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
9778 }
9779
9780 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
9781 {
9782         int rctx;
9783
9784         preempt_disable_notrace();
9785         rctx = perf_swevent_get_recursion_context();
9786         if (unlikely(rctx < 0))
9787                 goto fail;
9788
9789         ___perf_sw_event(event_id, nr, regs, addr);
9790
9791         perf_swevent_put_recursion_context(rctx);
9792 fail:
9793         preempt_enable_notrace();
9794 }
9795
9796 static void perf_swevent_read(struct perf_event *event)
9797 {
9798 }
9799
9800 static int perf_swevent_add(struct perf_event *event, int flags)
9801 {
9802         struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
9803         struct hw_perf_event *hwc = &event->hw;
9804         struct hlist_head *head;
9805
9806         if (is_sampling_event(event)) {
9807                 hwc->last_period = hwc->sample_period;
9808                 perf_swevent_set_period(event);
9809         }
9810
9811         hwc->state = !(flags & PERF_EF_START);
9812
9813         head = find_swevent_head(swhash, event);
9814         if (WARN_ON_ONCE(!head))
9815                 return -EINVAL;
9816
9817         hlist_add_head_rcu(&event->hlist_entry, head);
9818         perf_event_update_userpage(event);
9819
9820         return 0;
9821 }
9822
9823 static void perf_swevent_del(struct perf_event *event, int flags)
9824 {
9825         hlist_del_rcu(&event->hlist_entry);
9826 }
9827
9828 static void perf_swevent_start(struct perf_event *event, int flags)
9829 {
9830         event->hw.state = 0;
9831 }
9832
9833 static void perf_swevent_stop(struct perf_event *event, int flags)
9834 {
9835         event->hw.state = PERF_HES_STOPPED;
9836 }
9837
9838 /* Deref the hlist from the update side */
9839 static inline struct swevent_hlist *
9840 swevent_hlist_deref(struct swevent_htable *swhash)
9841 {
9842         return rcu_dereference_protected(swhash->swevent_hlist,
9843                                          lockdep_is_held(&swhash->hlist_mutex));
9844 }
9845
9846 static void swevent_hlist_release(struct swevent_htable *swhash)
9847 {
9848         struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
9849
9850         if (!hlist)
9851                 return;
9852
9853         RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
9854         kfree_rcu(hlist, rcu_head);
9855 }
9856
9857 static void swevent_hlist_put_cpu(int cpu)
9858 {
9859         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9860
9861         mutex_lock(&swhash->hlist_mutex);
9862
9863         if (!--swhash->hlist_refcount)
9864                 swevent_hlist_release(swhash);
9865
9866         mutex_unlock(&swhash->hlist_mutex);
9867 }
9868
9869 static void swevent_hlist_put(void)
9870 {
9871         int cpu;
9872
9873         for_each_possible_cpu(cpu)
9874                 swevent_hlist_put_cpu(cpu);
9875 }
9876
9877 static int swevent_hlist_get_cpu(int cpu)
9878 {
9879         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9880         int err = 0;
9881
9882         mutex_lock(&swhash->hlist_mutex);
9883         if (!swevent_hlist_deref(swhash) &&
9884             cpumask_test_cpu(cpu, perf_online_mask)) {
9885                 struct swevent_hlist *hlist;
9886
9887                 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
9888                 if (!hlist) {
9889                         err = -ENOMEM;
9890                         goto exit;
9891                 }
9892                 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9893         }
9894         swhash->hlist_refcount++;
9895 exit:
9896         mutex_unlock(&swhash->hlist_mutex);
9897
9898         return err;
9899 }
9900
9901 static int swevent_hlist_get(void)
9902 {
9903         int err, cpu, failed_cpu;
9904
9905         mutex_lock(&pmus_lock);
9906         for_each_possible_cpu(cpu) {
9907                 err = swevent_hlist_get_cpu(cpu);
9908                 if (err) {
9909                         failed_cpu = cpu;
9910                         goto fail;
9911                 }
9912         }
9913         mutex_unlock(&pmus_lock);
9914         return 0;
9915 fail:
9916         for_each_possible_cpu(cpu) {
9917                 if (cpu == failed_cpu)
9918                         break;
9919                 swevent_hlist_put_cpu(cpu);
9920         }
9921         mutex_unlock(&pmus_lock);
9922         return err;
9923 }
9924
9925 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
9926
9927 static void sw_perf_event_destroy(struct perf_event *event)
9928 {
9929         u64 event_id = event->attr.config;
9930
9931         WARN_ON(event->parent);
9932
9933         static_key_slow_dec(&perf_swevent_enabled[event_id]);
9934         swevent_hlist_put();
9935 }
9936
9937 static int perf_swevent_init(struct perf_event *event)
9938 {
9939         u64 event_id = event->attr.config;
9940
9941         if (event->attr.type != PERF_TYPE_SOFTWARE)
9942                 return -ENOENT;
9943
9944         /*
9945          * no branch sampling for software events
9946          */
9947         if (has_branch_stack(event))
9948                 return -EOPNOTSUPP;
9949
9950         switch (event_id) {
9951         case PERF_COUNT_SW_CPU_CLOCK:
9952         case PERF_COUNT_SW_TASK_CLOCK:
9953                 return -ENOENT;
9954
9955         default:
9956                 break;
9957         }
9958
9959         if (event_id >= PERF_COUNT_SW_MAX)
9960                 return -ENOENT;
9961
9962         if (!event->parent) {
9963                 int err;
9964
9965                 err = swevent_hlist_get();
9966                 if (err)
9967                         return err;
9968
9969                 static_key_slow_inc(&perf_swevent_enabled[event_id]);
9970                 event->destroy = sw_perf_event_destroy;
9971         }
9972
9973         return 0;
9974 }
9975
9976 static struct pmu perf_swevent = {
9977         .task_ctx_nr    = perf_sw_context,
9978
9979         .capabilities   = PERF_PMU_CAP_NO_NMI,
9980
9981         .event_init     = perf_swevent_init,
9982         .add            = perf_swevent_add,
9983         .del            = perf_swevent_del,
9984         .start          = perf_swevent_start,
9985         .stop           = perf_swevent_stop,
9986         .read           = perf_swevent_read,
9987 };
9988
9989 #ifdef CONFIG_EVENT_TRACING
9990
9991 static void tp_perf_event_destroy(struct perf_event *event)
9992 {
9993         perf_trace_destroy(event);
9994 }
9995
9996 static int perf_tp_event_init(struct perf_event *event)
9997 {
9998         int err;
9999
10000         if (event->attr.type != PERF_TYPE_TRACEPOINT)
10001                 return -ENOENT;
10002
10003         /*
10004          * no branch sampling for tracepoint events
10005          */
10006         if (has_branch_stack(event))
10007                 return -EOPNOTSUPP;
10008
10009         err = perf_trace_init(event);
10010         if (err)
10011                 return err;
10012
10013         event->destroy = tp_perf_event_destroy;
10014
10015         return 0;
10016 }
10017
10018 static struct pmu perf_tracepoint = {
10019         .task_ctx_nr    = perf_sw_context,
10020
10021         .event_init     = perf_tp_event_init,
10022         .add            = perf_trace_add,
10023         .del            = perf_trace_del,
10024         .start          = perf_swevent_start,
10025         .stop           = perf_swevent_stop,
10026         .read           = perf_swevent_read,
10027 };
10028
10029 static int perf_tp_filter_match(struct perf_event *event,
10030                                 struct perf_sample_data *data)
10031 {
10032         void *record = data->raw->frag.data;
10033
10034         /* only top level events have filters set */
10035         if (event->parent)
10036                 event = event->parent;
10037
10038         if (likely(!event->filter) || filter_match_preds(event->filter, record))
10039                 return 1;
10040         return 0;
10041 }
10042
10043 static int perf_tp_event_match(struct perf_event *event,
10044                                 struct perf_sample_data *data,
10045                                 struct pt_regs *regs)
10046 {
10047         if (event->hw.state & PERF_HES_STOPPED)
10048                 return 0;
10049         /*
10050          * If exclude_kernel, only trace user-space tracepoints (uprobes)
10051          */
10052         if (event->attr.exclude_kernel && !user_mode(regs))
10053                 return 0;
10054
10055         if (!perf_tp_filter_match(event, data))
10056                 return 0;
10057
10058         return 1;
10059 }
10060
10061 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
10062                                struct trace_event_call *call, u64 count,
10063                                struct pt_regs *regs, struct hlist_head *head,
10064                                struct task_struct *task)
10065 {
10066         if (bpf_prog_array_valid(call)) {
10067                 *(struct pt_regs **)raw_data = regs;
10068                 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
10069                         perf_swevent_put_recursion_context(rctx);
10070                         return;
10071                 }
10072         }
10073         perf_tp_event(call->event.type, count, raw_data, size, regs, head,
10074                       rctx, task);
10075 }
10076 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
10077
10078 static void __perf_tp_event_target_task(u64 count, void *record,
10079                                         struct pt_regs *regs,
10080                                         struct perf_sample_data *data,
10081                                         struct perf_event *event)
10082 {
10083         struct trace_entry *entry = record;
10084
10085         if (event->attr.config != entry->type)
10086                 return;
10087         /* Cannot deliver synchronous signal to other task. */
10088         if (event->attr.sigtrap)
10089                 return;
10090         if (perf_tp_event_match(event, data, regs))
10091                 perf_swevent_event(event, count, data, regs);
10092 }
10093
10094 static void perf_tp_event_target_task(u64 count, void *record,
10095                                       struct pt_regs *regs,
10096                                       struct perf_sample_data *data,
10097                                       struct perf_event_context *ctx)
10098 {
10099         unsigned int cpu = smp_processor_id();
10100         struct pmu *pmu = &perf_tracepoint;
10101         struct perf_event *event, *sibling;
10102
10103         perf_event_groups_for_cpu_pmu(event, &ctx->pinned_groups, cpu, pmu) {
10104                 __perf_tp_event_target_task(count, record, regs, data, event);
10105                 for_each_sibling_event(sibling, event)
10106                         __perf_tp_event_target_task(count, record, regs, data, sibling);
10107         }
10108
10109         perf_event_groups_for_cpu_pmu(event, &ctx->flexible_groups, cpu, pmu) {
10110                 __perf_tp_event_target_task(count, record, regs, data, event);
10111                 for_each_sibling_event(sibling, event)
10112                         __perf_tp_event_target_task(count, record, regs, data, sibling);
10113         }
10114 }
10115
10116 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
10117                    struct pt_regs *regs, struct hlist_head *head, int rctx,
10118                    struct task_struct *task)
10119 {
10120         struct perf_sample_data data;
10121         struct perf_event *event;
10122
10123         struct perf_raw_record raw = {
10124                 .frag = {
10125                         .size = entry_size,
10126                         .data = record,
10127                 },
10128         };
10129
10130         perf_sample_data_init(&data, 0, 0);
10131         data.raw = &raw;
10132         data.sample_flags |= PERF_SAMPLE_RAW;
10133
10134         perf_trace_buf_update(record, event_type);
10135
10136         hlist_for_each_entry_rcu(event, head, hlist_entry) {
10137                 if (perf_tp_event_match(event, &data, regs))
10138                         perf_swevent_event(event, count, &data, regs);
10139         }
10140
10141         /*
10142          * If we got specified a target task, also iterate its context and
10143          * deliver this event there too.
10144          */
10145         if (task && task != current) {
10146                 struct perf_event_context *ctx;
10147
10148                 rcu_read_lock();
10149                 ctx = rcu_dereference(task->perf_event_ctxp);
10150                 if (!ctx)
10151                         goto unlock;
10152
10153                 raw_spin_lock(&ctx->lock);
10154                 perf_tp_event_target_task(count, record, regs, &data, ctx);
10155                 raw_spin_unlock(&ctx->lock);
10156 unlock:
10157                 rcu_read_unlock();
10158         }
10159
10160         perf_swevent_put_recursion_context(rctx);
10161 }
10162 EXPORT_SYMBOL_GPL(perf_tp_event);
10163
10164 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
10165 /*
10166  * Flags in config, used by dynamic PMU kprobe and uprobe
10167  * The flags should match following PMU_FORMAT_ATTR().
10168  *
10169  * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
10170  *                               if not set, create kprobe/uprobe
10171  *
10172  * The following values specify a reference counter (or semaphore in the
10173  * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
10174  * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
10175  *
10176  * PERF_UPROBE_REF_CTR_OFFSET_BITS      # of bits in config as th offset
10177  * PERF_UPROBE_REF_CTR_OFFSET_SHIFT     # of bits to shift left
10178  */
10179 enum perf_probe_config {
10180         PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0,  /* [k,u]retprobe */
10181         PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
10182         PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
10183 };
10184
10185 PMU_FORMAT_ATTR(retprobe, "config:0");
10186 #endif
10187
10188 #ifdef CONFIG_KPROBE_EVENTS
10189 static struct attribute *kprobe_attrs[] = {
10190         &format_attr_retprobe.attr,
10191         NULL,
10192 };
10193
10194 static struct attribute_group kprobe_format_group = {
10195         .name = "format",
10196         .attrs = kprobe_attrs,
10197 };
10198
10199 static const struct attribute_group *kprobe_attr_groups[] = {
10200         &kprobe_format_group,
10201         NULL,
10202 };
10203
10204 static int perf_kprobe_event_init(struct perf_event *event);
10205 static struct pmu perf_kprobe = {
10206         .task_ctx_nr    = perf_sw_context,
10207         .event_init     = perf_kprobe_event_init,
10208         .add            = perf_trace_add,
10209         .del            = perf_trace_del,
10210         .start          = perf_swevent_start,
10211         .stop           = perf_swevent_stop,
10212         .read           = perf_swevent_read,
10213         .attr_groups    = kprobe_attr_groups,
10214 };
10215
10216 static int perf_kprobe_event_init(struct perf_event *event)
10217 {
10218         int err;
10219         bool is_retprobe;
10220
10221         if (event->attr.type != perf_kprobe.type)
10222                 return -ENOENT;
10223
10224         if (!perfmon_capable())
10225                 return -EACCES;
10226
10227         /*
10228          * no branch sampling for probe events
10229          */
10230         if (has_branch_stack(event))
10231                 return -EOPNOTSUPP;
10232
10233         is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
10234         err = perf_kprobe_init(event, is_retprobe);
10235         if (err)
10236                 return err;
10237
10238         event->destroy = perf_kprobe_destroy;
10239
10240         return 0;
10241 }
10242 #endif /* CONFIG_KPROBE_EVENTS */
10243
10244 #ifdef CONFIG_UPROBE_EVENTS
10245 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
10246
10247 static struct attribute *uprobe_attrs[] = {
10248         &format_attr_retprobe.attr,
10249         &format_attr_ref_ctr_offset.attr,
10250         NULL,
10251 };
10252
10253 static struct attribute_group uprobe_format_group = {
10254         .name = "format",
10255         .attrs = uprobe_attrs,
10256 };
10257
10258 static const struct attribute_group *uprobe_attr_groups[] = {
10259         &uprobe_format_group,
10260         NULL,
10261 };
10262
10263 static int perf_uprobe_event_init(struct perf_event *event);
10264 static struct pmu perf_uprobe = {
10265         .task_ctx_nr    = perf_sw_context,
10266         .event_init     = perf_uprobe_event_init,
10267         .add            = perf_trace_add,
10268         .del            = perf_trace_del,
10269         .start          = perf_swevent_start,
10270         .stop           = perf_swevent_stop,
10271         .read           = perf_swevent_read,
10272         .attr_groups    = uprobe_attr_groups,
10273 };
10274
10275 static int perf_uprobe_event_init(struct perf_event *event)
10276 {
10277         int err;
10278         unsigned long ref_ctr_offset;
10279         bool is_retprobe;
10280
10281         if (event->attr.type != perf_uprobe.type)
10282                 return -ENOENT;
10283
10284         if (!perfmon_capable())
10285                 return -EACCES;
10286
10287         /*
10288          * no branch sampling for probe events
10289          */
10290         if (has_branch_stack(event))
10291                 return -EOPNOTSUPP;
10292
10293         is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
10294         ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10295         err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
10296         if (err)
10297                 return err;
10298
10299         event->destroy = perf_uprobe_destroy;
10300
10301         return 0;
10302 }
10303 #endif /* CONFIG_UPROBE_EVENTS */
10304
10305 static inline void perf_tp_register(void)
10306 {
10307         perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
10308 #ifdef CONFIG_KPROBE_EVENTS
10309         perf_pmu_register(&perf_kprobe, "kprobe", -1);
10310 #endif
10311 #ifdef CONFIG_UPROBE_EVENTS
10312         perf_pmu_register(&perf_uprobe, "uprobe", -1);
10313 #endif
10314 }
10315
10316 static void perf_event_free_filter(struct perf_event *event)
10317 {
10318         ftrace_profile_free_filter(event);
10319 }
10320
10321 #ifdef CONFIG_BPF_SYSCALL
10322 static void bpf_overflow_handler(struct perf_event *event,
10323                                  struct perf_sample_data *data,
10324                                  struct pt_regs *regs)
10325 {
10326         struct bpf_perf_event_data_kern ctx = {
10327                 .data = data,
10328                 .event = event,
10329         };
10330         struct bpf_prog *prog;
10331         int ret = 0;
10332
10333         ctx.regs = perf_arch_bpf_user_pt_regs(regs);
10334         if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
10335                 goto out;
10336         rcu_read_lock();
10337         prog = READ_ONCE(event->prog);
10338         if (prog) {
10339                 if (prog->call_get_stack &&
10340                     (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) &&
10341                     !(data->sample_flags & PERF_SAMPLE_CALLCHAIN)) {
10342                         data->callchain = perf_callchain(event, regs);
10343                         data->sample_flags |= PERF_SAMPLE_CALLCHAIN;
10344                 }
10345
10346                 ret = bpf_prog_run(prog, &ctx);
10347         }
10348         rcu_read_unlock();
10349 out:
10350         __this_cpu_dec(bpf_prog_active);
10351         if (!ret)
10352                 return;
10353
10354         event->orig_overflow_handler(event, data, regs);
10355 }
10356
10357 static int perf_event_set_bpf_handler(struct perf_event *event,
10358                                       struct bpf_prog *prog,
10359                                       u64 bpf_cookie)
10360 {
10361         if (event->overflow_handler_context)
10362                 /* hw breakpoint or kernel counter */
10363                 return -EINVAL;
10364
10365         if (event->prog)
10366                 return -EEXIST;
10367
10368         if (prog->type != BPF_PROG_TYPE_PERF_EVENT)
10369                 return -EINVAL;
10370
10371         if (event->attr.precise_ip &&
10372             prog->call_get_stack &&
10373             (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) ||
10374              event->attr.exclude_callchain_kernel ||
10375              event->attr.exclude_callchain_user)) {
10376                 /*
10377                  * On perf_event with precise_ip, calling bpf_get_stack()
10378                  * may trigger unwinder warnings and occasional crashes.
10379                  * bpf_get_[stack|stackid] works around this issue by using
10380                  * callchain attached to perf_sample_data. If the
10381                  * perf_event does not full (kernel and user) callchain
10382                  * attached to perf_sample_data, do not allow attaching BPF
10383                  * program that calls bpf_get_[stack|stackid].
10384                  */
10385                 return -EPROTO;
10386         }
10387
10388         event->prog = prog;
10389         event->bpf_cookie = bpf_cookie;
10390         event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
10391         WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
10392         return 0;
10393 }
10394
10395 static void perf_event_free_bpf_handler(struct perf_event *event)
10396 {
10397         struct bpf_prog *prog = event->prog;
10398
10399         if (!prog)
10400                 return;
10401
10402         WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
10403         event->prog = NULL;
10404         bpf_prog_put(prog);
10405 }
10406 #else
10407 static int perf_event_set_bpf_handler(struct perf_event *event,
10408                                       struct bpf_prog *prog,
10409                                       u64 bpf_cookie)
10410 {
10411         return -EOPNOTSUPP;
10412 }
10413 static void perf_event_free_bpf_handler(struct perf_event *event)
10414 {
10415 }
10416 #endif
10417
10418 /*
10419  * returns true if the event is a tracepoint, or a kprobe/upprobe created
10420  * with perf_event_open()
10421  */
10422 static inline bool perf_event_is_tracing(struct perf_event *event)
10423 {
10424         if (event->pmu == &perf_tracepoint)
10425                 return true;
10426 #ifdef CONFIG_KPROBE_EVENTS
10427         if (event->pmu == &perf_kprobe)
10428                 return true;
10429 #endif
10430 #ifdef CONFIG_UPROBE_EVENTS
10431         if (event->pmu == &perf_uprobe)
10432                 return true;
10433 #endif
10434         return false;
10435 }
10436
10437 int perf_event_set_bpf_prog(struct perf_event *event, struct bpf_prog *prog,
10438                             u64 bpf_cookie)
10439 {
10440         bool is_kprobe, is_uprobe, is_tracepoint, is_syscall_tp;
10441
10442         if (!perf_event_is_tracing(event))
10443                 return perf_event_set_bpf_handler(event, prog, bpf_cookie);
10444
10445         is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_KPROBE;
10446         is_uprobe = event->tp_event->flags & TRACE_EVENT_FL_UPROBE;
10447         is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
10448         is_syscall_tp = is_syscall_trace_event(event->tp_event);
10449         if (!is_kprobe && !is_uprobe && !is_tracepoint && !is_syscall_tp)
10450                 /* bpf programs can only be attached to u/kprobe or tracepoint */
10451                 return -EINVAL;
10452
10453         if (((is_kprobe || is_uprobe) && prog->type != BPF_PROG_TYPE_KPROBE) ||
10454             (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
10455             (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT))
10456                 return -EINVAL;
10457
10458         if (prog->type == BPF_PROG_TYPE_KPROBE && prog->aux->sleepable && !is_uprobe)
10459                 /* only uprobe programs are allowed to be sleepable */
10460                 return -EINVAL;
10461
10462         /* Kprobe override only works for kprobes, not uprobes. */
10463         if (prog->kprobe_override && !is_kprobe)
10464                 return -EINVAL;
10465
10466         if (is_tracepoint || is_syscall_tp) {
10467                 int off = trace_event_get_offsets(event->tp_event);
10468
10469                 if (prog->aux->max_ctx_offset > off)
10470                         return -EACCES;
10471         }
10472
10473         return perf_event_attach_bpf_prog(event, prog, bpf_cookie);
10474 }
10475
10476 void perf_event_free_bpf_prog(struct perf_event *event)
10477 {
10478         if (!perf_event_is_tracing(event)) {
10479                 perf_event_free_bpf_handler(event);
10480                 return;
10481         }
10482         perf_event_detach_bpf_prog(event);
10483 }
10484
10485 #else
10486
10487 static inline void perf_tp_register(void)
10488 {
10489 }
10490
10491 static void perf_event_free_filter(struct perf_event *event)
10492 {
10493 }
10494
10495 int perf_event_set_bpf_prog(struct perf_event *event, struct bpf_prog *prog,
10496                             u64 bpf_cookie)
10497 {
10498         return -ENOENT;
10499 }
10500
10501 void perf_event_free_bpf_prog(struct perf_event *event)
10502 {
10503 }
10504 #endif /* CONFIG_EVENT_TRACING */
10505
10506 #ifdef CONFIG_HAVE_HW_BREAKPOINT
10507 void perf_bp_event(struct perf_event *bp, void *data)
10508 {
10509         struct perf_sample_data sample;
10510         struct pt_regs *regs = data;
10511
10512         perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
10513
10514         if (!bp->hw.state && !perf_exclude_event(bp, regs))
10515                 perf_swevent_event(bp, 1, &sample, regs);
10516 }
10517 #endif
10518
10519 /*
10520  * Allocate a new address filter
10521  */
10522 static struct perf_addr_filter *
10523 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
10524 {
10525         int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
10526         struct perf_addr_filter *filter;
10527
10528         filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
10529         if (!filter)
10530                 return NULL;
10531
10532         INIT_LIST_HEAD(&filter->entry);
10533         list_add_tail(&filter->entry, filters);
10534
10535         return filter;
10536 }
10537
10538 static void free_filters_list(struct list_head *filters)
10539 {
10540         struct perf_addr_filter *filter, *iter;
10541
10542         list_for_each_entry_safe(filter, iter, filters, entry) {
10543                 path_put(&filter->path);
10544                 list_del(&filter->entry);
10545                 kfree(filter);
10546         }
10547 }
10548
10549 /*
10550  * Free existing address filters and optionally install new ones
10551  */
10552 static void perf_addr_filters_splice(struct perf_event *event,
10553                                      struct list_head *head)
10554 {
10555         unsigned long flags;
10556         LIST_HEAD(list);
10557
10558         if (!has_addr_filter(event))
10559                 return;
10560
10561         /* don't bother with children, they don't have their own filters */
10562         if (event->parent)
10563                 return;
10564
10565         raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
10566
10567         list_splice_init(&event->addr_filters.list, &list);
10568         if (head)
10569                 list_splice(head, &event->addr_filters.list);
10570
10571         raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
10572
10573         free_filters_list(&list);
10574 }
10575
10576 /*
10577  * Scan through mm's vmas and see if one of them matches the
10578  * @filter; if so, adjust filter's address range.
10579  * Called with mm::mmap_lock down for reading.
10580  */
10581 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
10582                                    struct mm_struct *mm,
10583                                    struct perf_addr_filter_range *fr)
10584 {
10585         struct vm_area_struct *vma;
10586         VMA_ITERATOR(vmi, mm, 0);
10587
10588         for_each_vma(vmi, vma) {
10589                 if (!vma->vm_file)
10590                         continue;
10591
10592                 if (perf_addr_filter_vma_adjust(filter, vma, fr))
10593                         return;
10594         }
10595 }
10596
10597 /*
10598  * Update event's address range filters based on the
10599  * task's existing mappings, if any.
10600  */
10601 static void perf_event_addr_filters_apply(struct perf_event *event)
10602 {
10603         struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
10604         struct task_struct *task = READ_ONCE(event->ctx->task);
10605         struct perf_addr_filter *filter;
10606         struct mm_struct *mm = NULL;
10607         unsigned int count = 0;
10608         unsigned long flags;
10609
10610         /*
10611          * We may observe TASK_TOMBSTONE, which means that the event tear-down
10612          * will stop on the parent's child_mutex that our caller is also holding
10613          */
10614         if (task == TASK_TOMBSTONE)
10615                 return;
10616
10617         if (ifh->nr_file_filters) {
10618                 mm = get_task_mm(task);
10619                 if (!mm)
10620                         goto restart;
10621
10622                 mmap_read_lock(mm);
10623         }
10624
10625         raw_spin_lock_irqsave(&ifh->lock, flags);
10626         list_for_each_entry(filter, &ifh->list, entry) {
10627                 if (filter->path.dentry) {
10628                         /*
10629                          * Adjust base offset if the filter is associated to a
10630                          * binary that needs to be mapped:
10631                          */
10632                         event->addr_filter_ranges[count].start = 0;
10633                         event->addr_filter_ranges[count].size = 0;
10634
10635                         perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
10636                 } else {
10637                         event->addr_filter_ranges[count].start = filter->offset;
10638                         event->addr_filter_ranges[count].size  = filter->size;
10639                 }
10640
10641                 count++;
10642         }
10643
10644         event->addr_filters_gen++;
10645         raw_spin_unlock_irqrestore(&ifh->lock, flags);
10646
10647         if (ifh->nr_file_filters) {
10648                 mmap_read_unlock(mm);
10649
10650                 mmput(mm);
10651         }
10652
10653 restart:
10654         perf_event_stop(event, 1);
10655 }
10656
10657 /*
10658  * Address range filtering: limiting the data to certain
10659  * instruction address ranges. Filters are ioctl()ed to us from
10660  * userspace as ascii strings.
10661  *
10662  * Filter string format:
10663  *
10664  * ACTION RANGE_SPEC
10665  * where ACTION is one of the
10666  *  * "filter": limit the trace to this region
10667  *  * "start": start tracing from this address
10668  *  * "stop": stop tracing at this address/region;
10669  * RANGE_SPEC is
10670  *  * for kernel addresses: <start address>[/<size>]
10671  *  * for object files:     <start address>[/<size>]@</path/to/object/file>
10672  *
10673  * if <size> is not specified or is zero, the range is treated as a single
10674  * address; not valid for ACTION=="filter".
10675  */
10676 enum {
10677         IF_ACT_NONE = -1,
10678         IF_ACT_FILTER,
10679         IF_ACT_START,
10680         IF_ACT_STOP,
10681         IF_SRC_FILE,
10682         IF_SRC_KERNEL,
10683         IF_SRC_FILEADDR,
10684         IF_SRC_KERNELADDR,
10685 };
10686
10687 enum {
10688         IF_STATE_ACTION = 0,
10689         IF_STATE_SOURCE,
10690         IF_STATE_END,
10691 };
10692
10693 static const match_table_t if_tokens = {
10694         { IF_ACT_FILTER,        "filter" },
10695         { IF_ACT_START,         "start" },
10696         { IF_ACT_STOP,          "stop" },
10697         { IF_SRC_FILE,          "%u/%u@%s" },
10698         { IF_SRC_KERNEL,        "%u/%u" },
10699         { IF_SRC_FILEADDR,      "%u@%s" },
10700         { IF_SRC_KERNELADDR,    "%u" },
10701         { IF_ACT_NONE,          NULL },
10702 };
10703
10704 /*
10705  * Address filter string parser
10706  */
10707 static int
10708 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
10709                              struct list_head *filters)
10710 {
10711         struct perf_addr_filter *filter = NULL;
10712         char *start, *orig, *filename = NULL;
10713         substring_t args[MAX_OPT_ARGS];
10714         int state = IF_STATE_ACTION, token;
10715         unsigned int kernel = 0;
10716         int ret = -EINVAL;
10717
10718         orig = fstr = kstrdup(fstr, GFP_KERNEL);
10719         if (!fstr)
10720                 return -ENOMEM;
10721
10722         while ((start = strsep(&fstr, " ,\n")) != NULL) {
10723                 static const enum perf_addr_filter_action_t actions[] = {
10724                         [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
10725                         [IF_ACT_START]  = PERF_ADDR_FILTER_ACTION_START,
10726                         [IF_ACT_STOP]   = PERF_ADDR_FILTER_ACTION_STOP,
10727                 };
10728                 ret = -EINVAL;
10729
10730                 if (!*start)
10731                         continue;
10732
10733                 /* filter definition begins */
10734                 if (state == IF_STATE_ACTION) {
10735                         filter = perf_addr_filter_new(event, filters);
10736                         if (!filter)
10737                                 goto fail;
10738                 }
10739
10740                 token = match_token(start, if_tokens, args);
10741                 switch (token) {
10742                 case IF_ACT_FILTER:
10743                 case IF_ACT_START:
10744                 case IF_ACT_STOP:
10745                         if (state != IF_STATE_ACTION)
10746                                 goto fail;
10747
10748                         filter->action = actions[token];
10749                         state = IF_STATE_SOURCE;
10750                         break;
10751
10752                 case IF_SRC_KERNELADDR:
10753                 case IF_SRC_KERNEL:
10754                         kernel = 1;
10755                         fallthrough;
10756
10757                 case IF_SRC_FILEADDR:
10758                 case IF_SRC_FILE:
10759                         if (state != IF_STATE_SOURCE)
10760                                 goto fail;
10761
10762                         *args[0].to = 0;
10763                         ret = kstrtoul(args[0].from, 0, &filter->offset);
10764                         if (ret)
10765                                 goto fail;
10766
10767                         if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
10768                                 *args[1].to = 0;
10769                                 ret = kstrtoul(args[1].from, 0, &filter->size);
10770                                 if (ret)
10771                                         goto fail;
10772                         }
10773
10774                         if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
10775                                 int fpos = token == IF_SRC_FILE ? 2 : 1;
10776
10777                                 kfree(filename);
10778                                 filename = match_strdup(&args[fpos]);
10779                                 if (!filename) {
10780                                         ret = -ENOMEM;
10781                                         goto fail;
10782                                 }
10783                         }
10784
10785                         state = IF_STATE_END;
10786                         break;
10787
10788                 default:
10789                         goto fail;
10790                 }
10791
10792                 /*
10793                  * Filter definition is fully parsed, validate and install it.
10794                  * Make sure that it doesn't contradict itself or the event's
10795                  * attribute.
10796                  */
10797                 if (state == IF_STATE_END) {
10798                         ret = -EINVAL;
10799
10800                         /*
10801                          * ACTION "filter" must have a non-zero length region
10802                          * specified.
10803                          */
10804                         if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
10805                             !filter->size)
10806                                 goto fail;
10807
10808                         if (!kernel) {
10809                                 if (!filename)
10810                                         goto fail;
10811
10812                                 /*
10813                                  * For now, we only support file-based filters
10814                                  * in per-task events; doing so for CPU-wide
10815                                  * events requires additional context switching
10816                                  * trickery, since same object code will be
10817                                  * mapped at different virtual addresses in
10818                                  * different processes.
10819                                  */
10820                                 ret = -EOPNOTSUPP;
10821                                 if (!event->ctx->task)
10822                                         goto fail;
10823
10824                                 /* look up the path and grab its inode */
10825                                 ret = kern_path(filename, LOOKUP_FOLLOW,
10826                                                 &filter->path);
10827                                 if (ret)
10828                                         goto fail;
10829
10830                                 ret = -EINVAL;
10831                                 if (!filter->path.dentry ||
10832                                     !S_ISREG(d_inode(filter->path.dentry)
10833                                              ->i_mode))
10834                                         goto fail;
10835
10836                                 event->addr_filters.nr_file_filters++;
10837                         }
10838
10839                         /* ready to consume more filters */
10840                         kfree(filename);
10841                         filename = NULL;
10842                         state = IF_STATE_ACTION;
10843                         filter = NULL;
10844                         kernel = 0;
10845                 }
10846         }
10847
10848         if (state != IF_STATE_ACTION)
10849                 goto fail;
10850
10851         kfree(filename);
10852         kfree(orig);
10853
10854         return 0;
10855
10856 fail:
10857         kfree(filename);
10858         free_filters_list(filters);
10859         kfree(orig);
10860
10861         return ret;
10862 }
10863
10864 static int
10865 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
10866 {
10867         LIST_HEAD(filters);
10868         int ret;
10869
10870         /*
10871          * Since this is called in perf_ioctl() path, we're already holding
10872          * ctx::mutex.
10873          */
10874         lockdep_assert_held(&event->ctx->mutex);
10875
10876         if (WARN_ON_ONCE(event->parent))
10877                 return -EINVAL;
10878
10879         ret = perf_event_parse_addr_filter(event, filter_str, &filters);
10880         if (ret)
10881                 goto fail_clear_files;
10882
10883         ret = event->pmu->addr_filters_validate(&filters);
10884         if (ret)
10885                 goto fail_free_filters;
10886
10887         /* remove existing filters, if any */
10888         perf_addr_filters_splice(event, &filters);
10889
10890         /* install new filters */
10891         perf_event_for_each_child(event, perf_event_addr_filters_apply);
10892
10893         return ret;
10894
10895 fail_free_filters:
10896         free_filters_list(&filters);
10897
10898 fail_clear_files:
10899         event->addr_filters.nr_file_filters = 0;
10900
10901         return ret;
10902 }
10903
10904 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
10905 {
10906         int ret = -EINVAL;
10907         char *filter_str;
10908
10909         filter_str = strndup_user(arg, PAGE_SIZE);
10910         if (IS_ERR(filter_str))
10911                 return PTR_ERR(filter_str);
10912
10913 #ifdef CONFIG_EVENT_TRACING
10914         if (perf_event_is_tracing(event)) {
10915                 struct perf_event_context *ctx = event->ctx;
10916
10917                 /*
10918                  * Beware, here be dragons!!
10919                  *
10920                  * the tracepoint muck will deadlock against ctx->mutex, but
10921                  * the tracepoint stuff does not actually need it. So
10922                  * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
10923                  * already have a reference on ctx.
10924                  *
10925                  * This can result in event getting moved to a different ctx,
10926                  * but that does not affect the tracepoint state.
10927                  */
10928                 mutex_unlock(&ctx->mutex);
10929                 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
10930                 mutex_lock(&ctx->mutex);
10931         } else
10932 #endif
10933         if (has_addr_filter(event))
10934                 ret = perf_event_set_addr_filter(event, filter_str);
10935
10936         kfree(filter_str);
10937         return ret;
10938 }
10939
10940 /*
10941  * hrtimer based swevent callback
10942  */
10943
10944 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
10945 {
10946         enum hrtimer_restart ret = HRTIMER_RESTART;
10947         struct perf_sample_data data;
10948         struct pt_regs *regs;
10949         struct perf_event *event;
10950         u64 period;
10951
10952         event = container_of(hrtimer, struct perf_event, hw.hrtimer);
10953
10954         if (event->state != PERF_EVENT_STATE_ACTIVE)
10955                 return HRTIMER_NORESTART;
10956
10957         event->pmu->read(event);
10958
10959         perf_sample_data_init(&data, 0, event->hw.last_period);
10960         regs = get_irq_regs();
10961
10962         if (regs && !perf_exclude_event(event, regs)) {
10963                 if (!(event->attr.exclude_idle && is_idle_task(current)))
10964                         if (__perf_event_overflow(event, 1, &data, regs))
10965                                 ret = HRTIMER_NORESTART;
10966         }
10967
10968         period = max_t(u64, 10000, event->hw.sample_period);
10969         hrtimer_forward_now(hrtimer, ns_to_ktime(period));
10970
10971         return ret;
10972 }
10973
10974 static void perf_swevent_start_hrtimer(struct perf_event *event)
10975 {
10976         struct hw_perf_event *hwc = &event->hw;
10977         s64 period;
10978
10979         if (!is_sampling_event(event))
10980                 return;
10981
10982         period = local64_read(&hwc->period_left);
10983         if (period) {
10984                 if (period < 0)
10985                         period = 10000;
10986
10987                 local64_set(&hwc->period_left, 0);
10988         } else {
10989                 period = max_t(u64, 10000, hwc->sample_period);
10990         }
10991         hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
10992                       HRTIMER_MODE_REL_PINNED_HARD);
10993 }
10994
10995 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
10996 {
10997         struct hw_perf_event *hwc = &event->hw;
10998
10999         if (is_sampling_event(event)) {
11000                 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
11001                 local64_set(&hwc->period_left, ktime_to_ns(remaining));
11002
11003                 hrtimer_cancel(&hwc->hrtimer);
11004         }
11005 }
11006
11007 static void perf_swevent_init_hrtimer(struct perf_event *event)
11008 {
11009         struct hw_perf_event *hwc = &event->hw;
11010
11011         if (!is_sampling_event(event))
11012                 return;
11013
11014         hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
11015         hwc->hrtimer.function = perf_swevent_hrtimer;
11016
11017         /*
11018          * Since hrtimers have a fixed rate, we can do a static freq->period
11019          * mapping and avoid the whole period adjust feedback stuff.
11020          */
11021         if (event->attr.freq) {
11022                 long freq = event->attr.sample_freq;
11023
11024                 event->attr.sample_period = NSEC_PER_SEC / freq;
11025                 hwc->sample_period = event->attr.sample_period;
11026                 local64_set(&hwc->period_left, hwc->sample_period);
11027                 hwc->last_period = hwc->sample_period;
11028                 event->attr.freq = 0;
11029         }
11030 }
11031
11032 /*
11033  * Software event: cpu wall time clock
11034  */
11035
11036 static void cpu_clock_event_update(struct perf_event *event)
11037 {
11038         s64 prev;
11039         u64 now;
11040
11041         now = local_clock();
11042         prev = local64_xchg(&event->hw.prev_count, now);
11043         local64_add(now - prev, &event->count);
11044 }
11045
11046 static void cpu_clock_event_start(struct perf_event *event, int flags)
11047 {
11048         local64_set(&event->hw.prev_count, local_clock());
11049         perf_swevent_start_hrtimer(event);
11050 }
11051
11052 static void cpu_clock_event_stop(struct perf_event *event, int flags)
11053 {
11054         perf_swevent_cancel_hrtimer(event);
11055         cpu_clock_event_update(event);
11056 }
11057
11058 static int cpu_clock_event_add(struct perf_event *event, int flags)
11059 {
11060         if (flags & PERF_EF_START)
11061                 cpu_clock_event_start(event, flags);
11062         perf_event_update_userpage(event);
11063
11064         return 0;
11065 }
11066
11067 static void cpu_clock_event_del(struct perf_event *event, int flags)
11068 {
11069         cpu_clock_event_stop(event, flags);
11070 }
11071
11072 static void cpu_clock_event_read(struct perf_event *event)
11073 {
11074         cpu_clock_event_update(event);
11075 }
11076
11077 static int cpu_clock_event_init(struct perf_event *event)
11078 {
11079         if (event->attr.type != PERF_TYPE_SOFTWARE)
11080                 return -ENOENT;
11081
11082         if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
11083                 return -ENOENT;
11084
11085         /*
11086          * no branch sampling for software events
11087          */
11088         if (has_branch_stack(event))
11089                 return -EOPNOTSUPP;
11090
11091         perf_swevent_init_hrtimer(event);
11092
11093         return 0;
11094 }
11095
11096 static struct pmu perf_cpu_clock = {
11097         .task_ctx_nr    = perf_sw_context,
11098
11099         .capabilities   = PERF_PMU_CAP_NO_NMI,
11100
11101         .event_init     = cpu_clock_event_init,
11102         .add            = cpu_clock_event_add,
11103         .del            = cpu_clock_event_del,
11104         .start          = cpu_clock_event_start,
11105         .stop           = cpu_clock_event_stop,
11106         .read           = cpu_clock_event_read,
11107 };
11108
11109 /*
11110  * Software event: task time clock
11111  */
11112
11113 static void task_clock_event_update(struct perf_event *event, u64 now)
11114 {
11115         u64 prev;
11116         s64 delta;
11117
11118         prev = local64_xchg(&event->hw.prev_count, now);
11119         delta = now - prev;
11120         local64_add(delta, &event->count);
11121 }
11122
11123 static void task_clock_event_start(struct perf_event *event, int flags)
11124 {
11125         local64_set(&event->hw.prev_count, event->ctx->time);
11126         perf_swevent_start_hrtimer(event);
11127 }
11128
11129 static void task_clock_event_stop(struct perf_event *event, int flags)
11130 {
11131         perf_swevent_cancel_hrtimer(event);
11132         task_clock_event_update(event, event->ctx->time);
11133 }
11134
11135 static int task_clock_event_add(struct perf_event *event, int flags)
11136 {
11137         if (flags & PERF_EF_START)
11138                 task_clock_event_start(event, flags);
11139         perf_event_update_userpage(event);
11140
11141         return 0;
11142 }
11143
11144 static void task_clock_event_del(struct perf_event *event, int flags)
11145 {
11146         task_clock_event_stop(event, PERF_EF_UPDATE);
11147 }
11148
11149 static void task_clock_event_read(struct perf_event *event)
11150 {
11151         u64 now = perf_clock();
11152         u64 delta = now - event->ctx->timestamp;
11153         u64 time = event->ctx->time + delta;
11154
11155         task_clock_event_update(event, time);
11156 }
11157
11158 static int task_clock_event_init(struct perf_event *event)
11159 {
11160         if (event->attr.type != PERF_TYPE_SOFTWARE)
11161                 return -ENOENT;
11162
11163         if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
11164                 return -ENOENT;
11165
11166         /*
11167          * no branch sampling for software events
11168          */
11169         if (has_branch_stack(event))
11170                 return -EOPNOTSUPP;
11171
11172         perf_swevent_init_hrtimer(event);
11173
11174         return 0;
11175 }
11176
11177 static struct pmu perf_task_clock = {
11178         .task_ctx_nr    = perf_sw_context,
11179
11180         .capabilities   = PERF_PMU_CAP_NO_NMI,
11181
11182         .event_init     = task_clock_event_init,
11183         .add            = task_clock_event_add,
11184         .del            = task_clock_event_del,
11185         .start          = task_clock_event_start,
11186         .stop           = task_clock_event_stop,
11187         .read           = task_clock_event_read,
11188 };
11189
11190 static void perf_pmu_nop_void(struct pmu *pmu)
11191 {
11192 }
11193
11194 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
11195 {
11196 }
11197
11198 static int perf_pmu_nop_int(struct pmu *pmu)
11199 {
11200         return 0;
11201 }
11202
11203 static int perf_event_nop_int(struct perf_event *event, u64 value)
11204 {
11205         return 0;
11206 }
11207
11208 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
11209
11210 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
11211 {
11212         __this_cpu_write(nop_txn_flags, flags);
11213
11214         if (flags & ~PERF_PMU_TXN_ADD)
11215                 return;
11216
11217         perf_pmu_disable(pmu);
11218 }
11219
11220 static int perf_pmu_commit_txn(struct pmu *pmu)
11221 {
11222         unsigned int flags = __this_cpu_read(nop_txn_flags);
11223
11224         __this_cpu_write(nop_txn_flags, 0);
11225
11226         if (flags & ~PERF_PMU_TXN_ADD)
11227                 return 0;
11228
11229         perf_pmu_enable(pmu);
11230         return 0;
11231 }
11232
11233 static void perf_pmu_cancel_txn(struct pmu *pmu)
11234 {
11235         unsigned int flags =  __this_cpu_read(nop_txn_flags);
11236
11237         __this_cpu_write(nop_txn_flags, 0);
11238
11239         if (flags & ~PERF_PMU_TXN_ADD)
11240                 return;
11241
11242         perf_pmu_enable(pmu);
11243 }
11244
11245 static int perf_event_idx_default(struct perf_event *event)
11246 {
11247         return 0;
11248 }
11249
11250 static void free_pmu_context(struct pmu *pmu)
11251 {
11252         free_percpu(pmu->cpu_pmu_context);
11253 }
11254
11255 /*
11256  * Let userspace know that this PMU supports address range filtering:
11257  */
11258 static ssize_t nr_addr_filters_show(struct device *dev,
11259                                     struct device_attribute *attr,
11260                                     char *page)
11261 {
11262         struct pmu *pmu = dev_get_drvdata(dev);
11263
11264         return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
11265 }
11266 DEVICE_ATTR_RO(nr_addr_filters);
11267
11268 static struct idr pmu_idr;
11269
11270 static ssize_t
11271 type_show(struct device *dev, struct device_attribute *attr, char *page)
11272 {
11273         struct pmu *pmu = dev_get_drvdata(dev);
11274
11275         return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->type);
11276 }
11277 static DEVICE_ATTR_RO(type);
11278
11279 static ssize_t
11280 perf_event_mux_interval_ms_show(struct device *dev,
11281                                 struct device_attribute *attr,
11282                                 char *page)
11283 {
11284         struct pmu *pmu = dev_get_drvdata(dev);
11285
11286         return scnprintf(page, PAGE_SIZE - 1, "%d\n", pmu->hrtimer_interval_ms);
11287 }
11288
11289 static DEFINE_MUTEX(mux_interval_mutex);
11290
11291 static ssize_t
11292 perf_event_mux_interval_ms_store(struct device *dev,
11293                                  struct device_attribute *attr,
11294                                  const char *buf, size_t count)
11295 {
11296         struct pmu *pmu = dev_get_drvdata(dev);
11297         int timer, cpu, ret;
11298
11299         ret = kstrtoint(buf, 0, &timer);
11300         if (ret)
11301                 return ret;
11302
11303         if (timer < 1)
11304                 return -EINVAL;
11305
11306         /* same value, noting to do */
11307         if (timer == pmu->hrtimer_interval_ms)
11308                 return count;
11309
11310         mutex_lock(&mux_interval_mutex);
11311         pmu->hrtimer_interval_ms = timer;
11312
11313         /* update all cpuctx for this PMU */
11314         cpus_read_lock();
11315         for_each_online_cpu(cpu) {
11316                 struct perf_cpu_pmu_context *cpc;
11317                 cpc = per_cpu_ptr(pmu->cpu_pmu_context, cpu);
11318                 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
11319
11320                 cpu_function_call(cpu, perf_mux_hrtimer_restart_ipi, cpc);
11321         }
11322         cpus_read_unlock();
11323         mutex_unlock(&mux_interval_mutex);
11324
11325         return count;
11326 }
11327 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
11328
11329 static struct attribute *pmu_dev_attrs[] = {
11330         &dev_attr_type.attr,
11331         &dev_attr_perf_event_mux_interval_ms.attr,
11332         NULL,
11333 };
11334 ATTRIBUTE_GROUPS(pmu_dev);
11335
11336 static int pmu_bus_running;
11337 static struct bus_type pmu_bus = {
11338         .name           = "event_source",
11339         .dev_groups     = pmu_dev_groups,
11340 };
11341
11342 static void pmu_dev_release(struct device *dev)
11343 {
11344         kfree(dev);
11345 }
11346
11347 static int pmu_dev_alloc(struct pmu *pmu)
11348 {
11349         int ret = -ENOMEM;
11350
11351         pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
11352         if (!pmu->dev)
11353                 goto out;
11354
11355         pmu->dev->groups = pmu->attr_groups;
11356         device_initialize(pmu->dev);
11357
11358         dev_set_drvdata(pmu->dev, pmu);
11359         pmu->dev->bus = &pmu_bus;
11360         pmu->dev->release = pmu_dev_release;
11361
11362         ret = dev_set_name(pmu->dev, "%s", pmu->name);
11363         if (ret)
11364                 goto free_dev;
11365
11366         ret = device_add(pmu->dev);
11367         if (ret)
11368                 goto free_dev;
11369
11370         /* For PMUs with address filters, throw in an extra attribute: */
11371         if (pmu->nr_addr_filters)
11372                 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
11373
11374         if (ret)
11375                 goto del_dev;
11376
11377         if (pmu->attr_update)
11378                 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
11379
11380         if (ret)
11381                 goto del_dev;
11382
11383 out:
11384         return ret;
11385
11386 del_dev:
11387         device_del(pmu->dev);
11388
11389 free_dev:
11390         put_device(pmu->dev);
11391         goto out;
11392 }
11393
11394 static struct lock_class_key cpuctx_mutex;
11395 static struct lock_class_key cpuctx_lock;
11396
11397 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
11398 {
11399         int cpu, ret, max = PERF_TYPE_MAX;
11400
11401         mutex_lock(&pmus_lock);
11402         ret = -ENOMEM;
11403         pmu->pmu_disable_count = alloc_percpu(int);
11404         if (!pmu->pmu_disable_count)
11405                 goto unlock;
11406
11407         pmu->type = -1;
11408         if (!name)
11409                 goto skip_type;
11410         pmu->name = name;
11411
11412         if (type != PERF_TYPE_SOFTWARE) {
11413                 if (type >= 0)
11414                         max = type;
11415
11416                 ret = idr_alloc(&pmu_idr, pmu, max, 0, GFP_KERNEL);
11417                 if (ret < 0)
11418                         goto free_pdc;
11419
11420                 WARN_ON(type >= 0 && ret != type);
11421
11422                 type = ret;
11423         }
11424         pmu->type = type;
11425
11426         if (pmu_bus_running) {
11427                 ret = pmu_dev_alloc(pmu);
11428                 if (ret)
11429                         goto free_idr;
11430         }
11431
11432 skip_type:
11433         ret = -ENOMEM;
11434         pmu->cpu_pmu_context = alloc_percpu(struct perf_cpu_pmu_context);
11435         if (!pmu->cpu_pmu_context)
11436                 goto free_dev;
11437
11438         for_each_possible_cpu(cpu) {
11439                 struct perf_cpu_pmu_context *cpc;
11440
11441                 cpc = per_cpu_ptr(pmu->cpu_pmu_context, cpu);
11442                 __perf_init_event_pmu_context(&cpc->epc, pmu);
11443                 __perf_mux_hrtimer_init(cpc, cpu);
11444         }
11445
11446         if (!pmu->start_txn) {
11447                 if (pmu->pmu_enable) {
11448                         /*
11449                          * If we have pmu_enable/pmu_disable calls, install
11450                          * transaction stubs that use that to try and batch
11451                          * hardware accesses.
11452                          */
11453                         pmu->start_txn  = perf_pmu_start_txn;
11454                         pmu->commit_txn = perf_pmu_commit_txn;
11455                         pmu->cancel_txn = perf_pmu_cancel_txn;
11456                 } else {
11457                         pmu->start_txn  = perf_pmu_nop_txn;
11458                         pmu->commit_txn = perf_pmu_nop_int;
11459                         pmu->cancel_txn = perf_pmu_nop_void;
11460                 }
11461         }
11462
11463         if (!pmu->pmu_enable) {
11464                 pmu->pmu_enable  = perf_pmu_nop_void;
11465                 pmu->pmu_disable = perf_pmu_nop_void;
11466         }
11467
11468         if (!pmu->check_period)
11469                 pmu->check_period = perf_event_nop_int;
11470
11471         if (!pmu->event_idx)
11472                 pmu->event_idx = perf_event_idx_default;
11473
11474         /*
11475          * Ensure the TYPE_SOFTWARE PMUs are at the head of the list,
11476          * since these cannot be in the IDR. This way the linear search
11477          * is fast, provided a valid software event is provided.
11478          */
11479         if (type == PERF_TYPE_SOFTWARE || !name)
11480                 list_add_rcu(&pmu->entry, &pmus);
11481         else
11482                 list_add_tail_rcu(&pmu->entry, &pmus);
11483
11484         atomic_set(&pmu->exclusive_cnt, 0);
11485         ret = 0;
11486 unlock:
11487         mutex_unlock(&pmus_lock);
11488
11489         return ret;
11490
11491 free_dev:
11492         device_del(pmu->dev);
11493         put_device(pmu->dev);
11494
11495 free_idr:
11496         if (pmu->type != PERF_TYPE_SOFTWARE)
11497                 idr_remove(&pmu_idr, pmu->type);
11498
11499 free_pdc:
11500         free_percpu(pmu->pmu_disable_count);
11501         goto unlock;
11502 }
11503 EXPORT_SYMBOL_GPL(perf_pmu_register);
11504
11505 void perf_pmu_unregister(struct pmu *pmu)
11506 {
11507         mutex_lock(&pmus_lock);
11508         list_del_rcu(&pmu->entry);
11509
11510         /*
11511          * We dereference the pmu list under both SRCU and regular RCU, so
11512          * synchronize against both of those.
11513          */
11514         synchronize_srcu(&pmus_srcu);
11515         synchronize_rcu();
11516
11517         free_percpu(pmu->pmu_disable_count);
11518         if (pmu->type != PERF_TYPE_SOFTWARE)
11519                 idr_remove(&pmu_idr, pmu->type);
11520         if (pmu_bus_running) {
11521                 if (pmu->nr_addr_filters)
11522                         device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
11523                 device_del(pmu->dev);
11524                 put_device(pmu->dev);
11525         }
11526         free_pmu_context(pmu);
11527         mutex_unlock(&pmus_lock);
11528 }
11529 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
11530
11531 static inline bool has_extended_regs(struct perf_event *event)
11532 {
11533         return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
11534                (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
11535 }
11536
11537 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
11538 {
11539         struct perf_event_context *ctx = NULL;
11540         int ret;
11541
11542         if (!try_module_get(pmu->module))
11543                 return -ENODEV;
11544
11545         /*
11546          * A number of pmu->event_init() methods iterate the sibling_list to,
11547          * for example, validate if the group fits on the PMU. Therefore,
11548          * if this is a sibling event, acquire the ctx->mutex to protect
11549          * the sibling_list.
11550          */
11551         if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
11552                 /*
11553                  * This ctx->mutex can nest when we're called through
11554                  * inheritance. See the perf_event_ctx_lock_nested() comment.
11555                  */
11556                 ctx = perf_event_ctx_lock_nested(event->group_leader,
11557                                                  SINGLE_DEPTH_NESTING);
11558                 BUG_ON(!ctx);
11559         }
11560
11561         event->pmu = pmu;
11562         ret = pmu->event_init(event);
11563
11564         if (ctx)
11565                 perf_event_ctx_unlock(event->group_leader, ctx);
11566
11567         if (!ret) {
11568                 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
11569                     has_extended_regs(event))
11570                         ret = -EOPNOTSUPP;
11571
11572                 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
11573                     event_has_any_exclude_flag(event))
11574                         ret = -EINVAL;
11575
11576                 if (ret && event->destroy)
11577                         event->destroy(event);
11578         }
11579
11580         if (ret)
11581                 module_put(pmu->module);
11582
11583         return ret;
11584 }
11585
11586 static struct pmu *perf_init_event(struct perf_event *event)
11587 {
11588         bool extended_type = false;
11589         int idx, type, ret;
11590         struct pmu *pmu;
11591
11592         idx = srcu_read_lock(&pmus_srcu);
11593
11594         /* Try parent's PMU first: */
11595         if (event->parent && event->parent->pmu) {
11596                 pmu = event->parent->pmu;
11597                 ret = perf_try_init_event(pmu, event);
11598                 if (!ret)
11599                         goto unlock;
11600         }
11601
11602         /*
11603          * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
11604          * are often aliases for PERF_TYPE_RAW.
11605          */
11606         type = event->attr.type;
11607         if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE) {
11608                 type = event->attr.config >> PERF_PMU_TYPE_SHIFT;
11609                 if (!type) {
11610                         type = PERF_TYPE_RAW;
11611                 } else {
11612                         extended_type = true;
11613                         event->attr.config &= PERF_HW_EVENT_MASK;
11614                 }
11615         }
11616
11617 again:
11618         rcu_read_lock();
11619         pmu = idr_find(&pmu_idr, type);
11620         rcu_read_unlock();
11621         if (pmu) {
11622                 if (event->attr.type != type && type != PERF_TYPE_RAW &&
11623                     !(pmu->capabilities & PERF_PMU_CAP_EXTENDED_HW_TYPE))
11624                         goto fail;
11625
11626                 ret = perf_try_init_event(pmu, event);
11627                 if (ret == -ENOENT && event->attr.type != type && !extended_type) {
11628                         type = event->attr.type;
11629                         goto again;
11630                 }
11631
11632                 if (ret)
11633                         pmu = ERR_PTR(ret);
11634
11635                 goto unlock;
11636         }
11637
11638         list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
11639                 ret = perf_try_init_event(pmu, event);
11640                 if (!ret)
11641                         goto unlock;
11642
11643                 if (ret != -ENOENT) {
11644                         pmu = ERR_PTR(ret);
11645                         goto unlock;
11646                 }
11647         }
11648 fail:
11649         pmu = ERR_PTR(-ENOENT);
11650 unlock:
11651         srcu_read_unlock(&pmus_srcu, idx);
11652
11653         return pmu;
11654 }
11655
11656 static void attach_sb_event(struct perf_event *event)
11657 {
11658         struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
11659
11660         raw_spin_lock(&pel->lock);
11661         list_add_rcu(&event->sb_list, &pel->list);
11662         raw_spin_unlock(&pel->lock);
11663 }
11664
11665 /*
11666  * We keep a list of all !task (and therefore per-cpu) events
11667  * that need to receive side-band records.
11668  *
11669  * This avoids having to scan all the various PMU per-cpu contexts
11670  * looking for them.
11671  */
11672 static void account_pmu_sb_event(struct perf_event *event)
11673 {
11674         if (is_sb_event(event))
11675                 attach_sb_event(event);
11676 }
11677
11678 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
11679 static void account_freq_event_nohz(void)
11680 {
11681 #ifdef CONFIG_NO_HZ_FULL
11682         /* Lock so we don't race with concurrent unaccount */
11683         spin_lock(&nr_freq_lock);
11684         if (atomic_inc_return(&nr_freq_events) == 1)
11685                 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
11686         spin_unlock(&nr_freq_lock);
11687 #endif
11688 }
11689
11690 static void account_freq_event(void)
11691 {
11692         if (tick_nohz_full_enabled())
11693                 account_freq_event_nohz();
11694         else
11695                 atomic_inc(&nr_freq_events);
11696 }
11697
11698
11699 static void account_event(struct perf_event *event)
11700 {
11701         bool inc = false;
11702
11703         if (event->parent)
11704                 return;
11705
11706         if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
11707                 inc = true;
11708         if (event->attr.mmap || event->attr.mmap_data)
11709                 atomic_inc(&nr_mmap_events);
11710         if (event->attr.build_id)
11711                 atomic_inc(&nr_build_id_events);
11712         if (event->attr.comm)
11713                 atomic_inc(&nr_comm_events);
11714         if (event->attr.namespaces)
11715                 atomic_inc(&nr_namespaces_events);
11716         if (event->attr.cgroup)
11717                 atomic_inc(&nr_cgroup_events);
11718         if (event->attr.task)
11719                 atomic_inc(&nr_task_events);
11720         if (event->attr.freq)
11721                 account_freq_event();
11722         if (event->attr.context_switch) {
11723                 atomic_inc(&nr_switch_events);
11724                 inc = true;
11725         }
11726         if (has_branch_stack(event))
11727                 inc = true;
11728         if (is_cgroup_event(event))
11729                 inc = true;
11730         if (event->attr.ksymbol)
11731                 atomic_inc(&nr_ksymbol_events);
11732         if (event->attr.bpf_event)
11733                 atomic_inc(&nr_bpf_events);
11734         if (event->attr.text_poke)
11735                 atomic_inc(&nr_text_poke_events);
11736
11737         if (inc) {
11738                 /*
11739                  * We need the mutex here because static_branch_enable()
11740                  * must complete *before* the perf_sched_count increment
11741                  * becomes visible.
11742                  */
11743                 if (atomic_inc_not_zero(&perf_sched_count))
11744                         goto enabled;
11745
11746                 mutex_lock(&perf_sched_mutex);
11747                 if (!atomic_read(&perf_sched_count)) {
11748                         static_branch_enable(&perf_sched_events);
11749                         /*
11750                          * Guarantee that all CPUs observe they key change and
11751                          * call the perf scheduling hooks before proceeding to
11752                          * install events that need them.
11753                          */
11754                         synchronize_rcu();
11755                 }
11756                 /*
11757                  * Now that we have waited for the sync_sched(), allow further
11758                  * increments to by-pass the mutex.
11759                  */
11760                 atomic_inc(&perf_sched_count);
11761                 mutex_unlock(&perf_sched_mutex);
11762         }
11763 enabled:
11764
11765         account_pmu_sb_event(event);
11766 }
11767
11768 /*
11769  * Allocate and initialize an event structure
11770  */
11771 static struct perf_event *
11772 perf_event_alloc(struct perf_event_attr *attr, int cpu,
11773                  struct task_struct *task,
11774                  struct perf_event *group_leader,
11775                  struct perf_event *parent_event,
11776                  perf_overflow_handler_t overflow_handler,
11777                  void *context, int cgroup_fd)
11778 {
11779         struct pmu *pmu;
11780         struct perf_event *event;
11781         struct hw_perf_event *hwc;
11782         long err = -EINVAL;
11783         int node;
11784
11785         if ((unsigned)cpu >= nr_cpu_ids) {
11786                 if (!task || cpu != -1)
11787                         return ERR_PTR(-EINVAL);
11788         }
11789         if (attr->sigtrap && !task) {
11790                 /* Requires a task: avoid signalling random tasks. */
11791                 return ERR_PTR(-EINVAL);
11792         }
11793
11794         node = (cpu >= 0) ? cpu_to_node(cpu) : -1;
11795         event = kmem_cache_alloc_node(perf_event_cache, GFP_KERNEL | __GFP_ZERO,
11796                                       node);
11797         if (!event)
11798                 return ERR_PTR(-ENOMEM);
11799
11800         /*
11801          * Single events are their own group leaders, with an
11802          * empty sibling list:
11803          */
11804         if (!group_leader)
11805                 group_leader = event;
11806
11807         mutex_init(&event->child_mutex);
11808         INIT_LIST_HEAD(&event->child_list);
11809
11810         INIT_LIST_HEAD(&event->event_entry);
11811         INIT_LIST_HEAD(&event->sibling_list);
11812         INIT_LIST_HEAD(&event->active_list);
11813         init_event_group(event);
11814         INIT_LIST_HEAD(&event->rb_entry);
11815         INIT_LIST_HEAD(&event->active_entry);
11816         INIT_LIST_HEAD(&event->addr_filters.list);
11817         INIT_HLIST_NODE(&event->hlist_entry);
11818
11819
11820         init_waitqueue_head(&event->waitq);
11821         init_irq_work(&event->pending_irq, perf_pending_irq);
11822         init_task_work(&event->pending_task, perf_pending_task);
11823
11824         mutex_init(&event->mmap_mutex);
11825         raw_spin_lock_init(&event->addr_filters.lock);
11826
11827         atomic_long_set(&event->refcount, 1);
11828         event->cpu              = cpu;
11829         event->attr             = *attr;
11830         event->group_leader     = group_leader;
11831         event->pmu              = NULL;
11832         event->oncpu            = -1;
11833
11834         event->parent           = parent_event;
11835
11836         event->ns               = get_pid_ns(task_active_pid_ns(current));
11837         event->id               = atomic64_inc_return(&perf_event_id);
11838
11839         event->state            = PERF_EVENT_STATE_INACTIVE;
11840
11841         if (parent_event)
11842                 event->event_caps = parent_event->event_caps;
11843
11844         if (task) {
11845                 event->attach_state = PERF_ATTACH_TASK;
11846                 /*
11847                  * XXX pmu::event_init needs to know what task to account to
11848                  * and we cannot use the ctx information because we need the
11849                  * pmu before we get a ctx.
11850                  */
11851                 event->hw.target = get_task_struct(task);
11852         }
11853
11854         event->clock = &local_clock;
11855         if (parent_event)
11856                 event->clock = parent_event->clock;
11857
11858         if (!overflow_handler && parent_event) {
11859                 overflow_handler = parent_event->overflow_handler;
11860                 context = parent_event->overflow_handler_context;
11861 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
11862                 if (overflow_handler == bpf_overflow_handler) {
11863                         struct bpf_prog *prog = parent_event->prog;
11864
11865                         bpf_prog_inc(prog);
11866                         event->prog = prog;
11867                         event->orig_overflow_handler =
11868                                 parent_event->orig_overflow_handler;
11869                 }
11870 #endif
11871         }
11872
11873         if (overflow_handler) {
11874                 event->overflow_handler = overflow_handler;
11875                 event->overflow_handler_context = context;
11876         } else if (is_write_backward(event)){
11877                 event->overflow_handler = perf_event_output_backward;
11878                 event->overflow_handler_context = NULL;
11879         } else {
11880                 event->overflow_handler = perf_event_output_forward;
11881                 event->overflow_handler_context = NULL;
11882         }
11883
11884         perf_event__state_init(event);
11885
11886         pmu = NULL;
11887
11888         hwc = &event->hw;
11889         hwc->sample_period = attr->sample_period;
11890         if (attr->freq && attr->sample_freq)
11891                 hwc->sample_period = 1;
11892         hwc->last_period = hwc->sample_period;
11893
11894         local64_set(&hwc->period_left, hwc->sample_period);
11895
11896         /*
11897          * We currently do not support PERF_SAMPLE_READ on inherited events.
11898          * See perf_output_read().
11899          */
11900         if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
11901                 goto err_ns;
11902
11903         if (!has_branch_stack(event))
11904                 event->attr.branch_sample_type = 0;
11905
11906         pmu = perf_init_event(event);
11907         if (IS_ERR(pmu)) {
11908                 err = PTR_ERR(pmu);
11909                 goto err_ns;
11910         }
11911
11912         /*
11913          * Disallow uncore-task events. Similarly, disallow uncore-cgroup
11914          * events (they don't make sense as the cgroup will be different
11915          * on other CPUs in the uncore mask).
11916          */
11917         if (pmu->task_ctx_nr == perf_invalid_context && (task || cgroup_fd != -1)) {
11918                 err = -EINVAL;
11919                 goto err_pmu;
11920         }
11921
11922         if (event->attr.aux_output &&
11923             !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) {
11924                 err = -EOPNOTSUPP;
11925                 goto err_pmu;
11926         }
11927
11928         if (cgroup_fd != -1) {
11929                 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
11930                 if (err)
11931                         goto err_pmu;
11932         }
11933
11934         err = exclusive_event_init(event);
11935         if (err)
11936                 goto err_pmu;
11937
11938         if (has_addr_filter(event)) {
11939                 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
11940                                                     sizeof(struct perf_addr_filter_range),
11941                                                     GFP_KERNEL);
11942                 if (!event->addr_filter_ranges) {
11943                         err = -ENOMEM;
11944                         goto err_per_task;
11945                 }
11946
11947                 /*
11948                  * Clone the parent's vma offsets: they are valid until exec()
11949                  * even if the mm is not shared with the parent.
11950                  */
11951                 if (event->parent) {
11952                         struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11953
11954                         raw_spin_lock_irq(&ifh->lock);
11955                         memcpy(event->addr_filter_ranges,
11956                                event->parent->addr_filter_ranges,
11957                                pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
11958                         raw_spin_unlock_irq(&ifh->lock);
11959                 }
11960
11961                 /* force hw sync on the address filters */
11962                 event->addr_filters_gen = 1;
11963         }
11964
11965         if (!event->parent) {
11966                 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
11967                         err = get_callchain_buffers(attr->sample_max_stack);
11968                         if (err)
11969                                 goto err_addr_filters;
11970                 }
11971         }
11972
11973         err = security_perf_event_alloc(event);
11974         if (err)
11975                 goto err_callchain_buffer;
11976
11977         /* symmetric to unaccount_event() in _free_event() */
11978         account_event(event);
11979
11980         return event;
11981
11982 err_callchain_buffer:
11983         if (!event->parent) {
11984                 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
11985                         put_callchain_buffers();
11986         }
11987 err_addr_filters:
11988         kfree(event->addr_filter_ranges);
11989
11990 err_per_task:
11991         exclusive_event_destroy(event);
11992
11993 err_pmu:
11994         if (is_cgroup_event(event))
11995                 perf_detach_cgroup(event);
11996         if (event->destroy)
11997                 event->destroy(event);
11998         module_put(pmu->module);
11999 err_ns:
12000         if (event->hw.target)
12001                 put_task_struct(event->hw.target);
12002         call_rcu(&event->rcu_head, free_event_rcu);
12003
12004         return ERR_PTR(err);
12005 }
12006
12007 static int perf_copy_attr(struct perf_event_attr __user *uattr,
12008                           struct perf_event_attr *attr)
12009 {
12010         u32 size;
12011         int ret;
12012
12013         /* Zero the full structure, so that a short copy will be nice. */
12014         memset(attr, 0, sizeof(*attr));
12015
12016         ret = get_user(size, &uattr->size);
12017         if (ret)
12018                 return ret;
12019
12020         /* ABI compatibility quirk: */
12021         if (!size)
12022                 size = PERF_ATTR_SIZE_VER0;
12023         if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
12024                 goto err_size;
12025
12026         ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
12027         if (ret) {
12028                 if (ret == -E2BIG)
12029                         goto err_size;
12030                 return ret;
12031         }
12032
12033         attr->size = size;
12034
12035         if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
12036                 return -EINVAL;
12037
12038         if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
12039                 return -EINVAL;
12040
12041         if (attr->read_format & ~(PERF_FORMAT_MAX-1))
12042                 return -EINVAL;
12043
12044         if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
12045                 u64 mask = attr->branch_sample_type;
12046
12047                 /* only using defined bits */
12048                 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
12049                         return -EINVAL;
12050
12051                 /* at least one branch bit must be set */
12052                 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
12053                         return -EINVAL;
12054
12055                 /* propagate priv level, when not set for branch */
12056                 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
12057
12058                         /* exclude_kernel checked on syscall entry */
12059                         if (!attr->exclude_kernel)
12060                                 mask |= PERF_SAMPLE_BRANCH_KERNEL;
12061
12062                         if (!attr->exclude_user)
12063                                 mask |= PERF_SAMPLE_BRANCH_USER;
12064
12065                         if (!attr->exclude_hv)
12066                                 mask |= PERF_SAMPLE_BRANCH_HV;
12067                         /*
12068                          * adjust user setting (for HW filter setup)
12069                          */
12070                         attr->branch_sample_type = mask;
12071                 }
12072                 /* privileged levels capture (kernel, hv): check permissions */
12073                 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
12074                         ret = perf_allow_kernel(attr);
12075                         if (ret)
12076                                 return ret;
12077                 }
12078         }
12079
12080         if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
12081                 ret = perf_reg_validate(attr->sample_regs_user);
12082                 if (ret)
12083                         return ret;
12084         }
12085
12086         if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
12087                 if (!arch_perf_have_user_stack_dump())
12088                         return -ENOSYS;
12089
12090                 /*
12091                  * We have __u32 type for the size, but so far
12092                  * we can only use __u16 as maximum due to the
12093                  * __u16 sample size limit.
12094                  */
12095                 if (attr->sample_stack_user >= USHRT_MAX)
12096                         return -EINVAL;
12097                 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
12098                         return -EINVAL;
12099         }
12100
12101         if (!attr->sample_max_stack)
12102                 attr->sample_max_stack = sysctl_perf_event_max_stack;
12103
12104         if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
12105                 ret = perf_reg_validate(attr->sample_regs_intr);
12106
12107 #ifndef CONFIG_CGROUP_PERF
12108         if (attr->sample_type & PERF_SAMPLE_CGROUP)
12109                 return -EINVAL;
12110 #endif
12111         if ((attr->sample_type & PERF_SAMPLE_WEIGHT) &&
12112             (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT))
12113                 return -EINVAL;
12114
12115         if (!attr->inherit && attr->inherit_thread)
12116                 return -EINVAL;
12117
12118         if (attr->remove_on_exec && attr->enable_on_exec)
12119                 return -EINVAL;
12120
12121         if (attr->sigtrap && !attr->remove_on_exec)
12122                 return -EINVAL;
12123
12124 out:
12125         return ret;
12126
12127 err_size:
12128         put_user(sizeof(*attr), &uattr->size);
12129         ret = -E2BIG;
12130         goto out;
12131 }
12132
12133 static void mutex_lock_double(struct mutex *a, struct mutex *b)
12134 {
12135         if (b < a)
12136                 swap(a, b);
12137
12138         mutex_lock(a);
12139         mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
12140 }
12141
12142 static int
12143 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
12144 {
12145         struct perf_buffer *rb = NULL;
12146         int ret = -EINVAL;
12147
12148         if (!output_event) {
12149                 mutex_lock(&event->mmap_mutex);
12150                 goto set;
12151         }
12152
12153         /* don't allow circular references */
12154         if (event == output_event)
12155                 goto out;
12156
12157         /*
12158          * Don't allow cross-cpu buffers
12159          */
12160         if (output_event->cpu != event->cpu)
12161                 goto out;
12162
12163         /*
12164          * If its not a per-cpu rb, it must be the same task.
12165          */
12166         if (output_event->cpu == -1 && output_event->ctx != event->ctx)
12167                 goto out;
12168
12169         /*
12170          * Mixing clocks in the same buffer is trouble you don't need.
12171          */
12172         if (output_event->clock != event->clock)
12173                 goto out;
12174
12175         /*
12176          * Either writing ring buffer from beginning or from end.
12177          * Mixing is not allowed.
12178          */
12179         if (is_write_backward(output_event) != is_write_backward(event))
12180                 goto out;
12181
12182         /*
12183          * If both events generate aux data, they must be on the same PMU
12184          */
12185         if (has_aux(event) && has_aux(output_event) &&
12186             event->pmu != output_event->pmu)
12187                 goto out;
12188
12189         /*
12190          * Hold both mmap_mutex to serialize against perf_mmap_close().  Since
12191          * output_event is already on rb->event_list, and the list iteration
12192          * restarts after every removal, it is guaranteed this new event is
12193          * observed *OR* if output_event is already removed, it's guaranteed we
12194          * observe !rb->mmap_count.
12195          */
12196         mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex);
12197 set:
12198         /* Can't redirect output if we've got an active mmap() */
12199         if (atomic_read(&event->mmap_count))
12200                 goto unlock;
12201
12202         if (output_event) {
12203                 /* get the rb we want to redirect to */
12204                 rb = ring_buffer_get(output_event);
12205                 if (!rb)
12206                         goto unlock;
12207
12208                 /* did we race against perf_mmap_close() */
12209                 if (!atomic_read(&rb->mmap_count)) {
12210                         ring_buffer_put(rb);
12211                         goto unlock;
12212                 }
12213         }
12214
12215         ring_buffer_attach(event, rb);
12216
12217         ret = 0;
12218 unlock:
12219         mutex_unlock(&event->mmap_mutex);
12220         if (output_event)
12221                 mutex_unlock(&output_event->mmap_mutex);
12222
12223 out:
12224         return ret;
12225 }
12226
12227 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
12228 {
12229         bool nmi_safe = false;
12230
12231         switch (clk_id) {
12232         case CLOCK_MONOTONIC:
12233                 event->clock = &ktime_get_mono_fast_ns;
12234                 nmi_safe = true;
12235                 break;
12236
12237         case CLOCK_MONOTONIC_RAW:
12238                 event->clock = &ktime_get_raw_fast_ns;
12239                 nmi_safe = true;
12240                 break;
12241
12242         case CLOCK_REALTIME:
12243                 event->clock = &ktime_get_real_ns;
12244                 break;
12245
12246         case CLOCK_BOOTTIME:
12247                 event->clock = &ktime_get_boottime_ns;
12248                 break;
12249
12250         case CLOCK_TAI:
12251                 event->clock = &ktime_get_clocktai_ns;
12252                 break;
12253
12254         default:
12255                 return -EINVAL;
12256         }
12257
12258         if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
12259                 return -EINVAL;
12260
12261         return 0;
12262 }
12263
12264 static bool
12265 perf_check_permission(struct perf_event_attr *attr, struct task_struct *task)
12266 {
12267         unsigned int ptrace_mode = PTRACE_MODE_READ_REALCREDS;
12268         bool is_capable = perfmon_capable();
12269
12270         if (attr->sigtrap) {
12271                 /*
12272                  * perf_event_attr::sigtrap sends signals to the other task.
12273                  * Require the current task to also have CAP_KILL.
12274                  */
12275                 rcu_read_lock();
12276                 is_capable &= ns_capable(__task_cred(task)->user_ns, CAP_KILL);
12277                 rcu_read_unlock();
12278
12279                 /*
12280                  * If the required capabilities aren't available, checks for
12281                  * ptrace permissions: upgrade to ATTACH, since sending signals
12282                  * can effectively change the target task.
12283                  */
12284                 ptrace_mode = PTRACE_MODE_ATTACH_REALCREDS;
12285         }
12286
12287         /*
12288          * Preserve ptrace permission check for backwards compatibility. The
12289          * ptrace check also includes checks that the current task and other
12290          * task have matching uids, and is therefore not done here explicitly.
12291          */
12292         return is_capable || ptrace_may_access(task, ptrace_mode);
12293 }
12294
12295 /**
12296  * sys_perf_event_open - open a performance event, associate it to a task/cpu
12297  *
12298  * @attr_uptr:  event_id type attributes for monitoring/sampling
12299  * @pid:                target pid
12300  * @cpu:                target cpu
12301  * @group_fd:           group leader event fd
12302  * @flags:              perf event open flags
12303  */
12304 SYSCALL_DEFINE5(perf_event_open,
12305                 struct perf_event_attr __user *, attr_uptr,
12306                 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
12307 {
12308         struct perf_event *group_leader = NULL, *output_event = NULL;
12309         struct perf_event_pmu_context *pmu_ctx;
12310         struct perf_event *event, *sibling;
12311         struct perf_event_attr attr;
12312         struct perf_event_context *ctx;
12313         struct file *event_file = NULL;
12314         struct fd group = {NULL, 0};
12315         struct task_struct *task = NULL;
12316         struct pmu *pmu;
12317         int event_fd;
12318         int move_group = 0;
12319         int err;
12320         int f_flags = O_RDWR;
12321         int cgroup_fd = -1;
12322
12323         /* for future expandability... */
12324         if (flags & ~PERF_FLAG_ALL)
12325                 return -EINVAL;
12326
12327         err = perf_copy_attr(attr_uptr, &attr);
12328         if (err)
12329                 return err;
12330
12331         /* Do we allow access to perf_event_open(2) ? */
12332         err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
12333         if (err)
12334                 return err;
12335
12336         if (!attr.exclude_kernel) {
12337                 err = perf_allow_kernel(&attr);
12338                 if (err)
12339                         return err;
12340         }
12341
12342         if (attr.namespaces) {
12343                 if (!perfmon_capable())
12344                         return -EACCES;
12345         }
12346
12347         if (attr.freq) {
12348                 if (attr.sample_freq > sysctl_perf_event_sample_rate)
12349                         return -EINVAL;
12350         } else {
12351                 if (attr.sample_period & (1ULL << 63))
12352                         return -EINVAL;
12353         }
12354
12355         /* Only privileged users can get physical addresses */
12356         if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
12357                 err = perf_allow_kernel(&attr);
12358                 if (err)
12359                         return err;
12360         }
12361
12362         /* REGS_INTR can leak data, lockdown must prevent this */
12363         if (attr.sample_type & PERF_SAMPLE_REGS_INTR) {
12364                 err = security_locked_down(LOCKDOWN_PERF);
12365                 if (err)
12366                         return err;
12367         }
12368
12369         /*
12370          * In cgroup mode, the pid argument is used to pass the fd
12371          * opened to the cgroup directory in cgroupfs. The cpu argument
12372          * designates the cpu on which to monitor threads from that
12373          * cgroup.
12374          */
12375         if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
12376                 return -EINVAL;
12377
12378         if (flags & PERF_FLAG_FD_CLOEXEC)
12379                 f_flags |= O_CLOEXEC;
12380
12381         event_fd = get_unused_fd_flags(f_flags);
12382         if (event_fd < 0)
12383                 return event_fd;
12384
12385         if (group_fd != -1) {
12386                 err = perf_fget_light(group_fd, &group);
12387                 if (err)
12388                         goto err_fd;
12389                 group_leader = group.file->private_data;
12390                 if (flags & PERF_FLAG_FD_OUTPUT)
12391                         output_event = group_leader;
12392                 if (flags & PERF_FLAG_FD_NO_GROUP)
12393                         group_leader = NULL;
12394         }
12395
12396         if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
12397                 task = find_lively_task_by_vpid(pid);
12398                 if (IS_ERR(task)) {
12399                         err = PTR_ERR(task);
12400                         goto err_group_fd;
12401                 }
12402         }
12403
12404         if (task && group_leader &&
12405             group_leader->attr.inherit != attr.inherit) {
12406                 err = -EINVAL;
12407                 goto err_task;
12408         }
12409
12410         if (flags & PERF_FLAG_PID_CGROUP)
12411                 cgroup_fd = pid;
12412
12413         event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
12414                                  NULL, NULL, cgroup_fd);
12415         if (IS_ERR(event)) {
12416                 err = PTR_ERR(event);
12417                 goto err_task;
12418         }
12419
12420         if (is_sampling_event(event)) {
12421                 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
12422                         err = -EOPNOTSUPP;
12423                         goto err_alloc;
12424                 }
12425         }
12426
12427         /*
12428          * Special case software events and allow them to be part of
12429          * any hardware group.
12430          */
12431         pmu = event->pmu;
12432
12433         if (attr.use_clockid) {
12434                 err = perf_event_set_clock(event, attr.clockid);
12435                 if (err)
12436                         goto err_alloc;
12437         }
12438
12439         if (pmu->task_ctx_nr == perf_sw_context)
12440                 event->event_caps |= PERF_EV_CAP_SOFTWARE;
12441
12442         if (task) {
12443                 err = down_read_interruptible(&task->signal->exec_update_lock);
12444                 if (err)
12445                         goto err_alloc;
12446
12447                 /*
12448                  * We must hold exec_update_lock across this and any potential
12449                  * perf_install_in_context() call for this new event to
12450                  * serialize against exec() altering our credentials (and the
12451                  * perf_event_exit_task() that could imply).
12452                  */
12453                 err = -EACCES;
12454                 if (!perf_check_permission(&attr, task))
12455                         goto err_cred;
12456         }
12457
12458         /*
12459          * Get the target context (task or percpu):
12460          */
12461         ctx = find_get_context(task, event);
12462         if (IS_ERR(ctx)) {
12463                 err = PTR_ERR(ctx);
12464                 goto err_cred;
12465         }
12466
12467         mutex_lock(&ctx->mutex);
12468
12469         if (ctx->task == TASK_TOMBSTONE) {
12470                 err = -ESRCH;
12471                 goto err_locked;
12472         }
12473
12474         if (!task) {
12475                 /*
12476                  * Check if the @cpu we're creating an event for is online.
12477                  *
12478                  * We use the perf_cpu_context::ctx::mutex to serialize against
12479                  * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12480                  */
12481                 struct perf_cpu_context *cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
12482
12483                 if (!cpuctx->online) {
12484                         err = -ENODEV;
12485                         goto err_locked;
12486                 }
12487         }
12488
12489         if (group_leader) {
12490                 err = -EINVAL;
12491
12492                 /*
12493                  * Do not allow a recursive hierarchy (this new sibling
12494                  * becoming part of another group-sibling):
12495                  */
12496                 if (group_leader->group_leader != group_leader)
12497                         goto err_locked;
12498
12499                 /* All events in a group should have the same clock */
12500                 if (group_leader->clock != event->clock)
12501                         goto err_locked;
12502
12503                 /*
12504                  * Make sure we're both events for the same CPU;
12505                  * grouping events for different CPUs is broken; since
12506                  * you can never concurrently schedule them anyhow.
12507                  */
12508                 if (group_leader->cpu != event->cpu)
12509                         goto err_locked;
12510
12511                 /*
12512                  * Make sure we're both on the same context; either task or cpu.
12513                  */
12514                 if (group_leader->ctx != ctx)
12515                         goto err_locked;
12516
12517                 /*
12518                  * Only a group leader can be exclusive or pinned
12519                  */
12520                 if (attr.exclusive || attr.pinned)
12521                         goto err_locked;
12522
12523                 if (is_software_event(event) &&
12524                     !in_software_context(group_leader)) {
12525                         /*
12526                          * If the event is a sw event, but the group_leader
12527                          * is on hw context.
12528                          *
12529                          * Allow the addition of software events to hw
12530                          * groups, this is safe because software events
12531                          * never fail to schedule.
12532                          *
12533                          * Note the comment that goes with struct
12534                          * perf_event_pmu_context.
12535                          */
12536                         pmu = group_leader->pmu_ctx->pmu;
12537                 } else if (!is_software_event(event)) {
12538                         if (is_software_event(group_leader) &&
12539                             (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
12540                                 /*
12541                                  * In case the group is a pure software group, and we
12542                                  * try to add a hardware event, move the whole group to
12543                                  * the hardware context.
12544                                  */
12545                                 move_group = 1;
12546                         }
12547
12548                         /* Don't allow group of multiple hw events from different pmus */
12549                         if (!in_software_context(group_leader) &&
12550                             group_leader->pmu_ctx->pmu != pmu)
12551                                 goto err_locked;
12552                 }
12553         }
12554
12555         /*
12556          * Now that we're certain of the pmu; find the pmu_ctx.
12557          */
12558         pmu_ctx = find_get_pmu_context(pmu, ctx, event);
12559         if (IS_ERR(pmu_ctx)) {
12560                 err = PTR_ERR(pmu_ctx);
12561                 goto err_locked;
12562         }
12563         event->pmu_ctx = pmu_ctx;
12564
12565         if (output_event) {
12566                 err = perf_event_set_output(event, output_event);
12567                 if (err)
12568                         goto err_context;
12569         }
12570
12571         if (!perf_event_validate_size(event)) {
12572                 err = -E2BIG;
12573                 goto err_context;
12574         }
12575
12576         if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
12577                 err = -EINVAL;
12578                 goto err_context;
12579         }
12580
12581         /*
12582          * Must be under the same ctx::mutex as perf_install_in_context(),
12583          * because we need to serialize with concurrent event creation.
12584          */
12585         if (!exclusive_event_installable(event, ctx)) {
12586                 err = -EBUSY;
12587                 goto err_context;
12588         }
12589
12590         WARN_ON_ONCE(ctx->parent_ctx);
12591
12592         event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags);
12593         if (IS_ERR(event_file)) {
12594                 err = PTR_ERR(event_file);
12595                 event_file = NULL;
12596                 goto err_context;
12597         }
12598
12599         /*
12600          * This is the point on no return; we cannot fail hereafter. This is
12601          * where we start modifying current state.
12602          */
12603
12604         if (move_group) {
12605                 perf_remove_from_context(group_leader, 0);
12606                 put_pmu_ctx(group_leader->pmu_ctx);
12607
12608                 for_each_sibling_event(sibling, group_leader) {
12609                         perf_remove_from_context(sibling, 0);
12610                         put_pmu_ctx(sibling->pmu_ctx);
12611                 }
12612
12613                 /*
12614                  * Install the group siblings before the group leader.
12615                  *
12616                  * Because a group leader will try and install the entire group
12617                  * (through the sibling list, which is still in-tact), we can
12618                  * end up with siblings installed in the wrong context.
12619                  *
12620                  * By installing siblings first we NO-OP because they're not
12621                  * reachable through the group lists.
12622                  */
12623                 for_each_sibling_event(sibling, group_leader) {
12624                         sibling->pmu_ctx = pmu_ctx;
12625                         get_pmu_ctx(pmu_ctx);
12626                         perf_event__state_init(sibling);
12627                         perf_install_in_context(ctx, sibling, sibling->cpu);
12628                 }
12629
12630                 /*
12631                  * Removing from the context ends up with disabled
12632                  * event. What we want here is event in the initial
12633                  * startup state, ready to be add into new context.
12634                  */
12635                 group_leader->pmu_ctx = pmu_ctx;
12636                 get_pmu_ctx(pmu_ctx);
12637                 perf_event__state_init(group_leader);
12638                 perf_install_in_context(ctx, group_leader, group_leader->cpu);
12639         }
12640
12641         /*
12642          * Precalculate sample_data sizes; do while holding ctx::mutex such
12643          * that we're serialized against further additions and before
12644          * perf_install_in_context() which is the point the event is active and
12645          * can use these values.
12646          */
12647         perf_event__header_size(event);
12648         perf_event__id_header_size(event);
12649
12650         event->owner = current;
12651
12652         perf_install_in_context(ctx, event, event->cpu);
12653         perf_unpin_context(ctx);
12654
12655         mutex_unlock(&ctx->mutex);
12656
12657         if (task) {
12658                 up_read(&task->signal->exec_update_lock);
12659                 put_task_struct(task);
12660         }
12661
12662         mutex_lock(&current->perf_event_mutex);
12663         list_add_tail(&event->owner_entry, &current->perf_event_list);
12664         mutex_unlock(&current->perf_event_mutex);
12665
12666         /*
12667          * Drop the reference on the group_event after placing the
12668          * new event on the sibling_list. This ensures destruction
12669          * of the group leader will find the pointer to itself in
12670          * perf_group_detach().
12671          */
12672         fdput(group);
12673         fd_install(event_fd, event_file);
12674         return event_fd;
12675
12676 err_context:
12677         put_pmu_ctx(event->pmu_ctx);
12678         event->pmu_ctx = NULL; /* _free_event() */
12679 err_locked:
12680         mutex_unlock(&ctx->mutex);
12681         perf_unpin_context(ctx);
12682         put_ctx(ctx);
12683 err_cred:
12684         if (task)
12685                 up_read(&task->signal->exec_update_lock);
12686 err_alloc:
12687         free_event(event);
12688 err_task:
12689         if (task)
12690                 put_task_struct(task);
12691 err_group_fd:
12692         fdput(group);
12693 err_fd:
12694         put_unused_fd(event_fd);
12695         return err;
12696 }
12697
12698 /**
12699  * perf_event_create_kernel_counter
12700  *
12701  * @attr: attributes of the counter to create
12702  * @cpu: cpu in which the counter is bound
12703  * @task: task to profile (NULL for percpu)
12704  * @overflow_handler: callback to trigger when we hit the event
12705  * @context: context data could be used in overflow_handler callback
12706  */
12707 struct perf_event *
12708 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
12709                                  struct task_struct *task,
12710                                  perf_overflow_handler_t overflow_handler,
12711                                  void *context)
12712 {
12713         struct perf_event_pmu_context *pmu_ctx;
12714         struct perf_event_context *ctx;
12715         struct perf_event *event;
12716         struct pmu *pmu;
12717         int err;
12718
12719         /*
12720          * Grouping is not supported for kernel events, neither is 'AUX',
12721          * make sure the caller's intentions are adjusted.
12722          */
12723         if (attr->aux_output)
12724                 return ERR_PTR(-EINVAL);
12725
12726         event = perf_event_alloc(attr, cpu, task, NULL, NULL,
12727                                  overflow_handler, context, -1);
12728         if (IS_ERR(event)) {
12729                 err = PTR_ERR(event);
12730                 goto err;
12731         }
12732
12733         /* Mark owner so we could distinguish it from user events. */
12734         event->owner = TASK_TOMBSTONE;
12735         pmu = event->pmu;
12736
12737         if (pmu->task_ctx_nr == perf_sw_context)
12738                 event->event_caps |= PERF_EV_CAP_SOFTWARE;
12739
12740         /*
12741          * Get the target context (task or percpu):
12742          */
12743         ctx = find_get_context(task, event);
12744         if (IS_ERR(ctx)) {
12745                 err = PTR_ERR(ctx);
12746                 goto err_alloc;
12747         }
12748
12749         WARN_ON_ONCE(ctx->parent_ctx);
12750         mutex_lock(&ctx->mutex);
12751         if (ctx->task == TASK_TOMBSTONE) {
12752                 err = -ESRCH;
12753                 goto err_unlock;
12754         }
12755
12756         pmu_ctx = find_get_pmu_context(pmu, ctx, event);
12757         if (IS_ERR(pmu_ctx)) {
12758                 err = PTR_ERR(pmu_ctx);
12759                 goto err_unlock;
12760         }
12761         event->pmu_ctx = pmu_ctx;
12762
12763         if (!task) {
12764                 /*
12765                  * Check if the @cpu we're creating an event for is online.
12766                  *
12767                  * We use the perf_cpu_context::ctx::mutex to serialize against
12768                  * the hotplug notifiers. See perf_event_{init,exit}_cpu().
12769                  */
12770                 struct perf_cpu_context *cpuctx =
12771                         container_of(ctx, struct perf_cpu_context, ctx);
12772                 if (!cpuctx->online) {
12773                         err = -ENODEV;
12774                         goto err_pmu_ctx;
12775                 }
12776         }
12777
12778         if (!exclusive_event_installable(event, ctx)) {
12779                 err = -EBUSY;
12780                 goto err_pmu_ctx;
12781         }
12782
12783         perf_install_in_context(ctx, event, event->cpu);
12784         perf_unpin_context(ctx);
12785         mutex_unlock(&ctx->mutex);
12786
12787         return event;
12788
12789 err_pmu_ctx:
12790         put_pmu_ctx(pmu_ctx);
12791         event->pmu_ctx = NULL; /* _free_event() */
12792 err_unlock:
12793         mutex_unlock(&ctx->mutex);
12794         perf_unpin_context(ctx);
12795         put_ctx(ctx);
12796 err_alloc:
12797         free_event(event);
12798 err:
12799         return ERR_PTR(err);
12800 }
12801 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
12802
12803 static void __perf_pmu_remove(struct perf_event_context *ctx,
12804                               int cpu, struct pmu *pmu,
12805                               struct perf_event_groups *groups,
12806                               struct list_head *events)
12807 {
12808         struct perf_event *event, *sibling;
12809
12810         perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) {
12811                 perf_remove_from_context(event, 0);
12812                 put_pmu_ctx(event->pmu_ctx);
12813                 list_add(&event->migrate_entry, events);
12814
12815                 for_each_sibling_event(sibling, event) {
12816                         perf_remove_from_context(sibling, 0);
12817                         put_pmu_ctx(sibling->pmu_ctx);
12818                         list_add(&sibling->migrate_entry, events);
12819                 }
12820         }
12821 }
12822
12823 static void __perf_pmu_install_event(struct pmu *pmu,
12824                                      struct perf_event_context *ctx,
12825                                      int cpu, struct perf_event *event)
12826 {
12827         struct perf_event_pmu_context *epc;
12828
12829         event->cpu = cpu;
12830         epc = find_get_pmu_context(pmu, ctx, event);
12831         event->pmu_ctx = epc;
12832
12833         if (event->state >= PERF_EVENT_STATE_OFF)
12834                 event->state = PERF_EVENT_STATE_INACTIVE;
12835         perf_install_in_context(ctx, event, cpu);
12836 }
12837
12838 static void __perf_pmu_install(struct perf_event_context *ctx,
12839                                int cpu, struct pmu *pmu, struct list_head *events)
12840 {
12841         struct perf_event *event, *tmp;
12842
12843         /*
12844          * Re-instate events in 2 passes.
12845          *
12846          * Skip over group leaders and only install siblings on this first
12847          * pass, siblings will not get enabled without a leader, however a
12848          * leader will enable its siblings, even if those are still on the old
12849          * context.
12850          */
12851         list_for_each_entry_safe(event, tmp, events, migrate_entry) {
12852                 if (event->group_leader == event)
12853                         continue;
12854
12855                 list_del(&event->migrate_entry);
12856                 __perf_pmu_install_event(pmu, ctx, cpu, event);
12857         }
12858
12859         /*
12860          * Once all the siblings are setup properly, install the group leaders
12861          * to make it go.
12862          */
12863         list_for_each_entry_safe(event, tmp, events, migrate_entry) {
12864                 list_del(&event->migrate_entry);
12865                 __perf_pmu_install_event(pmu, ctx, cpu, event);
12866         }
12867 }
12868
12869 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
12870 {
12871         struct perf_event_context *src_ctx, *dst_ctx;
12872         LIST_HEAD(events);
12873
12874         src_ctx = &per_cpu_ptr(&perf_cpu_context, src_cpu)->ctx;
12875         dst_ctx = &per_cpu_ptr(&perf_cpu_context, dst_cpu)->ctx;
12876
12877         /*
12878          * See perf_event_ctx_lock() for comments on the details
12879          * of swizzling perf_event::ctx.
12880          */
12881         mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
12882
12883         __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->pinned_groups, &events);
12884         __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->flexible_groups, &events);
12885
12886         /*
12887          * Wait for the events to quiesce before re-instating them.
12888          */
12889         synchronize_rcu();
12890
12891         __perf_pmu_install(dst_ctx, dst_cpu, pmu, &events);
12892
12893         mutex_unlock(&dst_ctx->mutex);
12894         mutex_unlock(&src_ctx->mutex);
12895 }
12896 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
12897
12898 static void sync_child_event(struct perf_event *child_event)
12899 {
12900         struct perf_event *parent_event = child_event->parent;
12901         u64 child_val;
12902
12903         if (child_event->attr.inherit_stat) {
12904                 struct task_struct *task = child_event->ctx->task;
12905
12906                 if (task && task != TASK_TOMBSTONE)
12907                         perf_event_read_event(child_event, task);
12908         }
12909
12910         child_val = perf_event_count(child_event);
12911
12912         /*
12913          * Add back the child's count to the parent's count:
12914          */
12915         atomic64_add(child_val, &parent_event->child_count);
12916         atomic64_add(child_event->total_time_enabled,
12917                      &parent_event->child_total_time_enabled);
12918         atomic64_add(child_event->total_time_running,
12919                      &parent_event->child_total_time_running);
12920 }
12921
12922 static void
12923 perf_event_exit_event(struct perf_event *event, struct perf_event_context *ctx)
12924 {
12925         struct perf_event *parent_event = event->parent;
12926         unsigned long detach_flags = 0;
12927
12928         if (parent_event) {
12929                 /*
12930                  * Do not destroy the 'original' grouping; because of the
12931                  * context switch optimization the original events could've
12932                  * ended up in a random child task.
12933                  *
12934                  * If we were to destroy the original group, all group related
12935                  * operations would cease to function properly after this
12936                  * random child dies.
12937                  *
12938                  * Do destroy all inherited groups, we don't care about those
12939                  * and being thorough is better.
12940                  */
12941                 detach_flags = DETACH_GROUP | DETACH_CHILD;
12942                 mutex_lock(&parent_event->child_mutex);
12943         }
12944
12945         perf_remove_from_context(event, detach_flags);
12946
12947         raw_spin_lock_irq(&ctx->lock);
12948         if (event->state > PERF_EVENT_STATE_EXIT)
12949                 perf_event_set_state(event, PERF_EVENT_STATE_EXIT);
12950         raw_spin_unlock_irq(&ctx->lock);
12951
12952         /*
12953          * Child events can be freed.
12954          */
12955         if (parent_event) {
12956                 mutex_unlock(&parent_event->child_mutex);
12957                 /*
12958                  * Kick perf_poll() for is_event_hup();
12959                  */
12960                 perf_event_wakeup(parent_event);
12961                 free_event(event);
12962                 put_event(parent_event);
12963                 return;
12964         }
12965
12966         /*
12967          * Parent events are governed by their filedesc, retain them.
12968          */
12969         perf_event_wakeup(event);
12970 }
12971
12972 static void perf_event_exit_task_context(struct task_struct *child)
12973 {
12974         struct perf_event_context *child_ctx, *clone_ctx = NULL;
12975         struct perf_event *child_event, *next;
12976
12977         WARN_ON_ONCE(child != current);
12978
12979         child_ctx = perf_pin_task_context(child);
12980         if (!child_ctx)
12981                 return;
12982
12983         /*
12984          * In order to reduce the amount of tricky in ctx tear-down, we hold
12985          * ctx::mutex over the entire thing. This serializes against almost
12986          * everything that wants to access the ctx.
12987          *
12988          * The exception is sys_perf_event_open() /
12989          * perf_event_create_kernel_count() which does find_get_context()
12990          * without ctx::mutex (it cannot because of the move_group double mutex
12991          * lock thing). See the comments in perf_install_in_context().
12992          */
12993         mutex_lock(&child_ctx->mutex);
12994
12995         /*
12996          * In a single ctx::lock section, de-schedule the events and detach the
12997          * context from the task such that we cannot ever get it scheduled back
12998          * in.
12999          */
13000         raw_spin_lock_irq(&child_ctx->lock);
13001         task_ctx_sched_out(child_ctx, EVENT_ALL);
13002
13003         /*
13004          * Now that the context is inactive, destroy the task <-> ctx relation
13005          * and mark the context dead.
13006          */
13007         RCU_INIT_POINTER(child->perf_event_ctxp, NULL);
13008         put_ctx(child_ctx); /* cannot be last */
13009         WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
13010         put_task_struct(current); /* cannot be last */
13011
13012         clone_ctx = unclone_ctx(child_ctx);
13013         raw_spin_unlock_irq(&child_ctx->lock);
13014
13015         if (clone_ctx)
13016                 put_ctx(clone_ctx);
13017
13018         /*
13019          * Report the task dead after unscheduling the events so that we
13020          * won't get any samples after PERF_RECORD_EXIT. We can however still
13021          * get a few PERF_RECORD_READ events.
13022          */
13023         perf_event_task(child, child_ctx, 0);
13024
13025         list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
13026                 perf_event_exit_event(child_event, child_ctx);
13027
13028         mutex_unlock(&child_ctx->mutex);
13029
13030         put_ctx(child_ctx);
13031 }
13032
13033 /*
13034  * When a child task exits, feed back event values to parent events.
13035  *
13036  * Can be called with exec_update_lock held when called from
13037  * setup_new_exec().
13038  */
13039 void perf_event_exit_task(struct task_struct *child)
13040 {
13041         struct perf_event *event, *tmp;
13042
13043         mutex_lock(&child->perf_event_mutex);
13044         list_for_each_entry_safe(event, tmp, &child->perf_event_list,
13045                                  owner_entry) {
13046                 list_del_init(&event->owner_entry);
13047
13048                 /*
13049                  * Ensure the list deletion is visible before we clear
13050                  * the owner, closes a race against perf_release() where
13051                  * we need to serialize on the owner->perf_event_mutex.
13052                  */
13053                 smp_store_release(&event->owner, NULL);
13054         }
13055         mutex_unlock(&child->perf_event_mutex);
13056
13057         perf_event_exit_task_context(child);
13058
13059         /*
13060          * The perf_event_exit_task_context calls perf_event_task
13061          * with child's task_ctx, which generates EXIT events for
13062          * child contexts and sets child->perf_event_ctxp[] to NULL.
13063          * At this point we need to send EXIT events to cpu contexts.
13064          */
13065         perf_event_task(child, NULL, 0);
13066 }
13067
13068 static void perf_free_event(struct perf_event *event,
13069                             struct perf_event_context *ctx)
13070 {
13071         struct perf_event *parent = event->parent;
13072
13073         if (WARN_ON_ONCE(!parent))
13074                 return;
13075
13076         mutex_lock(&parent->child_mutex);
13077         list_del_init(&event->child_list);
13078         mutex_unlock(&parent->child_mutex);
13079
13080         put_event(parent);
13081
13082         raw_spin_lock_irq(&ctx->lock);
13083         perf_group_detach(event);
13084         list_del_event(event, ctx);
13085         raw_spin_unlock_irq(&ctx->lock);
13086         free_event(event);
13087 }
13088
13089 /*
13090  * Free a context as created by inheritance by perf_event_init_task() below,
13091  * used by fork() in case of fail.
13092  *
13093  * Even though the task has never lived, the context and events have been
13094  * exposed through the child_list, so we must take care tearing it all down.
13095  */
13096 void perf_event_free_task(struct task_struct *task)
13097 {
13098         struct perf_event_context *ctx;
13099         struct perf_event *event, *tmp;
13100
13101         ctx = rcu_access_pointer(task->perf_event_ctxp);
13102         if (!ctx)
13103                 return;
13104
13105         mutex_lock(&ctx->mutex);
13106         raw_spin_lock_irq(&ctx->lock);
13107         /*
13108          * Destroy the task <-> ctx relation and mark the context dead.
13109          *
13110          * This is important because even though the task hasn't been
13111          * exposed yet the context has been (through child_list).
13112          */
13113         RCU_INIT_POINTER(task->perf_event_ctxp, NULL);
13114         WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
13115         put_task_struct(task); /* cannot be last */
13116         raw_spin_unlock_irq(&ctx->lock);
13117
13118
13119         list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
13120                 perf_free_event(event, ctx);
13121
13122         mutex_unlock(&ctx->mutex);
13123
13124         /*
13125          * perf_event_release_kernel() could've stolen some of our
13126          * child events and still have them on its free_list. In that
13127          * case we must wait for these events to have been freed (in
13128          * particular all their references to this task must've been
13129          * dropped).
13130          *
13131          * Without this copy_process() will unconditionally free this
13132          * task (irrespective of its reference count) and
13133          * _free_event()'s put_task_struct(event->hw.target) will be a
13134          * use-after-free.
13135          *
13136          * Wait for all events to drop their context reference.
13137          */
13138         wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
13139         put_ctx(ctx); /* must be last */
13140 }
13141
13142 void perf_event_delayed_put(struct task_struct *task)
13143 {
13144         WARN_ON_ONCE(task->perf_event_ctxp);
13145 }
13146
13147 struct file *perf_event_get(unsigned int fd)
13148 {
13149         struct file *file = fget(fd);
13150         if (!file)
13151                 return ERR_PTR(-EBADF);
13152
13153         if (file->f_op != &perf_fops) {
13154                 fput(file);
13155                 return ERR_PTR(-EBADF);
13156         }
13157
13158         return file;
13159 }
13160
13161 const struct perf_event *perf_get_event(struct file *file)
13162 {
13163         if (file->f_op != &perf_fops)
13164                 return ERR_PTR(-EINVAL);
13165
13166         return file->private_data;
13167 }
13168
13169 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
13170 {
13171         if (!event)
13172                 return ERR_PTR(-EINVAL);
13173
13174         return &event->attr;
13175 }
13176
13177 /*
13178  * Inherit an event from parent task to child task.
13179  *
13180  * Returns:
13181  *  - valid pointer on success
13182  *  - NULL for orphaned events
13183  *  - IS_ERR() on error
13184  */
13185 static struct perf_event *
13186 inherit_event(struct perf_event *parent_event,
13187               struct task_struct *parent,
13188               struct perf_event_context *parent_ctx,
13189               struct task_struct *child,
13190               struct perf_event *group_leader,
13191               struct perf_event_context *child_ctx)
13192 {
13193         enum perf_event_state parent_state = parent_event->state;
13194         struct perf_event_pmu_context *pmu_ctx;
13195         struct perf_event *child_event;
13196         unsigned long flags;
13197
13198         /*
13199          * Instead of creating recursive hierarchies of events,
13200          * we link inherited events back to the original parent,
13201          * which has a filp for sure, which we use as the reference
13202          * count:
13203          */
13204         if (parent_event->parent)
13205                 parent_event = parent_event->parent;
13206
13207         child_event = perf_event_alloc(&parent_event->attr,
13208                                            parent_event->cpu,
13209                                            child,
13210                                            group_leader, parent_event,
13211                                            NULL, NULL, -1);
13212         if (IS_ERR(child_event))
13213                 return child_event;
13214
13215         pmu_ctx = find_get_pmu_context(child_event->pmu, child_ctx, child_event);
13216         if (IS_ERR(pmu_ctx)) {
13217                 free_event(child_event);
13218                 return ERR_CAST(pmu_ctx);
13219         }
13220         child_event->pmu_ctx = pmu_ctx;
13221
13222         /*
13223          * is_orphaned_event() and list_add_tail(&parent_event->child_list)
13224          * must be under the same lock in order to serialize against
13225          * perf_event_release_kernel(), such that either we must observe
13226          * is_orphaned_event() or they will observe us on the child_list.
13227          */
13228         mutex_lock(&parent_event->child_mutex);
13229         if (is_orphaned_event(parent_event) ||
13230             !atomic_long_inc_not_zero(&parent_event->refcount)) {
13231                 mutex_unlock(&parent_event->child_mutex);
13232                 /* task_ctx_data is freed with child_ctx */
13233                 free_event(child_event);
13234                 return NULL;
13235         }
13236
13237         get_ctx(child_ctx);
13238
13239         /*
13240          * Make the child state follow the state of the parent event,
13241          * not its attr.disabled bit.  We hold the parent's mutex,
13242          * so we won't race with perf_event_{en, dis}able_family.
13243          */
13244         if (parent_state >= PERF_EVENT_STATE_INACTIVE)
13245                 child_event->state = PERF_EVENT_STATE_INACTIVE;
13246         else
13247                 child_event->state = PERF_EVENT_STATE_OFF;
13248
13249         if (parent_event->attr.freq) {
13250                 u64 sample_period = parent_event->hw.sample_period;
13251                 struct hw_perf_event *hwc = &child_event->hw;
13252
13253                 hwc->sample_period = sample_period;
13254                 hwc->last_period   = sample_period;
13255
13256                 local64_set(&hwc->period_left, sample_period);
13257         }
13258
13259         child_event->ctx = child_ctx;
13260         child_event->overflow_handler = parent_event->overflow_handler;
13261         child_event->overflow_handler_context
13262                 = parent_event->overflow_handler_context;
13263
13264         /*
13265          * Precalculate sample_data sizes
13266          */
13267         perf_event__header_size(child_event);
13268         perf_event__id_header_size(child_event);
13269
13270         /*
13271          * Link it up in the child's context:
13272          */
13273         raw_spin_lock_irqsave(&child_ctx->lock, flags);
13274         add_event_to_ctx(child_event, child_ctx);
13275         child_event->attach_state |= PERF_ATTACH_CHILD;
13276         raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
13277
13278         /*
13279          * Link this into the parent event's child list
13280          */
13281         list_add_tail(&child_event->child_list, &parent_event->child_list);
13282         mutex_unlock(&parent_event->child_mutex);
13283
13284         return child_event;
13285 }
13286
13287 /*
13288  * Inherits an event group.
13289  *
13290  * This will quietly suppress orphaned events; !inherit_event() is not an error.
13291  * This matches with perf_event_release_kernel() removing all child events.
13292  *
13293  * Returns:
13294  *  - 0 on success
13295  *  - <0 on error
13296  */
13297 static int inherit_group(struct perf_event *parent_event,
13298               struct task_struct *parent,
13299               struct perf_event_context *parent_ctx,
13300               struct task_struct *child,
13301               struct perf_event_context *child_ctx)
13302 {
13303         struct perf_event *leader;
13304         struct perf_event *sub;
13305         struct perf_event *child_ctr;
13306
13307         leader = inherit_event(parent_event, parent, parent_ctx,
13308                                  child, NULL, child_ctx);
13309         if (IS_ERR(leader))
13310                 return PTR_ERR(leader);
13311         /*
13312          * @leader can be NULL here because of is_orphaned_event(). In this
13313          * case inherit_event() will create individual events, similar to what
13314          * perf_group_detach() would do anyway.
13315          */
13316         for_each_sibling_event(sub, parent_event) {
13317                 child_ctr = inherit_event(sub, parent, parent_ctx,
13318                                             child, leader, child_ctx);
13319                 if (IS_ERR(child_ctr))
13320                         return PTR_ERR(child_ctr);
13321
13322                 if (sub->aux_event == parent_event && child_ctr &&
13323                     !perf_get_aux_event(child_ctr, leader))
13324                         return -EINVAL;
13325         }
13326         return 0;
13327 }
13328
13329 /*
13330  * Creates the child task context and tries to inherit the event-group.
13331  *
13332  * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
13333  * inherited_all set when we 'fail' to inherit an orphaned event; this is
13334  * consistent with perf_event_release_kernel() removing all child events.
13335  *
13336  * Returns:
13337  *  - 0 on success
13338  *  - <0 on error
13339  */
13340 static int
13341 inherit_task_group(struct perf_event *event, struct task_struct *parent,
13342                    struct perf_event_context *parent_ctx,
13343                    struct task_struct *child,
13344                    u64 clone_flags, int *inherited_all)
13345 {
13346         struct perf_event_context *child_ctx;
13347         int ret;
13348
13349         if (!event->attr.inherit ||
13350             (event->attr.inherit_thread && !(clone_flags & CLONE_THREAD)) ||
13351             /* Do not inherit if sigtrap and signal handlers were cleared. */
13352             (event->attr.sigtrap && (clone_flags & CLONE_CLEAR_SIGHAND))) {
13353                 *inherited_all = 0;
13354                 return 0;
13355         }
13356
13357         child_ctx = child->perf_event_ctxp;
13358         if (!child_ctx) {
13359                 /*
13360                  * This is executed from the parent task context, so
13361                  * inherit events that have been marked for cloning.
13362                  * First allocate and initialize a context for the
13363                  * child.
13364                  */
13365                 child_ctx = alloc_perf_context(child);
13366                 if (!child_ctx)
13367                         return -ENOMEM;
13368
13369                 child->perf_event_ctxp = child_ctx;
13370         }
13371
13372         ret = inherit_group(event, parent, parent_ctx, child, child_ctx);
13373         if (ret)
13374                 *inherited_all = 0;
13375
13376         return ret;
13377 }
13378
13379 /*
13380  * Initialize the perf_event context in task_struct
13381  */
13382 static int perf_event_init_context(struct task_struct *child, u64 clone_flags)
13383 {
13384         struct perf_event_context *child_ctx, *parent_ctx;
13385         struct perf_event_context *cloned_ctx;
13386         struct perf_event *event;
13387         struct task_struct *parent = current;
13388         int inherited_all = 1;
13389         unsigned long flags;
13390         int ret = 0;
13391
13392         if (likely(!parent->perf_event_ctxp))
13393                 return 0;
13394
13395         /*
13396          * If the parent's context is a clone, pin it so it won't get
13397          * swapped under us.
13398          */
13399         parent_ctx = perf_pin_task_context(parent);
13400         if (!parent_ctx)
13401                 return 0;
13402
13403         /*
13404          * No need to check if parent_ctx != NULL here; since we saw
13405          * it non-NULL earlier, the only reason for it to become NULL
13406          * is if we exit, and since we're currently in the middle of
13407          * a fork we can't be exiting at the same time.
13408          */
13409
13410         /*
13411          * Lock the parent list. No need to lock the child - not PID
13412          * hashed yet and not running, so nobody can access it.
13413          */
13414         mutex_lock(&parent_ctx->mutex);
13415
13416         /*
13417          * We dont have to disable NMIs - we are only looking at
13418          * the list, not manipulating it:
13419          */
13420         perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
13421                 ret = inherit_task_group(event, parent, parent_ctx,
13422                                          child, clone_flags, &inherited_all);
13423                 if (ret)
13424                         goto out_unlock;
13425         }
13426
13427         /*
13428          * We can't hold ctx->lock when iterating the ->flexible_group list due
13429          * to allocations, but we need to prevent rotation because
13430          * rotate_ctx() will change the list from interrupt context.
13431          */
13432         raw_spin_lock_irqsave(&parent_ctx->lock, flags);
13433         parent_ctx->rotate_disable = 1;
13434         raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
13435
13436         perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
13437                 ret = inherit_task_group(event, parent, parent_ctx,
13438                                          child, clone_flags, &inherited_all);
13439                 if (ret)
13440                         goto out_unlock;
13441         }
13442
13443         raw_spin_lock_irqsave(&parent_ctx->lock, flags);
13444         parent_ctx->rotate_disable = 0;
13445
13446         child_ctx = child->perf_event_ctxp;
13447
13448         if (child_ctx && inherited_all) {
13449                 /*
13450                  * Mark the child context as a clone of the parent
13451                  * context, or of whatever the parent is a clone of.
13452                  *
13453                  * Note that if the parent is a clone, the holding of
13454                  * parent_ctx->lock avoids it from being uncloned.
13455                  */
13456                 cloned_ctx = parent_ctx->parent_ctx;
13457                 if (cloned_ctx) {
13458                         child_ctx->parent_ctx = cloned_ctx;
13459                         child_ctx->parent_gen = parent_ctx->parent_gen;
13460                 } else {
13461                         child_ctx->parent_ctx = parent_ctx;
13462                         child_ctx->parent_gen = parent_ctx->generation;
13463                 }
13464                 get_ctx(child_ctx->parent_ctx);
13465         }
13466
13467         raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
13468 out_unlock:
13469         mutex_unlock(&parent_ctx->mutex);
13470
13471         perf_unpin_context(parent_ctx);
13472         put_ctx(parent_ctx);
13473
13474         return ret;
13475 }
13476
13477 /*
13478  * Initialize the perf_event context in task_struct
13479  */
13480 int perf_event_init_task(struct task_struct *child, u64 clone_flags)
13481 {
13482         int ret;
13483
13484         child->perf_event_ctxp = NULL;
13485         mutex_init(&child->perf_event_mutex);
13486         INIT_LIST_HEAD(&child->perf_event_list);
13487
13488         ret = perf_event_init_context(child, clone_flags);
13489         if (ret) {
13490                 perf_event_free_task(child);
13491                 return ret;
13492         }
13493
13494         return 0;
13495 }
13496
13497 static void __init perf_event_init_all_cpus(void)
13498 {
13499         struct swevent_htable *swhash;
13500         struct perf_cpu_context *cpuctx;
13501         int cpu;
13502
13503         zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
13504
13505         for_each_possible_cpu(cpu) {
13506                 swhash = &per_cpu(swevent_htable, cpu);
13507                 mutex_init(&swhash->hlist_mutex);
13508
13509                 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
13510                 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
13511
13512                 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
13513
13514                 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
13515                 __perf_event_init_context(&cpuctx->ctx);
13516                 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
13517                 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
13518                 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
13519                 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
13520                 cpuctx->heap = cpuctx->heap_default;
13521         }
13522 }
13523
13524 static void perf_swevent_init_cpu(unsigned int cpu)
13525 {
13526         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
13527
13528         mutex_lock(&swhash->hlist_mutex);
13529         if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
13530                 struct swevent_hlist *hlist;
13531
13532                 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
13533                 WARN_ON(!hlist);
13534                 rcu_assign_pointer(swhash->swevent_hlist, hlist);
13535         }
13536         mutex_unlock(&swhash->hlist_mutex);
13537 }
13538
13539 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
13540 static void __perf_event_exit_context(void *__info)
13541 {
13542         struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
13543         struct perf_event_context *ctx = __info;
13544         struct perf_event *event;
13545
13546         raw_spin_lock(&ctx->lock);
13547         ctx_sched_out(ctx, EVENT_TIME);
13548         list_for_each_entry(event, &ctx->event_list, event_entry)
13549                 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
13550         raw_spin_unlock(&ctx->lock);
13551 }
13552
13553 static void perf_event_exit_cpu_context(int cpu)
13554 {
13555         struct perf_cpu_context *cpuctx;
13556         struct perf_event_context *ctx;
13557
13558         // XXX simplify cpuctx->online
13559         mutex_lock(&pmus_lock);
13560         cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
13561         ctx = &cpuctx->ctx;
13562
13563         mutex_lock(&ctx->mutex);
13564         smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
13565         cpuctx->online = 0;
13566         mutex_unlock(&ctx->mutex);
13567         cpumask_clear_cpu(cpu, perf_online_mask);
13568         mutex_unlock(&pmus_lock);
13569 }
13570 #else
13571
13572 static void perf_event_exit_cpu_context(int cpu) { }
13573
13574 #endif
13575
13576 int perf_event_init_cpu(unsigned int cpu)
13577 {
13578         struct perf_cpu_context *cpuctx;
13579         struct perf_event_context *ctx;
13580
13581         perf_swevent_init_cpu(cpu);
13582
13583         mutex_lock(&pmus_lock);
13584         cpumask_set_cpu(cpu, perf_online_mask);
13585         cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
13586         ctx = &cpuctx->ctx;
13587
13588         mutex_lock(&ctx->mutex);
13589         cpuctx->online = 1;
13590         mutex_unlock(&ctx->mutex);
13591         mutex_unlock(&pmus_lock);
13592
13593         return 0;
13594 }
13595
13596 int perf_event_exit_cpu(unsigned int cpu)
13597 {
13598         perf_event_exit_cpu_context(cpu);
13599         return 0;
13600 }
13601
13602 static int
13603 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
13604 {
13605         int cpu;
13606
13607         for_each_online_cpu(cpu)
13608                 perf_event_exit_cpu(cpu);
13609
13610         return NOTIFY_OK;
13611 }
13612
13613 /*
13614  * Run the perf reboot notifier at the very last possible moment so that
13615  * the generic watchdog code runs as long as possible.
13616  */
13617 static struct notifier_block perf_reboot_notifier = {
13618         .notifier_call = perf_reboot,
13619         .priority = INT_MIN,
13620 };
13621
13622 void __init perf_event_init(void)
13623 {
13624         int ret;
13625
13626         idr_init(&pmu_idr);
13627
13628         perf_event_init_all_cpus();
13629         init_srcu_struct(&pmus_srcu);
13630         perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
13631         perf_pmu_register(&perf_cpu_clock, NULL, -1);
13632         perf_pmu_register(&perf_task_clock, NULL, -1);
13633         perf_tp_register();
13634         perf_event_init_cpu(smp_processor_id());
13635         register_reboot_notifier(&perf_reboot_notifier);
13636
13637         ret = init_hw_breakpoint();
13638         WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
13639
13640         perf_event_cache = KMEM_CACHE(perf_event, SLAB_PANIC);
13641
13642         /*
13643          * Build time assertion that we keep the data_head at the intended
13644          * location.  IOW, validation we got the __reserved[] size right.
13645          */
13646         BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
13647                      != 1024);
13648 }
13649
13650 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
13651                               char *page)
13652 {
13653         struct perf_pmu_events_attr *pmu_attr =
13654                 container_of(attr, struct perf_pmu_events_attr, attr);
13655
13656         if (pmu_attr->event_str)
13657                 return sprintf(page, "%s\n", pmu_attr->event_str);
13658
13659         return 0;
13660 }
13661 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
13662
13663 static int __init perf_event_sysfs_init(void)
13664 {
13665         struct pmu *pmu;
13666         int ret;
13667
13668         mutex_lock(&pmus_lock);
13669
13670         ret = bus_register(&pmu_bus);
13671         if (ret)
13672                 goto unlock;
13673
13674         list_for_each_entry(pmu, &pmus, entry) {
13675                 if (!pmu->name || pmu->type < 0)
13676                         continue;
13677
13678                 ret = pmu_dev_alloc(pmu);
13679                 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
13680         }
13681         pmu_bus_running = 1;
13682         ret = 0;
13683
13684 unlock:
13685         mutex_unlock(&pmus_lock);
13686
13687         return ret;
13688 }
13689 device_initcall(perf_event_sysfs_init);
13690
13691 #ifdef CONFIG_CGROUP_PERF
13692 static struct cgroup_subsys_state *
13693 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
13694 {
13695         struct perf_cgroup *jc;
13696
13697         jc = kzalloc(sizeof(*jc), GFP_KERNEL);
13698         if (!jc)
13699                 return ERR_PTR(-ENOMEM);
13700
13701         jc->info = alloc_percpu(struct perf_cgroup_info);
13702         if (!jc->info) {
13703                 kfree(jc);
13704                 return ERR_PTR(-ENOMEM);
13705         }
13706
13707         return &jc->css;
13708 }
13709
13710 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
13711 {
13712         struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
13713
13714         free_percpu(jc->info);
13715         kfree(jc);
13716 }
13717
13718 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
13719 {
13720         perf_event_cgroup(css->cgroup);
13721         return 0;
13722 }
13723
13724 static int __perf_cgroup_move(void *info)
13725 {
13726         struct task_struct *task = info;
13727
13728         preempt_disable();
13729         perf_cgroup_switch(task);
13730         preempt_enable();
13731
13732         return 0;
13733 }
13734
13735 static void perf_cgroup_attach(struct cgroup_taskset *tset)
13736 {
13737         struct task_struct *task;
13738         struct cgroup_subsys_state *css;
13739
13740         cgroup_taskset_for_each(task, css, tset)
13741                 task_function_call(task, __perf_cgroup_move, task);
13742 }
13743
13744 struct cgroup_subsys perf_event_cgrp_subsys = {
13745         .css_alloc      = perf_cgroup_css_alloc,
13746         .css_free       = perf_cgroup_css_free,
13747         .css_online     = perf_cgroup_css_online,
13748         .attach         = perf_cgroup_attach,
13749         /*
13750          * Implicitly enable on dfl hierarchy so that perf events can
13751          * always be filtered by cgroup2 path as long as perf_event
13752          * controller is not mounted on a legacy hierarchy.
13753          */
13754         .implicit_on_dfl = true,
13755         .threaded       = true,
13756 };
13757 #endif /* CONFIG_CGROUP_PERF */
13758
13759 DEFINE_STATIC_CALL_RET0(perf_snapshot_branch_stack, perf_snapshot_branch_stack_t);