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