OSDN Git Service

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