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