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