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