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