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