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