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