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