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