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