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