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