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