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