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