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