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