OSDN Git Service

Merge 4.4.190 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->flags & PF_KTHREAD)) {
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         u32 type = mmap_event->event_id.header.type;
6007         int ret;
6008
6009         if (!perf_event_mmap_match(event, data))
6010                 return;
6011
6012         if (event->attr.mmap2) {
6013                 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
6014                 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
6015                 mmap_event->event_id.header.size += sizeof(mmap_event->min);
6016                 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
6017                 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
6018                 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
6019                 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
6020         }
6021
6022         perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
6023         ret = perf_output_begin(&handle, event,
6024                                 mmap_event->event_id.header.size);
6025         if (ret)
6026                 goto out;
6027
6028         mmap_event->event_id.pid = perf_event_pid(event, current);
6029         mmap_event->event_id.tid = perf_event_tid(event, current);
6030
6031         perf_output_put(&handle, mmap_event->event_id);
6032
6033         if (event->attr.mmap2) {
6034                 perf_output_put(&handle, mmap_event->maj);
6035                 perf_output_put(&handle, mmap_event->min);
6036                 perf_output_put(&handle, mmap_event->ino);
6037                 perf_output_put(&handle, mmap_event->ino_generation);
6038                 perf_output_put(&handle, mmap_event->prot);
6039                 perf_output_put(&handle, mmap_event->flags);
6040         }
6041
6042         __output_copy(&handle, mmap_event->file_name,
6043                                    mmap_event->file_size);
6044
6045         perf_event__output_id_sample(event, &handle, &sample);
6046
6047         perf_output_end(&handle);
6048 out:
6049         mmap_event->event_id.header.size = size;
6050         mmap_event->event_id.header.type = type;
6051 }
6052
6053 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
6054 {
6055         struct vm_area_struct *vma = mmap_event->vma;
6056         struct file *file = vma->vm_file;
6057         int maj = 0, min = 0;
6058         u64 ino = 0, gen = 0;
6059         u32 prot = 0, flags = 0;
6060         unsigned int size;
6061         char tmp[16];
6062         char *buf = NULL;
6063         char *name;
6064
6065         if (vma->vm_flags & VM_READ)
6066                 prot |= PROT_READ;
6067         if (vma->vm_flags & VM_WRITE)
6068                 prot |= PROT_WRITE;
6069         if (vma->vm_flags & VM_EXEC)
6070                 prot |= PROT_EXEC;
6071
6072         if (vma->vm_flags & VM_MAYSHARE)
6073                 flags = MAP_SHARED;
6074         else
6075                 flags = MAP_PRIVATE;
6076
6077         if (vma->vm_flags & VM_DENYWRITE)
6078                 flags |= MAP_DENYWRITE;
6079         if (vma->vm_flags & VM_MAYEXEC)
6080                 flags |= MAP_EXECUTABLE;
6081         if (vma->vm_flags & VM_LOCKED)
6082                 flags |= MAP_LOCKED;
6083         if (vma->vm_flags & VM_HUGETLB)
6084                 flags |= MAP_HUGETLB;
6085
6086         if (file) {
6087                 struct inode *inode;
6088                 dev_t dev;
6089
6090                 buf = kmalloc(PATH_MAX, GFP_KERNEL);
6091                 if (!buf) {
6092                         name = "//enomem";
6093                         goto cpy_name;
6094                 }
6095                 /*
6096                  * d_path() works from the end of the rb backwards, so we
6097                  * need to add enough zero bytes after the string to handle
6098                  * the 64bit alignment we do later.
6099                  */
6100                 name = file_path(file, buf, PATH_MAX - sizeof(u64));
6101                 if (IS_ERR(name)) {
6102                         name = "//toolong";
6103                         goto cpy_name;
6104                 }
6105                 inode = file_inode(vma->vm_file);
6106                 dev = inode->i_sb->s_dev;
6107                 ino = inode->i_ino;
6108                 gen = inode->i_generation;
6109                 maj = MAJOR(dev);
6110                 min = MINOR(dev);
6111
6112                 goto got_name;
6113         } else {
6114                 if (vma->vm_ops && vma->vm_ops->name) {
6115                         name = (char *) vma->vm_ops->name(vma);
6116                         if (name)
6117                                 goto cpy_name;
6118                 }
6119
6120                 name = (char *)arch_vma_name(vma);
6121                 if (name)
6122                         goto cpy_name;
6123
6124                 if (vma->vm_start <= vma->vm_mm->start_brk &&
6125                                 vma->vm_end >= vma->vm_mm->brk) {
6126                         name = "[heap]";
6127                         goto cpy_name;
6128                 }
6129                 if (vma->vm_start <= vma->vm_mm->start_stack &&
6130                                 vma->vm_end >= vma->vm_mm->start_stack) {
6131                         name = "[stack]";
6132                         goto cpy_name;
6133                 }
6134
6135                 name = "//anon";
6136                 goto cpy_name;
6137         }
6138
6139 cpy_name:
6140         strlcpy(tmp, name, sizeof(tmp));
6141         name = tmp;
6142 got_name:
6143         /*
6144          * Since our buffer works in 8 byte units we need to align our string
6145          * size to a multiple of 8. However, we must guarantee the tail end is
6146          * zero'd out to avoid leaking random bits to userspace.
6147          */
6148         size = strlen(name)+1;
6149         while (!IS_ALIGNED(size, sizeof(u64)))
6150                 name[size++] = '\0';
6151
6152         mmap_event->file_name = name;
6153         mmap_event->file_size = size;
6154         mmap_event->maj = maj;
6155         mmap_event->min = min;
6156         mmap_event->ino = ino;
6157         mmap_event->ino_generation = gen;
6158         mmap_event->prot = prot;
6159         mmap_event->flags = flags;
6160
6161         if (!(vma->vm_flags & VM_EXEC))
6162                 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
6163
6164         mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
6165
6166         perf_event_aux(perf_event_mmap_output,
6167                        mmap_event,
6168                        NULL);
6169
6170         kfree(buf);
6171 }
6172
6173 void perf_event_mmap(struct vm_area_struct *vma)
6174 {
6175         struct perf_mmap_event mmap_event;
6176
6177         if (!atomic_read(&nr_mmap_events))
6178                 return;
6179
6180         mmap_event = (struct perf_mmap_event){
6181                 .vma    = vma,
6182                 /* .file_name */
6183                 /* .file_size */
6184                 .event_id  = {
6185                         .header = {
6186                                 .type = PERF_RECORD_MMAP,
6187                                 .misc = PERF_RECORD_MISC_USER,
6188                                 /* .size */
6189                         },
6190                         /* .pid */
6191                         /* .tid */
6192                         .start  = vma->vm_start,
6193                         .len    = vma->vm_end - vma->vm_start,
6194                         .pgoff  = (u64)vma->vm_pgoff << PAGE_SHIFT,
6195                 },
6196                 /* .maj (attr_mmap2 only) */
6197                 /* .min (attr_mmap2 only) */
6198                 /* .ino (attr_mmap2 only) */
6199                 /* .ino_generation (attr_mmap2 only) */
6200                 /* .prot (attr_mmap2 only) */
6201                 /* .flags (attr_mmap2 only) */
6202         };
6203
6204         perf_event_mmap_event(&mmap_event);
6205 }
6206
6207 void perf_event_aux_event(struct perf_event *event, unsigned long head,
6208                           unsigned long size, u64 flags)
6209 {
6210         struct perf_output_handle handle;
6211         struct perf_sample_data sample;
6212         struct perf_aux_event {
6213                 struct perf_event_header        header;
6214                 u64                             offset;
6215                 u64                             size;
6216                 u64                             flags;
6217         } rec = {
6218                 .header = {
6219                         .type = PERF_RECORD_AUX,
6220                         .misc = 0,
6221                         .size = sizeof(rec),
6222                 },
6223                 .offset         = head,
6224                 .size           = size,
6225                 .flags          = flags,
6226         };
6227         int ret;
6228
6229         perf_event_header__init_id(&rec.header, &sample, event);
6230         ret = perf_output_begin(&handle, event, rec.header.size);
6231
6232         if (ret)
6233                 return;
6234
6235         perf_output_put(&handle, rec);
6236         perf_event__output_id_sample(event, &handle, &sample);
6237
6238         perf_output_end(&handle);
6239 }
6240
6241 /*
6242  * Lost/dropped samples logging
6243  */
6244 void perf_log_lost_samples(struct perf_event *event, u64 lost)
6245 {
6246         struct perf_output_handle handle;
6247         struct perf_sample_data sample;
6248         int ret;
6249
6250         struct {
6251                 struct perf_event_header        header;
6252                 u64                             lost;
6253         } lost_samples_event = {
6254                 .header = {
6255                         .type = PERF_RECORD_LOST_SAMPLES,
6256                         .misc = 0,
6257                         .size = sizeof(lost_samples_event),
6258                 },
6259                 .lost           = lost,
6260         };
6261
6262         perf_event_header__init_id(&lost_samples_event.header, &sample, event);
6263
6264         ret = perf_output_begin(&handle, event,
6265                                 lost_samples_event.header.size);
6266         if (ret)
6267                 return;
6268
6269         perf_output_put(&handle, lost_samples_event);
6270         perf_event__output_id_sample(event, &handle, &sample);
6271         perf_output_end(&handle);
6272 }
6273
6274 /*
6275  * context_switch tracking
6276  */
6277
6278 struct perf_switch_event {
6279         struct task_struct      *task;
6280         struct task_struct      *next_prev;
6281
6282         struct {
6283                 struct perf_event_header        header;
6284                 u32                             next_prev_pid;
6285                 u32                             next_prev_tid;
6286         } event_id;
6287 };
6288
6289 static int perf_event_switch_match(struct perf_event *event)
6290 {
6291         return event->attr.context_switch;
6292 }
6293
6294 static void perf_event_switch_output(struct perf_event *event, void *data)
6295 {
6296         struct perf_switch_event *se = data;
6297         struct perf_output_handle handle;
6298         struct perf_sample_data sample;
6299         int ret;
6300
6301         if (!perf_event_switch_match(event))
6302                 return;
6303
6304         /* Only CPU-wide events are allowed to see next/prev pid/tid */
6305         if (event->ctx->task) {
6306                 se->event_id.header.type = PERF_RECORD_SWITCH;
6307                 se->event_id.header.size = sizeof(se->event_id.header);
6308         } else {
6309                 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
6310                 se->event_id.header.size = sizeof(se->event_id);
6311                 se->event_id.next_prev_pid =
6312                                         perf_event_pid(event, se->next_prev);
6313                 se->event_id.next_prev_tid =
6314                                         perf_event_tid(event, se->next_prev);
6315         }
6316
6317         perf_event_header__init_id(&se->event_id.header, &sample, event);
6318
6319         ret = perf_output_begin(&handle, event, se->event_id.header.size);
6320         if (ret)
6321                 return;
6322
6323         if (event->ctx->task)
6324                 perf_output_put(&handle, se->event_id.header);
6325         else
6326                 perf_output_put(&handle, se->event_id);
6327
6328         perf_event__output_id_sample(event, &handle, &sample);
6329
6330         perf_output_end(&handle);
6331 }
6332
6333 static void perf_event_switch(struct task_struct *task,
6334                               struct task_struct *next_prev, bool sched_in)
6335 {
6336         struct perf_switch_event switch_event;
6337
6338         /* N.B. caller checks nr_switch_events != 0 */
6339
6340         switch_event = (struct perf_switch_event){
6341                 .task           = task,
6342                 .next_prev      = next_prev,
6343                 .event_id       = {
6344                         .header = {
6345                                 /* .type */
6346                                 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
6347                                 /* .size */
6348                         },
6349                         /* .next_prev_pid */
6350                         /* .next_prev_tid */
6351                 },
6352         };
6353
6354         perf_event_aux(perf_event_switch_output,
6355                        &switch_event,
6356                        NULL);
6357 }
6358
6359 /*
6360  * IRQ throttle logging
6361  */
6362
6363 static void perf_log_throttle(struct perf_event *event, int enable)
6364 {
6365         struct perf_output_handle handle;
6366         struct perf_sample_data sample;
6367         int ret;
6368
6369         struct {
6370                 struct perf_event_header        header;
6371                 u64                             time;
6372                 u64                             id;
6373                 u64                             stream_id;
6374         } throttle_event = {
6375                 .header = {
6376                         .type = PERF_RECORD_THROTTLE,
6377                         .misc = 0,
6378                         .size = sizeof(throttle_event),
6379                 },
6380                 .time           = perf_event_clock(event),
6381                 .id             = primary_event_id(event),
6382                 .stream_id      = event->id,
6383         };
6384
6385         if (enable)
6386                 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
6387
6388         perf_event_header__init_id(&throttle_event.header, &sample, event);
6389
6390         ret = perf_output_begin(&handle, event,
6391                                 throttle_event.header.size);
6392         if (ret)
6393                 return;
6394
6395         perf_output_put(&handle, throttle_event);
6396         perf_event__output_id_sample(event, &handle, &sample);
6397         perf_output_end(&handle);
6398 }
6399
6400 static void perf_log_itrace_start(struct perf_event *event)
6401 {
6402         struct perf_output_handle handle;
6403         struct perf_sample_data sample;
6404         struct perf_aux_event {
6405                 struct perf_event_header        header;
6406                 u32                             pid;
6407                 u32                             tid;
6408         } rec;
6409         int ret;
6410
6411         if (event->parent)
6412                 event = event->parent;
6413
6414         if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
6415             event->hw.itrace_started)
6416                 return;
6417
6418         rec.header.type = PERF_RECORD_ITRACE_START;
6419         rec.header.misc = 0;
6420         rec.header.size = sizeof(rec);
6421         rec.pid = perf_event_pid(event, current);
6422         rec.tid = perf_event_tid(event, current);
6423
6424         perf_event_header__init_id(&rec.header, &sample, event);
6425         ret = perf_output_begin(&handle, event, rec.header.size);
6426
6427         if (ret)
6428                 return;
6429
6430         perf_output_put(&handle, rec);
6431         perf_event__output_id_sample(event, &handle, &sample);
6432
6433         perf_output_end(&handle);
6434 }
6435
6436 /*
6437  * Generic event overflow handling, sampling.
6438  */
6439
6440 static int __perf_event_overflow(struct perf_event *event,
6441                                    int throttle, struct perf_sample_data *data,
6442                                    struct pt_regs *regs)
6443 {
6444         int events = atomic_read(&event->event_limit);
6445         struct hw_perf_event *hwc = &event->hw;
6446         u64 seq;
6447         int ret = 0;
6448
6449         /*
6450          * Non-sampling counters might still use the PMI to fold short
6451          * hardware counters, ignore those.
6452          */
6453         if (unlikely(!is_sampling_event(event)))
6454                 return 0;
6455
6456         seq = __this_cpu_read(perf_throttled_seq);
6457         if (seq != hwc->interrupts_seq) {
6458                 hwc->interrupts_seq = seq;
6459                 hwc->interrupts = 1;
6460         } else {
6461                 hwc->interrupts++;
6462                 if (unlikely(throttle
6463                              && hwc->interrupts >= max_samples_per_tick)) {
6464                         __this_cpu_inc(perf_throttled_count);
6465                         hwc->interrupts = MAX_INTERRUPTS;
6466                         perf_log_throttle(event, 0);
6467                         tick_nohz_full_kick();
6468                         ret = 1;
6469                 }
6470         }
6471
6472         if (event->attr.freq) {
6473                 u64 now = perf_clock();
6474                 s64 delta = now - hwc->freq_time_stamp;
6475
6476                 hwc->freq_time_stamp = now;
6477
6478                 if (delta > 0 && delta < 2*TICK_NSEC)
6479                         perf_adjust_period(event, delta, hwc->last_period, true);
6480         }
6481
6482         /*
6483          * XXX event_limit might not quite work as expected on inherited
6484          * events
6485          */
6486
6487         event->pending_kill = POLL_IN;
6488         if (events && atomic_dec_and_test(&event->event_limit)) {
6489                 ret = 1;
6490                 event->pending_kill = POLL_HUP;
6491                 event->pending_disable = 1;
6492                 irq_work_queue(&event->pending);
6493         }
6494
6495         if (event->overflow_handler)
6496                 event->overflow_handler(event, data, regs);
6497         else
6498                 perf_event_output(event, data, regs);
6499
6500         if (*perf_event_fasync(event) && event->pending_kill) {
6501                 event->pending_wakeup = 1;
6502                 irq_work_queue(&event->pending);
6503         }
6504
6505         return ret;
6506 }
6507
6508 int perf_event_overflow(struct perf_event *event,
6509                           struct perf_sample_data *data,
6510                           struct pt_regs *regs)
6511 {
6512         return __perf_event_overflow(event, 1, data, regs);
6513 }
6514
6515 /*
6516  * Generic software event infrastructure
6517  */
6518
6519 struct swevent_htable {
6520         struct swevent_hlist            *swevent_hlist;
6521         struct mutex                    hlist_mutex;
6522         int                             hlist_refcount;
6523
6524         /* Recursion avoidance in each contexts */
6525         int                             recursion[PERF_NR_CONTEXTS];
6526 };
6527
6528 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
6529
6530 /*
6531  * We directly increment event->count and keep a second value in
6532  * event->hw.period_left to count intervals. This period event
6533  * is kept in the range [-sample_period, 0] so that we can use the
6534  * sign as trigger.
6535  */
6536
6537 u64 perf_swevent_set_period(struct perf_event *event)
6538 {
6539         struct hw_perf_event *hwc = &event->hw;
6540         u64 period = hwc->last_period;
6541         u64 nr, offset;
6542         s64 old, val;
6543
6544         hwc->last_period = hwc->sample_period;
6545
6546 again:
6547         old = val = local64_read(&hwc->period_left);
6548         if (val < 0)
6549                 return 0;
6550
6551         nr = div64_u64(period + val, period);
6552         offset = nr * period;
6553         val -= offset;
6554         if (local64_cmpxchg(&hwc->period_left, old, val) != old)
6555                 goto again;
6556
6557         return nr;
6558 }
6559
6560 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
6561                                     struct perf_sample_data *data,
6562                                     struct pt_regs *regs)
6563 {
6564         struct hw_perf_event *hwc = &event->hw;
6565         int throttle = 0;
6566
6567         if (!overflow)
6568                 overflow = perf_swevent_set_period(event);
6569
6570         if (hwc->interrupts == MAX_INTERRUPTS)
6571                 return;
6572
6573         for (; overflow; overflow--) {
6574                 if (__perf_event_overflow(event, throttle,
6575                                             data, regs)) {
6576                         /*
6577                          * We inhibit the overflow from happening when
6578                          * hwc->interrupts == MAX_INTERRUPTS.
6579                          */
6580                         break;
6581                 }
6582                 throttle = 1;
6583         }
6584 }
6585
6586 static void perf_swevent_event(struct perf_event *event, u64 nr,
6587                                struct perf_sample_data *data,
6588                                struct pt_regs *regs)
6589 {
6590         struct hw_perf_event *hwc = &event->hw;
6591
6592         local64_add(nr, &event->count);
6593
6594         if (!regs)
6595                 return;
6596
6597         if (!is_sampling_event(event))
6598                 return;
6599
6600         if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
6601                 data->period = nr;
6602                 return perf_swevent_overflow(event, 1, data, regs);
6603         } else
6604                 data->period = event->hw.last_period;
6605
6606         if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
6607                 return perf_swevent_overflow(event, 1, data, regs);
6608
6609         if (local64_add_negative(nr, &hwc->period_left))
6610                 return;
6611
6612         perf_swevent_overflow(event, 0, data, regs);
6613 }
6614
6615 static int perf_exclude_event(struct perf_event *event,
6616                               struct pt_regs *regs)
6617 {
6618         if (event->hw.state & PERF_HES_STOPPED)
6619                 return 1;
6620
6621         if (regs) {
6622                 if (event->attr.exclude_user && user_mode(regs))
6623                         return 1;
6624
6625                 if (event->attr.exclude_kernel && !user_mode(regs))
6626                         return 1;
6627         }
6628
6629         return 0;
6630 }
6631
6632 static int perf_swevent_match(struct perf_event *event,
6633                                 enum perf_type_id type,
6634                                 u32 event_id,
6635                                 struct perf_sample_data *data,
6636                                 struct pt_regs *regs)
6637 {
6638         if (event->attr.type != type)
6639                 return 0;
6640
6641         if (event->attr.config != event_id)
6642                 return 0;
6643
6644         if (perf_exclude_event(event, regs))
6645                 return 0;
6646
6647         return 1;
6648 }
6649
6650 static inline u64 swevent_hash(u64 type, u32 event_id)
6651 {
6652         u64 val = event_id | (type << 32);
6653
6654         return hash_64(val, SWEVENT_HLIST_BITS);
6655 }
6656
6657 static inline struct hlist_head *
6658 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
6659 {
6660         u64 hash = swevent_hash(type, event_id);
6661
6662         return &hlist->heads[hash];
6663 }
6664
6665 /* For the read side: events when they trigger */
6666 static inline struct hlist_head *
6667 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
6668 {
6669         struct swevent_hlist *hlist;
6670
6671         hlist = rcu_dereference(swhash->swevent_hlist);
6672         if (!hlist)
6673                 return NULL;
6674
6675         return __find_swevent_head(hlist, type, event_id);
6676 }
6677
6678 /* For the event head insertion and removal in the hlist */
6679 static inline struct hlist_head *
6680 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
6681 {
6682         struct swevent_hlist *hlist;
6683         u32 event_id = event->attr.config;
6684         u64 type = event->attr.type;
6685
6686         /*
6687          * Event scheduling is always serialized against hlist allocation
6688          * and release. Which makes the protected version suitable here.
6689          * The context lock guarantees that.
6690          */
6691         hlist = rcu_dereference_protected(swhash->swevent_hlist,
6692                                           lockdep_is_held(&event->ctx->lock));
6693         if (!hlist)
6694                 return NULL;
6695
6696         return __find_swevent_head(hlist, type, event_id);
6697 }
6698
6699 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
6700                                     u64 nr,
6701                                     struct perf_sample_data *data,
6702                                     struct pt_regs *regs)
6703 {
6704         struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6705         struct perf_event *event;
6706         struct hlist_head *head;
6707
6708         rcu_read_lock();
6709         head = find_swevent_head_rcu(swhash, type, event_id);
6710         if (!head)
6711                 goto end;
6712
6713         hlist_for_each_entry_rcu(event, head, hlist_entry) {
6714                 if (perf_swevent_match(event, type, event_id, data, regs))
6715                         perf_swevent_event(event, nr, data, regs);
6716         }
6717 end:
6718         rcu_read_unlock();
6719 }
6720
6721 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
6722
6723 int perf_swevent_get_recursion_context(void)
6724 {
6725         struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6726
6727         return get_recursion_context(swhash->recursion);
6728 }
6729 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
6730
6731 inline void perf_swevent_put_recursion_context(int rctx)
6732 {
6733         struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6734
6735         put_recursion_context(swhash->recursion, rctx);
6736 }
6737
6738 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6739 {
6740         struct perf_sample_data data;
6741
6742         if (WARN_ON_ONCE(!regs))
6743                 return;
6744
6745         perf_sample_data_init(&data, addr, 0);
6746         do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
6747 }
6748
6749 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6750 {
6751         int rctx;
6752
6753         preempt_disable_notrace();
6754         rctx = perf_swevent_get_recursion_context();
6755         if (unlikely(rctx < 0))
6756                 goto fail;
6757
6758         ___perf_sw_event(event_id, nr, regs, addr);
6759
6760         perf_swevent_put_recursion_context(rctx);
6761 fail:
6762         preempt_enable_notrace();
6763 }
6764
6765 static void perf_swevent_read(struct perf_event *event)
6766 {
6767 }
6768
6769 static int perf_swevent_add(struct perf_event *event, int flags)
6770 {
6771         struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6772         struct hw_perf_event *hwc = &event->hw;
6773         struct hlist_head *head;
6774
6775         if (is_sampling_event(event)) {
6776                 hwc->last_period = hwc->sample_period;
6777                 perf_swevent_set_period(event);
6778         }
6779
6780         hwc->state = !(flags & PERF_EF_START);
6781
6782         head = find_swevent_head(swhash, event);
6783         if (WARN_ON_ONCE(!head))
6784                 return -EINVAL;
6785
6786         hlist_add_head_rcu(&event->hlist_entry, head);
6787         perf_event_update_userpage(event);
6788
6789         return 0;
6790 }
6791
6792 static void perf_swevent_del(struct perf_event *event, int flags)
6793 {
6794         hlist_del_rcu(&event->hlist_entry);
6795 }
6796
6797 static void perf_swevent_start(struct perf_event *event, int flags)
6798 {
6799         event->hw.state = 0;
6800 }
6801
6802 static void perf_swevent_stop(struct perf_event *event, int flags)
6803 {
6804         event->hw.state = PERF_HES_STOPPED;
6805 }
6806
6807 /* Deref the hlist from the update side */
6808 static inline struct swevent_hlist *
6809 swevent_hlist_deref(struct swevent_htable *swhash)
6810 {
6811         return rcu_dereference_protected(swhash->swevent_hlist,
6812                                          lockdep_is_held(&swhash->hlist_mutex));
6813 }
6814
6815 static void swevent_hlist_release(struct swevent_htable *swhash)
6816 {
6817         struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
6818
6819         if (!hlist)
6820                 return;
6821
6822         RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
6823         kfree_rcu(hlist, rcu_head);
6824 }
6825
6826 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
6827 {
6828         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6829
6830         mutex_lock(&swhash->hlist_mutex);
6831
6832         if (!--swhash->hlist_refcount)
6833                 swevent_hlist_release(swhash);
6834
6835         mutex_unlock(&swhash->hlist_mutex);
6836 }
6837
6838 static void swevent_hlist_put(struct perf_event *event)
6839 {
6840         int cpu;
6841
6842         for_each_possible_cpu(cpu)
6843                 swevent_hlist_put_cpu(event, cpu);
6844 }
6845
6846 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
6847 {
6848         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6849         int err = 0;
6850
6851         mutex_lock(&swhash->hlist_mutex);
6852         if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
6853                 struct swevent_hlist *hlist;
6854
6855                 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
6856                 if (!hlist) {
6857                         err = -ENOMEM;
6858                         goto exit;
6859                 }
6860                 rcu_assign_pointer(swhash->swevent_hlist, hlist);
6861         }
6862         swhash->hlist_refcount++;
6863 exit:
6864         mutex_unlock(&swhash->hlist_mutex);
6865
6866         return err;
6867 }
6868
6869 static int swevent_hlist_get(struct perf_event *event)
6870 {
6871         int err;
6872         int cpu, failed_cpu;
6873
6874         get_online_cpus();
6875         for_each_possible_cpu(cpu) {
6876                 err = swevent_hlist_get_cpu(event, cpu);
6877                 if (err) {
6878                         failed_cpu = cpu;
6879                         goto fail;
6880                 }
6881         }
6882         put_online_cpus();
6883
6884         return 0;
6885 fail:
6886         for_each_possible_cpu(cpu) {
6887                 if (cpu == failed_cpu)
6888                         break;
6889                 swevent_hlist_put_cpu(event, cpu);
6890         }
6891
6892         put_online_cpus();
6893         return err;
6894 }
6895
6896 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
6897
6898 static void sw_perf_event_destroy(struct perf_event *event)
6899 {
6900         u64 event_id = event->attr.config;
6901
6902         WARN_ON(event->parent);
6903
6904         static_key_slow_dec(&perf_swevent_enabled[event_id]);
6905         swevent_hlist_put(event);
6906 }
6907
6908 static int perf_swevent_init(struct perf_event *event)
6909 {
6910         u64 event_id = event->attr.config;
6911
6912         if (event->attr.type != PERF_TYPE_SOFTWARE)
6913                 return -ENOENT;
6914
6915         /*
6916          * no branch sampling for software events
6917          */
6918         if (has_branch_stack(event))
6919                 return -EOPNOTSUPP;
6920
6921         switch (event_id) {
6922         case PERF_COUNT_SW_CPU_CLOCK:
6923         case PERF_COUNT_SW_TASK_CLOCK:
6924                 return -ENOENT;
6925
6926         default:
6927                 break;
6928         }
6929
6930         if (event_id >= PERF_COUNT_SW_MAX)
6931                 return -ENOENT;
6932
6933         if (!event->parent) {
6934                 int err;
6935
6936                 err = swevent_hlist_get(event);
6937                 if (err)
6938                         return err;
6939
6940                 static_key_slow_inc(&perf_swevent_enabled[event_id]);
6941                 event->destroy = sw_perf_event_destroy;
6942         }
6943
6944         return 0;
6945 }
6946
6947 static struct pmu perf_swevent = {
6948         .task_ctx_nr    = perf_sw_context,
6949
6950         .capabilities   = PERF_PMU_CAP_NO_NMI,
6951
6952         .event_init     = perf_swevent_init,
6953         .add            = perf_swevent_add,
6954         .del            = perf_swevent_del,
6955         .start          = perf_swevent_start,
6956         .stop           = perf_swevent_stop,
6957         .read           = perf_swevent_read,
6958 };
6959
6960 #ifdef CONFIG_EVENT_TRACING
6961
6962 static int perf_tp_filter_match(struct perf_event *event,
6963                                 struct perf_sample_data *data)
6964 {
6965         void *record = data->raw->data;
6966
6967         /* only top level events have filters set */
6968         if (event->parent)
6969                 event = event->parent;
6970
6971         if (likely(!event->filter) || filter_match_preds(event->filter, record))
6972                 return 1;
6973         return 0;
6974 }
6975
6976 static int perf_tp_event_match(struct perf_event *event,
6977                                 struct perf_sample_data *data,
6978                                 struct pt_regs *regs)
6979 {
6980         if (event->hw.state & PERF_HES_STOPPED)
6981                 return 0;
6982         /*
6983          * All tracepoints are from kernel-space.
6984          */
6985         if (event->attr.exclude_kernel)
6986                 return 0;
6987
6988         if (!perf_tp_filter_match(event, data))
6989                 return 0;
6990
6991         return 1;
6992 }
6993
6994 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
6995                    struct pt_regs *regs, struct hlist_head *head, int rctx,
6996                    struct task_struct *task)
6997 {
6998         struct perf_sample_data data;
6999         struct perf_event *event;
7000
7001         struct perf_raw_record raw = {
7002                 .size = entry_size,
7003                 .data = record,
7004         };
7005
7006         perf_sample_data_init(&data, addr, 0);
7007         data.raw = &raw;
7008
7009         hlist_for_each_entry_rcu(event, head, hlist_entry) {
7010                 if (perf_tp_event_match(event, &data, regs))
7011                         perf_swevent_event(event, count, &data, regs);
7012         }
7013
7014         /*
7015          * If we got specified a target task, also iterate its context and
7016          * deliver this event there too.
7017          */
7018         if (task && task != current) {
7019                 struct perf_event_context *ctx;
7020                 struct trace_entry *entry = record;
7021
7022                 rcu_read_lock();
7023                 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
7024                 if (!ctx)
7025                         goto unlock;
7026
7027                 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
7028                         if (event->cpu != smp_processor_id())
7029                                 continue;
7030                         if (event->attr.type != PERF_TYPE_TRACEPOINT)
7031                                 continue;
7032                         if (event->attr.config != entry->type)
7033                                 continue;
7034                         if (perf_tp_event_match(event, &data, regs))
7035                                 perf_swevent_event(event, count, &data, regs);
7036                 }
7037 unlock:
7038                 rcu_read_unlock();
7039         }
7040
7041         perf_swevent_put_recursion_context(rctx);
7042 }
7043 EXPORT_SYMBOL_GPL(perf_tp_event);
7044
7045 static void tp_perf_event_destroy(struct perf_event *event)
7046 {
7047         perf_trace_destroy(event);
7048 }
7049
7050 static int perf_tp_event_init(struct perf_event *event)
7051 {
7052         int err;
7053
7054         if (event->attr.type != PERF_TYPE_TRACEPOINT)
7055                 return -ENOENT;
7056
7057         /*
7058          * no branch sampling for tracepoint events
7059          */
7060         if (has_branch_stack(event))
7061                 return -EOPNOTSUPP;
7062
7063         err = perf_trace_init(event);
7064         if (err)
7065                 return err;
7066
7067         event->destroy = tp_perf_event_destroy;
7068
7069         return 0;
7070 }
7071
7072 static struct pmu perf_tracepoint = {
7073         .task_ctx_nr    = perf_sw_context,
7074
7075         .event_init     = perf_tp_event_init,
7076         .add            = perf_trace_add,
7077         .del            = perf_trace_del,
7078         .start          = perf_swevent_start,
7079         .stop           = perf_swevent_stop,
7080         .read           = perf_swevent_read,
7081 };
7082
7083 static inline void perf_tp_register(void)
7084 {
7085         perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
7086 }
7087
7088 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7089 {
7090         char *filter_str;
7091         int ret;
7092
7093         if (event->attr.type != PERF_TYPE_TRACEPOINT)
7094                 return -EINVAL;
7095
7096         filter_str = strndup_user(arg, PAGE_SIZE);
7097         if (IS_ERR(filter_str))
7098                 return PTR_ERR(filter_str);
7099
7100         ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
7101
7102         kfree(filter_str);
7103         return ret;
7104 }
7105
7106 static void perf_event_free_filter(struct perf_event *event)
7107 {
7108         ftrace_profile_free_filter(event);
7109 }
7110
7111 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7112 {
7113         struct bpf_prog *prog;
7114
7115         if (event->attr.type != PERF_TYPE_TRACEPOINT)
7116                 return -EINVAL;
7117
7118         if (event->tp_event->prog)
7119                 return -EEXIST;
7120
7121         if (!(event->tp_event->flags & TRACE_EVENT_FL_UKPROBE))
7122                 /* bpf programs can only be attached to u/kprobes */
7123                 return -EINVAL;
7124
7125         prog = bpf_prog_get(prog_fd);
7126         if (IS_ERR(prog))
7127                 return PTR_ERR(prog);
7128
7129         if (prog->type != BPF_PROG_TYPE_KPROBE) {
7130                 /* valid fd, but invalid bpf program type */
7131                 bpf_prog_put(prog);
7132                 return -EINVAL;
7133         }
7134
7135         event->tp_event->prog = prog;
7136         event->tp_event->bpf_prog_owner = event;
7137
7138         return 0;
7139 }
7140
7141 static void perf_event_free_bpf_prog(struct perf_event *event)
7142 {
7143         struct bpf_prog *prog;
7144
7145         if (!event->tp_event)
7146                 return;
7147
7148         prog = event->tp_event->prog;
7149         if (prog && event->tp_event->bpf_prog_owner == event) {
7150                 event->tp_event->prog = NULL;
7151                 bpf_prog_put(prog);
7152         }
7153 }
7154
7155 #else
7156
7157 static inline void perf_tp_register(void)
7158 {
7159 }
7160
7161 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7162 {
7163         return -ENOENT;
7164 }
7165
7166 static void perf_event_free_filter(struct perf_event *event)
7167 {
7168 }
7169
7170 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7171 {
7172         return -ENOENT;
7173 }
7174
7175 static void perf_event_free_bpf_prog(struct perf_event *event)
7176 {
7177 }
7178 #endif /* CONFIG_EVENT_TRACING */
7179
7180 #ifdef CONFIG_HAVE_HW_BREAKPOINT
7181 void perf_bp_event(struct perf_event *bp, void *data)
7182 {
7183         struct perf_sample_data sample;
7184         struct pt_regs *regs = data;
7185
7186         perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
7187
7188         if (!bp->hw.state && !perf_exclude_event(bp, regs))
7189                 perf_swevent_event(bp, 1, &sample, regs);
7190 }
7191 #endif
7192
7193 /*
7194  * hrtimer based swevent callback
7195  */
7196
7197 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
7198 {
7199         enum hrtimer_restart ret = HRTIMER_RESTART;
7200         struct perf_sample_data data;
7201         struct pt_regs *regs;
7202         struct perf_event *event;
7203         u64 period;
7204
7205         event = container_of(hrtimer, struct perf_event, hw.hrtimer);
7206
7207         if (event->state != PERF_EVENT_STATE_ACTIVE)
7208                 return HRTIMER_NORESTART;
7209
7210         event->pmu->read(event);
7211
7212         perf_sample_data_init(&data, 0, event->hw.last_period);
7213         regs = get_irq_regs();
7214
7215         if (regs && !perf_exclude_event(event, regs)) {
7216                 if (!(event->attr.exclude_idle && is_idle_task(current)))
7217                         if (__perf_event_overflow(event, 1, &data, regs))
7218                                 ret = HRTIMER_NORESTART;
7219         }
7220
7221         period = max_t(u64, 10000, event->hw.sample_period);
7222         hrtimer_forward_now(hrtimer, ns_to_ktime(period));
7223
7224         return ret;
7225 }
7226
7227 static void perf_swevent_start_hrtimer(struct perf_event *event)
7228 {
7229         struct hw_perf_event *hwc = &event->hw;
7230         s64 period;
7231
7232         if (!is_sampling_event(event))
7233                 return;
7234
7235         period = local64_read(&hwc->period_left);
7236         if (period) {
7237                 if (period < 0)
7238                         period = 10000;
7239
7240                 local64_set(&hwc->period_left, 0);
7241         } else {
7242                 period = max_t(u64, 10000, hwc->sample_period);
7243         }
7244         hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
7245                       HRTIMER_MODE_REL_PINNED);
7246 }
7247
7248 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
7249 {
7250         struct hw_perf_event *hwc = &event->hw;
7251
7252         if (is_sampling_event(event)) {
7253                 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
7254                 local64_set(&hwc->period_left, ktime_to_ns(remaining));
7255
7256                 hrtimer_cancel(&hwc->hrtimer);
7257         }
7258 }
7259
7260 static void perf_swevent_init_hrtimer(struct perf_event *event)
7261 {
7262         struct hw_perf_event *hwc = &event->hw;
7263
7264         if (!is_sampling_event(event))
7265                 return;
7266
7267         hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7268         hwc->hrtimer.function = perf_swevent_hrtimer;
7269
7270         /*
7271          * Since hrtimers have a fixed rate, we can do a static freq->period
7272          * mapping and avoid the whole period adjust feedback stuff.
7273          */
7274         if (event->attr.freq) {
7275                 long freq = event->attr.sample_freq;
7276
7277                 event->attr.sample_period = NSEC_PER_SEC / freq;
7278                 hwc->sample_period = event->attr.sample_period;
7279                 local64_set(&hwc->period_left, hwc->sample_period);
7280                 hwc->last_period = hwc->sample_period;
7281                 event->attr.freq = 0;
7282         }
7283 }
7284
7285 /*
7286  * Software event: cpu wall time clock
7287  */
7288
7289 static void cpu_clock_event_update(struct perf_event *event)
7290 {
7291         s64 prev;
7292         u64 now;
7293
7294         now = local_clock();
7295         prev = local64_xchg(&event->hw.prev_count, now);
7296         local64_add(now - prev, &event->count);
7297 }
7298
7299 static void cpu_clock_event_start(struct perf_event *event, int flags)
7300 {
7301         local64_set(&event->hw.prev_count, local_clock());
7302         perf_swevent_start_hrtimer(event);
7303 }
7304
7305 static void cpu_clock_event_stop(struct perf_event *event, int flags)
7306 {
7307         perf_swevent_cancel_hrtimer(event);
7308         cpu_clock_event_update(event);
7309 }
7310
7311 static int cpu_clock_event_add(struct perf_event *event, int flags)
7312 {
7313         if (flags & PERF_EF_START)
7314                 cpu_clock_event_start(event, flags);
7315         perf_event_update_userpage(event);
7316
7317         return 0;
7318 }
7319
7320 static void cpu_clock_event_del(struct perf_event *event, int flags)
7321 {
7322         cpu_clock_event_stop(event, flags);
7323 }
7324
7325 static void cpu_clock_event_read(struct perf_event *event)
7326 {
7327         cpu_clock_event_update(event);
7328 }
7329
7330 static int cpu_clock_event_init(struct perf_event *event)
7331 {
7332         if (event->attr.type != PERF_TYPE_SOFTWARE)
7333                 return -ENOENT;
7334
7335         if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
7336                 return -ENOENT;
7337
7338         /*
7339          * no branch sampling for software events
7340          */
7341         if (has_branch_stack(event))
7342                 return -EOPNOTSUPP;
7343
7344         perf_swevent_init_hrtimer(event);
7345
7346         return 0;
7347 }
7348
7349 static struct pmu perf_cpu_clock = {
7350         .task_ctx_nr    = perf_sw_context,
7351
7352         .capabilities   = PERF_PMU_CAP_NO_NMI,
7353
7354         .event_init     = cpu_clock_event_init,
7355         .add            = cpu_clock_event_add,
7356         .del            = cpu_clock_event_del,
7357         .start          = cpu_clock_event_start,
7358         .stop           = cpu_clock_event_stop,
7359         .read           = cpu_clock_event_read,
7360 };
7361
7362 /*
7363  * Software event: task time clock
7364  */
7365
7366 static void task_clock_event_update(struct perf_event *event, u64 now)
7367 {
7368         u64 prev;
7369         s64 delta;
7370
7371         prev = local64_xchg(&event->hw.prev_count, now);
7372         delta = now - prev;
7373         local64_add(delta, &event->count);
7374 }
7375
7376 static void task_clock_event_start(struct perf_event *event, int flags)
7377 {
7378         local64_set(&event->hw.prev_count, event->ctx->time);
7379         perf_swevent_start_hrtimer(event);
7380 }
7381
7382 static void task_clock_event_stop(struct perf_event *event, int flags)
7383 {
7384         perf_swevent_cancel_hrtimer(event);
7385         task_clock_event_update(event, event->ctx->time);
7386 }
7387
7388 static int task_clock_event_add(struct perf_event *event, int flags)
7389 {
7390         if (flags & PERF_EF_START)
7391                 task_clock_event_start(event, flags);
7392         perf_event_update_userpage(event);
7393
7394         return 0;
7395 }
7396
7397 static void task_clock_event_del(struct perf_event *event, int flags)
7398 {
7399         task_clock_event_stop(event, PERF_EF_UPDATE);
7400 }
7401
7402 static void task_clock_event_read(struct perf_event *event)
7403 {
7404         u64 now = perf_clock();
7405         u64 delta = now - event->ctx->timestamp;
7406         u64 time = event->ctx->time + delta;
7407
7408         task_clock_event_update(event, time);
7409 }
7410
7411 static int task_clock_event_init(struct perf_event *event)
7412 {
7413         if (event->attr.type != PERF_TYPE_SOFTWARE)
7414                 return -ENOENT;
7415
7416         if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
7417                 return -ENOENT;
7418
7419         /*
7420          * no branch sampling for software events
7421          */
7422         if (has_branch_stack(event))
7423                 return -EOPNOTSUPP;
7424
7425         perf_swevent_init_hrtimer(event);
7426
7427         return 0;
7428 }
7429
7430 static struct pmu perf_task_clock = {
7431         .task_ctx_nr    = perf_sw_context,
7432
7433         .capabilities   = PERF_PMU_CAP_NO_NMI,
7434
7435         .event_init     = task_clock_event_init,
7436         .add            = task_clock_event_add,
7437         .del            = task_clock_event_del,
7438         .start          = task_clock_event_start,
7439         .stop           = task_clock_event_stop,
7440         .read           = task_clock_event_read,
7441 };
7442
7443 static void perf_pmu_nop_void(struct pmu *pmu)
7444 {
7445 }
7446
7447 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
7448 {
7449 }
7450
7451 static int perf_pmu_nop_int(struct pmu *pmu)
7452 {
7453         return 0;
7454 }
7455
7456 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
7457
7458 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
7459 {
7460         __this_cpu_write(nop_txn_flags, flags);
7461
7462         if (flags & ~PERF_PMU_TXN_ADD)
7463                 return;
7464
7465         perf_pmu_disable(pmu);
7466 }
7467
7468 static int perf_pmu_commit_txn(struct pmu *pmu)
7469 {
7470         unsigned int flags = __this_cpu_read(nop_txn_flags);
7471
7472         __this_cpu_write(nop_txn_flags, 0);
7473
7474         if (flags & ~PERF_PMU_TXN_ADD)
7475                 return 0;
7476
7477         perf_pmu_enable(pmu);
7478         return 0;
7479 }
7480
7481 static void perf_pmu_cancel_txn(struct pmu *pmu)
7482 {
7483         unsigned int flags =  __this_cpu_read(nop_txn_flags);
7484
7485         __this_cpu_write(nop_txn_flags, 0);
7486
7487         if (flags & ~PERF_PMU_TXN_ADD)
7488                 return;
7489
7490         perf_pmu_enable(pmu);
7491 }
7492
7493 static int perf_event_idx_default(struct perf_event *event)
7494 {
7495         return 0;
7496 }
7497
7498 /*
7499  * Ensures all contexts with the same task_ctx_nr have the same
7500  * pmu_cpu_context too.
7501  */
7502 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
7503 {
7504         struct pmu *pmu;
7505
7506         if (ctxn < 0)
7507                 return NULL;
7508
7509         list_for_each_entry(pmu, &pmus, entry) {
7510                 if (pmu->task_ctx_nr == ctxn)
7511                         return pmu->pmu_cpu_context;
7512         }
7513
7514         return NULL;
7515 }
7516
7517 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
7518 {
7519         int cpu;
7520
7521         for_each_possible_cpu(cpu) {
7522                 struct perf_cpu_context *cpuctx;
7523
7524                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7525
7526                 if (cpuctx->unique_pmu == old_pmu)
7527                         cpuctx->unique_pmu = pmu;
7528         }
7529 }
7530
7531 static void free_pmu_context(struct pmu *pmu)
7532 {
7533         struct pmu *i;
7534
7535         mutex_lock(&pmus_lock);
7536         /*
7537          * Like a real lame refcount.
7538          */
7539         list_for_each_entry(i, &pmus, entry) {
7540                 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
7541                         update_pmu_context(i, pmu);
7542                         goto out;
7543                 }
7544         }
7545
7546         free_percpu(pmu->pmu_cpu_context);
7547 out:
7548         mutex_unlock(&pmus_lock);
7549 }
7550 static struct idr pmu_idr;
7551
7552 static ssize_t
7553 type_show(struct device *dev, struct device_attribute *attr, char *page)
7554 {
7555         struct pmu *pmu = dev_get_drvdata(dev);
7556
7557         return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
7558 }
7559 static DEVICE_ATTR_RO(type);
7560
7561 static ssize_t
7562 perf_event_mux_interval_ms_show(struct device *dev,
7563                                 struct device_attribute *attr,
7564                                 char *page)
7565 {
7566         struct pmu *pmu = dev_get_drvdata(dev);
7567
7568         return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
7569 }
7570
7571 static DEFINE_MUTEX(mux_interval_mutex);
7572
7573 static ssize_t
7574 perf_event_mux_interval_ms_store(struct device *dev,
7575                                  struct device_attribute *attr,
7576                                  const char *buf, size_t count)
7577 {
7578         struct pmu *pmu = dev_get_drvdata(dev);
7579         int timer, cpu, ret;
7580
7581         ret = kstrtoint(buf, 0, &timer);
7582         if (ret)
7583                 return ret;
7584
7585         if (timer < 1)
7586                 return -EINVAL;
7587
7588         /* same value, noting to do */
7589         if (timer == pmu->hrtimer_interval_ms)
7590                 return count;
7591
7592         mutex_lock(&mux_interval_mutex);
7593         pmu->hrtimer_interval_ms = timer;
7594
7595         /* update all cpuctx for this PMU */
7596         get_online_cpus();
7597         for_each_online_cpu(cpu) {
7598                 struct perf_cpu_context *cpuctx;
7599                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7600                 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
7601
7602                 cpu_function_call(cpu,
7603                         (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
7604         }
7605         put_online_cpus();
7606         mutex_unlock(&mux_interval_mutex);
7607
7608         return count;
7609 }
7610 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
7611
7612 static struct attribute *pmu_dev_attrs[] = {
7613         &dev_attr_type.attr,
7614         &dev_attr_perf_event_mux_interval_ms.attr,
7615         NULL,
7616 };
7617 ATTRIBUTE_GROUPS(pmu_dev);
7618
7619 static int pmu_bus_running;
7620 static struct bus_type pmu_bus = {
7621         .name           = "event_source",
7622         .dev_groups     = pmu_dev_groups,
7623 };
7624
7625 static void pmu_dev_release(struct device *dev)
7626 {
7627         kfree(dev);
7628 }
7629
7630 static int pmu_dev_alloc(struct pmu *pmu)
7631 {
7632         int ret = -ENOMEM;
7633
7634         pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
7635         if (!pmu->dev)
7636                 goto out;
7637
7638         pmu->dev->groups = pmu->attr_groups;
7639         device_initialize(pmu->dev);
7640         ret = dev_set_name(pmu->dev, "%s", pmu->name);
7641         if (ret)
7642                 goto free_dev;
7643
7644         dev_set_drvdata(pmu->dev, pmu);
7645         pmu->dev->bus = &pmu_bus;
7646         pmu->dev->release = pmu_dev_release;
7647         ret = device_add(pmu->dev);
7648         if (ret)
7649                 goto free_dev;
7650
7651 out:
7652         return ret;
7653
7654 free_dev:
7655         put_device(pmu->dev);
7656         goto out;
7657 }
7658
7659 static struct lock_class_key cpuctx_mutex;
7660 static struct lock_class_key cpuctx_lock;
7661
7662 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
7663 {
7664         int cpu, ret;
7665
7666         mutex_lock(&pmus_lock);
7667         ret = -ENOMEM;
7668         pmu->pmu_disable_count = alloc_percpu(int);
7669         if (!pmu->pmu_disable_count)
7670                 goto unlock;
7671
7672         pmu->type = -1;
7673         if (!name)
7674                 goto skip_type;
7675         pmu->name = name;
7676
7677         if (type < 0) {
7678                 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
7679                 if (type < 0) {
7680                         ret = type;
7681                         goto free_pdc;
7682                 }
7683         }
7684         pmu->type = type;
7685
7686         if (pmu_bus_running) {
7687                 ret = pmu_dev_alloc(pmu);
7688                 if (ret)
7689                         goto free_idr;
7690         }
7691
7692 skip_type:
7693         pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
7694         if (pmu->pmu_cpu_context)
7695                 goto got_cpu_context;
7696
7697         ret = -ENOMEM;
7698         pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
7699         if (!pmu->pmu_cpu_context)
7700                 goto free_dev;
7701
7702         for_each_possible_cpu(cpu) {
7703                 struct perf_cpu_context *cpuctx;
7704
7705                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7706                 __perf_event_init_context(&cpuctx->ctx);
7707                 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
7708                 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
7709                 cpuctx->ctx.pmu = pmu;
7710
7711                 __perf_mux_hrtimer_init(cpuctx, cpu);
7712
7713                 cpuctx->unique_pmu = pmu;
7714         }
7715
7716 got_cpu_context:
7717         if (!pmu->start_txn) {
7718                 if (pmu->pmu_enable) {
7719                         /*
7720                          * If we have pmu_enable/pmu_disable calls, install
7721                          * transaction stubs that use that to try and batch
7722                          * hardware accesses.
7723                          */
7724                         pmu->start_txn  = perf_pmu_start_txn;
7725                         pmu->commit_txn = perf_pmu_commit_txn;
7726                         pmu->cancel_txn = perf_pmu_cancel_txn;
7727                 } else {
7728                         pmu->start_txn  = perf_pmu_nop_txn;
7729                         pmu->commit_txn = perf_pmu_nop_int;
7730                         pmu->cancel_txn = perf_pmu_nop_void;
7731                 }
7732         }
7733
7734         if (!pmu->pmu_enable) {
7735                 pmu->pmu_enable  = perf_pmu_nop_void;
7736                 pmu->pmu_disable = perf_pmu_nop_void;
7737         }
7738
7739         if (!pmu->event_idx)
7740                 pmu->event_idx = perf_event_idx_default;
7741
7742         list_add_rcu(&pmu->entry, &pmus);
7743         atomic_set(&pmu->exclusive_cnt, 0);
7744         ret = 0;
7745 unlock:
7746         mutex_unlock(&pmus_lock);
7747
7748         return ret;
7749
7750 free_dev:
7751         device_del(pmu->dev);
7752         put_device(pmu->dev);
7753
7754 free_idr:
7755         if (pmu->type >= PERF_TYPE_MAX)
7756                 idr_remove(&pmu_idr, pmu->type);
7757
7758 free_pdc:
7759         free_percpu(pmu->pmu_disable_count);
7760         goto unlock;
7761 }
7762 EXPORT_SYMBOL_GPL(perf_pmu_register);
7763
7764 void perf_pmu_unregister(struct pmu *pmu)
7765 {
7766         mutex_lock(&pmus_lock);
7767         list_del_rcu(&pmu->entry);
7768         mutex_unlock(&pmus_lock);
7769
7770         /*
7771          * We dereference the pmu list under both SRCU and regular RCU, so
7772          * synchronize against both of those.
7773          */
7774         synchronize_srcu(&pmus_srcu);
7775         synchronize_rcu();
7776
7777         free_percpu(pmu->pmu_disable_count);
7778         if (pmu->type >= PERF_TYPE_MAX)
7779                 idr_remove(&pmu_idr, pmu->type);
7780         device_del(pmu->dev);
7781         put_device(pmu->dev);
7782         free_pmu_context(pmu);
7783 }
7784 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
7785
7786 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
7787 {
7788         struct perf_event_context *ctx = NULL;
7789         int ret;
7790
7791         if (!try_module_get(pmu->module))
7792                 return -ENODEV;
7793
7794         if (event->group_leader != event) {
7795                 /*
7796                  * This ctx->mutex can nest when we're called through
7797                  * inheritance. See the perf_event_ctx_lock_nested() comment.
7798                  */
7799                 ctx = perf_event_ctx_lock_nested(event->group_leader,
7800                                                  SINGLE_DEPTH_NESTING);
7801                 BUG_ON(!ctx);
7802         }
7803
7804         event->pmu = pmu;
7805         ret = pmu->event_init(event);
7806
7807         if (ctx)
7808                 perf_event_ctx_unlock(event->group_leader, ctx);
7809
7810         if (ret)
7811                 module_put(pmu->module);
7812
7813         return ret;
7814 }
7815
7816 static struct pmu *perf_init_event(struct perf_event *event)
7817 {
7818         struct pmu *pmu = NULL;
7819         int idx;
7820         int ret;
7821
7822         idx = srcu_read_lock(&pmus_srcu);
7823
7824         rcu_read_lock();
7825         pmu = idr_find(&pmu_idr, event->attr.type);
7826         rcu_read_unlock();
7827         if (pmu) {
7828                 ret = perf_try_init_event(pmu, event);
7829                 if (ret)
7830                         pmu = ERR_PTR(ret);
7831                 goto unlock;
7832         }
7833
7834         list_for_each_entry_rcu(pmu, &pmus, entry) {
7835                 ret = perf_try_init_event(pmu, event);
7836                 if (!ret)
7837                         goto unlock;
7838
7839                 if (ret != -ENOENT) {
7840                         pmu = ERR_PTR(ret);
7841                         goto unlock;
7842                 }
7843         }
7844         pmu = ERR_PTR(-ENOENT);
7845 unlock:
7846         srcu_read_unlock(&pmus_srcu, idx);
7847
7848         return pmu;
7849 }
7850
7851 static void account_event_cpu(struct perf_event *event, int cpu)
7852 {
7853         if (event->parent)
7854                 return;
7855
7856         if (is_cgroup_event(event))
7857                 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
7858 }
7859
7860 static void account_event(struct perf_event *event)
7861 {
7862         if (event->parent)
7863                 return;
7864
7865         if (event->attach_state & PERF_ATTACH_TASK)
7866                 static_key_slow_inc(&perf_sched_events.key);
7867         if (event->attr.mmap || event->attr.mmap_data)
7868                 atomic_inc(&nr_mmap_events);
7869         if (event->attr.comm)
7870                 atomic_inc(&nr_comm_events);
7871         if (event->attr.task)
7872                 atomic_inc(&nr_task_events);
7873         if (event->attr.freq) {
7874                 if (atomic_inc_return(&nr_freq_events) == 1)
7875                         tick_nohz_full_kick_all();
7876         }
7877         if (event->attr.context_switch) {
7878                 atomic_inc(&nr_switch_events);
7879                 static_key_slow_inc(&perf_sched_events.key);
7880         }
7881         if (has_branch_stack(event))
7882                 static_key_slow_inc(&perf_sched_events.key);
7883         if (is_cgroup_event(event))
7884                 static_key_slow_inc(&perf_sched_events.key);
7885
7886         account_event_cpu(event, event->cpu);
7887 }
7888
7889 /*
7890  * Allocate and initialize a event structure
7891  */
7892 static struct perf_event *
7893 perf_event_alloc(struct perf_event_attr *attr, int cpu,
7894                  struct task_struct *task,
7895                  struct perf_event *group_leader,
7896                  struct perf_event *parent_event,
7897                  perf_overflow_handler_t overflow_handler,
7898                  void *context, int cgroup_fd)
7899 {
7900         struct pmu *pmu;
7901         struct perf_event *event;
7902         struct hw_perf_event *hwc;
7903         long err = -EINVAL;
7904
7905         if ((unsigned)cpu >= nr_cpu_ids) {
7906                 if (!task || cpu != -1)
7907                         return ERR_PTR(-EINVAL);
7908         }
7909
7910         event = kzalloc(sizeof(*event), GFP_KERNEL);
7911         if (!event)
7912                 return ERR_PTR(-ENOMEM);
7913
7914         /*
7915          * Single events are their own group leaders, with an
7916          * empty sibling list:
7917          */
7918         if (!group_leader)
7919                 group_leader = event;
7920
7921         mutex_init(&event->child_mutex);
7922         INIT_LIST_HEAD(&event->child_list);
7923
7924         INIT_LIST_HEAD(&event->group_entry);
7925         INIT_LIST_HEAD(&event->event_entry);
7926         INIT_LIST_HEAD(&event->sibling_list);
7927         INIT_LIST_HEAD(&event->rb_entry);
7928         INIT_LIST_HEAD(&event->active_entry);
7929         INIT_HLIST_NODE(&event->hlist_entry);
7930
7931
7932         init_waitqueue_head(&event->waitq);
7933         init_irq_work(&event->pending, perf_pending_event);
7934
7935         mutex_init(&event->mmap_mutex);
7936
7937         atomic_long_set(&event->refcount, 1);
7938         event->cpu              = cpu;
7939         event->attr             = *attr;
7940         event->group_leader     = group_leader;
7941         event->pmu              = NULL;
7942         event->oncpu            = -1;
7943
7944         event->parent           = parent_event;
7945
7946         event->ns               = get_pid_ns(task_active_pid_ns(current));
7947         event->id               = atomic64_inc_return(&perf_event_id);
7948
7949         event->state            = PERF_EVENT_STATE_INACTIVE;
7950
7951         if (task) {
7952                 event->attach_state = PERF_ATTACH_TASK;
7953                 /*
7954                  * XXX pmu::event_init needs to know what task to account to
7955                  * and we cannot use the ctx information because we need the
7956                  * pmu before we get a ctx.
7957                  */
7958                 event->hw.target = task;
7959         }
7960
7961         event->clock = &local_clock;
7962         if (parent_event)
7963                 event->clock = parent_event->clock;
7964
7965         if (!overflow_handler && parent_event) {
7966                 overflow_handler = parent_event->overflow_handler;
7967                 context = parent_event->overflow_handler_context;
7968         }
7969
7970         event->overflow_handler = overflow_handler;
7971         event->overflow_handler_context = context;
7972
7973         perf_event__state_init(event);
7974
7975         pmu = NULL;
7976
7977         hwc = &event->hw;
7978         hwc->sample_period = attr->sample_period;
7979         if (attr->freq && attr->sample_freq)
7980                 hwc->sample_period = 1;
7981         hwc->last_period = hwc->sample_period;
7982
7983         local64_set(&hwc->period_left, hwc->sample_period);
7984
7985         /*
7986          * We currently do not support PERF_SAMPLE_READ on inherited events.
7987          * See perf_output_read().
7988          */
7989         if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
7990                 goto err_ns;
7991
7992         if (!has_branch_stack(event))
7993                 event->attr.branch_sample_type = 0;
7994
7995         if (cgroup_fd != -1) {
7996                 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
7997                 if (err)
7998                         goto err_ns;
7999         }
8000
8001         pmu = perf_init_event(event);
8002         if (!pmu)
8003                 goto err_ns;
8004         else if (IS_ERR(pmu)) {
8005                 err = PTR_ERR(pmu);
8006                 goto err_ns;
8007         }
8008
8009         err = exclusive_event_init(event);
8010         if (err)
8011                 goto err_pmu;
8012
8013         if (!event->parent) {
8014                 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
8015                         err = get_callchain_buffers();
8016                         if (err)
8017                                 goto err_per_task;
8018                 }
8019         }
8020
8021         /* symmetric to unaccount_event() in _free_event() */
8022         account_event(event);
8023
8024         return event;
8025
8026 err_per_task:
8027         exclusive_event_destroy(event);
8028
8029 err_pmu:
8030         if (event->destroy)
8031                 event->destroy(event);
8032         module_put(pmu->module);
8033 err_ns:
8034         if (is_cgroup_event(event))
8035                 perf_detach_cgroup(event);
8036         if (event->ns)
8037                 put_pid_ns(event->ns);
8038         kfree(event);
8039
8040         return ERR_PTR(err);
8041 }
8042
8043 static int perf_copy_attr(struct perf_event_attr __user *uattr,
8044                           struct perf_event_attr *attr)
8045 {
8046         u32 size;
8047         int ret;
8048
8049         if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
8050                 return -EFAULT;
8051
8052         /*
8053          * zero the full structure, so that a short copy will be nice.
8054          */
8055         memset(attr, 0, sizeof(*attr));
8056
8057         ret = get_user(size, &uattr->size);
8058         if (ret)
8059                 return ret;
8060
8061         if (size > PAGE_SIZE)   /* silly large */
8062                 goto err_size;
8063
8064         if (!size)              /* abi compat */
8065                 size = PERF_ATTR_SIZE_VER0;
8066
8067         if (size < PERF_ATTR_SIZE_VER0)
8068                 goto err_size;
8069
8070         /*
8071          * If we're handed a bigger struct than we know of,
8072          * ensure all the unknown bits are 0 - i.e. new
8073          * user-space does not rely on any kernel feature
8074          * extensions we dont know about yet.
8075          */
8076         if (size > sizeof(*attr)) {
8077                 unsigned char __user *addr;
8078                 unsigned char __user *end;
8079                 unsigned char val;
8080
8081                 addr = (void __user *)uattr + sizeof(*attr);
8082                 end  = (void __user *)uattr + size;
8083
8084                 for (; addr < end; addr++) {
8085                         ret = get_user(val, addr);
8086                         if (ret)
8087                                 return ret;
8088                         if (val)
8089                                 goto err_size;
8090                 }
8091                 size = sizeof(*attr);
8092         }
8093
8094         ret = copy_from_user(attr, uattr, size);
8095         if (ret)
8096                 return -EFAULT;
8097
8098         if (attr->__reserved_1)
8099                 return -EINVAL;
8100
8101         if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
8102                 return -EINVAL;
8103
8104         if (attr->read_format & ~(PERF_FORMAT_MAX-1))
8105                 return -EINVAL;
8106
8107         if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
8108                 u64 mask = attr->branch_sample_type;
8109
8110                 /* only using defined bits */
8111                 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
8112                         return -EINVAL;
8113
8114                 /* at least one branch bit must be set */
8115                 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
8116                         return -EINVAL;
8117
8118                 /* propagate priv level, when not set for branch */
8119                 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
8120
8121                         /* exclude_kernel checked on syscall entry */
8122                         if (!attr->exclude_kernel)
8123                                 mask |= PERF_SAMPLE_BRANCH_KERNEL;
8124
8125                         if (!attr->exclude_user)
8126                                 mask |= PERF_SAMPLE_BRANCH_USER;
8127
8128                         if (!attr->exclude_hv)
8129                                 mask |= PERF_SAMPLE_BRANCH_HV;
8130                         /*
8131                          * adjust user setting (for HW filter setup)
8132                          */
8133                         attr->branch_sample_type = mask;
8134                 }
8135                 /* privileged levels capture (kernel, hv): check permissions */
8136                 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
8137                     && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8138                         return -EACCES;
8139         }
8140
8141         if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
8142                 ret = perf_reg_validate(attr->sample_regs_user);
8143                 if (ret)
8144                         return ret;
8145         }
8146
8147         if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
8148                 if (!arch_perf_have_user_stack_dump())
8149                         return -ENOSYS;
8150
8151                 /*
8152                  * We have __u32 type for the size, but so far
8153                  * we can only use __u16 as maximum due to the
8154                  * __u16 sample size limit.
8155                  */
8156                 if (attr->sample_stack_user >= USHRT_MAX)
8157                         return -EINVAL;
8158                 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
8159                         return -EINVAL;
8160         }
8161
8162         if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
8163                 ret = perf_reg_validate(attr->sample_regs_intr);
8164 out:
8165         return ret;
8166
8167 err_size:
8168         put_user(sizeof(*attr), &uattr->size);
8169         ret = -E2BIG;
8170         goto out;
8171 }
8172
8173 static int
8174 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
8175 {
8176         struct ring_buffer *rb = NULL;
8177         int ret = -EINVAL;
8178
8179         if (!output_event)
8180                 goto set;
8181
8182         /* don't allow circular references */
8183         if (event == output_event)
8184                 goto out;
8185
8186         /*
8187          * Don't allow cross-cpu buffers
8188          */
8189         if (output_event->cpu != event->cpu)
8190                 goto out;
8191
8192         /*
8193          * If its not a per-cpu rb, it must be the same task.
8194          */
8195         if (output_event->cpu == -1 && output_event->ctx != event->ctx)
8196                 goto out;
8197
8198         /*
8199          * Mixing clocks in the same buffer is trouble you don't need.
8200          */
8201         if (output_event->clock != event->clock)
8202                 goto out;
8203
8204         /*
8205          * If both events generate aux data, they must be on the same PMU
8206          */
8207         if (has_aux(event) && has_aux(output_event) &&
8208             event->pmu != output_event->pmu)
8209                 goto out;
8210
8211 set:
8212         mutex_lock(&event->mmap_mutex);
8213         /* Can't redirect output if we've got an active mmap() */
8214         if (atomic_read(&event->mmap_count))
8215                 goto unlock;
8216
8217         if (output_event) {
8218                 /* get the rb we want to redirect to */
8219                 rb = ring_buffer_get(output_event);
8220                 if (!rb)
8221                         goto unlock;
8222         }
8223
8224         ring_buffer_attach(event, rb);
8225
8226         ret = 0;
8227 unlock:
8228         mutex_unlock(&event->mmap_mutex);
8229
8230 out:
8231         return ret;
8232 }
8233
8234 static void mutex_lock_double(struct mutex *a, struct mutex *b)
8235 {
8236         if (b < a)
8237                 swap(a, b);
8238
8239         mutex_lock(a);
8240         mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
8241 }
8242
8243 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
8244 {
8245         bool nmi_safe = false;
8246
8247         switch (clk_id) {
8248         case CLOCK_MONOTONIC:
8249                 event->clock = &ktime_get_mono_fast_ns;
8250                 nmi_safe = true;
8251                 break;
8252
8253         case CLOCK_MONOTONIC_RAW:
8254                 event->clock = &ktime_get_raw_fast_ns;
8255                 nmi_safe = true;
8256                 break;
8257
8258         case CLOCK_REALTIME:
8259                 event->clock = &ktime_get_real_ns;
8260                 break;
8261
8262         case CLOCK_BOOTTIME:
8263                 event->clock = &ktime_get_boot_ns;
8264                 break;
8265
8266         case CLOCK_TAI:
8267                 event->clock = &ktime_get_tai_ns;
8268                 break;
8269
8270         default:
8271                 return -EINVAL;
8272         }
8273
8274         if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
8275                 return -EINVAL;
8276
8277         return 0;
8278 }
8279
8280 /*
8281  * Variation on perf_event_ctx_lock_nested(), except we take two context
8282  * mutexes.
8283  */
8284 static struct perf_event_context *
8285 __perf_event_ctx_lock_double(struct perf_event *group_leader,
8286                              struct perf_event_context *ctx)
8287 {
8288         struct perf_event_context *gctx;
8289
8290 again:
8291         rcu_read_lock();
8292         gctx = READ_ONCE(group_leader->ctx);
8293         if (!atomic_inc_not_zero(&gctx->refcount)) {
8294                 rcu_read_unlock();
8295                 goto again;
8296         }
8297         rcu_read_unlock();
8298
8299         mutex_lock_double(&gctx->mutex, &ctx->mutex);
8300
8301         if (group_leader->ctx != gctx) {
8302                 mutex_unlock(&ctx->mutex);
8303                 mutex_unlock(&gctx->mutex);
8304                 put_ctx(gctx);
8305                 goto again;
8306         }
8307
8308         return gctx;
8309 }
8310
8311 /**
8312  * sys_perf_event_open - open a performance event, associate it to a task/cpu
8313  *
8314  * @attr_uptr:  event_id type attributes for monitoring/sampling
8315  * @pid:                target pid
8316  * @cpu:                target cpu
8317  * @group_fd:           group leader event fd
8318  */
8319 SYSCALL_DEFINE5(perf_event_open,
8320                 struct perf_event_attr __user *, attr_uptr,
8321                 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
8322 {
8323         struct perf_event *group_leader = NULL, *output_event = NULL;
8324         struct perf_event *event, *sibling;
8325         struct perf_event_attr attr;
8326         struct perf_event_context *ctx, *uninitialized_var(gctx);
8327         struct file *event_file = NULL;
8328         struct fd group = {NULL, 0};
8329         struct task_struct *task = NULL;
8330         struct pmu *pmu;
8331         int event_fd;
8332         int move_group = 0;
8333         int err;
8334         int f_flags = O_RDWR;
8335         int cgroup_fd = -1;
8336
8337         /* for future expandability... */
8338         if (flags & ~PERF_FLAG_ALL)
8339                 return -EINVAL;
8340
8341         if (perf_paranoid_any() && !capable(CAP_SYS_ADMIN))
8342                 return -EACCES;
8343
8344         err = perf_copy_attr(attr_uptr, &attr);
8345         if (err)
8346                 return err;
8347
8348         if (!attr.exclude_kernel) {
8349                 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8350                         return -EACCES;
8351         }
8352
8353         if (attr.freq) {
8354                 if (attr.sample_freq > sysctl_perf_event_sample_rate)
8355                         return -EINVAL;
8356         } else {
8357                 if (attr.sample_period & (1ULL << 63))
8358                         return -EINVAL;
8359         }
8360
8361         /*
8362          * In cgroup mode, the pid argument is used to pass the fd
8363          * opened to the cgroup directory in cgroupfs. The cpu argument
8364          * designates the cpu on which to monitor threads from that
8365          * cgroup.
8366          */
8367         if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
8368                 return -EINVAL;
8369
8370         if (flags & PERF_FLAG_FD_CLOEXEC)
8371                 f_flags |= O_CLOEXEC;
8372
8373         event_fd = get_unused_fd_flags(f_flags);
8374         if (event_fd < 0)
8375                 return event_fd;
8376
8377         if (group_fd != -1) {
8378                 err = perf_fget_light(group_fd, &group);
8379                 if (err)
8380                         goto err_fd;
8381                 group_leader = group.file->private_data;
8382                 if (flags & PERF_FLAG_FD_OUTPUT)
8383                         output_event = group_leader;
8384                 if (flags & PERF_FLAG_FD_NO_GROUP)
8385                         group_leader = NULL;
8386         }
8387
8388         if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
8389                 task = find_lively_task_by_vpid(pid);
8390                 if (IS_ERR(task)) {
8391                         err = PTR_ERR(task);
8392                         goto err_group_fd;
8393                 }
8394         }
8395
8396         if (task && group_leader &&
8397             group_leader->attr.inherit != attr.inherit) {
8398                 err = -EINVAL;
8399                 goto err_task;
8400         }
8401
8402         get_online_cpus();
8403
8404         if (task) {
8405                 err = mutex_lock_interruptible(&task->signal->cred_guard_mutex);
8406                 if (err)
8407                         goto err_cpus;
8408
8409                 /*
8410                  * Reuse ptrace permission checks for now.
8411                  *
8412                  * We must hold cred_guard_mutex across this and any potential
8413                  * perf_install_in_context() call for this new event to
8414                  * serialize against exec() altering our credentials (and the
8415                  * perf_event_exit_task() that could imply).
8416                  */
8417                 err = -EACCES;
8418                 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
8419                         goto err_cred;
8420         }
8421
8422         if (flags & PERF_FLAG_PID_CGROUP)
8423                 cgroup_fd = pid;
8424
8425         event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
8426                                  NULL, NULL, cgroup_fd);
8427         if (IS_ERR(event)) {
8428                 err = PTR_ERR(event);
8429                 goto err_cred;
8430         }
8431
8432         if (is_sampling_event(event)) {
8433                 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
8434                         err = -ENOTSUPP;
8435                         goto err_alloc;
8436                 }
8437         }
8438
8439         /*
8440          * Special case software events and allow them to be part of
8441          * any hardware group.
8442          */
8443         pmu = event->pmu;
8444
8445         if (attr.use_clockid) {
8446                 err = perf_event_set_clock(event, attr.clockid);
8447                 if (err)
8448                         goto err_alloc;
8449         }
8450
8451         if (group_leader &&
8452             (is_software_event(event) != is_software_event(group_leader))) {
8453                 if (is_software_event(event)) {
8454                         /*
8455                          * If event and group_leader are not both a software
8456                          * event, and event is, then group leader is not.
8457                          *
8458                          * Allow the addition of software events to !software
8459                          * groups, this is safe because software events never
8460                          * fail to schedule.
8461                          */
8462                         pmu = group_leader->pmu;
8463                 } else if (is_software_event(group_leader) &&
8464                            (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
8465                         /*
8466                          * In case the group is a pure software group, and we
8467                          * try to add a hardware event, move the whole group to
8468                          * the hardware context.
8469                          */
8470                         move_group = 1;
8471                 }
8472         }
8473
8474         /*
8475          * Get the target context (task or percpu):
8476          */
8477         ctx = find_get_context(pmu, task, event);
8478         if (IS_ERR(ctx)) {
8479                 err = PTR_ERR(ctx);
8480                 goto err_alloc;
8481         }
8482
8483         if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
8484                 err = -EBUSY;
8485                 goto err_context;
8486         }
8487
8488         /*
8489          * Look up the group leader (we will attach this event to it):
8490          */
8491         if (group_leader) {
8492                 err = -EINVAL;
8493
8494                 /*
8495                  * Do not allow a recursive hierarchy (this new sibling
8496                  * becoming part of another group-sibling):
8497                  */
8498                 if (group_leader->group_leader != group_leader)
8499                         goto err_context;
8500
8501                 /* All events in a group should have the same clock */
8502                 if (group_leader->clock != event->clock)
8503                         goto err_context;
8504
8505                 /*
8506                  * Make sure we're both events for the same CPU;
8507                  * grouping events for different CPUs is broken; since
8508                  * you can never concurrently schedule them anyhow.
8509                  */
8510                 if (group_leader->cpu != event->cpu)
8511                         goto err_context;
8512
8513                 /*
8514                  * Make sure we're both on the same task, or both
8515                  * per-CPU events.
8516                  */
8517                 if (group_leader->ctx->task != ctx->task)
8518                         goto err_context;
8519
8520                 /*
8521                  * Do not allow to attach to a group in a different task
8522                  * or CPU context. If we're moving SW events, we'll fix
8523                  * this up later, so allow that.
8524                  */
8525                 if (!move_group && group_leader->ctx != ctx)
8526                         goto err_context;
8527
8528                 /*
8529                  * Only a group leader can be exclusive or pinned
8530                  */
8531                 if (attr.exclusive || attr.pinned)
8532                         goto err_context;
8533         }
8534
8535         if (output_event) {
8536                 err = perf_event_set_output(event, output_event);
8537                 if (err)
8538                         goto err_context;
8539         }
8540
8541         event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
8542                                         f_flags);
8543         if (IS_ERR(event_file)) {
8544                 err = PTR_ERR(event_file);
8545                 event_file = NULL;
8546                 goto err_context;
8547         }
8548
8549         if (move_group) {
8550                 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
8551
8552                 /*
8553                  * Check if we raced against another sys_perf_event_open() call
8554                  * moving the software group underneath us.
8555                  */
8556                 if (!(group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
8557                         /*
8558                          * If someone moved the group out from under us, check
8559                          * if this new event wound up on the same ctx, if so
8560                          * its the regular !move_group case, otherwise fail.
8561                          */
8562                         if (gctx != ctx) {
8563                                 err = -EINVAL;
8564                                 goto err_locked;
8565                         } else {
8566                                 perf_event_ctx_unlock(group_leader, gctx);
8567                                 move_group = 0;
8568                         }
8569                 }
8570         } else {
8571                 mutex_lock(&ctx->mutex);
8572         }
8573
8574         if (!perf_event_validate_size(event)) {
8575                 err = -E2BIG;
8576                 goto err_locked;
8577         }
8578
8579         /*
8580          * Must be under the same ctx::mutex as perf_install_in_context(),
8581          * because we need to serialize with concurrent event creation.
8582          */
8583         if (!exclusive_event_installable(event, ctx)) {
8584                 /* exclusive and group stuff are assumed mutually exclusive */
8585                 WARN_ON_ONCE(move_group);
8586
8587                 err = -EBUSY;
8588                 goto err_locked;
8589         }
8590
8591         WARN_ON_ONCE(ctx->parent_ctx);
8592
8593         /*
8594          * This is the point on no return; we cannot fail hereafter. This is
8595          * where we start modifying current state.
8596          */
8597
8598         if (move_group) {
8599                 /*
8600                  * See perf_event_ctx_lock() for comments on the details
8601                  * of swizzling perf_event::ctx.
8602                  */
8603                 perf_remove_from_context(group_leader, false);
8604
8605                 list_for_each_entry(sibling, &group_leader->sibling_list,
8606                                     group_entry) {
8607                         perf_remove_from_context(sibling, false);
8608                         put_ctx(gctx);
8609                 }
8610
8611                 /*
8612                  * Wait for everybody to stop referencing the events through
8613                  * the old lists, before installing it on new lists.
8614                  */
8615                 synchronize_rcu();
8616
8617                 /*
8618                  * Install the group siblings before the group leader.
8619                  *
8620                  * Because a group leader will try and install the entire group
8621                  * (through the sibling list, which is still in-tact), we can
8622                  * end up with siblings installed in the wrong context.
8623                  *
8624                  * By installing siblings first we NO-OP because they're not
8625                  * reachable through the group lists.
8626                  */
8627                 list_for_each_entry(sibling, &group_leader->sibling_list,
8628                                     group_entry) {
8629                         perf_event__state_init(sibling);
8630                         perf_install_in_context(ctx, sibling, sibling->cpu);
8631                         get_ctx(ctx);
8632                 }
8633
8634                 /*
8635                  * Removing from the context ends up with disabled
8636                  * event. What we want here is event in the initial
8637                  * startup state, ready to be add into new context.
8638                  */
8639                 perf_event__state_init(group_leader);
8640                 perf_install_in_context(ctx, group_leader, group_leader->cpu);
8641                 get_ctx(ctx);
8642
8643                 /*
8644                  * Now that all events are installed in @ctx, nothing
8645                  * references @gctx anymore, so drop the last reference we have
8646                  * on it.
8647                  */
8648                 put_ctx(gctx);
8649         }
8650
8651         /*
8652          * Precalculate sample_data sizes; do while holding ctx::mutex such
8653          * that we're serialized against further additions and before
8654          * perf_install_in_context() which is the point the event is active and
8655          * can use these values.
8656          */
8657         perf_event__header_size(event);
8658         perf_event__id_header_size(event);
8659
8660         perf_install_in_context(ctx, event, event->cpu);
8661         perf_unpin_context(ctx);
8662
8663         if (move_group)
8664                 perf_event_ctx_unlock(group_leader, gctx);
8665         mutex_unlock(&ctx->mutex);
8666
8667         if (task) {
8668                 mutex_unlock(&task->signal->cred_guard_mutex);
8669                 put_task_struct(task);
8670         }
8671
8672         put_online_cpus();
8673
8674         event->owner = current;
8675
8676         mutex_lock(&current->perf_event_mutex);
8677         list_add_tail(&event->owner_entry, &current->perf_event_list);
8678         mutex_unlock(&current->perf_event_mutex);
8679
8680         /*
8681          * Drop the reference on the group_event after placing the
8682          * new event on the sibling_list. This ensures destruction
8683          * of the group leader will find the pointer to itself in
8684          * perf_group_detach().
8685          */
8686         fdput(group);
8687         fd_install(event_fd, event_file);
8688         return event_fd;
8689
8690 err_locked:
8691         if (move_group)
8692                 perf_event_ctx_unlock(group_leader, gctx);
8693         mutex_unlock(&ctx->mutex);
8694 /* err_file: */
8695         fput(event_file);
8696 err_context:
8697         perf_unpin_context(ctx);
8698         put_ctx(ctx);
8699 err_alloc:
8700         /*
8701          * If event_file is set, the fput() above will have called ->release()
8702          * and that will take care of freeing the event.
8703          */
8704         if (!event_file)
8705                 free_event(event);
8706 err_cred:
8707         if (task)
8708                 mutex_unlock(&task->signal->cred_guard_mutex);
8709 err_cpus:
8710         put_online_cpus();
8711 err_task:
8712         if (task)
8713                 put_task_struct(task);
8714 err_group_fd:
8715         fdput(group);
8716 err_fd:
8717         put_unused_fd(event_fd);
8718         return err;
8719 }
8720
8721 /**
8722  * perf_event_create_kernel_counter
8723  *
8724  * @attr: attributes of the counter to create
8725  * @cpu: cpu in which the counter is bound
8726  * @task: task to profile (NULL for percpu)
8727  */
8728 struct perf_event *
8729 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
8730                                  struct task_struct *task,
8731                                  perf_overflow_handler_t overflow_handler,
8732                                  void *context)
8733 {
8734         struct perf_event_context *ctx;
8735         struct perf_event *event;
8736         int err;
8737
8738         /*
8739          * Get the target context (task or percpu):
8740          */
8741
8742         event = perf_event_alloc(attr, cpu, task, NULL, NULL,
8743                                  overflow_handler, context, -1);
8744         if (IS_ERR(event)) {
8745                 err = PTR_ERR(event);
8746                 goto err;
8747         }
8748
8749         /* Mark owner so we could distinguish it from user events. */
8750         event->owner = EVENT_OWNER_KERNEL;
8751
8752         ctx = find_get_context(event->pmu, task, event);
8753         if (IS_ERR(ctx)) {
8754                 err = PTR_ERR(ctx);
8755                 goto err_free;
8756         }
8757
8758         WARN_ON_ONCE(ctx->parent_ctx);
8759         mutex_lock(&ctx->mutex);
8760         if (!exclusive_event_installable(event, ctx)) {
8761                 mutex_unlock(&ctx->mutex);
8762                 perf_unpin_context(ctx);
8763                 put_ctx(ctx);
8764                 err = -EBUSY;
8765                 goto err_free;
8766         }
8767
8768         perf_install_in_context(ctx, event, event->cpu);
8769         perf_unpin_context(ctx);
8770         mutex_unlock(&ctx->mutex);
8771
8772         return event;
8773
8774 err_free:
8775         free_event(event);
8776 err:
8777         return ERR_PTR(err);
8778 }
8779 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
8780
8781 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
8782 {
8783         struct perf_event_context *src_ctx;
8784         struct perf_event_context *dst_ctx;
8785         struct perf_event *event, *tmp;
8786         LIST_HEAD(events);
8787
8788         src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
8789         dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
8790
8791         /*
8792          * See perf_event_ctx_lock() for comments on the details
8793          * of swizzling perf_event::ctx.
8794          */
8795         mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
8796         list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
8797                                  event_entry) {
8798                 perf_remove_from_context(event, false);
8799                 unaccount_event_cpu(event, src_cpu);
8800                 put_ctx(src_ctx);
8801                 list_add(&event->migrate_entry, &events);
8802         }
8803
8804         /*
8805          * Wait for the events to quiesce before re-instating them.
8806          */
8807         synchronize_rcu();
8808
8809         /*
8810          * Re-instate events in 2 passes.
8811          *
8812          * Skip over group leaders and only install siblings on this first
8813          * pass, siblings will not get enabled without a leader, however a
8814          * leader will enable its siblings, even if those are still on the old
8815          * context.
8816          */
8817         list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
8818                 if (event->group_leader == event)
8819                         continue;
8820
8821                 list_del(&event->migrate_entry);
8822                 if (event->state >= PERF_EVENT_STATE_OFF)
8823                         event->state = PERF_EVENT_STATE_INACTIVE;
8824                 account_event_cpu(event, dst_cpu);
8825                 perf_install_in_context(dst_ctx, event, dst_cpu);
8826                 get_ctx(dst_ctx);
8827         }
8828
8829         /*
8830          * Once all the siblings are setup properly, install the group leaders
8831          * to make it go.
8832          */
8833         list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
8834                 list_del(&event->migrate_entry);
8835                 if (event->state >= PERF_EVENT_STATE_OFF)
8836                         event->state = PERF_EVENT_STATE_INACTIVE;
8837                 account_event_cpu(event, dst_cpu);
8838                 perf_install_in_context(dst_ctx, event, dst_cpu);
8839                 get_ctx(dst_ctx);
8840         }
8841         mutex_unlock(&dst_ctx->mutex);
8842         mutex_unlock(&src_ctx->mutex);
8843 }
8844 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
8845
8846 static void sync_child_event(struct perf_event *child_event,
8847                                struct task_struct *child)
8848 {
8849         struct perf_event *parent_event = child_event->parent;
8850         u64 child_val;
8851
8852         if (child_event->attr.inherit_stat)
8853                 perf_event_read_event(child_event, child);
8854
8855         child_val = perf_event_count(child_event);
8856
8857         /*
8858          * Add back the child's count to the parent's count:
8859          */
8860         atomic64_add(child_val, &parent_event->child_count);
8861         atomic64_add(child_event->total_time_enabled,
8862                      &parent_event->child_total_time_enabled);
8863         atomic64_add(child_event->total_time_running,
8864                      &parent_event->child_total_time_running);
8865
8866         /*
8867          * Remove this event from the parent's list
8868          */
8869         WARN_ON_ONCE(parent_event->ctx->parent_ctx);
8870         mutex_lock(&parent_event->child_mutex);
8871         list_del_init(&child_event->child_list);
8872         mutex_unlock(&parent_event->child_mutex);
8873
8874         /*
8875          * Make sure user/parent get notified, that we just
8876          * lost one event.
8877          */
8878         perf_event_wakeup(parent_event);
8879
8880         /*
8881          * Release the parent event, if this was the last
8882          * reference to it.
8883          */
8884         put_event(parent_event);
8885 }
8886
8887 static void
8888 __perf_event_exit_task(struct perf_event *child_event,
8889                          struct perf_event_context *child_ctx,
8890                          struct task_struct *child)
8891 {
8892         /*
8893          * Do not destroy the 'original' grouping; because of the context
8894          * switch optimization the original events could've ended up in a
8895          * random child task.
8896          *
8897          * If we were to destroy the original group, all group related
8898          * operations would cease to function properly after this random
8899          * child dies.
8900          *
8901          * Do destroy all inherited groups, we don't care about those
8902          * and being thorough is better.
8903          */
8904         perf_remove_from_context(child_event, !!child_event->parent);
8905
8906         /*
8907          * It can happen that the parent exits first, and has events
8908          * that are still around due to the child reference. These
8909          * events need to be zapped.
8910          */
8911         if (child_event->parent) {
8912                 sync_child_event(child_event, child);
8913                 free_event(child_event);
8914         } else {
8915                 child_event->state = PERF_EVENT_STATE_EXIT;
8916                 perf_event_wakeup(child_event);
8917         }
8918 }
8919
8920 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
8921 {
8922         struct perf_event *child_event, *next;
8923         struct perf_event_context *child_ctx, *clone_ctx = NULL;
8924         unsigned long flags;
8925
8926         if (likely(!child->perf_event_ctxp[ctxn]))
8927                 return;
8928
8929         local_irq_save(flags);
8930         /*
8931          * We can't reschedule here because interrupts are disabled,
8932          * and either child is current or it is a task that can't be
8933          * scheduled, so we are now safe from rescheduling changing
8934          * our context.
8935          */
8936         child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
8937
8938         /*
8939          * Take the context lock here so that if find_get_context is
8940          * reading child->perf_event_ctxp, we wait until it has
8941          * incremented the context's refcount before we do put_ctx below.
8942          */
8943         raw_spin_lock(&child_ctx->lock);
8944         task_ctx_sched_out(child_ctx);
8945         child->perf_event_ctxp[ctxn] = NULL;
8946
8947         /*
8948          * If this context is a clone; unclone it so it can't get
8949          * swapped to another process while we're removing all
8950          * the events from it.
8951          */
8952         clone_ctx = unclone_ctx(child_ctx);
8953         update_context_time(child_ctx);
8954         raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
8955
8956         if (clone_ctx)
8957                 put_ctx(clone_ctx);
8958
8959         /*
8960          * Report the task dead after unscheduling the events so that we
8961          * won't get any samples after PERF_RECORD_EXIT. We can however still
8962          * get a few PERF_RECORD_READ events.
8963          */
8964         perf_event_task(child, child_ctx, 0);
8965
8966         /*
8967          * We can recurse on the same lock type through:
8968          *
8969          *   __perf_event_exit_task()
8970          *     sync_child_event()
8971          *       put_event()
8972          *         mutex_lock(&ctx->mutex)
8973          *
8974          * But since its the parent context it won't be the same instance.
8975          */
8976         mutex_lock(&child_ctx->mutex);
8977
8978         list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
8979                 __perf_event_exit_task(child_event, child_ctx, child);
8980
8981         mutex_unlock(&child_ctx->mutex);
8982
8983         put_ctx(child_ctx);
8984 }
8985
8986 /*
8987  * When a child task exits, feed back event values to parent events.
8988  *
8989  * Can be called with cred_guard_mutex held when called from
8990  * install_exec_creds().
8991  */
8992 void perf_event_exit_task(struct task_struct *child)
8993 {
8994         struct perf_event *event, *tmp;
8995         int ctxn;
8996
8997         mutex_lock(&child->perf_event_mutex);
8998         list_for_each_entry_safe(event, tmp, &child->perf_event_list,
8999                                  owner_entry) {
9000                 list_del_init(&event->owner_entry);
9001
9002                 /*
9003                  * Ensure the list deletion is visible before we clear
9004                  * the owner, closes a race against perf_release() where
9005                  * we need to serialize on the owner->perf_event_mutex.
9006                  */
9007                 smp_wmb();
9008                 event->owner = NULL;
9009         }
9010         mutex_unlock(&child->perf_event_mutex);
9011
9012         for_each_task_context_nr(ctxn)
9013                 perf_event_exit_task_context(child, ctxn);
9014
9015         /*
9016          * The perf_event_exit_task_context calls perf_event_task
9017          * with child's task_ctx, which generates EXIT events for
9018          * child contexts and sets child->perf_event_ctxp[] to NULL.
9019          * At this point we need to send EXIT events to cpu contexts.
9020          */
9021         perf_event_task(child, NULL, 0);
9022 }
9023
9024 static void perf_free_event(struct perf_event *event,
9025                             struct perf_event_context *ctx)
9026 {
9027         struct perf_event *parent = event->parent;
9028
9029         if (WARN_ON_ONCE(!parent))
9030                 return;
9031
9032         mutex_lock(&parent->child_mutex);
9033         list_del_init(&event->child_list);
9034         mutex_unlock(&parent->child_mutex);
9035
9036         put_event(parent);
9037
9038         raw_spin_lock_irq(&ctx->lock);
9039         perf_group_detach(event);
9040         list_del_event(event, ctx);
9041         raw_spin_unlock_irq(&ctx->lock);
9042         free_event(event);
9043 }
9044
9045 /*
9046  * Free an unexposed, unused context as created by inheritance by
9047  * perf_event_init_task below, used by fork() in case of fail.
9048  *
9049  * Not all locks are strictly required, but take them anyway to be nice and
9050  * help out with the lockdep assertions.
9051  */
9052 void perf_event_free_task(struct task_struct *task)
9053 {
9054         struct perf_event_context *ctx;
9055         struct perf_event *event, *tmp;
9056         int ctxn;
9057
9058         for_each_task_context_nr(ctxn) {
9059                 ctx = task->perf_event_ctxp[ctxn];
9060                 if (!ctx)
9061                         continue;
9062
9063                 mutex_lock(&ctx->mutex);
9064 again:
9065                 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
9066                                 group_entry)
9067                         perf_free_event(event, ctx);
9068
9069                 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
9070                                 group_entry)
9071                         perf_free_event(event, ctx);
9072
9073                 if (!list_empty(&ctx->pinned_groups) ||
9074                                 !list_empty(&ctx->flexible_groups))
9075                         goto again;
9076
9077                 mutex_unlock(&ctx->mutex);
9078
9079                 put_ctx(ctx);
9080         }
9081 }
9082
9083 void perf_event_delayed_put(struct task_struct *task)
9084 {
9085         int ctxn;
9086
9087         for_each_task_context_nr(ctxn)
9088                 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
9089 }
9090
9091 struct perf_event *perf_event_get(unsigned int fd)
9092 {
9093         int err;
9094         struct fd f;
9095         struct perf_event *event;
9096
9097         err = perf_fget_light(fd, &f);
9098         if (err)
9099                 return ERR_PTR(err);
9100
9101         event = f.file->private_data;
9102         atomic_long_inc(&event->refcount);
9103         fdput(f);
9104
9105         return event;
9106 }
9107
9108 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
9109 {
9110         if (!event)
9111                 return ERR_PTR(-EINVAL);
9112
9113         return &event->attr;
9114 }
9115
9116 /*
9117  * inherit a event from parent task to child task:
9118  */
9119 static struct perf_event *
9120 inherit_event(struct perf_event *parent_event,
9121               struct task_struct *parent,
9122               struct perf_event_context *parent_ctx,
9123               struct task_struct *child,
9124               struct perf_event *group_leader,
9125               struct perf_event_context *child_ctx)
9126 {
9127         enum perf_event_active_state parent_state = parent_event->state;
9128         struct perf_event *child_event;
9129         unsigned long flags;
9130
9131         /*
9132          * Instead of creating recursive hierarchies of events,
9133          * we link inherited events back to the original parent,
9134          * which has a filp for sure, which we use as the reference
9135          * count:
9136          */
9137         if (parent_event->parent)
9138                 parent_event = parent_event->parent;
9139
9140         child_event = perf_event_alloc(&parent_event->attr,
9141                                            parent_event->cpu,
9142                                            child,
9143                                            group_leader, parent_event,
9144                                            NULL, NULL, -1);
9145         if (IS_ERR(child_event))
9146                 return child_event;
9147
9148         if (is_orphaned_event(parent_event) ||
9149             !atomic_long_inc_not_zero(&parent_event->refcount)) {
9150                 free_event(child_event);
9151                 return NULL;
9152         }
9153
9154         get_ctx(child_ctx);
9155
9156         /*
9157          * Make the child state follow the state of the parent event,
9158          * not its attr.disabled bit.  We hold the parent's mutex,
9159          * so we won't race with perf_event_{en, dis}able_family.
9160          */
9161         if (parent_state >= PERF_EVENT_STATE_INACTIVE)
9162                 child_event->state = PERF_EVENT_STATE_INACTIVE;
9163         else
9164                 child_event->state = PERF_EVENT_STATE_OFF;
9165
9166         if (parent_event->attr.freq) {
9167                 u64 sample_period = parent_event->hw.sample_period;
9168                 struct hw_perf_event *hwc = &child_event->hw;
9169
9170                 hwc->sample_period = sample_period;
9171                 hwc->last_period   = sample_period;
9172
9173                 local64_set(&hwc->period_left, sample_period);
9174         }
9175
9176         child_event->ctx = child_ctx;
9177         child_event->overflow_handler = parent_event->overflow_handler;
9178         child_event->overflow_handler_context
9179                 = parent_event->overflow_handler_context;
9180
9181         /*
9182          * Precalculate sample_data sizes
9183          */
9184         perf_event__header_size(child_event);
9185         perf_event__id_header_size(child_event);
9186
9187         /*
9188          * Link it up in the child's context:
9189          */
9190         raw_spin_lock_irqsave(&child_ctx->lock, flags);
9191         add_event_to_ctx(child_event, child_ctx);
9192         raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
9193
9194         /*
9195          * Link this into the parent event's child list
9196          */
9197         WARN_ON_ONCE(parent_event->ctx->parent_ctx);
9198         mutex_lock(&parent_event->child_mutex);
9199         list_add_tail(&child_event->child_list, &parent_event->child_list);
9200         mutex_unlock(&parent_event->child_mutex);
9201
9202         return child_event;
9203 }
9204
9205 static int inherit_group(struct perf_event *parent_event,
9206               struct task_struct *parent,
9207               struct perf_event_context *parent_ctx,
9208               struct task_struct *child,
9209               struct perf_event_context *child_ctx)
9210 {
9211         struct perf_event *leader;
9212         struct perf_event *sub;
9213         struct perf_event *child_ctr;
9214
9215         leader = inherit_event(parent_event, parent, parent_ctx,
9216                                  child, NULL, child_ctx);
9217         if (IS_ERR(leader))
9218                 return PTR_ERR(leader);
9219         list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
9220                 child_ctr = inherit_event(sub, parent, parent_ctx,
9221                                             child, leader, child_ctx);
9222                 if (IS_ERR(child_ctr))
9223                         return PTR_ERR(child_ctr);
9224         }
9225         return 0;
9226 }
9227
9228 static int
9229 inherit_task_group(struct perf_event *event, struct task_struct *parent,
9230                    struct perf_event_context *parent_ctx,
9231                    struct task_struct *child, int ctxn,
9232                    int *inherited_all)
9233 {
9234         int ret;
9235         struct perf_event_context *child_ctx;
9236
9237         if (!event->attr.inherit) {
9238                 *inherited_all = 0;
9239                 return 0;
9240         }
9241
9242         child_ctx = child->perf_event_ctxp[ctxn];
9243         if (!child_ctx) {
9244                 /*
9245                  * This is executed from the parent task context, so
9246                  * inherit events that have been marked for cloning.
9247                  * First allocate and initialize a context for the
9248                  * child.
9249                  */
9250
9251                 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
9252                 if (!child_ctx)
9253                         return -ENOMEM;
9254
9255                 child->perf_event_ctxp[ctxn] = child_ctx;
9256         }
9257
9258         ret = inherit_group(event, parent, parent_ctx,
9259                             child, child_ctx);
9260
9261         if (ret)
9262                 *inherited_all = 0;
9263
9264         return ret;
9265 }
9266
9267 /*
9268  * Initialize the perf_event context in task_struct
9269  */
9270 static int perf_event_init_context(struct task_struct *child, int ctxn)
9271 {
9272         struct perf_event_context *child_ctx, *parent_ctx;
9273         struct perf_event_context *cloned_ctx;
9274         struct perf_event *event;
9275         struct task_struct *parent = current;
9276         int inherited_all = 1;
9277         unsigned long flags;
9278         int ret = 0;
9279
9280         if (likely(!parent->perf_event_ctxp[ctxn]))
9281                 return 0;
9282
9283         /*
9284          * If the parent's context is a clone, pin it so it won't get
9285          * swapped under us.
9286          */
9287         parent_ctx = perf_pin_task_context(parent, ctxn);
9288         if (!parent_ctx)
9289                 return 0;
9290
9291         /*
9292          * No need to check if parent_ctx != NULL here; since we saw
9293          * it non-NULL earlier, the only reason for it to become NULL
9294          * is if we exit, and since we're currently in the middle of
9295          * a fork we can't be exiting at the same time.
9296          */
9297
9298         /*
9299          * Lock the parent list. No need to lock the child - not PID
9300          * hashed yet and not running, so nobody can access it.
9301          */
9302         mutex_lock(&parent_ctx->mutex);
9303
9304         /*
9305          * We dont have to disable NMIs - we are only looking at
9306          * the list, not manipulating it:
9307          */
9308         list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
9309                 ret = inherit_task_group(event, parent, parent_ctx,
9310                                          child, ctxn, &inherited_all);
9311                 if (ret)
9312                         goto out_unlock;
9313         }
9314
9315         /*
9316          * We can't hold ctx->lock when iterating the ->flexible_group list due
9317          * to allocations, but we need to prevent rotation because
9318          * rotate_ctx() will change the list from interrupt context.
9319          */
9320         raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9321         parent_ctx->rotate_disable = 1;
9322         raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
9323
9324         list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
9325                 ret = inherit_task_group(event, parent, parent_ctx,
9326                                          child, ctxn, &inherited_all);
9327                 if (ret)
9328                         goto out_unlock;
9329         }
9330
9331         raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9332         parent_ctx->rotate_disable = 0;
9333
9334         child_ctx = child->perf_event_ctxp[ctxn];
9335
9336         if (child_ctx && inherited_all) {
9337                 /*
9338                  * Mark the child context as a clone of the parent
9339                  * context, or of whatever the parent is a clone of.
9340                  *
9341                  * Note that if the parent is a clone, the holding of
9342                  * parent_ctx->lock avoids it from being uncloned.
9343                  */
9344                 cloned_ctx = parent_ctx->parent_ctx;
9345                 if (cloned_ctx) {
9346                         child_ctx->parent_ctx = cloned_ctx;
9347                         child_ctx->parent_gen = parent_ctx->parent_gen;
9348                 } else {
9349                         child_ctx->parent_ctx = parent_ctx;
9350                         child_ctx->parent_gen = parent_ctx->generation;
9351                 }
9352                 get_ctx(child_ctx->parent_ctx);
9353         }
9354
9355         raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
9356 out_unlock:
9357         mutex_unlock(&parent_ctx->mutex);
9358
9359         perf_unpin_context(parent_ctx);
9360         put_ctx(parent_ctx);
9361
9362         return ret;
9363 }
9364
9365 /*
9366  * Initialize the perf_event context in task_struct
9367  */
9368 int perf_event_init_task(struct task_struct *child)
9369 {
9370         int ctxn, ret;
9371
9372         memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
9373         mutex_init(&child->perf_event_mutex);
9374         INIT_LIST_HEAD(&child->perf_event_list);
9375
9376         for_each_task_context_nr(ctxn) {
9377                 ret = perf_event_init_context(child, ctxn);
9378                 if (ret) {
9379                         perf_event_free_task(child);
9380                         return ret;
9381                 }
9382         }
9383
9384         return 0;
9385 }
9386
9387 static void __init perf_event_init_all_cpus(void)
9388 {
9389         struct swevent_htable *swhash;
9390         int cpu;
9391
9392         for_each_possible_cpu(cpu) {
9393                 swhash = &per_cpu(swevent_htable, cpu);
9394                 mutex_init(&swhash->hlist_mutex);
9395                 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
9396         }
9397 }
9398
9399 static void perf_event_init_cpu(int cpu)
9400 {
9401         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
9402
9403         mutex_lock(&swhash->hlist_mutex);
9404         if (swhash->hlist_refcount > 0) {
9405                 struct swevent_hlist *hlist;
9406
9407                 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
9408                 WARN_ON(!hlist);
9409                 rcu_assign_pointer(swhash->swevent_hlist, hlist);
9410         }
9411         mutex_unlock(&swhash->hlist_mutex);
9412 }
9413
9414 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
9415 static void __perf_event_exit_context(void *__info)
9416 {
9417         struct remove_event re = { .detach_group = true };
9418         struct perf_event_context *ctx = __info;
9419
9420         rcu_read_lock();
9421         list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
9422                 __perf_remove_from_context(&re);
9423         rcu_read_unlock();
9424 }
9425
9426 static void perf_event_exit_cpu_context(int cpu)
9427 {
9428         struct perf_event_context *ctx;
9429         struct pmu *pmu;
9430         int idx;
9431
9432         idx = srcu_read_lock(&pmus_srcu);
9433         list_for_each_entry_rcu(pmu, &pmus, entry) {
9434                 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
9435
9436                 mutex_lock(&ctx->mutex);
9437                 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
9438                 mutex_unlock(&ctx->mutex);
9439         }
9440         srcu_read_unlock(&pmus_srcu, idx);
9441 }
9442
9443 static void perf_event_exit_cpu(int cpu)
9444 {
9445         perf_event_exit_cpu_context(cpu);
9446 }
9447 #else
9448 static inline void perf_event_exit_cpu(int cpu) { }
9449 #endif
9450
9451 static int
9452 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
9453 {
9454         int cpu;
9455
9456         for_each_online_cpu(cpu)
9457                 perf_event_exit_cpu(cpu);
9458
9459         return NOTIFY_OK;
9460 }
9461
9462 /*
9463  * Run the perf reboot notifier at the very last possible moment so that
9464  * the generic watchdog code runs as long as possible.
9465  */
9466 static struct notifier_block perf_reboot_notifier = {
9467         .notifier_call = perf_reboot,
9468         .priority = INT_MIN,
9469 };
9470
9471 static int
9472 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
9473 {
9474         unsigned int cpu = (long)hcpu;
9475
9476         switch (action & ~CPU_TASKS_FROZEN) {
9477
9478         case CPU_UP_PREPARE:
9479         case CPU_DOWN_FAILED:
9480                 perf_event_init_cpu(cpu);
9481                 break;
9482
9483         case CPU_UP_CANCELED:
9484         case CPU_DOWN_PREPARE:
9485                 perf_event_exit_cpu(cpu);
9486                 break;
9487         default:
9488                 break;
9489         }
9490
9491         return NOTIFY_OK;
9492 }
9493
9494 void __init perf_event_init(void)
9495 {
9496         int ret;
9497
9498         idr_init(&pmu_idr);
9499
9500         perf_event_init_all_cpus();
9501         init_srcu_struct(&pmus_srcu);
9502         perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
9503         perf_pmu_register(&perf_cpu_clock, NULL, -1);
9504         perf_pmu_register(&perf_task_clock, NULL, -1);
9505         perf_tp_register();
9506         perf_cpu_notifier(perf_cpu_notify);
9507         register_reboot_notifier(&perf_reboot_notifier);
9508
9509         ret = init_hw_breakpoint();
9510         WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
9511
9512         /* do not patch jump label more than once per second */
9513         jump_label_rate_limit(&perf_sched_events, HZ);
9514
9515         /*
9516          * Build time assertion that we keep the data_head at the intended
9517          * location.  IOW, validation we got the __reserved[] size right.
9518          */
9519         BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
9520                      != 1024);
9521 }
9522
9523 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
9524                               char *page)
9525 {
9526         struct perf_pmu_events_attr *pmu_attr =
9527                 container_of(attr, struct perf_pmu_events_attr, attr);
9528
9529         if (pmu_attr->event_str)
9530                 return sprintf(page, "%s\n", pmu_attr->event_str);
9531
9532         return 0;
9533 }
9534
9535 static int __init perf_event_sysfs_init(void)
9536 {
9537         struct pmu *pmu;
9538         int ret;
9539
9540         mutex_lock(&pmus_lock);
9541
9542         ret = bus_register(&pmu_bus);
9543         if (ret)
9544                 goto unlock;
9545
9546         list_for_each_entry(pmu, &pmus, entry) {
9547                 if (!pmu->name || pmu->type < 0)
9548                         continue;
9549
9550                 ret = pmu_dev_alloc(pmu);
9551                 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
9552         }
9553         pmu_bus_running = 1;
9554         ret = 0;
9555
9556 unlock:
9557         mutex_unlock(&pmus_lock);
9558
9559         return ret;
9560 }
9561 device_initcall(perf_event_sysfs_init);
9562
9563 #ifdef CONFIG_CGROUP_PERF
9564 static struct cgroup_subsys_state *
9565 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
9566 {
9567         struct perf_cgroup *jc;
9568
9569         jc = kzalloc(sizeof(*jc), GFP_KERNEL);
9570         if (!jc)
9571                 return ERR_PTR(-ENOMEM);
9572
9573         jc->info = alloc_percpu(struct perf_cgroup_info);
9574         if (!jc->info) {
9575                 kfree(jc);
9576                 return ERR_PTR(-ENOMEM);
9577         }
9578
9579         return &jc->css;
9580 }
9581
9582 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
9583 {
9584         struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
9585
9586         free_percpu(jc->info);
9587         kfree(jc);
9588 }
9589
9590 static int __perf_cgroup_move(void *info)
9591 {
9592         struct task_struct *task = info;
9593         rcu_read_lock();
9594         perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
9595         rcu_read_unlock();
9596         return 0;
9597 }
9598
9599 static void perf_cgroup_attach(struct cgroup_taskset *tset)
9600 {
9601         struct task_struct *task;
9602         struct cgroup_subsys_state *css;
9603
9604         cgroup_taskset_for_each(task, css, tset)
9605                 task_function_call(task, __perf_cgroup_move, task);
9606 }
9607
9608 struct cgroup_subsys perf_event_cgrp_subsys = {
9609         .css_alloc      = perf_cgroup_css_alloc,
9610         .css_free       = perf_cgroup_css_free,
9611         .attach         = perf_cgroup_attach,
9612 };
9613 #endif /* CONFIG_CGROUP_PERF */