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