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