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