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