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