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