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