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