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