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