Merge branch 'perf/x86' into perf/core, because it's ready
[cascardo/linux.git] / kernel / events / core.c
1 /*
2  * Performance events core code:
3  *
4  *  Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
5  *  Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
6  *  Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
7  *  Copyright  ©  2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
8  *
9  * For licensing details see kernel-base/COPYING
10  */
11
12 #include <linux/fs.h>
13 #include <linux/mm.h>
14 #include <linux/cpu.h>
15 #include <linux/smp.h>
16 #include <linux/idr.h>
17 #include <linux/file.h>
18 #include <linux/poll.h>
19 #include <linux/slab.h>
20 #include <linux/hash.h>
21 #include <linux/tick.h>
22 #include <linux/sysfs.h>
23 #include <linux/dcache.h>
24 #include <linux/percpu.h>
25 #include <linux/ptrace.h>
26 #include <linux/reboot.h>
27 #include <linux/vmstat.h>
28 #include <linux/device.h>
29 #include <linux/export.h>
30 #include <linux/vmalloc.h>
31 #include <linux/hardirq.h>
32 #include <linux/rculist.h>
33 #include <linux/uaccess.h>
34 #include <linux/syscalls.h>
35 #include <linux/anon_inodes.h>
36 #include <linux/kernel_stat.h>
37 #include <linux/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         if (event->pmu->count)
3198                 return event->pmu->count(event);
3199
3200         return __perf_event_count(event);
3201 }
3202
3203 static u64 perf_event_read(struct perf_event *event)
3204 {
3205         /*
3206          * If event is enabled and currently active on a CPU, update the
3207          * value in the event structure:
3208          */
3209         if (event->state == PERF_EVENT_STATE_ACTIVE) {
3210                 smp_call_function_single(event->oncpu,
3211                                          __perf_event_read, event, 1);
3212         } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3213                 struct perf_event_context *ctx = event->ctx;
3214                 unsigned long flags;
3215
3216                 raw_spin_lock_irqsave(&ctx->lock, flags);
3217                 /*
3218                  * may read while context is not active
3219                  * (e.g., thread is blocked), in that case
3220                  * we cannot update context time
3221                  */
3222                 if (ctx->is_active) {
3223                         update_context_time(ctx);
3224                         update_cgrp_time_from_event(event);
3225                 }
3226                 update_event_times(event);
3227                 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3228         }
3229
3230         return perf_event_count(event);
3231 }
3232
3233 /*
3234  * Initialize the perf_event context in a task_struct:
3235  */
3236 static void __perf_event_init_context(struct perf_event_context *ctx)
3237 {
3238         raw_spin_lock_init(&ctx->lock);
3239         mutex_init(&ctx->mutex);
3240         INIT_LIST_HEAD(&ctx->active_ctx_list);
3241         INIT_LIST_HEAD(&ctx->pinned_groups);
3242         INIT_LIST_HEAD(&ctx->flexible_groups);
3243         INIT_LIST_HEAD(&ctx->event_list);
3244         atomic_set(&ctx->refcount, 1);
3245         INIT_DELAYED_WORK(&ctx->orphans_remove, orphans_remove_work);
3246 }
3247
3248 static struct perf_event_context *
3249 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3250 {
3251         struct perf_event_context *ctx;
3252
3253         ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3254         if (!ctx)
3255                 return NULL;
3256
3257         __perf_event_init_context(ctx);
3258         if (task) {
3259                 ctx->task = task;
3260                 get_task_struct(task);
3261         }
3262         ctx->pmu = pmu;
3263
3264         return ctx;
3265 }
3266
3267 static struct task_struct *
3268 find_lively_task_by_vpid(pid_t vpid)
3269 {
3270         struct task_struct *task;
3271         int err;
3272
3273         rcu_read_lock();
3274         if (!vpid)
3275                 task = current;
3276         else
3277                 task = find_task_by_vpid(vpid);
3278         if (task)
3279                 get_task_struct(task);
3280         rcu_read_unlock();
3281
3282         if (!task)
3283                 return ERR_PTR(-ESRCH);
3284
3285         /* Reuse ptrace permission checks for now. */
3286         err = -EACCES;
3287         if (!ptrace_may_access(task, PTRACE_MODE_READ))
3288                 goto errout;
3289
3290         return task;
3291 errout:
3292         put_task_struct(task);
3293         return ERR_PTR(err);
3294
3295 }
3296
3297 /*
3298  * Returns a matching context with refcount and pincount.
3299  */
3300 static struct perf_event_context *
3301 find_get_context(struct pmu *pmu, struct task_struct *task,
3302                 struct perf_event *event)
3303 {
3304         struct perf_event_context *ctx, *clone_ctx = NULL;
3305         struct perf_cpu_context *cpuctx;
3306         void *task_ctx_data = NULL;
3307         unsigned long flags;
3308         int ctxn, err;
3309         int cpu = event->cpu;
3310
3311         if (!task) {
3312                 /* Must be root to operate on a CPU event: */
3313                 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3314                         return ERR_PTR(-EACCES);
3315
3316                 /*
3317                  * We could be clever and allow to attach a event to an
3318                  * offline CPU and activate it when the CPU comes up, but
3319                  * that's for later.
3320                  */
3321                 if (!cpu_online(cpu))
3322                         return ERR_PTR(-ENODEV);
3323
3324                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3325                 ctx = &cpuctx->ctx;
3326                 get_ctx(ctx);
3327                 ++ctx->pin_count;
3328
3329                 return ctx;
3330         }
3331
3332         err = -EINVAL;
3333         ctxn = pmu->task_ctx_nr;
3334         if (ctxn < 0)
3335                 goto errout;
3336
3337         if (event->attach_state & PERF_ATTACH_TASK_DATA) {
3338                 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
3339                 if (!task_ctx_data) {
3340                         err = -ENOMEM;
3341                         goto errout;
3342                 }
3343         }
3344
3345 retry:
3346         ctx = perf_lock_task_context(task, ctxn, &flags);
3347         if (ctx) {
3348                 clone_ctx = unclone_ctx(ctx);
3349                 ++ctx->pin_count;
3350
3351                 if (task_ctx_data && !ctx->task_ctx_data) {
3352                         ctx->task_ctx_data = task_ctx_data;
3353                         task_ctx_data = NULL;
3354                 }
3355                 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3356
3357                 if (clone_ctx)
3358                         put_ctx(clone_ctx);
3359         } else {
3360                 ctx = alloc_perf_context(pmu, task);
3361                 err = -ENOMEM;
3362                 if (!ctx)
3363                         goto errout;
3364
3365                 if (task_ctx_data) {
3366                         ctx->task_ctx_data = task_ctx_data;
3367                         task_ctx_data = NULL;
3368                 }
3369
3370                 err = 0;
3371                 mutex_lock(&task->perf_event_mutex);
3372                 /*
3373                  * If it has already passed perf_event_exit_task().
3374                  * we must see PF_EXITING, it takes this mutex too.
3375                  */
3376                 if (task->flags & PF_EXITING)
3377                         err = -ESRCH;
3378                 else if (task->perf_event_ctxp[ctxn])
3379                         err = -EAGAIN;
3380                 else {
3381                         get_ctx(ctx);
3382                         ++ctx->pin_count;
3383                         rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3384                 }
3385                 mutex_unlock(&task->perf_event_mutex);
3386
3387                 if (unlikely(err)) {
3388                         put_ctx(ctx);
3389
3390                         if (err == -EAGAIN)
3391                                 goto retry;
3392                         goto errout;
3393                 }
3394         }
3395
3396         kfree(task_ctx_data);
3397         return ctx;
3398
3399 errout:
3400         kfree(task_ctx_data);
3401         return ERR_PTR(err);
3402 }
3403
3404 static void perf_event_free_filter(struct perf_event *event);
3405
3406 static void free_event_rcu(struct rcu_head *head)
3407 {
3408         struct perf_event *event;
3409
3410         event = container_of(head, struct perf_event, rcu_head);
3411         if (event->ns)
3412                 put_pid_ns(event->ns);
3413         perf_event_free_filter(event);
3414         kfree(event);
3415 }
3416
3417 static void ring_buffer_put(struct ring_buffer *rb);
3418 static void ring_buffer_attach(struct perf_event *event,
3419                                struct ring_buffer *rb);
3420
3421 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3422 {
3423         if (event->parent)
3424                 return;
3425
3426         if (is_cgroup_event(event))
3427                 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3428 }
3429
3430 static void unaccount_event(struct perf_event *event)
3431 {
3432         if (event->parent)
3433                 return;
3434
3435         if (event->attach_state & PERF_ATTACH_TASK)
3436                 static_key_slow_dec_deferred(&perf_sched_events);
3437         if (event->attr.mmap || event->attr.mmap_data)
3438                 atomic_dec(&nr_mmap_events);
3439         if (event->attr.comm)
3440                 atomic_dec(&nr_comm_events);
3441         if (event->attr.task)
3442                 atomic_dec(&nr_task_events);
3443         if (event->attr.freq)
3444                 atomic_dec(&nr_freq_events);
3445         if (is_cgroup_event(event))
3446                 static_key_slow_dec_deferred(&perf_sched_events);
3447         if (has_branch_stack(event))
3448                 static_key_slow_dec_deferred(&perf_sched_events);
3449
3450         unaccount_event_cpu(event, event->cpu);
3451 }
3452
3453 static void __free_event(struct perf_event *event)
3454 {
3455         if (!event->parent) {
3456                 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3457                         put_callchain_buffers();
3458         }
3459
3460         if (event->destroy)
3461                 event->destroy(event);
3462
3463         if (event->ctx)
3464                 put_ctx(event->ctx);
3465
3466         if (event->pmu)
3467                 module_put(event->pmu->module);
3468
3469         call_rcu(&event->rcu_head, free_event_rcu);
3470 }
3471
3472 static void _free_event(struct perf_event *event)
3473 {
3474         irq_work_sync(&event->pending);
3475
3476         unaccount_event(event);
3477
3478         if (event->rb) {
3479                 /*
3480                  * Can happen when we close an event with re-directed output.
3481                  *
3482                  * Since we have a 0 refcount, perf_mmap_close() will skip
3483                  * over us; possibly making our ring_buffer_put() the last.
3484                  */
3485                 mutex_lock(&event->mmap_mutex);
3486                 ring_buffer_attach(event, NULL);
3487                 mutex_unlock(&event->mmap_mutex);
3488         }
3489
3490         if (is_cgroup_event(event))
3491                 perf_detach_cgroup(event);
3492
3493         __free_event(event);
3494 }
3495
3496 /*
3497  * Used to free events which have a known refcount of 1, such as in error paths
3498  * where the event isn't exposed yet and inherited events.
3499  */
3500 static void free_event(struct perf_event *event)
3501 {
3502         if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3503                                 "unexpected event refcount: %ld; ptr=%p\n",
3504                                 atomic_long_read(&event->refcount), event)) {
3505                 /* leak to avoid use-after-free */
3506                 return;
3507         }
3508
3509         _free_event(event);
3510 }
3511
3512 /*
3513  * Remove user event from the owner task.
3514  */
3515 static void perf_remove_from_owner(struct perf_event *event)
3516 {
3517         struct task_struct *owner;
3518
3519         rcu_read_lock();
3520         owner = ACCESS_ONCE(event->owner);
3521         /*
3522          * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3523          * !owner it means the list deletion is complete and we can indeed
3524          * free this event, otherwise we need to serialize on
3525          * owner->perf_event_mutex.
3526          */
3527         smp_read_barrier_depends();
3528         if (owner) {
3529                 /*
3530                  * Since delayed_put_task_struct() also drops the last
3531                  * task reference we can safely take a new reference
3532                  * while holding the rcu_read_lock().
3533                  */
3534                 get_task_struct(owner);
3535         }
3536         rcu_read_unlock();
3537
3538         if (owner) {
3539                 /*
3540                  * If we're here through perf_event_exit_task() we're already
3541                  * holding ctx->mutex which would be an inversion wrt. the
3542                  * normal lock order.
3543                  *
3544                  * However we can safely take this lock because its the child
3545                  * ctx->mutex.
3546                  */
3547                 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
3548
3549                 /*
3550                  * We have to re-check the event->owner field, if it is cleared
3551                  * we raced with perf_event_exit_task(), acquiring the mutex
3552                  * ensured they're done, and we can proceed with freeing the
3553                  * event.
3554                  */
3555                 if (event->owner)
3556                         list_del_init(&event->owner_entry);
3557                 mutex_unlock(&owner->perf_event_mutex);
3558                 put_task_struct(owner);
3559         }
3560 }
3561
3562 /*
3563  * Called when the last reference to the file is gone.
3564  */
3565 static void put_event(struct perf_event *event)
3566 {
3567         struct perf_event_context *ctx;
3568
3569         if (!atomic_long_dec_and_test(&event->refcount))
3570                 return;
3571
3572         if (!is_kernel_event(event))
3573                 perf_remove_from_owner(event);
3574
3575         /*
3576          * There are two ways this annotation is useful:
3577          *
3578          *  1) there is a lock recursion from perf_event_exit_task
3579          *     see the comment there.
3580          *
3581          *  2) there is a lock-inversion with mmap_sem through
3582          *     perf_event_read_group(), which takes faults while
3583          *     holding ctx->mutex, however this is called after
3584          *     the last filedesc died, so there is no possibility
3585          *     to trigger the AB-BA case.
3586          */
3587         ctx = perf_event_ctx_lock_nested(event, SINGLE_DEPTH_NESTING);
3588         WARN_ON_ONCE(ctx->parent_ctx);
3589         perf_remove_from_context(event, true);
3590         perf_event_ctx_unlock(event, ctx);
3591
3592         _free_event(event);
3593 }
3594
3595 int perf_event_release_kernel(struct perf_event *event)
3596 {
3597         put_event(event);
3598         return 0;
3599 }
3600 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3601
3602 static int perf_release(struct inode *inode, struct file *file)
3603 {
3604         put_event(file->private_data);
3605         return 0;
3606 }
3607
3608 /*
3609  * Remove all orphanes events from the context.
3610  */
3611 static void orphans_remove_work(struct work_struct *work)
3612 {
3613         struct perf_event_context *ctx;
3614         struct perf_event *event, *tmp;
3615
3616         ctx = container_of(work, struct perf_event_context,
3617                            orphans_remove.work);
3618
3619         mutex_lock(&ctx->mutex);
3620         list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry) {
3621                 struct perf_event *parent_event = event->parent;
3622
3623                 if (!is_orphaned_child(event))
3624                         continue;
3625
3626                 perf_remove_from_context(event, true);
3627
3628                 mutex_lock(&parent_event->child_mutex);
3629                 list_del_init(&event->child_list);
3630                 mutex_unlock(&parent_event->child_mutex);
3631
3632                 free_event(event);
3633                 put_event(parent_event);
3634         }
3635
3636         raw_spin_lock_irq(&ctx->lock);
3637         ctx->orphans_remove_sched = false;
3638         raw_spin_unlock_irq(&ctx->lock);
3639         mutex_unlock(&ctx->mutex);
3640
3641         put_ctx(ctx);
3642 }
3643
3644 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3645 {
3646         struct perf_event *child;
3647         u64 total = 0;
3648
3649         *enabled = 0;
3650         *running = 0;
3651
3652         mutex_lock(&event->child_mutex);
3653         total += perf_event_read(event);
3654         *enabled += event->total_time_enabled +
3655                         atomic64_read(&event->child_total_time_enabled);
3656         *running += event->total_time_running +
3657                         atomic64_read(&event->child_total_time_running);
3658
3659         list_for_each_entry(child, &event->child_list, child_list) {
3660                 total += perf_event_read(child);
3661                 *enabled += child->total_time_enabled;
3662                 *running += child->total_time_running;
3663         }
3664         mutex_unlock(&event->child_mutex);
3665
3666         return total;
3667 }
3668 EXPORT_SYMBOL_GPL(perf_event_read_value);
3669
3670 static int perf_event_read_group(struct perf_event *event,
3671                                    u64 read_format, char __user *buf)
3672 {
3673         struct perf_event *leader = event->group_leader, *sub;
3674         struct perf_event_context *ctx = leader->ctx;
3675         int n = 0, size = 0, ret;
3676         u64 count, enabled, running;
3677         u64 values[5];
3678
3679         lockdep_assert_held(&ctx->mutex);
3680
3681         count = perf_event_read_value(leader, &enabled, &running);
3682
3683         values[n++] = 1 + leader->nr_siblings;
3684         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3685                 values[n++] = enabled;
3686         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3687                 values[n++] = running;
3688         values[n++] = count;
3689         if (read_format & PERF_FORMAT_ID)
3690                 values[n++] = primary_event_id(leader);
3691
3692         size = n * sizeof(u64);
3693
3694         if (copy_to_user(buf, values, size))
3695                 return -EFAULT;
3696
3697         ret = size;
3698
3699         list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3700                 n = 0;
3701
3702                 values[n++] = perf_event_read_value(sub, &enabled, &running);
3703                 if (read_format & PERF_FORMAT_ID)
3704                         values[n++] = primary_event_id(sub);
3705
3706                 size = n * sizeof(u64);
3707
3708                 if (copy_to_user(buf + ret, values, size)) {
3709                         return -EFAULT;
3710                 }
3711
3712                 ret += size;
3713         }
3714
3715         return ret;
3716 }
3717
3718 static int perf_event_read_one(struct perf_event *event,
3719                                  u64 read_format, char __user *buf)
3720 {
3721         u64 enabled, running;
3722         u64 values[4];
3723         int n = 0;
3724
3725         values[n++] = perf_event_read_value(event, &enabled, &running);
3726         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3727                 values[n++] = enabled;
3728         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3729                 values[n++] = running;
3730         if (read_format & PERF_FORMAT_ID)
3731                 values[n++] = primary_event_id(event);
3732
3733         if (copy_to_user(buf, values, n * sizeof(u64)))
3734                 return -EFAULT;
3735
3736         return n * sizeof(u64);
3737 }
3738
3739 static bool is_event_hup(struct perf_event *event)
3740 {
3741         bool no_children;
3742
3743         if (event->state != PERF_EVENT_STATE_EXIT)
3744                 return false;
3745
3746         mutex_lock(&event->child_mutex);
3747         no_children = list_empty(&event->child_list);
3748         mutex_unlock(&event->child_mutex);
3749         return no_children;
3750 }
3751
3752 /*
3753  * Read the performance event - simple non blocking version for now
3754  */
3755 static ssize_t
3756 perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
3757 {
3758         u64 read_format = event->attr.read_format;
3759         int ret;
3760
3761         /*
3762          * Return end-of-file for a read on a event that is in
3763          * error state (i.e. because it was pinned but it couldn't be
3764          * scheduled on to the CPU at some point).
3765          */
3766         if (event->state == PERF_EVENT_STATE_ERROR)
3767                 return 0;
3768
3769         if (count < event->read_size)
3770                 return -ENOSPC;
3771
3772         WARN_ON_ONCE(event->ctx->parent_ctx);
3773         if (read_format & PERF_FORMAT_GROUP)
3774                 ret = perf_event_read_group(event, read_format, buf);
3775         else
3776                 ret = perf_event_read_one(event, read_format, buf);
3777
3778         return ret;
3779 }
3780
3781 static ssize_t
3782 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
3783 {
3784         struct perf_event *event = file->private_data;
3785         struct perf_event_context *ctx;
3786         int ret;
3787
3788         ctx = perf_event_ctx_lock(event);
3789         ret = perf_read_hw(event, buf, count);
3790         perf_event_ctx_unlock(event, ctx);
3791
3792         return ret;
3793 }
3794
3795 static unsigned int perf_poll(struct file *file, poll_table *wait)
3796 {
3797         struct perf_event *event = file->private_data;
3798         struct ring_buffer *rb;
3799         unsigned int events = POLLHUP;
3800
3801         poll_wait(file, &event->waitq, wait);
3802
3803         if (is_event_hup(event))
3804                 return events;
3805
3806         /*
3807          * Pin the event->rb by taking event->mmap_mutex; otherwise
3808          * perf_event_set_output() can swizzle our rb and make us miss wakeups.
3809          */
3810         mutex_lock(&event->mmap_mutex);
3811         rb = event->rb;
3812         if (rb)
3813                 events = atomic_xchg(&rb->poll, 0);
3814         mutex_unlock(&event->mmap_mutex);
3815         return events;
3816 }
3817
3818 static void _perf_event_reset(struct perf_event *event)
3819 {
3820         (void)perf_event_read(event);
3821         local64_set(&event->count, 0);
3822         perf_event_update_userpage(event);
3823 }
3824
3825 /*
3826  * Holding the top-level event's child_mutex means that any
3827  * descendant process that has inherited this event will block
3828  * in sync_child_event if it goes to exit, thus satisfying the
3829  * task existence requirements of perf_event_enable/disable.
3830  */
3831 static void perf_event_for_each_child(struct perf_event *event,
3832                                         void (*func)(struct perf_event *))
3833 {
3834         struct perf_event *child;
3835
3836         WARN_ON_ONCE(event->ctx->parent_ctx);
3837
3838         mutex_lock(&event->child_mutex);
3839         func(event);
3840         list_for_each_entry(child, &event->child_list, child_list)
3841                 func(child);
3842         mutex_unlock(&event->child_mutex);
3843 }
3844
3845 static void perf_event_for_each(struct perf_event *event,
3846                                   void (*func)(struct perf_event *))
3847 {
3848         struct perf_event_context *ctx = event->ctx;
3849         struct perf_event *sibling;
3850
3851         lockdep_assert_held(&ctx->mutex);
3852
3853         event = event->group_leader;
3854
3855         perf_event_for_each_child(event, func);
3856         list_for_each_entry(sibling, &event->sibling_list, group_entry)
3857                 perf_event_for_each_child(sibling, func);
3858 }
3859
3860 static int perf_event_period(struct perf_event *event, u64 __user *arg)
3861 {
3862         struct perf_event_context *ctx = event->ctx;
3863         int ret = 0, active;
3864         u64 value;
3865
3866         if (!is_sampling_event(event))
3867                 return -EINVAL;
3868
3869         if (copy_from_user(&value, arg, sizeof(value)))
3870                 return -EFAULT;
3871
3872         if (!value)
3873                 return -EINVAL;
3874
3875         raw_spin_lock_irq(&ctx->lock);
3876         if (event->attr.freq) {
3877                 if (value > sysctl_perf_event_sample_rate) {
3878                         ret = -EINVAL;
3879                         goto unlock;
3880                 }
3881
3882                 event->attr.sample_freq = value;
3883         } else {
3884                 event->attr.sample_period = value;
3885                 event->hw.sample_period = value;
3886         }
3887
3888         active = (event->state == PERF_EVENT_STATE_ACTIVE);
3889         if (active) {
3890                 perf_pmu_disable(ctx->pmu);
3891                 event->pmu->stop(event, PERF_EF_UPDATE);
3892         }
3893
3894         local64_set(&event->hw.period_left, 0);
3895
3896         if (active) {
3897                 event->pmu->start(event, PERF_EF_RELOAD);
3898                 perf_pmu_enable(ctx->pmu);
3899         }
3900
3901 unlock:
3902         raw_spin_unlock_irq(&ctx->lock);
3903
3904         return ret;
3905 }
3906
3907 static const struct file_operations perf_fops;
3908
3909 static inline int perf_fget_light(int fd, struct fd *p)
3910 {
3911         struct fd f = fdget(fd);
3912         if (!f.file)
3913                 return -EBADF;
3914
3915         if (f.file->f_op != &perf_fops) {
3916                 fdput(f);
3917                 return -EBADF;
3918         }
3919         *p = f;
3920         return 0;
3921 }
3922
3923 static int perf_event_set_output(struct perf_event *event,
3924                                  struct perf_event *output_event);
3925 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
3926
3927 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
3928 {
3929         void (*func)(struct perf_event *);
3930         u32 flags = arg;
3931
3932         switch (cmd) {
3933         case PERF_EVENT_IOC_ENABLE:
3934                 func = _perf_event_enable;
3935                 break;
3936         case PERF_EVENT_IOC_DISABLE:
3937                 func = _perf_event_disable;
3938                 break;
3939         case PERF_EVENT_IOC_RESET:
3940                 func = _perf_event_reset;
3941                 break;
3942
3943         case PERF_EVENT_IOC_REFRESH:
3944                 return _perf_event_refresh(event, arg);
3945
3946         case PERF_EVENT_IOC_PERIOD:
3947                 return perf_event_period(event, (u64 __user *)arg);
3948
3949         case PERF_EVENT_IOC_ID:
3950         {
3951                 u64 id = primary_event_id(event);
3952
3953                 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
3954                         return -EFAULT;
3955                 return 0;
3956         }
3957
3958         case PERF_EVENT_IOC_SET_OUTPUT:
3959         {
3960                 int ret;
3961                 if (arg != -1) {
3962                         struct perf_event *output_event;
3963                         struct fd output;
3964                         ret = perf_fget_light(arg, &output);
3965                         if (ret)
3966                                 return ret;
3967                         output_event = output.file->private_data;
3968                         ret = perf_event_set_output(event, output_event);
3969                         fdput(output);
3970                 } else {
3971                         ret = perf_event_set_output(event, NULL);
3972                 }
3973                 return ret;
3974         }
3975
3976         case PERF_EVENT_IOC_SET_FILTER:
3977                 return perf_event_set_filter(event, (void __user *)arg);
3978
3979         default:
3980                 return -ENOTTY;
3981         }
3982
3983         if (flags & PERF_IOC_FLAG_GROUP)
3984                 perf_event_for_each(event, func);
3985         else
3986                 perf_event_for_each_child(event, func);
3987
3988         return 0;
3989 }
3990
3991 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
3992 {
3993         struct perf_event *event = file->private_data;
3994         struct perf_event_context *ctx;
3995         long ret;
3996
3997         ctx = perf_event_ctx_lock(event);
3998         ret = _perf_ioctl(event, cmd, arg);
3999         perf_event_ctx_unlock(event, ctx);
4000
4001         return ret;
4002 }
4003
4004 #ifdef CONFIG_COMPAT
4005 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
4006                                 unsigned long arg)
4007 {
4008         switch (_IOC_NR(cmd)) {
4009         case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
4010         case _IOC_NR(PERF_EVENT_IOC_ID):
4011                 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
4012                 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
4013                         cmd &= ~IOCSIZE_MASK;
4014                         cmd |= sizeof(void *) << IOCSIZE_SHIFT;
4015                 }
4016                 break;
4017         }
4018         return perf_ioctl(file, cmd, arg);
4019 }
4020 #else
4021 # define perf_compat_ioctl NULL
4022 #endif
4023
4024 int perf_event_task_enable(void)
4025 {
4026         struct perf_event_context *ctx;
4027         struct perf_event *event;
4028
4029         mutex_lock(&current->perf_event_mutex);
4030         list_for_each_entry(event, &current->perf_event_list, owner_entry) {
4031                 ctx = perf_event_ctx_lock(event);
4032                 perf_event_for_each_child(event, _perf_event_enable);
4033                 perf_event_ctx_unlock(event, ctx);
4034         }
4035         mutex_unlock(&current->perf_event_mutex);
4036
4037         return 0;
4038 }
4039
4040 int perf_event_task_disable(void)
4041 {
4042         struct perf_event_context *ctx;
4043         struct perf_event *event;
4044
4045         mutex_lock(&current->perf_event_mutex);
4046         list_for_each_entry(event, &current->perf_event_list, owner_entry) {
4047                 ctx = perf_event_ctx_lock(event);
4048                 perf_event_for_each_child(event, _perf_event_disable);
4049                 perf_event_ctx_unlock(event, ctx);
4050         }
4051         mutex_unlock(&current->perf_event_mutex);
4052
4053         return 0;
4054 }
4055
4056 static int perf_event_index(struct perf_event *event)
4057 {
4058         if (event->hw.state & PERF_HES_STOPPED)
4059                 return 0;
4060
4061         if (event->state != PERF_EVENT_STATE_ACTIVE)
4062                 return 0;
4063
4064         return event->pmu->event_idx(event);
4065 }
4066
4067 static void calc_timer_values(struct perf_event *event,
4068                                 u64 *now,
4069                                 u64 *enabled,
4070                                 u64 *running)
4071 {
4072         u64 ctx_time;
4073
4074         *now = perf_clock();
4075         ctx_time = event->shadow_ctx_time + *now;
4076         *enabled = ctx_time - event->tstamp_enabled;
4077         *running = ctx_time - event->tstamp_running;
4078 }
4079
4080 static void perf_event_init_userpage(struct perf_event *event)
4081 {
4082         struct perf_event_mmap_page *userpg;
4083         struct ring_buffer *rb;
4084
4085         rcu_read_lock();
4086         rb = rcu_dereference(event->rb);
4087         if (!rb)
4088                 goto unlock;
4089
4090         userpg = rb->user_page;
4091
4092         /* Allow new userspace to detect that bit 0 is deprecated */
4093         userpg->cap_bit0_is_deprecated = 1;
4094         userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
4095
4096 unlock:
4097         rcu_read_unlock();
4098 }
4099
4100 void __weak arch_perf_update_userpage(
4101         struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
4102 {
4103 }
4104
4105 /*
4106  * Callers need to ensure there can be no nesting of this function, otherwise
4107  * the seqlock logic goes bad. We can not serialize this because the arch
4108  * code calls this from NMI context.
4109  */
4110 void perf_event_update_userpage(struct perf_event *event)
4111 {
4112         struct perf_event_mmap_page *userpg;
4113         struct ring_buffer *rb;
4114         u64 enabled, running, now;
4115
4116         rcu_read_lock();
4117         rb = rcu_dereference(event->rb);
4118         if (!rb)
4119                 goto unlock;
4120
4121         /*
4122          * compute total_time_enabled, total_time_running
4123          * based on snapshot values taken when the event
4124          * was last scheduled in.
4125          *
4126          * we cannot simply called update_context_time()
4127          * because of locking issue as we can be called in
4128          * NMI context
4129          */
4130         calc_timer_values(event, &now, &enabled, &running);
4131
4132         userpg = rb->user_page;
4133         /*
4134          * Disable preemption so as to not let the corresponding user-space
4135          * spin too long if we get preempted.
4136          */
4137         preempt_disable();
4138         ++userpg->lock;
4139         barrier();
4140         userpg->index = perf_event_index(event);
4141         userpg->offset = perf_event_count(event);
4142         if (userpg->index)
4143                 userpg->offset -= local64_read(&event->hw.prev_count);
4144
4145         userpg->time_enabled = enabled +
4146                         atomic64_read(&event->child_total_time_enabled);
4147
4148         userpg->time_running = running +
4149                         atomic64_read(&event->child_total_time_running);
4150
4151         arch_perf_update_userpage(event, userpg, now);
4152
4153         barrier();
4154         ++userpg->lock;
4155         preempt_enable();
4156 unlock:
4157         rcu_read_unlock();
4158 }
4159
4160 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
4161 {
4162         struct perf_event *event = vma->vm_file->private_data;
4163         struct ring_buffer *rb;
4164         int ret = VM_FAULT_SIGBUS;
4165
4166         if (vmf->flags & FAULT_FLAG_MKWRITE) {
4167                 if (vmf->pgoff == 0)
4168                         ret = 0;
4169                 return ret;
4170         }
4171
4172         rcu_read_lock();
4173         rb = rcu_dereference(event->rb);
4174         if (!rb)
4175                 goto unlock;
4176
4177         if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
4178                 goto unlock;
4179
4180         vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
4181         if (!vmf->page)
4182                 goto unlock;
4183
4184         get_page(vmf->page);
4185         vmf->page->mapping = vma->vm_file->f_mapping;
4186         vmf->page->index   = vmf->pgoff;
4187
4188         ret = 0;
4189 unlock:
4190         rcu_read_unlock();
4191
4192         return ret;
4193 }
4194
4195 static void ring_buffer_attach(struct perf_event *event,
4196                                struct ring_buffer *rb)
4197 {
4198         struct ring_buffer *old_rb = NULL;
4199         unsigned long flags;
4200
4201         if (event->rb) {
4202                 /*
4203                  * Should be impossible, we set this when removing
4204                  * event->rb_entry and wait/clear when adding event->rb_entry.
4205                  */
4206                 WARN_ON_ONCE(event->rcu_pending);
4207
4208                 old_rb = event->rb;
4209                 event->rcu_batches = get_state_synchronize_rcu();
4210                 event->rcu_pending = 1;
4211
4212                 spin_lock_irqsave(&old_rb->event_lock, flags);
4213                 list_del_rcu(&event->rb_entry);
4214                 spin_unlock_irqrestore(&old_rb->event_lock, flags);
4215         }
4216
4217         if (event->rcu_pending && rb) {
4218                 cond_synchronize_rcu(event->rcu_batches);
4219                 event->rcu_pending = 0;
4220         }
4221
4222         if (rb) {
4223                 spin_lock_irqsave(&rb->event_lock, flags);
4224                 list_add_rcu(&event->rb_entry, &rb->event_list);
4225                 spin_unlock_irqrestore(&rb->event_lock, flags);
4226         }
4227
4228         rcu_assign_pointer(event->rb, rb);
4229
4230         if (old_rb) {
4231                 ring_buffer_put(old_rb);
4232                 /*
4233                  * Since we detached before setting the new rb, so that we
4234                  * could attach the new rb, we could have missed a wakeup.
4235                  * Provide it now.
4236                  */
4237                 wake_up_all(&event->waitq);
4238         }
4239 }
4240
4241 static void ring_buffer_wakeup(struct perf_event *event)
4242 {
4243         struct ring_buffer *rb;
4244
4245         rcu_read_lock();
4246         rb = rcu_dereference(event->rb);
4247         if (rb) {
4248                 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
4249                         wake_up_all(&event->waitq);
4250         }
4251         rcu_read_unlock();
4252 }
4253
4254 static void rb_free_rcu(struct rcu_head *rcu_head)
4255 {
4256         struct ring_buffer *rb;
4257
4258         rb = container_of(rcu_head, struct ring_buffer, rcu_head);
4259         rb_free(rb);
4260 }
4261
4262 static struct ring_buffer *ring_buffer_get(struct perf_event *event)
4263 {
4264         struct ring_buffer *rb;
4265
4266         rcu_read_lock();
4267         rb = rcu_dereference(event->rb);
4268         if (rb) {
4269                 if (!atomic_inc_not_zero(&rb->refcount))
4270                         rb = NULL;
4271         }
4272         rcu_read_unlock();
4273
4274         return rb;
4275 }
4276
4277 static void ring_buffer_put(struct ring_buffer *rb)
4278 {
4279         if (!atomic_dec_and_test(&rb->refcount))
4280                 return;
4281
4282         WARN_ON_ONCE(!list_empty(&rb->event_list));
4283
4284         call_rcu(&rb->rcu_head, rb_free_rcu);
4285 }
4286
4287 static void perf_mmap_open(struct vm_area_struct *vma)
4288 {
4289         struct perf_event *event = vma->vm_file->private_data;
4290
4291         atomic_inc(&event->mmap_count);
4292         atomic_inc(&event->rb->mmap_count);
4293
4294         if (event->pmu->event_mapped)
4295                 event->pmu->event_mapped(event);
4296 }
4297
4298 /*
4299  * A buffer can be mmap()ed multiple times; either directly through the same
4300  * event, or through other events by use of perf_event_set_output().
4301  *
4302  * In order to undo the VM accounting done by perf_mmap() we need to destroy
4303  * the buffer here, where we still have a VM context. This means we need
4304  * to detach all events redirecting to us.
4305  */
4306 static void perf_mmap_close(struct vm_area_struct *vma)
4307 {
4308         struct perf_event *event = vma->vm_file->private_data;
4309
4310         struct ring_buffer *rb = ring_buffer_get(event);
4311         struct user_struct *mmap_user = rb->mmap_user;
4312         int mmap_locked = rb->mmap_locked;
4313         unsigned long size = perf_data_size(rb);
4314
4315         if (event->pmu->event_unmapped)
4316                 event->pmu->event_unmapped(event);
4317
4318         atomic_dec(&rb->mmap_count);
4319
4320         if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
4321                 goto out_put;
4322
4323         ring_buffer_attach(event, NULL);
4324         mutex_unlock(&event->mmap_mutex);
4325
4326         /* If there's still other mmap()s of this buffer, we're done. */
4327         if (atomic_read(&rb->mmap_count))
4328                 goto out_put;
4329
4330         /*
4331          * No other mmap()s, detach from all other events that might redirect
4332          * into the now unreachable buffer. Somewhat complicated by the
4333          * fact that rb::event_lock otherwise nests inside mmap_mutex.
4334          */
4335 again:
4336         rcu_read_lock();
4337         list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
4338                 if (!atomic_long_inc_not_zero(&event->refcount)) {
4339                         /*
4340                          * This event is en-route to free_event() which will
4341                          * detach it and remove it from the list.
4342                          */
4343                         continue;
4344                 }
4345                 rcu_read_unlock();
4346
4347                 mutex_lock(&event->mmap_mutex);
4348                 /*
4349                  * Check we didn't race with perf_event_set_output() which can
4350                  * swizzle the rb from under us while we were waiting to
4351                  * acquire mmap_mutex.
4352                  *
4353                  * If we find a different rb; ignore this event, a next
4354                  * iteration will no longer find it on the list. We have to
4355                  * still restart the iteration to make sure we're not now
4356                  * iterating the wrong list.
4357                  */
4358                 if (event->rb == rb)
4359                         ring_buffer_attach(event, NULL);
4360
4361                 mutex_unlock(&event->mmap_mutex);
4362                 put_event(event);
4363
4364                 /*
4365                  * Restart the iteration; either we're on the wrong list or
4366                  * destroyed its integrity by doing a deletion.
4367                  */
4368                 goto again;
4369         }
4370         rcu_read_unlock();
4371
4372         /*
4373          * It could be there's still a few 0-ref events on the list; they'll
4374          * get cleaned up by free_event() -- they'll also still have their
4375          * ref on the rb and will free it whenever they are done with it.
4376          *
4377          * Aside from that, this buffer is 'fully' detached and unmapped,
4378          * undo the VM accounting.
4379          */
4380
4381         atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4382         vma->vm_mm->pinned_vm -= mmap_locked;
4383         free_uid(mmap_user);
4384
4385 out_put:
4386         ring_buffer_put(rb); /* could be last */
4387 }
4388
4389 static const struct vm_operations_struct perf_mmap_vmops = {
4390         .open           = perf_mmap_open,
4391         .close          = perf_mmap_close,
4392         .fault          = perf_mmap_fault,
4393         .page_mkwrite   = perf_mmap_fault,
4394 };
4395
4396 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
4397 {
4398         struct perf_event *event = file->private_data;
4399         unsigned long user_locked, user_lock_limit;
4400         struct user_struct *user = current_user();
4401         unsigned long locked, lock_limit;
4402         struct ring_buffer *rb;
4403         unsigned long vma_size;
4404         unsigned long nr_pages;
4405         long user_extra, extra;
4406         int ret = 0, flags = 0;
4407
4408         /*
4409          * Don't allow mmap() of inherited per-task counters. This would
4410          * create a performance issue due to all children writing to the
4411          * same rb.
4412          */
4413         if (event->cpu == -1 && event->attr.inherit)
4414                 return -EINVAL;
4415
4416         if (!(vma->vm_flags & VM_SHARED))
4417                 return -EINVAL;
4418
4419         vma_size = vma->vm_end - vma->vm_start;
4420         nr_pages = (vma_size / PAGE_SIZE) - 1;
4421
4422         /*
4423          * If we have rb pages ensure they're a power-of-two number, so we
4424          * can do bitmasks instead of modulo.
4425          */
4426         if (nr_pages != 0 && !is_power_of_2(nr_pages))
4427                 return -EINVAL;
4428
4429         if (vma_size != PAGE_SIZE * (1 + nr_pages))
4430                 return -EINVAL;
4431
4432         if (vma->vm_pgoff != 0)
4433                 return -EINVAL;
4434
4435         WARN_ON_ONCE(event->ctx->parent_ctx);
4436 again:
4437         mutex_lock(&event->mmap_mutex);
4438         if (event->rb) {
4439                 if (event->rb->nr_pages != nr_pages) {
4440                         ret = -EINVAL;
4441                         goto unlock;
4442                 }
4443
4444                 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4445                         /*
4446                          * Raced against perf_mmap_close() through
4447                          * perf_event_set_output(). Try again, hope for better
4448                          * luck.
4449                          */
4450                         mutex_unlock(&event->mmap_mutex);
4451                         goto again;
4452                 }
4453
4454                 goto unlock;
4455         }
4456
4457         user_extra = nr_pages + 1;
4458         user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
4459
4460         /*
4461          * Increase the limit linearly with more CPUs:
4462          */
4463         user_lock_limit *= num_online_cpus();
4464
4465         user_locked = atomic_long_read(&user->locked_vm) + user_extra;
4466
4467         extra = 0;
4468         if (user_locked > user_lock_limit)
4469                 extra = user_locked - user_lock_limit;
4470
4471         lock_limit = rlimit(RLIMIT_MEMLOCK);
4472         lock_limit >>= PAGE_SHIFT;
4473         locked = vma->vm_mm->pinned_vm + extra;
4474
4475         if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
4476                 !capable(CAP_IPC_LOCK)) {
4477                 ret = -EPERM;
4478                 goto unlock;
4479         }
4480
4481         WARN_ON(event->rb);
4482
4483         if (vma->vm_flags & VM_WRITE)
4484                 flags |= RING_BUFFER_WRITABLE;
4485
4486         rb = rb_alloc(nr_pages, 
4487                 event->attr.watermark ? event->attr.wakeup_watermark : 0,
4488                 event->cpu, flags);
4489
4490         if (!rb) {
4491                 ret = -ENOMEM;
4492                 goto unlock;
4493         }
4494
4495         atomic_set(&rb->mmap_count, 1);
4496         rb->mmap_locked = extra;
4497         rb->mmap_user = get_current_user();
4498
4499         atomic_long_add(user_extra, &user->locked_vm);
4500         vma->vm_mm->pinned_vm += extra;
4501
4502         ring_buffer_attach(event, rb);
4503
4504         perf_event_init_userpage(event);
4505         perf_event_update_userpage(event);
4506
4507 unlock:
4508         if (!ret)
4509                 atomic_inc(&event->mmap_count);
4510         mutex_unlock(&event->mmap_mutex);
4511
4512         /*
4513          * Since pinned accounting is per vm we cannot allow fork() to copy our
4514          * vma.
4515          */
4516         vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
4517         vma->vm_ops = &perf_mmap_vmops;
4518
4519         if (event->pmu->event_mapped)
4520                 event->pmu->event_mapped(event);
4521
4522         return ret;
4523 }
4524
4525 static int perf_fasync(int fd, struct file *filp, int on)
4526 {
4527         struct inode *inode = file_inode(filp);
4528         struct perf_event *event = filp->private_data;
4529         int retval;
4530
4531         mutex_lock(&inode->i_mutex);
4532         retval = fasync_helper(fd, filp, on, &event->fasync);
4533         mutex_unlock(&inode->i_mutex);
4534
4535         if (retval < 0)
4536                 return retval;
4537
4538         return 0;
4539 }
4540
4541 static const struct file_operations perf_fops = {
4542         .llseek                 = no_llseek,
4543         .release                = perf_release,
4544         .read                   = perf_read,
4545         .poll                   = perf_poll,
4546         .unlocked_ioctl         = perf_ioctl,
4547         .compat_ioctl           = perf_compat_ioctl,
4548         .mmap                   = perf_mmap,
4549         .fasync                 = perf_fasync,
4550 };
4551
4552 /*
4553  * Perf event wakeup
4554  *
4555  * If there's data, ensure we set the poll() state and publish everything
4556  * to user-space before waking everybody up.
4557  */
4558
4559 void perf_event_wakeup(struct perf_event *event)
4560 {
4561         ring_buffer_wakeup(event);
4562
4563         if (event->pending_kill) {
4564                 kill_fasync(&event->fasync, SIGIO, event->pending_kill);
4565                 event->pending_kill = 0;
4566         }
4567 }
4568
4569 static void perf_pending_event(struct irq_work *entry)
4570 {
4571         struct perf_event *event = container_of(entry,
4572                         struct perf_event, pending);
4573         int rctx;
4574
4575         rctx = perf_swevent_get_recursion_context();
4576         /*
4577          * If we 'fail' here, that's OK, it means recursion is already disabled
4578          * and we won't recurse 'further'.
4579          */
4580
4581         if (event->pending_disable) {
4582                 event->pending_disable = 0;
4583                 __perf_event_disable(event);
4584         }
4585
4586         if (event->pending_wakeup) {
4587                 event->pending_wakeup = 0;
4588                 perf_event_wakeup(event);
4589         }
4590
4591         if (rctx >= 0)
4592                 perf_swevent_put_recursion_context(rctx);
4593 }
4594
4595 /*
4596  * We assume there is only KVM supporting the callbacks.
4597  * Later on, we might change it to a list if there is
4598  * another virtualization implementation supporting the callbacks.
4599  */
4600 struct perf_guest_info_callbacks *perf_guest_cbs;
4601
4602 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4603 {
4604         perf_guest_cbs = cbs;
4605         return 0;
4606 }
4607 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
4608
4609 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4610 {
4611         perf_guest_cbs = NULL;
4612         return 0;
4613 }
4614 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
4615
4616 static void
4617 perf_output_sample_regs(struct perf_output_handle *handle,
4618                         struct pt_regs *regs, u64 mask)
4619 {
4620         int bit;
4621
4622         for_each_set_bit(bit, (const unsigned long *) &mask,
4623                          sizeof(mask) * BITS_PER_BYTE) {
4624                 u64 val;
4625
4626                 val = perf_reg_value(regs, bit);
4627                 perf_output_put(handle, val);
4628         }
4629 }
4630
4631 static void perf_sample_regs_user(struct perf_regs *regs_user,
4632                                   struct pt_regs *regs,
4633                                   struct pt_regs *regs_user_copy)
4634 {
4635         if (user_mode(regs)) {
4636                 regs_user->abi = perf_reg_abi(current);
4637                 regs_user->regs = regs;
4638         } else if (current->mm) {
4639                 perf_get_regs_user(regs_user, regs, regs_user_copy);
4640         } else {
4641                 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
4642                 regs_user->regs = NULL;
4643         }
4644 }
4645
4646 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
4647                                   struct pt_regs *regs)
4648 {
4649         regs_intr->regs = regs;
4650         regs_intr->abi  = perf_reg_abi(current);
4651 }
4652
4653
4654 /*
4655  * Get remaining task size from user stack pointer.
4656  *
4657  * It'd be better to take stack vma map and limit this more
4658  * precisly, but there's no way to get it safely under interrupt,
4659  * so using TASK_SIZE as limit.
4660  */
4661 static u64 perf_ustack_task_size(struct pt_regs *regs)
4662 {
4663         unsigned long addr = perf_user_stack_pointer(regs);
4664
4665         if (!addr || addr >= TASK_SIZE)
4666                 return 0;
4667
4668         return TASK_SIZE - addr;
4669 }
4670
4671 static u16
4672 perf_sample_ustack_size(u16 stack_size, u16 header_size,
4673                         struct pt_regs *regs)
4674 {
4675         u64 task_size;
4676
4677         /* No regs, no stack pointer, no dump. */
4678         if (!regs)
4679                 return 0;
4680
4681         /*
4682          * Check if we fit in with the requested stack size into the:
4683          * - TASK_SIZE
4684          *   If we don't, we limit the size to the TASK_SIZE.
4685          *
4686          * - remaining sample size
4687          *   If we don't, we customize the stack size to
4688          *   fit in to the remaining sample size.
4689          */
4690
4691         task_size  = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
4692         stack_size = min(stack_size, (u16) task_size);
4693
4694         /* Current header size plus static size and dynamic size. */
4695         header_size += 2 * sizeof(u64);
4696
4697         /* Do we fit in with the current stack dump size? */
4698         if ((u16) (header_size + stack_size) < header_size) {
4699                 /*
4700                  * If we overflow the maximum size for the sample,
4701                  * we customize the stack dump size to fit in.
4702                  */
4703                 stack_size = USHRT_MAX - header_size - sizeof(u64);
4704                 stack_size = round_up(stack_size, sizeof(u64));
4705         }
4706
4707         return stack_size;
4708 }
4709
4710 static void
4711 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
4712                           struct pt_regs *regs)
4713 {
4714         /* Case of a kernel thread, nothing to dump */
4715         if (!regs) {
4716                 u64 size = 0;
4717                 perf_output_put(handle, size);
4718         } else {
4719                 unsigned long sp;
4720                 unsigned int rem;
4721                 u64 dyn_size;
4722
4723                 /*
4724                  * We dump:
4725                  * static size
4726                  *   - the size requested by user or the best one we can fit
4727                  *     in to the sample max size
4728                  * data
4729                  *   - user stack dump data
4730                  * dynamic size
4731                  *   - the actual dumped size
4732                  */
4733
4734                 /* Static size. */
4735                 perf_output_put(handle, dump_size);
4736
4737                 /* Data. */
4738                 sp = perf_user_stack_pointer(regs);
4739                 rem = __output_copy_user(handle, (void *) sp, dump_size);
4740                 dyn_size = dump_size - rem;
4741
4742                 perf_output_skip(handle, rem);
4743
4744                 /* Dynamic size. */
4745                 perf_output_put(handle, dyn_size);
4746         }
4747 }
4748
4749 static void __perf_event_header__init_id(struct perf_event_header *header,
4750                                          struct perf_sample_data *data,
4751                                          struct perf_event *event)
4752 {
4753         u64 sample_type = event->attr.sample_type;
4754
4755         data->type = sample_type;
4756         header->size += event->id_header_size;
4757
4758         if (sample_type & PERF_SAMPLE_TID) {
4759                 /* namespace issues */
4760                 data->tid_entry.pid = perf_event_pid(event, current);
4761                 data->tid_entry.tid = perf_event_tid(event, current);
4762         }
4763
4764         if (sample_type & PERF_SAMPLE_TIME)
4765                 data->time = perf_clock();
4766
4767         if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
4768                 data->id = primary_event_id(event);
4769
4770         if (sample_type & PERF_SAMPLE_STREAM_ID)
4771                 data->stream_id = event->id;
4772
4773         if (sample_type & PERF_SAMPLE_CPU) {
4774                 data->cpu_entry.cpu      = raw_smp_processor_id();
4775                 data->cpu_entry.reserved = 0;
4776         }
4777 }
4778
4779 void perf_event_header__init_id(struct perf_event_header *header,
4780                                 struct perf_sample_data *data,
4781                                 struct perf_event *event)
4782 {
4783         if (event->attr.sample_id_all)
4784                 __perf_event_header__init_id(header, data, event);
4785 }
4786
4787 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
4788                                            struct perf_sample_data *data)
4789 {
4790         u64 sample_type = data->type;
4791
4792         if (sample_type & PERF_SAMPLE_TID)
4793                 perf_output_put(handle, data->tid_entry);
4794
4795         if (sample_type & PERF_SAMPLE_TIME)
4796                 perf_output_put(handle, data->time);
4797
4798         if (sample_type & PERF_SAMPLE_ID)
4799                 perf_output_put(handle, data->id);
4800
4801         if (sample_type & PERF_SAMPLE_STREAM_ID)
4802                 perf_output_put(handle, data->stream_id);
4803
4804         if (sample_type & PERF_SAMPLE_CPU)
4805                 perf_output_put(handle, data->cpu_entry);
4806
4807         if (sample_type & PERF_SAMPLE_IDENTIFIER)
4808                 perf_output_put(handle, data->id);
4809 }
4810
4811 void perf_event__output_id_sample(struct perf_event *event,
4812                                   struct perf_output_handle *handle,
4813                                   struct perf_sample_data *sample)
4814 {
4815         if (event->attr.sample_id_all)
4816                 __perf_event__output_id_sample(handle, sample);
4817 }
4818
4819 static void perf_output_read_one(struct perf_output_handle *handle,
4820                                  struct perf_event *event,
4821                                  u64 enabled, u64 running)
4822 {
4823         u64 read_format = event->attr.read_format;
4824         u64 values[4];
4825         int n = 0;
4826
4827         values[n++] = perf_event_count(event);
4828         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4829                 values[n++] = enabled +
4830                         atomic64_read(&event->child_total_time_enabled);
4831         }
4832         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4833                 values[n++] = running +
4834                         atomic64_read(&event->child_total_time_running);
4835         }
4836         if (read_format & PERF_FORMAT_ID)
4837                 values[n++] = primary_event_id(event);
4838
4839         __output_copy(handle, values, n * sizeof(u64));
4840 }
4841
4842 /*
4843  * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
4844  */
4845 static void perf_output_read_group(struct perf_output_handle *handle,
4846                             struct perf_event *event,
4847                             u64 enabled, u64 running)
4848 {
4849         struct perf_event *leader = event->group_leader, *sub;
4850         u64 read_format = event->attr.read_format;
4851         u64 values[5];
4852         int n = 0;
4853
4854         values[n++] = 1 + leader->nr_siblings;
4855
4856         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4857                 values[n++] = enabled;
4858
4859         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4860                 values[n++] = running;
4861
4862         if (leader != event)
4863                 leader->pmu->read(leader);
4864
4865         values[n++] = perf_event_count(leader);
4866         if (read_format & PERF_FORMAT_ID)
4867                 values[n++] = primary_event_id(leader);
4868
4869         __output_copy(handle, values, n * sizeof(u64));
4870
4871         list_for_each_entry(sub, &leader->sibling_list, group_entry) {
4872                 n = 0;
4873
4874                 if ((sub != event) &&
4875                     (sub->state == PERF_EVENT_STATE_ACTIVE))
4876                         sub->pmu->read(sub);
4877
4878                 values[n++] = perf_event_count(sub);
4879                 if (read_format & PERF_FORMAT_ID)
4880                         values[n++] = primary_event_id(sub);
4881
4882                 __output_copy(handle, values, n * sizeof(u64));
4883         }
4884 }
4885
4886 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
4887                                  PERF_FORMAT_TOTAL_TIME_RUNNING)
4888
4889 static void perf_output_read(struct perf_output_handle *handle,
4890                              struct perf_event *event)
4891 {
4892         u64 enabled = 0, running = 0, now;
4893         u64 read_format = event->attr.read_format;
4894
4895         /*
4896          * compute total_time_enabled, total_time_running
4897          * based on snapshot values taken when the event
4898          * was last scheduled in.
4899          *
4900          * we cannot simply called update_context_time()
4901          * because of locking issue as we are called in
4902          * NMI context
4903          */
4904         if (read_format & PERF_FORMAT_TOTAL_TIMES)
4905                 calc_timer_values(event, &now, &enabled, &running);
4906
4907         if (event->attr.read_format & PERF_FORMAT_GROUP)
4908                 perf_output_read_group(handle, event, enabled, running);
4909         else
4910                 perf_output_read_one(handle, event, enabled, running);
4911 }
4912
4913 void perf_output_sample(struct perf_output_handle *handle,
4914                         struct perf_event_header *header,
4915                         struct perf_sample_data *data,
4916                         struct perf_event *event)
4917 {
4918         u64 sample_type = data->type;
4919
4920         perf_output_put(handle, *header);
4921
4922         if (sample_type & PERF_SAMPLE_IDENTIFIER)
4923                 perf_output_put(handle, data->id);
4924
4925         if (sample_type & PERF_SAMPLE_IP)
4926                 perf_output_put(handle, data->ip);
4927
4928         if (sample_type & PERF_SAMPLE_TID)
4929                 perf_output_put(handle, data->tid_entry);
4930
4931         if (sample_type & PERF_SAMPLE_TIME)
4932                 perf_output_put(handle, data->time);
4933
4934         if (sample_type & PERF_SAMPLE_ADDR)
4935                 perf_output_put(handle, data->addr);
4936
4937         if (sample_type & PERF_SAMPLE_ID)
4938                 perf_output_put(handle, data->id);
4939
4940         if (sample_type & PERF_SAMPLE_STREAM_ID)
4941                 perf_output_put(handle, data->stream_id);
4942
4943         if (sample_type & PERF_SAMPLE_CPU)
4944                 perf_output_put(handle, data->cpu_entry);
4945
4946         if (sample_type & PERF_SAMPLE_PERIOD)
4947                 perf_output_put(handle, data->period);
4948
4949         if (sample_type & PERF_SAMPLE_READ)
4950                 perf_output_read(handle, event);
4951
4952         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
4953                 if (data->callchain) {
4954                         int size = 1;
4955
4956                         if (data->callchain)
4957                                 size += data->callchain->nr;
4958
4959                         size *= sizeof(u64);
4960
4961                         __output_copy(handle, data->callchain, size);
4962                 } else {
4963                         u64 nr = 0;
4964                         perf_output_put(handle, nr);
4965                 }
4966         }
4967
4968         if (sample_type & PERF_SAMPLE_RAW) {
4969                 if (data->raw) {
4970                         perf_output_put(handle, data->raw->size);
4971                         __output_copy(handle, data->raw->data,
4972                                            data->raw->size);
4973                 } else {
4974                         struct {
4975                                 u32     size;
4976                                 u32     data;
4977                         } raw = {
4978                                 .size = sizeof(u32),
4979                                 .data = 0,
4980                         };
4981                         perf_output_put(handle, raw);
4982                 }
4983         }
4984
4985         if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
4986                 if (data->br_stack) {
4987                         size_t size;
4988
4989                         size = data->br_stack->nr
4990                              * sizeof(struct perf_branch_entry);
4991
4992                         perf_output_put(handle, data->br_stack->nr);
4993                         perf_output_copy(handle, data->br_stack->entries, size);
4994                 } else {
4995                         /*
4996                          * we always store at least the value of nr
4997                          */
4998                         u64 nr = 0;
4999                         perf_output_put(handle, nr);
5000                 }
5001         }
5002
5003         if (sample_type & PERF_SAMPLE_REGS_USER) {
5004                 u64 abi = data->regs_user.abi;
5005
5006                 /*
5007                  * If there are no regs to dump, notice it through
5008                  * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5009                  */
5010                 perf_output_put(handle, abi);
5011
5012                 if (abi) {
5013                         u64 mask = event->attr.sample_regs_user;
5014                         perf_output_sample_regs(handle,
5015                                                 data->regs_user.regs,
5016                                                 mask);
5017                 }
5018         }
5019
5020         if (sample_type & PERF_SAMPLE_STACK_USER) {
5021                 perf_output_sample_ustack(handle,
5022                                           data->stack_user_size,
5023                                           data->regs_user.regs);
5024         }
5025
5026         if (sample_type & PERF_SAMPLE_WEIGHT)
5027                 perf_output_put(handle, data->weight);
5028
5029         if (sample_type & PERF_SAMPLE_DATA_SRC)
5030                 perf_output_put(handle, data->data_src.val);
5031
5032         if (sample_type & PERF_SAMPLE_TRANSACTION)
5033                 perf_output_put(handle, data->txn);
5034
5035         if (sample_type & PERF_SAMPLE_REGS_INTR) {
5036                 u64 abi = data->regs_intr.abi;
5037                 /*
5038                  * If there are no regs to dump, notice it through
5039                  * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5040                  */
5041                 perf_output_put(handle, abi);
5042
5043                 if (abi) {
5044                         u64 mask = event->attr.sample_regs_intr;
5045
5046                         perf_output_sample_regs(handle,
5047                                                 data->regs_intr.regs,
5048                                                 mask);
5049                 }
5050         }
5051
5052         if (!event->attr.watermark) {
5053                 int wakeup_events = event->attr.wakeup_events;
5054
5055                 if (wakeup_events) {
5056                         struct ring_buffer *rb = handle->rb;
5057                         int events = local_inc_return(&rb->events);
5058
5059                         if (events >= wakeup_events) {
5060                                 local_sub(wakeup_events, &rb->events);
5061                                 local_inc(&rb->wakeup);
5062                         }
5063                 }
5064         }
5065 }
5066
5067 void perf_prepare_sample(struct perf_event_header *header,
5068                          struct perf_sample_data *data,
5069                          struct perf_event *event,
5070                          struct pt_regs *regs)
5071 {
5072         u64 sample_type = event->attr.sample_type;
5073
5074         header->type = PERF_RECORD_SAMPLE;
5075         header->size = sizeof(*header) + event->header_size;
5076
5077         header->misc = 0;
5078         header->misc |= perf_misc_flags(regs);
5079
5080         __perf_event_header__init_id(header, data, event);
5081
5082         if (sample_type & PERF_SAMPLE_IP)
5083                 data->ip = perf_instruction_pointer(regs);
5084
5085         if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5086                 int size = 1;
5087
5088                 data->callchain = perf_callchain(event, regs);
5089
5090                 if (data->callchain)
5091                         size += data->callchain->nr;
5092
5093                 header->size += size * sizeof(u64);
5094         }
5095
5096         if (sample_type & PERF_SAMPLE_RAW) {
5097                 int size = sizeof(u32);
5098
5099                 if (data->raw)
5100                         size += data->raw->size;
5101                 else
5102                         size += sizeof(u32);
5103
5104                 WARN_ON_ONCE(size & (sizeof(u64)-1));
5105                 header->size += size;
5106         }
5107
5108         if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5109                 int size = sizeof(u64); /* nr */
5110                 if (data->br_stack) {
5111                         size += data->br_stack->nr
5112                               * sizeof(struct perf_branch_entry);
5113                 }
5114                 header->size += size;
5115         }
5116
5117         if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
5118                 perf_sample_regs_user(&data->regs_user, regs,
5119                                       &data->regs_user_copy);
5120
5121         if (sample_type & PERF_SAMPLE_REGS_USER) {
5122                 /* regs dump ABI info */
5123                 int size = sizeof(u64);
5124
5125                 if (data->regs_user.regs) {
5126                         u64 mask = event->attr.sample_regs_user;
5127                         size += hweight64(mask) * sizeof(u64);
5128                 }
5129
5130                 header->size += size;
5131         }
5132
5133         if (sample_type & PERF_SAMPLE_STACK_USER) {
5134                 /*
5135                  * Either we need PERF_SAMPLE_STACK_USER bit to be allways
5136                  * processed as the last one or have additional check added
5137                  * in case new sample type is added, because we could eat
5138                  * up the rest of the sample size.
5139                  */
5140                 u16 stack_size = event->attr.sample_stack_user;
5141                 u16 size = sizeof(u64);
5142
5143                 stack_size = perf_sample_ustack_size(stack_size, header->size,
5144                                                      data->regs_user.regs);
5145
5146                 /*
5147                  * If there is something to dump, add space for the dump
5148                  * itself and for the field that tells the dynamic size,
5149                  * which is how many have been actually dumped.
5150                  */
5151                 if (stack_size)
5152                         size += sizeof(u64) + stack_size;
5153
5154                 data->stack_user_size = stack_size;
5155                 header->size += size;
5156         }
5157
5158         if (sample_type & PERF_SAMPLE_REGS_INTR) {
5159                 /* regs dump ABI info */
5160                 int size = sizeof(u64);
5161
5162                 perf_sample_regs_intr(&data->regs_intr, regs);
5163
5164                 if (data->regs_intr.regs) {
5165                         u64 mask = event->attr.sample_regs_intr;
5166
5167                         size += hweight64(mask) * sizeof(u64);
5168                 }
5169
5170                 header->size += size;
5171         }
5172 }
5173
5174 static void perf_event_output(struct perf_event *event,
5175                                 struct perf_sample_data *data,
5176                                 struct pt_regs *regs)
5177 {
5178         struct perf_output_handle handle;
5179         struct perf_event_header header;
5180
5181         /* protect the callchain buffers */
5182         rcu_read_lock();
5183
5184         perf_prepare_sample(&header, data, event, regs);
5185
5186         if (perf_output_begin(&handle, event, header.size))
5187                 goto exit;
5188
5189         perf_output_sample(&handle, &header, data, event);
5190
5191         perf_output_end(&handle);
5192
5193 exit:
5194         rcu_read_unlock();
5195 }
5196
5197 /*
5198  * read event_id
5199  */
5200
5201 struct perf_read_event {
5202         struct perf_event_header        header;
5203
5204         u32                             pid;
5205         u32                             tid;
5206 };
5207
5208 static void
5209 perf_event_read_event(struct perf_event *event,
5210                         struct task_struct *task)
5211 {
5212         struct perf_output_handle handle;
5213         struct perf_sample_data sample;
5214         struct perf_read_event read_event = {
5215                 .header = {
5216                         .type = PERF_RECORD_READ,
5217                         .misc = 0,
5218                         .size = sizeof(read_event) + event->read_size,
5219                 },
5220                 .pid = perf_event_pid(event, task),
5221                 .tid = perf_event_tid(event, task),
5222         };
5223         int ret;
5224
5225         perf_event_header__init_id(&read_event.header, &sample, event);
5226         ret = perf_output_begin(&handle, event, read_event.header.size);
5227         if (ret)
5228                 return;
5229
5230         perf_output_put(&handle, read_event);
5231         perf_output_read(&handle, event);
5232         perf_event__output_id_sample(event, &handle, &sample);
5233
5234         perf_output_end(&handle);
5235 }
5236
5237 typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
5238
5239 static void
5240 perf_event_aux_ctx(struct perf_event_context *ctx,
5241                    perf_event_aux_output_cb output,
5242                    void *data)
5243 {
5244         struct perf_event *event;
5245
5246         list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5247                 if (event->state < PERF_EVENT_STATE_INACTIVE)
5248                         continue;
5249                 if (!event_filter_match(event))
5250                         continue;
5251                 output(event, data);
5252         }
5253 }
5254
5255 static void
5256 perf_event_aux(perf_event_aux_output_cb output, void *data,
5257                struct perf_event_context *task_ctx)
5258 {
5259         struct perf_cpu_context *cpuctx;
5260         struct perf_event_context *ctx;
5261         struct pmu *pmu;
5262         int ctxn;
5263
5264         rcu_read_lock();
5265         list_for_each_entry_rcu(pmu, &pmus, entry) {
5266                 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
5267                 if (cpuctx->unique_pmu != pmu)
5268                         goto next;
5269                 perf_event_aux_ctx(&cpuctx->ctx, output, data);
5270                 if (task_ctx)
5271                         goto next;
5272                 ctxn = pmu->task_ctx_nr;
5273                 if (ctxn < 0)
5274                         goto next;
5275                 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
5276                 if (ctx)
5277                         perf_event_aux_ctx(ctx, output, data);
5278 next:
5279                 put_cpu_ptr(pmu->pmu_cpu_context);
5280         }
5281
5282         if (task_ctx) {
5283                 preempt_disable();
5284                 perf_event_aux_ctx(task_ctx, output, data);
5285                 preempt_enable();
5286         }
5287         rcu_read_unlock();
5288 }
5289
5290 /*
5291  * task tracking -- fork/exit
5292  *
5293  * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
5294  */
5295
5296 struct perf_task_event {
5297         struct task_struct              *task;
5298         struct perf_event_context       *task_ctx;
5299
5300         struct {
5301                 struct perf_event_header        header;
5302
5303                 u32                             pid;
5304                 u32                             ppid;
5305                 u32                             tid;
5306                 u32                             ptid;
5307                 u64                             time;
5308         } event_id;
5309 };
5310
5311 static int perf_event_task_match(struct perf_event *event)
5312 {
5313         return event->attr.comm  || event->attr.mmap ||
5314                event->attr.mmap2 || event->attr.mmap_data ||
5315                event->attr.task;
5316 }
5317
5318 static void perf_event_task_output(struct perf_event *event,
5319                                    void *data)
5320 {
5321         struct perf_task_event *task_event = data;
5322         struct perf_output_handle handle;
5323         struct perf_sample_data sample;
5324         struct task_struct *task = task_event->task;
5325         int ret, size = task_event->event_id.header.size;
5326
5327         if (!perf_event_task_match(event))
5328                 return;
5329
5330         perf_event_header__init_id(&task_event->event_id.header, &sample, event);
5331
5332         ret = perf_output_begin(&handle, event,
5333                                 task_event->event_id.header.size);
5334         if (ret)
5335                 goto out;
5336
5337         task_event->event_id.pid = perf_event_pid(event, task);
5338         task_event->event_id.ppid = perf_event_pid(event, current);
5339
5340         task_event->event_id.tid = perf_event_tid(event, task);
5341         task_event->event_id.ptid = perf_event_tid(event, current);
5342
5343         perf_output_put(&handle, task_event->event_id);
5344
5345         perf_event__output_id_sample(event, &handle, &sample);
5346
5347         perf_output_end(&handle);
5348 out:
5349         task_event->event_id.header.size = size;
5350 }
5351
5352 static void perf_event_task(struct task_struct *task,
5353                               struct perf_event_context *task_ctx,
5354                               int new)
5355 {
5356         struct perf_task_event task_event;
5357
5358         if (!atomic_read(&nr_comm_events) &&
5359             !atomic_read(&nr_mmap_events) &&
5360             !atomic_read(&nr_task_events))
5361                 return;
5362
5363         task_event = (struct perf_task_event){
5364                 .task     = task,
5365                 .task_ctx = task_ctx,
5366                 .event_id    = {
5367                         .header = {
5368                                 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
5369                                 .misc = 0,
5370                                 .size = sizeof(task_event.event_id),
5371                         },
5372                         /* .pid  */
5373                         /* .ppid */
5374                         /* .tid  */
5375                         /* .ptid */
5376                         .time = perf_clock(),
5377                 },
5378         };
5379
5380         perf_event_aux(perf_event_task_output,
5381                        &task_event,
5382                        task_ctx);
5383 }
5384
5385 void perf_event_fork(struct task_struct *task)
5386 {
5387         perf_event_task(task, NULL, 1);
5388 }
5389
5390 /*
5391  * comm tracking
5392  */
5393
5394 struct perf_comm_event {
5395         struct task_struct      *task;
5396         char                    *comm;
5397         int                     comm_size;
5398
5399         struct {
5400                 struct perf_event_header        header;
5401
5402                 u32                             pid;
5403                 u32                             tid;
5404         } event_id;
5405 };
5406
5407 static int perf_event_comm_match(struct perf_event *event)
5408 {
5409         return event->attr.comm;
5410 }
5411
5412 static void perf_event_comm_output(struct perf_event *event,
5413                                    void *data)
5414 {
5415         struct perf_comm_event *comm_event = data;
5416         struct perf_output_handle handle;
5417         struct perf_sample_data sample;
5418         int size = comm_event->event_id.header.size;
5419         int ret;
5420
5421         if (!perf_event_comm_match(event))
5422                 return;
5423
5424         perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
5425         ret = perf_output_begin(&handle, event,
5426                                 comm_event->event_id.header.size);
5427
5428         if (ret)
5429                 goto out;
5430
5431         comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
5432         comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
5433
5434         perf_output_put(&handle, comm_event->event_id);
5435         __output_copy(&handle, comm_event->comm,
5436                                    comm_event->comm_size);
5437
5438         perf_event__output_id_sample(event, &handle, &sample);
5439
5440         perf_output_end(&handle);
5441 out:
5442         comm_event->event_id.header.size = size;
5443 }
5444
5445 static void perf_event_comm_event(struct perf_comm_event *comm_event)
5446 {
5447         char comm[TASK_COMM_LEN];
5448         unsigned int size;
5449
5450         memset(comm, 0, sizeof(comm));
5451         strlcpy(comm, comm_event->task->comm, sizeof(comm));
5452         size = ALIGN(strlen(comm)+1, sizeof(u64));
5453
5454         comm_event->comm = comm;
5455         comm_event->comm_size = size;
5456
5457         comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
5458
5459         perf_event_aux(perf_event_comm_output,
5460                        comm_event,
5461                        NULL);
5462 }
5463
5464 void perf_event_comm(struct task_struct *task, bool exec)
5465 {
5466         struct perf_comm_event comm_event;
5467
5468         if (!atomic_read(&nr_comm_events))
5469                 return;
5470
5471         comm_event = (struct perf_comm_event){
5472                 .task   = task,
5473                 /* .comm      */
5474                 /* .comm_size */
5475                 .event_id  = {
5476                         .header = {
5477                                 .type = PERF_RECORD_COMM,
5478                                 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
5479                                 /* .size */
5480                         },
5481                         /* .pid */
5482                         /* .tid */
5483                 },
5484         };
5485
5486         perf_event_comm_event(&comm_event);
5487 }
5488
5489 /*
5490  * mmap tracking
5491  */
5492
5493 struct perf_mmap_event {
5494         struct vm_area_struct   *vma;
5495
5496         const char              *file_name;
5497         int                     file_size;
5498         int                     maj, min;
5499         u64                     ino;
5500         u64                     ino_generation;
5501         u32                     prot, flags;
5502
5503         struct {
5504                 struct perf_event_header        header;
5505
5506                 u32                             pid;
5507                 u32                             tid;
5508                 u64                             start;
5509                 u64                             len;
5510                 u64                             pgoff;
5511         } event_id;
5512 };
5513
5514 static int perf_event_mmap_match(struct perf_event *event,
5515                                  void *data)
5516 {
5517         struct perf_mmap_event *mmap_event = data;
5518         struct vm_area_struct *vma = mmap_event->vma;
5519         int executable = vma->vm_flags & VM_EXEC;
5520
5521         return (!executable && event->attr.mmap_data) ||
5522                (executable && (event->attr.mmap || event->attr.mmap2));
5523 }
5524
5525 static void perf_event_mmap_output(struct perf_event *event,
5526                                    void *data)
5527 {
5528         struct perf_mmap_event *mmap_event = data;
5529         struct perf_output_handle handle;
5530         struct perf_sample_data sample;
5531         int size = mmap_event->event_id.header.size;
5532         int ret;
5533
5534         if (!perf_event_mmap_match(event, data))
5535                 return;
5536
5537         if (event->attr.mmap2) {
5538                 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
5539                 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
5540                 mmap_event->event_id.header.size += sizeof(mmap_event->min);
5541                 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
5542                 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
5543                 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
5544                 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
5545         }
5546
5547         perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
5548         ret = perf_output_begin(&handle, event,
5549                                 mmap_event->event_id.header.size);
5550         if (ret)
5551                 goto out;
5552
5553         mmap_event->event_id.pid = perf_event_pid(event, current);
5554         mmap_event->event_id.tid = perf_event_tid(event, current);
5555
5556         perf_output_put(&handle, mmap_event->event_id);
5557
5558         if (event->attr.mmap2) {
5559                 perf_output_put(&handle, mmap_event->maj);
5560                 perf_output_put(&handle, mmap_event->min);
5561                 perf_output_put(&handle, mmap_event->ino);
5562                 perf_output_put(&handle, mmap_event->ino_generation);
5563                 perf_output_put(&handle, mmap_event->prot);
5564                 perf_output_put(&handle, mmap_event->flags);
5565         }
5566
5567         __output_copy(&handle, mmap_event->file_name,
5568                                    mmap_event->file_size);
5569
5570         perf_event__output_id_sample(event, &handle, &sample);
5571
5572         perf_output_end(&handle);
5573 out:
5574         mmap_event->event_id.header.size = size;
5575 }
5576
5577 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
5578 {
5579         struct vm_area_struct *vma = mmap_event->vma;
5580         struct file *file = vma->vm_file;
5581         int maj = 0, min = 0;
5582         u64 ino = 0, gen = 0;
5583         u32 prot = 0, flags = 0;
5584         unsigned int size;
5585         char tmp[16];
5586         char *buf = NULL;
5587         char *name;
5588
5589         if (file) {
5590                 struct inode *inode;
5591                 dev_t dev;
5592
5593                 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5594                 if (!buf) {
5595                         name = "//enomem";
5596                         goto cpy_name;
5597                 }
5598                 /*
5599                  * d_path() works from the end of the rb backwards, so we
5600                  * need to add enough zero bytes after the string to handle
5601                  * the 64bit alignment we do later.
5602                  */
5603                 name = d_path(&file->f_path, buf, PATH_MAX - sizeof(u64));
5604                 if (IS_ERR(name)) {
5605                         name = "//toolong";
5606                         goto cpy_name;
5607                 }
5608                 inode = file_inode(vma->vm_file);
5609                 dev = inode->i_sb->s_dev;
5610                 ino = inode->i_ino;
5611                 gen = inode->i_generation;
5612                 maj = MAJOR(dev);
5613                 min = MINOR(dev);
5614
5615                 if (vma->vm_flags & VM_READ)
5616                         prot |= PROT_READ;
5617                 if (vma->vm_flags & VM_WRITE)
5618                         prot |= PROT_WRITE;
5619                 if (vma->vm_flags & VM_EXEC)
5620                         prot |= PROT_EXEC;
5621
5622                 if (vma->vm_flags & VM_MAYSHARE)
5623                         flags = MAP_SHARED;
5624                 else
5625                         flags = MAP_PRIVATE;
5626
5627                 if (vma->vm_flags & VM_DENYWRITE)
5628                         flags |= MAP_DENYWRITE;
5629                 if (vma->vm_flags & VM_MAYEXEC)
5630                         flags |= MAP_EXECUTABLE;
5631                 if (vma->vm_flags & VM_LOCKED)
5632                         flags |= MAP_LOCKED;
5633                 if (vma->vm_flags & VM_HUGETLB)
5634                         flags |= MAP_HUGETLB;
5635
5636                 goto got_name;
5637         } else {
5638                 if (vma->vm_ops && vma->vm_ops->name) {
5639                         name = (char *) vma->vm_ops->name(vma);
5640                         if (name)
5641                                 goto cpy_name;
5642                 }
5643
5644                 name = (char *)arch_vma_name(vma);
5645                 if (name)
5646                         goto cpy_name;
5647
5648                 if (vma->vm_start <= vma->vm_mm->start_brk &&
5649                                 vma->vm_end >= vma->vm_mm->brk) {
5650                         name = "[heap]";
5651                         goto cpy_name;
5652                 }
5653                 if (vma->vm_start <= vma->vm_mm->start_stack &&
5654                                 vma->vm_end >= vma->vm_mm->start_stack) {
5655                         name = "[stack]";
5656                         goto cpy_name;
5657                 }
5658
5659                 name = "//anon";
5660                 goto cpy_name;
5661         }
5662
5663 cpy_name:
5664         strlcpy(tmp, name, sizeof(tmp));
5665         name = tmp;
5666 got_name:
5667         /*
5668          * Since our buffer works in 8 byte units we need to align our string
5669          * size to a multiple of 8. However, we must guarantee the tail end is
5670          * zero'd out to avoid leaking random bits to userspace.
5671          */
5672         size = strlen(name)+1;
5673         while (!IS_ALIGNED(size, sizeof(u64)))
5674                 name[size++] = '\0';
5675
5676         mmap_event->file_name = name;
5677         mmap_event->file_size = size;
5678         mmap_event->maj = maj;
5679         mmap_event->min = min;
5680         mmap_event->ino = ino;
5681         mmap_event->ino_generation = gen;
5682         mmap_event->prot = prot;
5683         mmap_event->flags = flags;
5684
5685         if (!(vma->vm_flags & VM_EXEC))
5686                 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
5687
5688         mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
5689
5690         perf_event_aux(perf_event_mmap_output,
5691                        mmap_event,
5692                        NULL);
5693
5694         kfree(buf);
5695 }
5696
5697 void perf_event_mmap(struct vm_area_struct *vma)
5698 {
5699         struct perf_mmap_event mmap_event;
5700
5701         if (!atomic_read(&nr_mmap_events))
5702                 return;
5703
5704         mmap_event = (struct perf_mmap_event){
5705                 .vma    = vma,
5706                 /* .file_name */
5707                 /* .file_size */
5708                 .event_id  = {
5709                         .header = {
5710                                 .type = PERF_RECORD_MMAP,
5711                                 .misc = PERF_RECORD_MISC_USER,
5712                                 /* .size */
5713                         },
5714                         /* .pid */
5715                         /* .tid */
5716                         .start  = vma->vm_start,
5717                         .len    = vma->vm_end - vma->vm_start,
5718                         .pgoff  = (u64)vma->vm_pgoff << PAGE_SHIFT,
5719                 },
5720                 /* .maj (attr_mmap2 only) */
5721                 /* .min (attr_mmap2 only) */
5722                 /* .ino (attr_mmap2 only) */
5723                 /* .ino_generation (attr_mmap2 only) */
5724                 /* .prot (attr_mmap2 only) */
5725                 /* .flags (attr_mmap2 only) */
5726         };
5727
5728         perf_event_mmap_event(&mmap_event);
5729 }
5730
5731 /*
5732  * IRQ throttle logging
5733  */
5734
5735 static void perf_log_throttle(struct perf_event *event, int enable)
5736 {
5737         struct perf_output_handle handle;
5738         struct perf_sample_data sample;
5739         int ret;
5740
5741         struct {
5742                 struct perf_event_header        header;
5743                 u64                             time;
5744                 u64                             id;
5745                 u64                             stream_id;
5746         } throttle_event = {
5747                 .header = {
5748                         .type = PERF_RECORD_THROTTLE,
5749                         .misc = 0,
5750                         .size = sizeof(throttle_event),
5751                 },
5752                 .time           = perf_clock(),
5753                 .id             = primary_event_id(event),
5754                 .stream_id      = event->id,
5755         };
5756
5757         if (enable)
5758                 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
5759
5760         perf_event_header__init_id(&throttle_event.header, &sample, event);
5761
5762         ret = perf_output_begin(&handle, event,
5763                                 throttle_event.header.size);
5764         if (ret)
5765                 return;
5766
5767         perf_output_put(&handle, throttle_event);
5768         perf_event__output_id_sample(event, &handle, &sample);
5769         perf_output_end(&handle);
5770 }
5771
5772 /*
5773  * Generic event overflow handling, sampling.
5774  */
5775
5776 static int __perf_event_overflow(struct perf_event *event,
5777                                    int throttle, struct perf_sample_data *data,
5778                                    struct pt_regs *regs)
5779 {
5780         int events = atomic_read(&event->event_limit);
5781         struct hw_perf_event *hwc = &event->hw;
5782         u64 seq;
5783         int ret = 0;
5784
5785         /*
5786          * Non-sampling counters might still use the PMI to fold short
5787          * hardware counters, ignore those.
5788          */
5789         if (unlikely(!is_sampling_event(event)))
5790                 return 0;
5791
5792         seq = __this_cpu_read(perf_throttled_seq);
5793         if (seq != hwc->interrupts_seq) {
5794                 hwc->interrupts_seq = seq;
5795                 hwc->interrupts = 1;
5796         } else {
5797                 hwc->interrupts++;
5798                 if (unlikely(throttle
5799                              && hwc->interrupts >= max_samples_per_tick)) {
5800                         __this_cpu_inc(perf_throttled_count);
5801                         hwc->interrupts = MAX_INTERRUPTS;
5802                         perf_log_throttle(event, 0);
5803                         tick_nohz_full_kick();
5804                         ret = 1;
5805                 }
5806         }
5807
5808         if (event->attr.freq) {
5809                 u64 now = perf_clock();
5810                 s64 delta = now - hwc->freq_time_stamp;
5811
5812                 hwc->freq_time_stamp = now;
5813
5814                 if (delta > 0 && delta < 2*TICK_NSEC)
5815                         perf_adjust_period(event, delta, hwc->last_period, true);
5816         }
5817
5818         /*
5819          * XXX event_limit might not quite work as expected on inherited
5820          * events
5821          */
5822
5823         event->pending_kill = POLL_IN;
5824         if (events && atomic_dec_and_test(&event->event_limit)) {
5825                 ret = 1;
5826                 event->pending_kill = POLL_HUP;
5827                 event->pending_disable = 1;
5828                 irq_work_queue(&event->pending);
5829         }
5830
5831         if (event->overflow_handler)
5832                 event->overflow_handler(event, data, regs);
5833         else
5834                 perf_event_output(event, data, regs);
5835
5836         if (event->fasync && event->pending_kill) {
5837                 event->pending_wakeup = 1;
5838                 irq_work_queue(&event->pending);
5839         }
5840
5841         return ret;
5842 }
5843
5844 int perf_event_overflow(struct perf_event *event,
5845                           struct perf_sample_data *data,
5846                           struct pt_regs *regs)
5847 {
5848         return __perf_event_overflow(event, 1, data, regs);
5849 }
5850
5851 /*
5852  * Generic software event infrastructure
5853  */
5854
5855 struct swevent_htable {
5856         struct swevent_hlist            *swevent_hlist;
5857         struct mutex                    hlist_mutex;
5858         int                             hlist_refcount;
5859
5860         /* Recursion avoidance in each contexts */
5861         int                             recursion[PERF_NR_CONTEXTS];
5862
5863         /* Keeps track of cpu being initialized/exited */
5864         bool                            online;
5865 };
5866
5867 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
5868
5869 /*
5870  * We directly increment event->count and keep a second value in
5871  * event->hw.period_left to count intervals. This period event
5872  * is kept in the range [-sample_period, 0] so that we can use the
5873  * sign as trigger.
5874  */
5875
5876 u64 perf_swevent_set_period(struct perf_event *event)
5877 {
5878         struct hw_perf_event *hwc = &event->hw;
5879         u64 period = hwc->last_period;
5880         u64 nr, offset;
5881         s64 old, val;
5882
5883         hwc->last_period = hwc->sample_period;
5884
5885 again:
5886         old = val = local64_read(&hwc->period_left);
5887         if (val < 0)
5888                 return 0;
5889
5890         nr = div64_u64(period + val, period);
5891         offset = nr * period;
5892         val -= offset;
5893         if (local64_cmpxchg(&hwc->period_left, old, val) != old)
5894                 goto again;
5895
5896         return nr;
5897 }
5898
5899 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
5900                                     struct perf_sample_data *data,
5901                                     struct pt_regs *regs)
5902 {
5903         struct hw_perf_event *hwc = &event->hw;
5904         int throttle = 0;
5905
5906         if (!overflow)
5907                 overflow = perf_swevent_set_period(event);
5908
5909         if (hwc->interrupts == MAX_INTERRUPTS)
5910                 return;
5911
5912         for (; overflow; overflow--) {
5913                 if (__perf_event_overflow(event, throttle,
5914                                             data, regs)) {
5915                         /*
5916                          * We inhibit the overflow from happening when
5917                          * hwc->interrupts == MAX_INTERRUPTS.
5918                          */
5919                         break;
5920                 }
5921                 throttle = 1;
5922         }
5923 }
5924
5925 static void perf_swevent_event(struct perf_event *event, u64 nr,
5926                                struct perf_sample_data *data,
5927                                struct pt_regs *regs)
5928 {
5929         struct hw_perf_event *hwc = &event->hw;
5930
5931         local64_add(nr, &event->count);
5932
5933         if (!regs)
5934                 return;
5935
5936         if (!is_sampling_event(event))
5937                 return;
5938
5939         if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
5940                 data->period = nr;
5941                 return perf_swevent_overflow(event, 1, data, regs);
5942         } else
5943                 data->period = event->hw.last_period;
5944
5945         if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
5946                 return perf_swevent_overflow(event, 1, data, regs);
5947
5948         if (local64_add_negative(nr, &hwc->period_left))
5949                 return;
5950
5951         perf_swevent_overflow(event, 0, data, regs);
5952 }
5953
5954 static int perf_exclude_event(struct perf_event *event,
5955                               struct pt_regs *regs)
5956 {
5957         if (event->hw.state & PERF_HES_STOPPED)
5958                 return 1;
5959
5960         if (regs) {
5961                 if (event->attr.exclude_user && user_mode(regs))
5962                         return 1;
5963
5964                 if (event->attr.exclude_kernel && !user_mode(regs))
5965                         return 1;
5966         }
5967
5968         return 0;
5969 }
5970
5971 static int perf_swevent_match(struct perf_event *event,
5972                                 enum perf_type_id type,
5973                                 u32 event_id,
5974                                 struct perf_sample_data *data,
5975                                 struct pt_regs *regs)
5976 {
5977         if (event->attr.type != type)
5978                 return 0;
5979
5980         if (event->attr.config != event_id)
5981                 return 0;
5982
5983         if (perf_exclude_event(event, regs))
5984                 return 0;
5985
5986         return 1;
5987 }
5988
5989 static inline u64 swevent_hash(u64 type, u32 event_id)
5990 {
5991         u64 val = event_id | (type << 32);
5992
5993         return hash_64(val, SWEVENT_HLIST_BITS);
5994 }
5995
5996 static inline struct hlist_head *
5997 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
5998 {
5999         u64 hash = swevent_hash(type, event_id);
6000
6001         return &hlist->heads[hash];
6002 }
6003
6004 /* For the read side: events when they trigger */
6005 static inline struct hlist_head *
6006 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
6007 {
6008         struct swevent_hlist *hlist;
6009
6010         hlist = rcu_dereference(swhash->swevent_hlist);
6011         if (!hlist)
6012                 return NULL;
6013
6014         return __find_swevent_head(hlist, type, event_id);
6015 }
6016
6017 /* For the event head insertion and removal in the hlist */
6018 static inline struct hlist_head *
6019 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
6020 {
6021         struct swevent_hlist *hlist;
6022         u32 event_id = event->attr.config;
6023         u64 type = event->attr.type;
6024
6025         /*
6026          * Event scheduling is always serialized against hlist allocation
6027          * and release. Which makes the protected version suitable here.
6028          * The context lock guarantees that.
6029          */
6030         hlist = rcu_dereference_protected(swhash->swevent_hlist,
6031                                           lockdep_is_held(&event->ctx->lock));
6032         if (!hlist)
6033                 return NULL;
6034
6035         return __find_swevent_head(hlist, type, event_id);
6036 }
6037
6038 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
6039                                     u64 nr,
6040                                     struct perf_sample_data *data,
6041                                     struct pt_regs *regs)
6042 {
6043         struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6044         struct perf_event *event;
6045         struct hlist_head *head;
6046
6047         rcu_read_lock();
6048         head = find_swevent_head_rcu(swhash, type, event_id);
6049         if (!head)
6050                 goto end;
6051
6052         hlist_for_each_entry_rcu(event, head, hlist_entry) {
6053                 if (perf_swevent_match(event, type, event_id, data, regs))
6054                         perf_swevent_event(event, nr, data, regs);
6055         }
6056 end:
6057         rcu_read_unlock();
6058 }
6059
6060 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
6061
6062 int perf_swevent_get_recursion_context(void)
6063 {
6064         struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6065
6066         return get_recursion_context(swhash->recursion);
6067 }
6068 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
6069
6070 inline void perf_swevent_put_recursion_context(int rctx)
6071 {
6072         struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6073
6074         put_recursion_context(swhash->recursion, rctx);
6075 }
6076
6077 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6078 {
6079         struct perf_sample_data data;
6080
6081         if (WARN_ON_ONCE(!regs))
6082                 return;
6083
6084         perf_sample_data_init(&data, addr, 0);
6085         do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
6086 }
6087
6088 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6089 {
6090         int rctx;
6091
6092         preempt_disable_notrace();
6093         rctx = perf_swevent_get_recursion_context();
6094         if (unlikely(rctx < 0))
6095                 goto fail;
6096
6097         ___perf_sw_event(event_id, nr, regs, addr);
6098
6099         perf_swevent_put_recursion_context(rctx);
6100 fail:
6101         preempt_enable_notrace();
6102 }
6103
6104 static void perf_swevent_read(struct perf_event *event)
6105 {
6106 }
6107
6108 static int perf_swevent_add(struct perf_event *event, int flags)
6109 {
6110         struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
6111         struct hw_perf_event *hwc = &event->hw;
6112         struct hlist_head *head;
6113
6114         if (is_sampling_event(event)) {
6115                 hwc->last_period = hwc->sample_period;
6116                 perf_swevent_set_period(event);
6117         }
6118
6119         hwc->state = !(flags & PERF_EF_START);
6120
6121         head = find_swevent_head(swhash, event);
6122         if (!head) {
6123                 /*
6124                  * We can race with cpu hotplug code. Do not
6125                  * WARN if the cpu just got unplugged.
6126                  */
6127                 WARN_ON_ONCE(swhash->online);
6128                 return -EINVAL;
6129         }
6130
6131         hlist_add_head_rcu(&event->hlist_entry, head);
6132         perf_event_update_userpage(event);
6133
6134         return 0;
6135 }
6136
6137 static void perf_swevent_del(struct perf_event *event, int flags)
6138 {
6139         hlist_del_rcu(&event->hlist_entry);
6140 }
6141
6142 static void perf_swevent_start(struct perf_event *event, int flags)
6143 {
6144         event->hw.state = 0;
6145 }
6146
6147 static void perf_swevent_stop(struct perf_event *event, int flags)
6148 {
6149         event->hw.state = PERF_HES_STOPPED;
6150 }
6151
6152 /* Deref the hlist from the update side */
6153 static inline struct swevent_hlist *
6154 swevent_hlist_deref(struct swevent_htable *swhash)
6155 {
6156         return rcu_dereference_protected(swhash->swevent_hlist,
6157                                          lockdep_is_held(&swhash->hlist_mutex));
6158 }
6159
6160 static void swevent_hlist_release(struct swevent_htable *swhash)
6161 {
6162         struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
6163
6164         if (!hlist)
6165                 return;
6166
6167         RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
6168         kfree_rcu(hlist, rcu_head);
6169 }
6170
6171 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
6172 {
6173         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6174
6175         mutex_lock(&swhash->hlist_mutex);
6176
6177         if (!--swhash->hlist_refcount)
6178                 swevent_hlist_release(swhash);
6179
6180         mutex_unlock(&swhash->hlist_mutex);
6181 }
6182
6183 static void swevent_hlist_put(struct perf_event *event)
6184 {
6185         int cpu;
6186
6187         for_each_possible_cpu(cpu)
6188                 swevent_hlist_put_cpu(event, cpu);
6189 }
6190
6191 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
6192 {
6193         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6194         int err = 0;
6195
6196         mutex_lock(&swhash->hlist_mutex);
6197
6198         if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
6199                 struct swevent_hlist *hlist;
6200
6201                 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
6202                 if (!hlist) {
6203                         err = -ENOMEM;
6204                         goto exit;
6205                 }
6206                 rcu_assign_pointer(swhash->swevent_hlist, hlist);
6207         }
6208         swhash->hlist_refcount++;
6209 exit:
6210         mutex_unlock(&swhash->hlist_mutex);
6211
6212         return err;
6213 }
6214
6215 static int swevent_hlist_get(struct perf_event *event)
6216 {
6217         int err;
6218         int cpu, failed_cpu;
6219
6220         get_online_cpus();
6221         for_each_possible_cpu(cpu) {
6222                 err = swevent_hlist_get_cpu(event, cpu);
6223                 if (err) {
6224                         failed_cpu = cpu;
6225                         goto fail;
6226                 }
6227         }
6228         put_online_cpus();
6229
6230         return 0;
6231 fail:
6232         for_each_possible_cpu(cpu) {
6233                 if (cpu == failed_cpu)
6234                         break;
6235                 swevent_hlist_put_cpu(event, cpu);
6236         }
6237
6238         put_online_cpus();
6239         return err;
6240 }
6241
6242 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
6243
6244 static void sw_perf_event_destroy(struct perf_event *event)
6245 {
6246         u64 event_id = event->attr.config;
6247
6248         WARN_ON(event->parent);
6249
6250         static_key_slow_dec(&perf_swevent_enabled[event_id]);
6251         swevent_hlist_put(event);
6252 }
6253
6254 static int perf_swevent_init(struct perf_event *event)
6255 {
6256         u64 event_id = event->attr.config;
6257
6258         if (event->attr.type != PERF_TYPE_SOFTWARE)
6259                 return -ENOENT;
6260
6261         /*
6262          * no branch sampling for software events
6263          */
6264         if (has_branch_stack(event))
6265                 return -EOPNOTSUPP;
6266
6267         switch (event_id) {
6268         case PERF_COUNT_SW_CPU_CLOCK:
6269         case PERF_COUNT_SW_TASK_CLOCK:
6270                 return -ENOENT;
6271
6272         default:
6273                 break;
6274         }
6275
6276         if (event_id >= PERF_COUNT_SW_MAX)
6277                 return -ENOENT;
6278
6279         if (!event->parent) {
6280                 int err;
6281
6282                 err = swevent_hlist_get(event);
6283                 if (err)
6284                         return err;
6285
6286                 static_key_slow_inc(&perf_swevent_enabled[event_id]);
6287                 event->destroy = sw_perf_event_destroy;
6288         }
6289
6290         return 0;
6291 }
6292
6293 static struct pmu perf_swevent = {
6294         .task_ctx_nr    = perf_sw_context,
6295
6296         .event_init     = perf_swevent_init,
6297         .add            = perf_swevent_add,
6298         .del            = perf_swevent_del,
6299         .start          = perf_swevent_start,
6300         .stop           = perf_swevent_stop,
6301         .read           = perf_swevent_read,
6302 };
6303
6304 #ifdef CONFIG_EVENT_TRACING
6305
6306 static int perf_tp_filter_match(struct perf_event *event,
6307                                 struct perf_sample_data *data)
6308 {
6309         void *record = data->raw->data;
6310
6311         if (likely(!event->filter) || filter_match_preds(event->filter, record))
6312                 return 1;
6313         return 0;
6314 }
6315
6316 static int perf_tp_event_match(struct perf_event *event,
6317                                 struct perf_sample_data *data,
6318                                 struct pt_regs *regs)
6319 {
6320         if (event->hw.state & PERF_HES_STOPPED)
6321                 return 0;
6322         /*
6323          * All tracepoints are from kernel-space.
6324          */
6325         if (event->attr.exclude_kernel)
6326                 return 0;
6327
6328         if (!perf_tp_filter_match(event, data))
6329                 return 0;
6330
6331         return 1;
6332 }
6333
6334 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
6335                    struct pt_regs *regs, struct hlist_head *head, int rctx,
6336                    struct task_struct *task)
6337 {
6338         struct perf_sample_data data;
6339         struct perf_event *event;
6340
6341         struct perf_raw_record raw = {
6342                 .size = entry_size,
6343                 .data = record,
6344         };
6345
6346         perf_sample_data_init(&data, addr, 0);
6347         data.raw = &raw;
6348
6349         hlist_for_each_entry_rcu(event, head, hlist_entry) {
6350                 if (perf_tp_event_match(event, &data, regs))
6351                         perf_swevent_event(event, count, &data, regs);
6352         }
6353
6354         /*
6355          * If we got specified a target task, also iterate its context and
6356          * deliver this event there too.
6357          */
6358         if (task && task != current) {
6359                 struct perf_event_context *ctx;
6360                 struct trace_entry *entry = record;
6361
6362                 rcu_read_lock();
6363                 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
6364                 if (!ctx)
6365                         goto unlock;
6366
6367                 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
6368                         if (event->attr.type != PERF_TYPE_TRACEPOINT)
6369                                 continue;
6370                         if (event->attr.config != entry->type)
6371                                 continue;
6372                         if (perf_tp_event_match(event, &data, regs))
6373                                 perf_swevent_event(event, count, &data, regs);
6374                 }
6375 unlock:
6376                 rcu_read_unlock();
6377         }
6378
6379         perf_swevent_put_recursion_context(rctx);
6380 }
6381 EXPORT_SYMBOL_GPL(perf_tp_event);
6382
6383 static void tp_perf_event_destroy(struct perf_event *event)
6384 {
6385         perf_trace_destroy(event);
6386 }
6387
6388 static int perf_tp_event_init(struct perf_event *event)
6389 {
6390         int err;
6391
6392         if (event->attr.type != PERF_TYPE_TRACEPOINT)
6393                 return -ENOENT;
6394
6395         /*
6396          * no branch sampling for tracepoint events
6397          */
6398         if (has_branch_stack(event))
6399                 return -EOPNOTSUPP;
6400
6401         err = perf_trace_init(event);
6402         if (err)
6403                 return err;
6404
6405         event->destroy = tp_perf_event_destroy;
6406
6407         return 0;
6408 }
6409
6410 static struct pmu perf_tracepoint = {
6411         .task_ctx_nr    = perf_sw_context,
6412
6413         .event_init     = perf_tp_event_init,
6414         .add            = perf_trace_add,
6415         .del            = perf_trace_del,
6416         .start          = perf_swevent_start,
6417         .stop           = perf_swevent_stop,
6418         .read           = perf_swevent_read,
6419 };
6420
6421 static inline void perf_tp_register(void)
6422 {
6423         perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
6424 }
6425
6426 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
6427 {
6428         char *filter_str;
6429         int ret;
6430
6431         if (event->attr.type != PERF_TYPE_TRACEPOINT)
6432                 return -EINVAL;
6433
6434         filter_str = strndup_user(arg, PAGE_SIZE);
6435         if (IS_ERR(filter_str))
6436                 return PTR_ERR(filter_str);
6437
6438         ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
6439
6440         kfree(filter_str);
6441         return ret;
6442 }
6443
6444 static void perf_event_free_filter(struct perf_event *event)
6445 {
6446         ftrace_profile_free_filter(event);
6447 }
6448
6449 #else
6450
6451 static inline void perf_tp_register(void)
6452 {
6453 }
6454
6455 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
6456 {
6457         return -ENOENT;
6458 }
6459
6460 static void perf_event_free_filter(struct perf_event *event)
6461 {
6462 }
6463
6464 #endif /* CONFIG_EVENT_TRACING */
6465
6466 #ifdef CONFIG_HAVE_HW_BREAKPOINT
6467 void perf_bp_event(struct perf_event *bp, void *data)
6468 {
6469         struct perf_sample_data sample;
6470         struct pt_regs *regs = data;
6471
6472         perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
6473
6474         if (!bp->hw.state && !perf_exclude_event(bp, regs))
6475                 perf_swevent_event(bp, 1, &sample, regs);
6476 }
6477 #endif
6478
6479 /*
6480  * hrtimer based swevent callback
6481  */
6482
6483 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
6484 {
6485         enum hrtimer_restart ret = HRTIMER_RESTART;
6486         struct perf_sample_data data;
6487         struct pt_regs *regs;
6488         struct perf_event *event;
6489         u64 period;
6490
6491         event = container_of(hrtimer, struct perf_event, hw.hrtimer);
6492
6493         if (event->state != PERF_EVENT_STATE_ACTIVE)
6494                 return HRTIMER_NORESTART;
6495
6496         event->pmu->read(event);
6497
6498         perf_sample_data_init(&data, 0, event->hw.last_period);
6499         regs = get_irq_regs();
6500
6501         if (regs && !perf_exclude_event(event, regs)) {
6502                 if (!(event->attr.exclude_idle && is_idle_task(current)))
6503                         if (__perf_event_overflow(event, 1, &data, regs))
6504                                 ret = HRTIMER_NORESTART;
6505         }
6506
6507         period = max_t(u64, 10000, event->hw.sample_period);
6508         hrtimer_forward_now(hrtimer, ns_to_ktime(period));
6509
6510         return ret;
6511 }
6512
6513 static void perf_swevent_start_hrtimer(struct perf_event *event)
6514 {
6515         struct hw_perf_event *hwc = &event->hw;
6516         s64 period;
6517
6518         if (!is_sampling_event(event))
6519                 return;
6520
6521         period = local64_read(&hwc->period_left);
6522         if (period) {
6523                 if (period < 0)
6524                         period = 10000;
6525
6526                 local64_set(&hwc->period_left, 0);
6527         } else {
6528                 period = max_t(u64, 10000, hwc->sample_period);
6529         }
6530         __hrtimer_start_range_ns(&hwc->hrtimer,
6531                                 ns_to_ktime(period), 0,
6532                                 HRTIMER_MODE_REL_PINNED, 0);
6533 }
6534
6535 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
6536 {
6537         struct hw_perf_event *hwc = &event->hw;
6538
6539         if (is_sampling_event(event)) {
6540                 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
6541                 local64_set(&hwc->period_left, ktime_to_ns(remaining));
6542
6543                 hrtimer_cancel(&hwc->hrtimer);
6544         }
6545 }
6546
6547 static void perf_swevent_init_hrtimer(struct perf_event *event)
6548 {
6549         struct hw_perf_event *hwc = &event->hw;
6550
6551         if (!is_sampling_event(event))
6552                 return;
6553
6554         hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6555         hwc->hrtimer.function = perf_swevent_hrtimer;
6556
6557         /*
6558          * Since hrtimers have a fixed rate, we can do a static freq->period
6559          * mapping and avoid the whole period adjust feedback stuff.
6560          */
6561         if (event->attr.freq) {
6562                 long freq = event->attr.sample_freq;
6563
6564                 event->attr.sample_period = NSEC_PER_SEC / freq;
6565                 hwc->sample_period = event->attr.sample_period;
6566                 local64_set(&hwc->period_left, hwc->sample_period);
6567                 hwc->last_period = hwc->sample_period;
6568                 event->attr.freq = 0;
6569         }
6570 }
6571
6572 /*
6573  * Software event: cpu wall time clock
6574  */
6575
6576 static void cpu_clock_event_update(struct perf_event *event)
6577 {
6578         s64 prev;
6579         u64 now;
6580
6581         now = local_clock();
6582         prev = local64_xchg(&event->hw.prev_count, now);
6583         local64_add(now - prev, &event->count);
6584 }
6585
6586 static void cpu_clock_event_start(struct perf_event *event, int flags)
6587 {
6588         local64_set(&event->hw.prev_count, local_clock());
6589         perf_swevent_start_hrtimer(event);
6590 }
6591
6592 static void cpu_clock_event_stop(struct perf_event *event, int flags)
6593 {
6594         perf_swevent_cancel_hrtimer(event);
6595         cpu_clock_event_update(event);
6596 }
6597
6598 static int cpu_clock_event_add(struct perf_event *event, int flags)
6599 {
6600         if (flags & PERF_EF_START)
6601                 cpu_clock_event_start(event, flags);
6602         perf_event_update_userpage(event);
6603
6604         return 0;
6605 }
6606
6607 static void cpu_clock_event_del(struct perf_event *event, int flags)
6608 {
6609         cpu_clock_event_stop(event, flags);
6610 }
6611
6612 static void cpu_clock_event_read(struct perf_event *event)
6613 {
6614         cpu_clock_event_update(event);
6615 }
6616
6617 static int cpu_clock_event_init(struct perf_event *event)
6618 {
6619         if (event->attr.type != PERF_TYPE_SOFTWARE)
6620                 return -ENOENT;
6621
6622         if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
6623                 return -ENOENT;
6624
6625         /*
6626          * no branch sampling for software events
6627          */
6628         if (has_branch_stack(event))
6629                 return -EOPNOTSUPP;
6630
6631         perf_swevent_init_hrtimer(event);
6632
6633         return 0;
6634 }
6635
6636 static struct pmu perf_cpu_clock = {
6637         .task_ctx_nr    = perf_sw_context,
6638
6639         .event_init     = cpu_clock_event_init,
6640         .add            = cpu_clock_event_add,
6641         .del            = cpu_clock_event_del,
6642         .start          = cpu_clock_event_start,
6643         .stop           = cpu_clock_event_stop,
6644         .read           = cpu_clock_event_read,
6645 };
6646
6647 /*
6648  * Software event: task time clock
6649  */
6650
6651 static void task_clock_event_update(struct perf_event *event, u64 now)
6652 {
6653         u64 prev;
6654         s64 delta;
6655
6656         prev = local64_xchg(&event->hw.prev_count, now);
6657         delta = now - prev;
6658         local64_add(delta, &event->count);
6659 }
6660
6661 static void task_clock_event_start(struct perf_event *event, int flags)
6662 {
6663         local64_set(&event->hw.prev_count, event->ctx->time);
6664         perf_swevent_start_hrtimer(event);
6665 }
6666
6667 static void task_clock_event_stop(struct perf_event *event, int flags)
6668 {
6669         perf_swevent_cancel_hrtimer(event);
6670         task_clock_event_update(event, event->ctx->time);
6671 }
6672
6673 static int task_clock_event_add(struct perf_event *event, int flags)
6674 {
6675         if (flags & PERF_EF_START)
6676                 task_clock_event_start(event, flags);
6677         perf_event_update_userpage(event);
6678
6679         return 0;
6680 }
6681
6682 static void task_clock_event_del(struct perf_event *event, int flags)
6683 {
6684         task_clock_event_stop(event, PERF_EF_UPDATE);
6685 }
6686
6687 static void task_clock_event_read(struct perf_event *event)
6688 {
6689         u64 now = perf_clock();
6690         u64 delta = now - event->ctx->timestamp;
6691         u64 time = event->ctx->time + delta;
6692
6693         task_clock_event_update(event, time);
6694 }
6695
6696 static int task_clock_event_init(struct perf_event *event)
6697 {
6698         if (event->attr.type != PERF_TYPE_SOFTWARE)
6699                 return -ENOENT;
6700
6701         if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
6702                 return -ENOENT;
6703
6704         /*
6705          * no branch sampling for software events
6706          */
6707         if (has_branch_stack(event))
6708                 return -EOPNOTSUPP;
6709
6710         perf_swevent_init_hrtimer(event);
6711
6712         return 0;
6713 }
6714
6715 static struct pmu perf_task_clock = {
6716         .task_ctx_nr    = perf_sw_context,
6717
6718         .event_init     = task_clock_event_init,
6719         .add            = task_clock_event_add,
6720         .del            = task_clock_event_del,
6721         .start          = task_clock_event_start,
6722         .stop           = task_clock_event_stop,
6723         .read           = task_clock_event_read,
6724 };
6725
6726 static void perf_pmu_nop_void(struct pmu *pmu)
6727 {
6728 }
6729
6730 static int perf_pmu_nop_int(struct pmu *pmu)
6731 {
6732         return 0;
6733 }
6734
6735 static void perf_pmu_start_txn(struct pmu *pmu)
6736 {
6737         perf_pmu_disable(pmu);
6738 }
6739
6740 static int perf_pmu_commit_txn(struct pmu *pmu)
6741 {
6742         perf_pmu_enable(pmu);
6743         return 0;
6744 }
6745
6746 static void perf_pmu_cancel_txn(struct pmu *pmu)
6747 {
6748         perf_pmu_enable(pmu);
6749 }
6750
6751 static int perf_event_idx_default(struct perf_event *event)
6752 {
6753         return 0;
6754 }
6755
6756 /*
6757  * Ensures all contexts with the same task_ctx_nr have the same
6758  * pmu_cpu_context too.
6759  */
6760 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
6761 {
6762         struct pmu *pmu;
6763
6764         if (ctxn < 0)
6765                 return NULL;
6766
6767         list_for_each_entry(pmu, &pmus, entry) {
6768                 if (pmu->task_ctx_nr == ctxn)
6769                         return pmu->pmu_cpu_context;
6770         }
6771
6772         return NULL;
6773 }
6774
6775 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
6776 {
6777         int cpu;
6778
6779         for_each_possible_cpu(cpu) {
6780                 struct perf_cpu_context *cpuctx;
6781
6782                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6783
6784                 if (cpuctx->unique_pmu == old_pmu)
6785                         cpuctx->unique_pmu = pmu;
6786         }
6787 }
6788
6789 static void free_pmu_context(struct pmu *pmu)
6790 {
6791         struct pmu *i;
6792
6793         mutex_lock(&pmus_lock);
6794         /*
6795          * Like a real lame refcount.
6796          */
6797         list_for_each_entry(i, &pmus, entry) {
6798                 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
6799                         update_pmu_context(i, pmu);
6800                         goto out;
6801                 }
6802         }
6803
6804         free_percpu(pmu->pmu_cpu_context);
6805 out:
6806         mutex_unlock(&pmus_lock);
6807 }
6808 static struct idr pmu_idr;
6809
6810 static ssize_t
6811 type_show(struct device *dev, struct device_attribute *attr, char *page)
6812 {
6813         struct pmu *pmu = dev_get_drvdata(dev);
6814
6815         return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
6816 }
6817 static DEVICE_ATTR_RO(type);
6818
6819 static ssize_t
6820 perf_event_mux_interval_ms_show(struct device *dev,
6821                                 struct device_attribute *attr,
6822                                 char *page)
6823 {
6824         struct pmu *pmu = dev_get_drvdata(dev);
6825
6826         return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
6827 }
6828
6829 static ssize_t
6830 perf_event_mux_interval_ms_store(struct device *dev,
6831                                  struct device_attribute *attr,
6832                                  const char *buf, size_t count)
6833 {
6834         struct pmu *pmu = dev_get_drvdata(dev);
6835         int timer, cpu, ret;
6836
6837         ret = kstrtoint(buf, 0, &timer);
6838         if (ret)
6839                 return ret;
6840
6841         if (timer < 1)
6842                 return -EINVAL;
6843
6844         /* same value, noting to do */
6845         if (timer == pmu->hrtimer_interval_ms)
6846                 return count;
6847
6848         pmu->hrtimer_interval_ms = timer;
6849
6850         /* update all cpuctx for this PMU */
6851         for_each_possible_cpu(cpu) {
6852                 struct perf_cpu_context *cpuctx;
6853                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6854                 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
6855
6856                 if (hrtimer_active(&cpuctx->hrtimer))
6857                         hrtimer_forward_now(&cpuctx->hrtimer, cpuctx->hrtimer_interval);
6858         }
6859
6860         return count;
6861 }
6862 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
6863
6864 static struct attribute *pmu_dev_attrs[] = {
6865         &dev_attr_type.attr,
6866         &dev_attr_perf_event_mux_interval_ms.attr,
6867         NULL,
6868 };
6869 ATTRIBUTE_GROUPS(pmu_dev);
6870
6871 static int pmu_bus_running;
6872 static struct bus_type pmu_bus = {
6873         .name           = "event_source",
6874         .dev_groups     = pmu_dev_groups,
6875 };
6876
6877 static void pmu_dev_release(struct device *dev)
6878 {
6879         kfree(dev);
6880 }
6881
6882 static int pmu_dev_alloc(struct pmu *pmu)
6883 {
6884         int ret = -ENOMEM;
6885
6886         pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
6887         if (!pmu->dev)
6888                 goto out;
6889
6890         pmu->dev->groups = pmu->attr_groups;
6891         device_initialize(pmu->dev);
6892         ret = dev_set_name(pmu->dev, "%s", pmu->name);
6893         if (ret)
6894                 goto free_dev;
6895
6896         dev_set_drvdata(pmu->dev, pmu);
6897         pmu->dev->bus = &pmu_bus;
6898         pmu->dev->release = pmu_dev_release;
6899         ret = device_add(pmu->dev);
6900         if (ret)
6901                 goto free_dev;
6902
6903 out:
6904         return ret;
6905
6906 free_dev:
6907         put_device(pmu->dev);
6908         goto out;
6909 }
6910
6911 static struct lock_class_key cpuctx_mutex;
6912 static struct lock_class_key cpuctx_lock;
6913
6914 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
6915 {
6916         int cpu, ret;
6917
6918         mutex_lock(&pmus_lock);
6919         ret = -ENOMEM;
6920         pmu->pmu_disable_count = alloc_percpu(int);
6921         if (!pmu->pmu_disable_count)
6922                 goto unlock;
6923
6924         pmu->type = -1;
6925         if (!name)
6926                 goto skip_type;
6927         pmu->name = name;
6928
6929         if (type < 0) {
6930                 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
6931                 if (type < 0) {
6932                         ret = type;
6933                         goto free_pdc;
6934                 }
6935         }
6936         pmu->type = type;
6937
6938         if (pmu_bus_running) {
6939                 ret = pmu_dev_alloc(pmu);
6940                 if (ret)
6941                         goto free_idr;
6942         }
6943
6944 skip_type:
6945         pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
6946         if (pmu->pmu_cpu_context)
6947                 goto got_cpu_context;
6948
6949         ret = -ENOMEM;
6950         pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
6951         if (!pmu->pmu_cpu_context)
6952                 goto free_dev;
6953
6954         for_each_possible_cpu(cpu) {
6955                 struct perf_cpu_context *cpuctx;
6956
6957                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
6958                 __perf_event_init_context(&cpuctx->ctx);
6959                 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
6960                 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
6961                 cpuctx->ctx.pmu = pmu;
6962
6963                 __perf_cpu_hrtimer_init(cpuctx, cpu);
6964
6965                 cpuctx->unique_pmu = pmu;
6966         }
6967
6968 got_cpu_context:
6969         if (!pmu->start_txn) {
6970                 if (pmu->pmu_enable) {
6971                         /*
6972                          * If we have pmu_enable/pmu_disable calls, install
6973                          * transaction stubs that use that to try and batch
6974                          * hardware accesses.
6975                          */
6976                         pmu->start_txn  = perf_pmu_start_txn;
6977                         pmu->commit_txn = perf_pmu_commit_txn;
6978                         pmu->cancel_txn = perf_pmu_cancel_txn;
6979                 } else {
6980                         pmu->start_txn  = perf_pmu_nop_void;
6981                         pmu->commit_txn = perf_pmu_nop_int;
6982                         pmu->cancel_txn = perf_pmu_nop_void;
6983                 }
6984         }
6985
6986         if (!pmu->pmu_enable) {
6987                 pmu->pmu_enable  = perf_pmu_nop_void;
6988                 pmu->pmu_disable = perf_pmu_nop_void;
6989         }
6990
6991         if (!pmu->event_idx)
6992                 pmu->event_idx = perf_event_idx_default;
6993
6994         list_add_rcu(&pmu->entry, &pmus);
6995         ret = 0;
6996 unlock:
6997         mutex_unlock(&pmus_lock);
6998
6999         return ret;
7000
7001 free_dev:
7002         device_del(pmu->dev);
7003         put_device(pmu->dev);
7004
7005 free_idr:
7006         if (pmu->type >= PERF_TYPE_MAX)
7007                 idr_remove(&pmu_idr, pmu->type);
7008
7009 free_pdc:
7010         free_percpu(pmu->pmu_disable_count);
7011         goto unlock;
7012 }
7013 EXPORT_SYMBOL_GPL(perf_pmu_register);
7014
7015 void perf_pmu_unregister(struct pmu *pmu)
7016 {
7017         mutex_lock(&pmus_lock);
7018         list_del_rcu(&pmu->entry);
7019         mutex_unlock(&pmus_lock);
7020
7021         /*
7022          * We dereference the pmu list under both SRCU and regular RCU, so
7023          * synchronize against both of those.
7024          */
7025         synchronize_srcu(&pmus_srcu);
7026         synchronize_rcu();
7027
7028         free_percpu(pmu->pmu_disable_count);
7029         if (pmu->type >= PERF_TYPE_MAX)
7030                 idr_remove(&pmu_idr, pmu->type);
7031         device_del(pmu->dev);
7032         put_device(pmu->dev);
7033         free_pmu_context(pmu);
7034 }
7035 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
7036
7037 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
7038 {
7039         int ret;
7040
7041         if (!try_module_get(pmu->module))
7042                 return -ENODEV;
7043         event->pmu = pmu;
7044         ret = pmu->event_init(event);
7045         if (ret)
7046                 module_put(pmu->module);
7047
7048         return ret;
7049 }
7050
7051 struct pmu *perf_init_event(struct perf_event *event)
7052 {
7053         struct pmu *pmu = NULL;
7054         int idx;
7055         int ret;
7056
7057         idx = srcu_read_lock(&pmus_srcu);
7058
7059         rcu_read_lock();
7060         pmu = idr_find(&pmu_idr, event->attr.type);
7061         rcu_read_unlock();
7062         if (pmu) {
7063                 ret = perf_try_init_event(pmu, event);
7064                 if (ret)
7065                         pmu = ERR_PTR(ret);
7066                 goto unlock;
7067         }
7068
7069         list_for_each_entry_rcu(pmu, &pmus, entry) {
7070                 ret = perf_try_init_event(pmu, event);
7071                 if (!ret)
7072                         goto unlock;
7073
7074                 if (ret != -ENOENT) {
7075                         pmu = ERR_PTR(ret);
7076                         goto unlock;
7077                 }
7078         }
7079         pmu = ERR_PTR(-ENOENT);
7080 unlock:
7081         srcu_read_unlock(&pmus_srcu, idx);
7082
7083         return pmu;
7084 }
7085
7086 static void account_event_cpu(struct perf_event *event, int cpu)
7087 {
7088         if (event->parent)
7089                 return;
7090
7091         if (is_cgroup_event(event))
7092                 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
7093 }
7094
7095 static void account_event(struct perf_event *event)
7096 {
7097         if (event->parent)
7098                 return;
7099
7100         if (event->attach_state & PERF_ATTACH_TASK)
7101                 static_key_slow_inc(&perf_sched_events.key);
7102         if (event->attr.mmap || event->attr.mmap_data)
7103                 atomic_inc(&nr_mmap_events);
7104         if (event->attr.comm)
7105                 atomic_inc(&nr_comm_events);
7106         if (event->attr.task)
7107                 atomic_inc(&nr_task_events);
7108         if (event->attr.freq) {
7109                 if (atomic_inc_return(&nr_freq_events) == 1)
7110                         tick_nohz_full_kick_all();
7111         }
7112         if (has_branch_stack(event))
7113                 static_key_slow_inc(&perf_sched_events.key);
7114         if (is_cgroup_event(event))
7115                 static_key_slow_inc(&perf_sched_events.key);
7116
7117         account_event_cpu(event, event->cpu);
7118 }
7119
7120 /*
7121  * Allocate and initialize a event structure
7122  */
7123 static struct perf_event *
7124 perf_event_alloc(struct perf_event_attr *attr, int cpu,
7125                  struct task_struct *task,
7126                  struct perf_event *group_leader,
7127                  struct perf_event *parent_event,
7128                  perf_overflow_handler_t overflow_handler,
7129                  void *context, int cgroup_fd)
7130 {
7131         struct pmu *pmu;
7132         struct perf_event *event;
7133         struct hw_perf_event *hwc;
7134         long err = -EINVAL;
7135
7136         if ((unsigned)cpu >= nr_cpu_ids) {
7137                 if (!task || cpu != -1)
7138                         return ERR_PTR(-EINVAL);
7139         }
7140
7141         event = kzalloc(sizeof(*event), GFP_KERNEL);
7142         if (!event)
7143                 return ERR_PTR(-ENOMEM);
7144
7145         /*
7146          * Single events are their own group leaders, with an
7147          * empty sibling list:
7148          */
7149         if (!group_leader)
7150                 group_leader = event;
7151
7152         mutex_init(&event->child_mutex);
7153         INIT_LIST_HEAD(&event->child_list);
7154
7155         INIT_LIST_HEAD(&event->group_entry);
7156         INIT_LIST_HEAD(&event->event_entry);
7157         INIT_LIST_HEAD(&event->sibling_list);
7158         INIT_LIST_HEAD(&event->rb_entry);
7159         INIT_LIST_HEAD(&event->active_entry);
7160         INIT_HLIST_NODE(&event->hlist_entry);
7161
7162
7163         init_waitqueue_head(&event->waitq);
7164         init_irq_work(&event->pending, perf_pending_event);
7165
7166         mutex_init(&event->mmap_mutex);
7167
7168         atomic_long_set(&event->refcount, 1);
7169         event->cpu              = cpu;
7170         event->attr             = *attr;
7171         event->group_leader     = group_leader;
7172         event->pmu              = NULL;
7173         event->oncpu            = -1;
7174
7175         event->parent           = parent_event;
7176
7177         event->ns               = get_pid_ns(task_active_pid_ns(current));
7178         event->id               = atomic64_inc_return(&perf_event_id);
7179
7180         event->state            = PERF_EVENT_STATE_INACTIVE;
7181
7182         if (task) {
7183                 event->attach_state = PERF_ATTACH_TASK;
7184                 /*
7185                  * XXX pmu::event_init needs to know what task to account to
7186                  * and we cannot use the ctx information because we need the
7187                  * pmu before we get a ctx.
7188                  */
7189                 event->hw.target = task;
7190         }
7191
7192         if (!overflow_handler && parent_event) {
7193                 overflow_handler = parent_event->overflow_handler;
7194                 context = parent_event->overflow_handler_context;
7195         }
7196
7197         event->overflow_handler = overflow_handler;
7198         event->overflow_handler_context = context;
7199
7200         perf_event__state_init(event);
7201
7202         pmu = NULL;
7203
7204         hwc = &event->hw;
7205         hwc->sample_period = attr->sample_period;
7206         if (attr->freq && attr->sample_freq)
7207                 hwc->sample_period = 1;
7208         hwc->last_period = hwc->sample_period;
7209
7210         local64_set(&hwc->period_left, hwc->sample_period);
7211
7212         /*
7213          * we currently do not support PERF_FORMAT_GROUP on inherited events
7214          */
7215         if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
7216                 goto err_ns;
7217
7218         if (!has_branch_stack(event))
7219                 event->attr.branch_sample_type = 0;
7220
7221         if (cgroup_fd != -1) {
7222                 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
7223                 if (err)
7224                         goto err_ns;
7225         }
7226
7227         pmu = perf_init_event(event);
7228         if (!pmu)
7229                 goto err_ns;
7230         else if (IS_ERR(pmu)) {
7231                 err = PTR_ERR(pmu);
7232                 goto err_ns;
7233         }
7234
7235         if (!event->parent) {
7236                 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
7237                         err = get_callchain_buffers();
7238                         if (err)
7239                                 goto err_pmu;
7240                 }
7241         }
7242
7243         return event;
7244
7245 err_pmu:
7246         if (event->destroy)
7247                 event->destroy(event);
7248         module_put(pmu->module);
7249 err_ns:
7250         if (is_cgroup_event(event))
7251                 perf_detach_cgroup(event);
7252         if (event->ns)
7253                 put_pid_ns(event->ns);
7254         kfree(event);
7255
7256         return ERR_PTR(err);
7257 }
7258
7259 static int perf_copy_attr(struct perf_event_attr __user *uattr,
7260                           struct perf_event_attr *attr)
7261 {
7262         u32 size;
7263         int ret;
7264
7265         if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
7266                 return -EFAULT;
7267
7268         /*
7269          * zero the full structure, so that a short copy will be nice.
7270          */
7271         memset(attr, 0, sizeof(*attr));
7272
7273         ret = get_user(size, &uattr->size);
7274         if (ret)
7275                 return ret;
7276
7277         if (size > PAGE_SIZE)   /* silly large */
7278                 goto err_size;
7279
7280         if (!size)              /* abi compat */
7281                 size = PERF_ATTR_SIZE_VER0;
7282
7283         if (size < PERF_ATTR_SIZE_VER0)
7284                 goto err_size;
7285
7286         /*
7287          * If we're handed a bigger struct than we know of,
7288          * ensure all the unknown bits are 0 - i.e. new
7289          * user-space does not rely on any kernel feature
7290          * extensions we dont know about yet.
7291          */
7292         if (size > sizeof(*attr)) {
7293                 unsigned char __user *addr;
7294                 unsigned char __user *end;
7295                 unsigned char val;
7296
7297                 addr = (void __user *)uattr + sizeof(*attr);
7298                 end  = (void __user *)uattr + size;
7299
7300                 for (; addr < end; addr++) {
7301                         ret = get_user(val, addr);
7302                         if (ret)
7303                                 return ret;
7304                         if (val)
7305                                 goto err_size;
7306                 }
7307                 size = sizeof(*attr);
7308         }
7309
7310         ret = copy_from_user(attr, uattr, size);
7311         if (ret)
7312                 return -EFAULT;
7313
7314         if (attr->__reserved_1)
7315                 return -EINVAL;
7316
7317         if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
7318                 return -EINVAL;
7319
7320         if (attr->read_format & ~(PERF_FORMAT_MAX-1))
7321                 return -EINVAL;
7322
7323         if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
7324                 u64 mask = attr->branch_sample_type;
7325
7326                 /* only using defined bits */
7327                 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
7328                         return -EINVAL;
7329
7330                 /* at least one branch bit must be set */
7331                 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
7332                         return -EINVAL;
7333
7334                 /* propagate priv level, when not set for branch */
7335                 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
7336
7337                         /* exclude_kernel checked on syscall entry */
7338                         if (!attr->exclude_kernel)
7339                                 mask |= PERF_SAMPLE_BRANCH_KERNEL;
7340
7341                         if (!attr->exclude_user)
7342                                 mask |= PERF_SAMPLE_BRANCH_USER;
7343
7344                         if (!attr->exclude_hv)
7345                                 mask |= PERF_SAMPLE_BRANCH_HV;
7346                         /*
7347                          * adjust user setting (for HW filter setup)
7348                          */
7349                         attr->branch_sample_type = mask;
7350                 }
7351                 /* privileged levels capture (kernel, hv): check permissions */
7352                 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
7353                     && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
7354                         return -EACCES;
7355         }
7356
7357         if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
7358                 ret = perf_reg_validate(attr->sample_regs_user);
7359                 if (ret)
7360                         return ret;
7361         }
7362
7363         if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
7364                 if (!arch_perf_have_user_stack_dump())
7365                         return -ENOSYS;
7366
7367                 /*
7368                  * We have __u32 type for the size, but so far
7369                  * we can only use __u16 as maximum due to the
7370                  * __u16 sample size limit.
7371                  */
7372                 if (attr->sample_stack_user >= USHRT_MAX)
7373                         ret = -EINVAL;
7374                 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
7375                         ret = -EINVAL;
7376         }
7377
7378         if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
7379                 ret = perf_reg_validate(attr->sample_regs_intr);
7380 out:
7381         return ret;
7382
7383 err_size:
7384         put_user(sizeof(*attr), &uattr->size);
7385         ret = -E2BIG;
7386         goto out;
7387 }
7388
7389 static int
7390 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
7391 {
7392         struct ring_buffer *rb = NULL;
7393         int ret = -EINVAL;
7394
7395         if (!output_event)
7396                 goto set;
7397
7398         /* don't allow circular references */
7399         if (event == output_event)
7400                 goto out;
7401
7402         /*
7403          * Don't allow cross-cpu buffers
7404          */
7405         if (output_event->cpu != event->cpu)
7406                 goto out;
7407
7408         /*
7409          * If its not a per-cpu rb, it must be the same task.
7410          */
7411         if (output_event->cpu == -1 && output_event->ctx != event->ctx)
7412                 goto out;
7413
7414 set:
7415         mutex_lock(&event->mmap_mutex);
7416         /* Can't redirect output if we've got an active mmap() */
7417         if (atomic_read(&event->mmap_count))
7418                 goto unlock;
7419
7420         if (output_event) {
7421                 /* get the rb we want to redirect to */
7422                 rb = ring_buffer_get(output_event);
7423                 if (!rb)
7424                         goto unlock;
7425         }
7426
7427         ring_buffer_attach(event, rb);
7428
7429         ret = 0;
7430 unlock:
7431         mutex_unlock(&event->mmap_mutex);
7432
7433 out:
7434         return ret;
7435 }
7436
7437 static void mutex_lock_double(struct mutex *a, struct mutex *b)
7438 {
7439         if (b < a)
7440                 swap(a, b);
7441
7442         mutex_lock(a);
7443         mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
7444 }
7445
7446 /**
7447  * sys_perf_event_open - open a performance event, associate it to a task/cpu
7448  *
7449  * @attr_uptr:  event_id type attributes for monitoring/sampling
7450  * @pid:                target pid
7451  * @cpu:                target cpu
7452  * @group_fd:           group leader event fd
7453  */
7454 SYSCALL_DEFINE5(perf_event_open,
7455                 struct perf_event_attr __user *, attr_uptr,
7456                 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
7457 {
7458         struct perf_event *group_leader = NULL, *output_event = NULL;
7459         struct perf_event *event, *sibling;
7460         struct perf_event_attr attr;
7461         struct perf_event_context *ctx, *uninitialized_var(gctx);
7462         struct file *event_file = NULL;
7463         struct fd group = {NULL, 0};
7464         struct task_struct *task = NULL;
7465         struct pmu *pmu;
7466         int event_fd;
7467         int move_group = 0;
7468         int err;
7469         int f_flags = O_RDWR;
7470         int cgroup_fd = -1;
7471
7472         /* for future expandability... */
7473         if (flags & ~PERF_FLAG_ALL)
7474                 return -EINVAL;
7475
7476         err = perf_copy_attr(attr_uptr, &attr);
7477         if (err)
7478                 return err;
7479
7480         if (!attr.exclude_kernel) {
7481                 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
7482                         return -EACCES;
7483         }
7484
7485         if (attr.freq) {
7486                 if (attr.sample_freq > sysctl_perf_event_sample_rate)
7487                         return -EINVAL;
7488         } else {
7489                 if (attr.sample_period & (1ULL << 63))
7490                         return -EINVAL;
7491         }
7492
7493         /*
7494          * In cgroup mode, the pid argument is used to pass the fd
7495          * opened to the cgroup directory in cgroupfs. The cpu argument
7496          * designates the cpu on which to monitor threads from that
7497          * cgroup.
7498          */
7499         if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
7500                 return -EINVAL;
7501
7502         if (flags & PERF_FLAG_FD_CLOEXEC)
7503                 f_flags |= O_CLOEXEC;
7504
7505         event_fd = get_unused_fd_flags(f_flags);
7506         if (event_fd < 0)
7507                 return event_fd;
7508
7509         if (group_fd != -1) {
7510                 err = perf_fget_light(group_fd, &group);
7511                 if (err)
7512                         goto err_fd;
7513                 group_leader = group.file->private_data;
7514                 if (flags & PERF_FLAG_FD_OUTPUT)
7515                         output_event = group_leader;
7516                 if (flags & PERF_FLAG_FD_NO_GROUP)
7517                         group_leader = NULL;
7518         }
7519
7520         if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
7521                 task = find_lively_task_by_vpid(pid);
7522                 if (IS_ERR(task)) {
7523                         err = PTR_ERR(task);
7524                         goto err_group_fd;
7525                 }
7526         }
7527
7528         if (task && group_leader &&
7529             group_leader->attr.inherit != attr.inherit) {
7530                 err = -EINVAL;
7531                 goto err_task;
7532         }
7533
7534         get_online_cpus();
7535
7536         if (flags & PERF_FLAG_PID_CGROUP)
7537                 cgroup_fd = pid;
7538
7539         event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
7540                                  NULL, NULL, cgroup_fd);
7541         if (IS_ERR(event)) {
7542                 err = PTR_ERR(event);
7543                 goto err_cpus;
7544         }
7545
7546         if (is_sampling_event(event)) {
7547                 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
7548                         err = -ENOTSUPP;
7549                         goto err_alloc;
7550                 }
7551         }
7552
7553         account_event(event);
7554
7555         /*
7556          * Special case software events and allow them to be part of
7557          * any hardware group.
7558          */
7559         pmu = event->pmu;
7560
7561         if (group_leader &&
7562             (is_software_event(event) != is_software_event(group_leader))) {
7563                 if (is_software_event(event)) {
7564                         /*
7565                          * If event and group_leader are not both a software
7566                          * event, and event is, then group leader is not.
7567                          *
7568                          * Allow the addition of software events to !software
7569                          * groups, this is safe because software events never
7570                          * fail to schedule.
7571                          */
7572                         pmu = group_leader->pmu;
7573                 } else if (is_software_event(group_leader) &&
7574                            (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
7575                         /*
7576                          * In case the group is a pure software group, and we
7577                          * try to add a hardware event, move the whole group to
7578                          * the hardware context.
7579                          */
7580                         move_group = 1;
7581                 }
7582         }
7583
7584         /*
7585          * Get the target context (task or percpu):
7586          */
7587         ctx = find_get_context(pmu, task, event);
7588         if (IS_ERR(ctx)) {
7589                 err = PTR_ERR(ctx);
7590                 goto err_alloc;
7591         }
7592
7593         if (task) {
7594                 put_task_struct(task);
7595                 task = NULL;
7596         }
7597
7598         /*
7599          * Look up the group leader (we will attach this event to it):
7600          */
7601         if (group_leader) {
7602                 err = -EINVAL;
7603
7604                 /*
7605                  * Do not allow a recursive hierarchy (this new sibling
7606                  * becoming part of another group-sibling):
7607                  */
7608                 if (group_leader->group_leader != group_leader)
7609                         goto err_context;
7610                 /*
7611                  * Do not allow to attach to a group in a different
7612                  * task or CPU context:
7613                  */
7614                 if (move_group) {
7615                         /*
7616                          * Make sure we're both on the same task, or both
7617                          * per-cpu events.
7618                          */
7619                         if (group_leader->ctx->task != ctx->task)
7620                                 goto err_context;
7621
7622                         /*
7623                          * Make sure we're both events for the same CPU;
7624                          * grouping events for different CPUs is broken; since
7625                          * you can never concurrently schedule them anyhow.
7626                          */
7627                         if (group_leader->cpu != event->cpu)
7628                                 goto err_context;
7629                 } else {
7630                         if (group_leader->ctx != ctx)
7631                                 goto err_context;
7632                 }
7633
7634                 /*
7635                  * Only a group leader can be exclusive or pinned
7636                  */
7637                 if (attr.exclusive || attr.pinned)
7638                         goto err_context;
7639         }
7640
7641         if (output_event) {
7642                 err = perf_event_set_output(event, output_event);
7643                 if (err)
7644                         goto err_context;
7645         }
7646
7647         event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
7648                                         f_flags);
7649         if (IS_ERR(event_file)) {
7650                 err = PTR_ERR(event_file);
7651                 goto err_context;
7652         }
7653
7654         if (move_group) {
7655                 gctx = group_leader->ctx;
7656
7657                 /*
7658                  * See perf_event_ctx_lock() for comments on the details
7659                  * of swizzling perf_event::ctx.
7660                  */
7661                 mutex_lock_double(&gctx->mutex, &ctx->mutex);
7662
7663                 perf_remove_from_context(group_leader, false);
7664
7665                 list_for_each_entry(sibling, &group_leader->sibling_list,
7666                                     group_entry) {
7667                         perf_remove_from_context(sibling, false);
7668                         put_ctx(gctx);
7669                 }
7670         } else {
7671                 mutex_lock(&ctx->mutex);
7672         }
7673
7674         WARN_ON_ONCE(ctx->parent_ctx);
7675
7676         if (move_group) {
7677                 /*
7678                  * Wait for everybody to stop referencing the events through
7679                  * the old lists, before installing it on new lists.
7680                  */
7681                 synchronize_rcu();
7682
7683                 /*
7684                  * Install the group siblings before the group leader.
7685                  *
7686                  * Because a group leader will try and install the entire group
7687                  * (through the sibling list, which is still in-tact), we can
7688                  * end up with siblings installed in the wrong context.
7689                  *
7690                  * By installing siblings first we NO-OP because they're not
7691                  * reachable through the group lists.
7692                  */
7693                 list_for_each_entry(sibling, &group_leader->sibling_list,
7694                                     group_entry) {
7695                         perf_event__state_init(sibling);
7696                         perf_install_in_context(ctx, sibling, sibling->cpu);
7697                         get_ctx(ctx);
7698                 }
7699
7700                 /*
7701                  * Removing from the context ends up with disabled
7702                  * event. What we want here is event in the initial
7703                  * startup state, ready to be add into new context.
7704                  */
7705                 perf_event__state_init(group_leader);
7706                 perf_install_in_context(ctx, group_leader, group_leader->cpu);
7707                 get_ctx(ctx);
7708         }
7709
7710         perf_install_in_context(ctx, event, event->cpu);
7711         perf_unpin_context(ctx);
7712
7713         if (move_group) {
7714                 mutex_unlock(&gctx->mutex);
7715                 put_ctx(gctx);
7716         }
7717         mutex_unlock(&ctx->mutex);
7718
7719         put_online_cpus();
7720
7721         event->owner = current;
7722
7723         mutex_lock(&current->perf_event_mutex);
7724         list_add_tail(&event->owner_entry, &current->perf_event_list);
7725         mutex_unlock(&current->perf_event_mutex);
7726
7727         /*
7728          * Precalculate sample_data sizes
7729          */
7730         perf_event__header_size(event);
7731         perf_event__id_header_size(event);
7732
7733         /*
7734          * Drop the reference on the group_event after placing the
7735          * new event on the sibling_list. This ensures destruction
7736          * of the group leader will find the pointer to itself in
7737          * perf_group_detach().
7738          */
7739         fdput(group);
7740         fd_install(event_fd, event_file);
7741         return event_fd;
7742
7743 err_context:
7744         perf_unpin_context(ctx);
7745         put_ctx(ctx);
7746 err_alloc:
7747         free_event(event);
7748 err_cpus:
7749         put_online_cpus();
7750 err_task:
7751         if (task)
7752                 put_task_struct(task);
7753 err_group_fd:
7754         fdput(group);
7755 err_fd:
7756         put_unused_fd(event_fd);
7757         return err;
7758 }
7759
7760 /**
7761  * perf_event_create_kernel_counter
7762  *
7763  * @attr: attributes of the counter to create
7764  * @cpu: cpu in which the counter is bound
7765  * @task: task to profile (NULL for percpu)
7766  */
7767 struct perf_event *
7768 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
7769                                  struct task_struct *task,
7770                                  perf_overflow_handler_t overflow_handler,
7771                                  void *context)
7772 {
7773         struct perf_event_context *ctx;
7774         struct perf_event *event;
7775         int err;
7776
7777         /*
7778          * Get the target context (task or percpu):
7779          */
7780
7781         event = perf_event_alloc(attr, cpu, task, NULL, NULL,
7782                                  overflow_handler, context, -1);
7783         if (IS_ERR(event)) {
7784                 err = PTR_ERR(event);
7785                 goto err;
7786         }
7787
7788         /* Mark owner so we could distinguish it from user events. */
7789         event->owner = EVENT_OWNER_KERNEL;
7790
7791         account_event(event);
7792
7793         ctx = find_get_context(event->pmu, task, event);
7794         if (IS_ERR(ctx)) {
7795                 err = PTR_ERR(ctx);
7796                 goto err_free;
7797         }
7798
7799         WARN_ON_ONCE(ctx->parent_ctx);
7800         mutex_lock(&ctx->mutex);
7801         perf_install_in_context(ctx, event, cpu);
7802         perf_unpin_context(ctx);
7803         mutex_unlock(&ctx->mutex);
7804
7805         return event;
7806
7807 err_free:
7808         free_event(event);
7809 err:
7810         return ERR_PTR(err);
7811 }
7812 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
7813
7814 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
7815 {
7816         struct perf_event_context *src_ctx;
7817         struct perf_event_context *dst_ctx;
7818         struct perf_event *event, *tmp;
7819         LIST_HEAD(events);
7820
7821         src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
7822         dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
7823
7824         /*
7825          * See perf_event_ctx_lock() for comments on the details
7826          * of swizzling perf_event::ctx.
7827          */
7828         mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
7829         list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
7830                                  event_entry) {
7831                 perf_remove_from_context(event, false);
7832                 unaccount_event_cpu(event, src_cpu);
7833                 put_ctx(src_ctx);
7834                 list_add(&event->migrate_entry, &events);
7835         }
7836
7837         /*
7838          * Wait for the events to quiesce before re-instating them.
7839          */
7840         synchronize_rcu();
7841
7842         /*
7843          * Re-instate events in 2 passes.
7844          *
7845          * Skip over group leaders and only install siblings on this first
7846          * pass, siblings will not get enabled without a leader, however a
7847          * leader will enable its siblings, even if those are still on the old
7848          * context.
7849          */
7850         list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
7851                 if (event->group_leader == event)
7852                         continue;
7853
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
7862         /*
7863          * Once all the siblings are setup properly, install the group leaders
7864          * to make it go.
7865          */
7866         list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
7867                 list_del(&event->migrate_entry);
7868                 if (event->state >= PERF_EVENT_STATE_OFF)
7869                         event->state = PERF_EVENT_STATE_INACTIVE;
7870                 account_event_cpu(event, dst_cpu);
7871                 perf_install_in_context(dst_ctx, event, dst_cpu);
7872                 get_ctx(dst_ctx);
7873         }
7874         mutex_unlock(&dst_ctx->mutex);
7875         mutex_unlock(&src_ctx->mutex);
7876 }
7877 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
7878
7879 static void sync_child_event(struct perf_event *child_event,
7880                                struct task_struct *child)
7881 {
7882         struct perf_event *parent_event = child_event->parent;
7883         u64 child_val;
7884
7885         if (child_event->attr.inherit_stat)
7886                 perf_event_read_event(child_event, child);
7887
7888         child_val = perf_event_count(child_event);
7889
7890         /*
7891          * Add back the child's count to the parent's count:
7892          */
7893         atomic64_add(child_val, &parent_event->child_count);
7894         atomic64_add(child_event->total_time_enabled,
7895                      &parent_event->child_total_time_enabled);
7896         atomic64_add(child_event->total_time_running,
7897                      &parent_event->child_total_time_running);
7898
7899         /*
7900          * Remove this event from the parent's list
7901          */
7902         WARN_ON_ONCE(parent_event->ctx->parent_ctx);
7903         mutex_lock(&parent_event->child_mutex);
7904         list_del_init(&child_event->child_list);
7905         mutex_unlock(&parent_event->child_mutex);
7906
7907         /*
7908          * Make sure user/parent get notified, that we just
7909          * lost one event.
7910          */
7911         perf_event_wakeup(parent_event);
7912
7913         /*
7914          * Release the parent event, if this was the last
7915          * reference to it.
7916          */
7917         put_event(parent_event);
7918 }
7919
7920 static void
7921 __perf_event_exit_task(struct perf_event *child_event,
7922                          struct perf_event_context *child_ctx,
7923                          struct task_struct *child)
7924 {
7925         /*
7926          * Do not destroy the 'original' grouping; because of the context
7927          * switch optimization the original events could've ended up in a
7928          * random child task.
7929          *
7930          * If we were to destroy the original group, all group related
7931          * operations would cease to function properly after this random
7932          * child dies.
7933          *
7934          * Do destroy all inherited groups, we don't care about those
7935          * and being thorough is better.
7936          */
7937         perf_remove_from_context(child_event, !!child_event->parent);
7938
7939         /*
7940          * It can happen that the parent exits first, and has events
7941          * that are still around due to the child reference. These
7942          * events need to be zapped.
7943          */
7944         if (child_event->parent) {
7945                 sync_child_event(child_event, child);
7946                 free_event(child_event);
7947         } else {
7948                 child_event->state = PERF_EVENT_STATE_EXIT;
7949                 perf_event_wakeup(child_event);
7950         }
7951 }
7952
7953 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
7954 {
7955         struct perf_event *child_event, *next;
7956         struct perf_event_context *child_ctx, *clone_ctx = NULL;
7957         unsigned long flags;
7958
7959         if (likely(!child->perf_event_ctxp[ctxn])) {
7960                 perf_event_task(child, NULL, 0);
7961                 return;
7962         }
7963
7964         local_irq_save(flags);
7965         /*
7966          * We can't reschedule here because interrupts are disabled,
7967          * and either child is current or it is a task that can't be
7968          * scheduled, so we are now safe from rescheduling changing
7969          * our context.
7970          */
7971         child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
7972
7973         /*
7974          * Take the context lock here so that if find_get_context is
7975          * reading child->perf_event_ctxp, we wait until it has
7976          * incremented the context's refcount before we do put_ctx below.
7977          */
7978         raw_spin_lock(&child_ctx->lock);
7979         task_ctx_sched_out(child_ctx);
7980         child->perf_event_ctxp[ctxn] = NULL;
7981
7982         /*
7983          * If this context is a clone; unclone it so it can't get
7984          * swapped to another process while we're removing all
7985          * the events from it.
7986          */
7987         clone_ctx = unclone_ctx(child_ctx);
7988         update_context_time(child_ctx);
7989         raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
7990
7991         if (clone_ctx)
7992                 put_ctx(clone_ctx);
7993
7994         /*
7995          * Report the task dead after unscheduling the events so that we
7996          * won't get any samples after PERF_RECORD_EXIT. We can however still
7997          * get a few PERF_RECORD_READ events.
7998          */
7999         perf_event_task(child, child_ctx, 0);
8000
8001         /*
8002          * We can recurse on the same lock type through:
8003          *
8004          *   __perf_event_exit_task()
8005          *     sync_child_event()
8006          *       put_event()
8007          *         mutex_lock(&ctx->mutex)
8008          *
8009          * But since its the parent context it won't be the same instance.
8010          */
8011         mutex_lock(&child_ctx->mutex);
8012
8013         list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
8014                 __perf_event_exit_task(child_event, child_ctx, child);
8015
8016         mutex_unlock(&child_ctx->mutex);
8017
8018         put_ctx(child_ctx);
8019 }
8020
8021 /*
8022  * When a child task exits, feed back event values to parent events.
8023  */
8024 void perf_event_exit_task(struct task_struct *child)
8025 {
8026         struct perf_event *event, *tmp;
8027         int ctxn;
8028
8029         mutex_lock(&child->perf_event_mutex);
8030         list_for_each_entry_safe(event, tmp, &child->perf_event_list,
8031                                  owner_entry) {
8032                 list_del_init(&event->owner_entry);
8033
8034                 /*
8035                  * Ensure the list deletion is visible before we clear
8036                  * the owner, closes a race against perf_release() where
8037                  * we need to serialize on the owner->perf_event_mutex.
8038                  */
8039                 smp_wmb();
8040                 event->owner = NULL;
8041         }
8042         mutex_unlock(&child->perf_event_mutex);
8043
8044         for_each_task_context_nr(ctxn)
8045                 perf_event_exit_task_context(child, ctxn);
8046 }
8047
8048 static void perf_free_event(struct perf_event *event,
8049                             struct perf_event_context *ctx)
8050 {
8051         struct perf_event *parent = event->parent;
8052
8053         if (WARN_ON_ONCE(!parent))
8054                 return;
8055
8056         mutex_lock(&parent->child_mutex);
8057         list_del_init(&event->child_list);
8058         mutex_unlock(&parent->child_mutex);
8059
8060         put_event(parent);
8061
8062         raw_spin_lock_irq(&ctx->lock);
8063         perf_group_detach(event);
8064         list_del_event(event, ctx);
8065         raw_spin_unlock_irq(&ctx->lock);
8066         free_event(event);
8067 }
8068
8069 /*
8070  * Free an unexposed, unused context as created by inheritance by
8071  * perf_event_init_task below, used by fork() in case of fail.
8072  *
8073  * Not all locks are strictly required, but take them anyway to be nice and
8074  * help out with the lockdep assertions.
8075  */
8076 void perf_event_free_task(struct task_struct *task)
8077 {
8078         struct perf_event_context *ctx;
8079         struct perf_event *event, *tmp;
8080         int ctxn;
8081
8082         for_each_task_context_nr(ctxn) {
8083                 ctx = task->perf_event_ctxp[ctxn];
8084                 if (!ctx)
8085                         continue;
8086
8087                 mutex_lock(&ctx->mutex);
8088 again:
8089                 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
8090                                 group_entry)
8091                         perf_free_event(event, ctx);
8092
8093                 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
8094                                 group_entry)
8095                         perf_free_event(event, ctx);
8096
8097                 if (!list_empty(&ctx->pinned_groups) ||
8098                                 !list_empty(&ctx->flexible_groups))
8099                         goto again;
8100
8101                 mutex_unlock(&ctx->mutex);
8102
8103                 put_ctx(ctx);
8104         }
8105 }
8106
8107 void perf_event_delayed_put(struct task_struct *task)
8108 {
8109         int ctxn;
8110
8111         for_each_task_context_nr(ctxn)
8112                 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
8113 }
8114
8115 /*
8116  * inherit a event from parent task to child task:
8117  */
8118 static struct perf_event *
8119 inherit_event(struct perf_event *parent_event,
8120               struct task_struct *parent,
8121               struct perf_event_context *parent_ctx,
8122               struct task_struct *child,
8123               struct perf_event *group_leader,
8124               struct perf_event_context *child_ctx)
8125 {
8126         enum perf_event_active_state parent_state = parent_event->state;
8127         struct perf_event *child_event;
8128         unsigned long flags;
8129
8130         /*
8131          * Instead of creating recursive hierarchies of events,
8132          * we link inherited events back to the original parent,
8133          * which has a filp for sure, which we use as the reference
8134          * count:
8135          */
8136         if (parent_event->parent)
8137                 parent_event = parent_event->parent;
8138
8139         child_event = perf_event_alloc(&parent_event->attr,
8140                                            parent_event->cpu,
8141                                            child,
8142                                            group_leader, parent_event,
8143                                            NULL, NULL, -1);
8144         if (IS_ERR(child_event))
8145                 return child_event;
8146
8147         if (is_orphaned_event(parent_event) ||
8148             !atomic_long_inc_not_zero(&parent_event->refcount)) {
8149                 free_event(child_event);
8150                 return NULL;
8151         }
8152
8153         get_ctx(child_ctx);
8154
8155         /*
8156          * Make the child state follow the state of the parent event,
8157          * not its attr.disabled bit.  We hold the parent's mutex,
8158          * so we won't race with perf_event_{en, dis}able_family.
8159          */
8160         if (parent_state >= PERF_EVENT_STATE_INACTIVE)
8161                 child_event->state = PERF_EVENT_STATE_INACTIVE;
8162         else
8163                 child_event->state = PERF_EVENT_STATE_OFF;
8164
8165         if (parent_event->attr.freq) {
8166                 u64 sample_period = parent_event->hw.sample_period;
8167                 struct hw_perf_event *hwc = &child_event->hw;
8168
8169                 hwc->sample_period = sample_period;
8170                 hwc->last_period   = sample_period;
8171
8172                 local64_set(&hwc->period_left, sample_period);
8173         }
8174
8175         child_event->ctx = child_ctx;
8176         child_event->overflow_handler = parent_event->overflow_handler;
8177         child_event->overflow_handler_context
8178                 = parent_event->overflow_handler_context;
8179
8180         /*
8181          * Precalculate sample_data sizes
8182          */
8183         perf_event__header_size(child_event);
8184         perf_event__id_header_size(child_event);
8185
8186         /*
8187          * Link it up in the child's context:
8188          */
8189         raw_spin_lock_irqsave(&child_ctx->lock, flags);
8190         add_event_to_ctx(child_event, child_ctx);
8191         raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
8192
8193         /*
8194          * Link this into the parent event's child list
8195          */
8196         WARN_ON_ONCE(parent_event->ctx->parent_ctx);
8197         mutex_lock(&parent_event->child_mutex);
8198         list_add_tail(&child_event->child_list, &parent_event->child_list);
8199         mutex_unlock(&parent_event->child_mutex);
8200
8201         return child_event;
8202 }
8203
8204 static int inherit_group(struct perf_event *parent_event,
8205               struct task_struct *parent,
8206               struct perf_event_context *parent_ctx,
8207               struct task_struct *child,
8208               struct perf_event_context *child_ctx)
8209 {
8210         struct perf_event *leader;
8211         struct perf_event *sub;
8212         struct perf_event *child_ctr;
8213
8214         leader = inherit_event(parent_event, parent, parent_ctx,
8215                                  child, NULL, child_ctx);
8216         if (IS_ERR(leader))
8217                 return PTR_ERR(leader);
8218         list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
8219                 child_ctr = inherit_event(sub, parent, parent_ctx,
8220                                             child, leader, child_ctx);
8221                 if (IS_ERR(child_ctr))
8222                         return PTR_ERR(child_ctr);
8223         }
8224         return 0;
8225 }
8226
8227 static int
8228 inherit_task_group(struct perf_event *event, struct task_struct *parent,
8229                    struct perf_event_context *parent_ctx,
8230                    struct task_struct *child, int ctxn,
8231                    int *inherited_all)
8232 {
8233         int ret;
8234         struct perf_event_context *child_ctx;
8235
8236         if (!event->attr.inherit) {
8237                 *inherited_all = 0;
8238                 return 0;
8239         }
8240
8241         child_ctx = child->perf_event_ctxp[ctxn];
8242         if (!child_ctx) {
8243                 /*
8244                  * This is executed from the parent task context, so
8245                  * inherit events that have been marked for cloning.
8246                  * First allocate and initialize a context for the
8247                  * child.
8248                  */
8249
8250                 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
8251                 if (!child_ctx)
8252                         return -ENOMEM;
8253
8254                 child->perf_event_ctxp[ctxn] = child_ctx;
8255         }
8256
8257         ret = inherit_group(event, parent, parent_ctx,
8258                             child, child_ctx);
8259
8260         if (ret)
8261                 *inherited_all = 0;
8262
8263         return ret;
8264 }
8265
8266 /*
8267  * Initialize the perf_event context in task_struct
8268  */
8269 static int perf_event_init_context(struct task_struct *child, int ctxn)
8270 {
8271         struct perf_event_context *child_ctx, *parent_ctx;
8272         struct perf_event_context *cloned_ctx;
8273         struct perf_event *event;
8274         struct task_struct *parent = current;
8275         int inherited_all = 1;
8276         unsigned long flags;
8277         int ret = 0;
8278
8279         if (likely(!parent->perf_event_ctxp[ctxn]))
8280                 return 0;
8281
8282         /*
8283          * If the parent's context is a clone, pin it so it won't get
8284          * swapped under us.
8285          */
8286         parent_ctx = perf_pin_task_context(parent, ctxn);
8287         if (!parent_ctx)
8288                 return 0;
8289
8290         /*
8291          * No need to check if parent_ctx != NULL here; since we saw
8292          * it non-NULL earlier, the only reason for it to become NULL
8293          * is if we exit, and since we're currently in the middle of
8294          * a fork we can't be exiting at the same time.
8295          */
8296
8297         /*
8298          * Lock the parent list. No need to lock the child - not PID
8299          * hashed yet and not running, so nobody can access it.
8300          */
8301         mutex_lock(&parent_ctx->mutex);
8302
8303         /*
8304          * We dont have to disable NMIs - we are only looking at
8305          * the list, not manipulating it:
8306          */
8307         list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
8308                 ret = inherit_task_group(event, parent, parent_ctx,
8309                                          child, ctxn, &inherited_all);
8310                 if (ret)
8311                         break;
8312         }
8313
8314         /*
8315          * We can't hold ctx->lock when iterating the ->flexible_group list due
8316          * to allocations, but we need to prevent rotation because
8317          * rotate_ctx() will change the list from interrupt context.
8318          */
8319         raw_spin_lock_irqsave(&parent_ctx->lock, flags);
8320         parent_ctx->rotate_disable = 1;
8321         raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
8322
8323         list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
8324                 ret = inherit_task_group(event, parent, parent_ctx,
8325                                          child, ctxn, &inherited_all);
8326                 if (ret)
8327                         break;
8328         }
8329
8330         raw_spin_lock_irqsave(&parent_ctx->lock, flags);
8331         parent_ctx->rotate_disable = 0;
8332
8333         child_ctx = child->perf_event_ctxp[ctxn];
8334
8335         if (child_ctx && inherited_all) {
8336                 /*
8337                  * Mark the child context as a clone of the parent
8338                  * context, or of whatever the parent is a clone of.
8339                  *
8340                  * Note that if the parent is a clone, the holding of
8341                  * parent_ctx->lock avoids it from being uncloned.
8342                  */
8343                 cloned_ctx = parent_ctx->parent_ctx;
8344                 if (cloned_ctx) {
8345                         child_ctx->parent_ctx = cloned_ctx;
8346                         child_ctx->parent_gen = parent_ctx->parent_gen;
8347                 } else {
8348                         child_ctx->parent_ctx = parent_ctx;
8349                         child_ctx->parent_gen = parent_ctx->generation;
8350                 }
8351                 get_ctx(child_ctx->parent_ctx);
8352         }
8353
8354         raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
8355         mutex_unlock(&parent_ctx->mutex);
8356
8357         perf_unpin_context(parent_ctx);
8358         put_ctx(parent_ctx);
8359
8360         return ret;
8361 }
8362
8363 /*
8364  * Initialize the perf_event context in task_struct
8365  */
8366 int perf_event_init_task(struct task_struct *child)
8367 {
8368         int ctxn, ret;
8369
8370         memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
8371         mutex_init(&child->perf_event_mutex);
8372         INIT_LIST_HEAD(&child->perf_event_list);
8373
8374         for_each_task_context_nr(ctxn) {
8375                 ret = perf_event_init_context(child, ctxn);
8376                 if (ret) {
8377                         perf_event_free_task(child);
8378                         return ret;
8379                 }
8380         }
8381
8382         return 0;
8383 }
8384
8385 static void __init perf_event_init_all_cpus(void)
8386 {
8387         struct swevent_htable *swhash;
8388         int cpu;
8389
8390         for_each_possible_cpu(cpu) {
8391                 swhash = &per_cpu(swevent_htable, cpu);
8392                 mutex_init(&swhash->hlist_mutex);
8393                 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
8394         }
8395 }
8396
8397 static void perf_event_init_cpu(int cpu)
8398 {
8399         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
8400
8401         mutex_lock(&swhash->hlist_mutex);
8402         swhash->online = true;
8403         if (swhash->hlist_refcount > 0) {
8404                 struct swevent_hlist *hlist;
8405
8406                 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
8407                 WARN_ON(!hlist);
8408                 rcu_assign_pointer(swhash->swevent_hlist, hlist);
8409         }
8410         mutex_unlock(&swhash->hlist_mutex);
8411 }
8412
8413 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC
8414 static void __perf_event_exit_context(void *__info)
8415 {
8416         struct remove_event re = { .detach_group = true };
8417         struct perf_event_context *ctx = __info;
8418
8419         rcu_read_lock();
8420         list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
8421                 __perf_remove_from_context(&re);
8422         rcu_read_unlock();
8423 }
8424
8425 static void perf_event_exit_cpu_context(int cpu)
8426 {
8427         struct perf_event_context *ctx;
8428         struct pmu *pmu;
8429         int idx;
8430
8431         idx = srcu_read_lock(&pmus_srcu);
8432         list_for_each_entry_rcu(pmu, &pmus, entry) {
8433                 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
8434
8435                 mutex_lock(&ctx->mutex);
8436                 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
8437                 mutex_unlock(&ctx->mutex);
8438         }
8439         srcu_read_unlock(&pmus_srcu, idx);
8440 }
8441
8442 static void perf_event_exit_cpu(int cpu)
8443 {
8444         struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
8445
8446         perf_event_exit_cpu_context(cpu);
8447
8448         mutex_lock(&swhash->hlist_mutex);
8449         swhash->online = false;
8450         swevent_hlist_release(swhash);
8451         mutex_unlock(&swhash->hlist_mutex);
8452 }
8453 #else
8454 static inline void perf_event_exit_cpu(int cpu) { }
8455 #endif
8456
8457 static int
8458 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
8459 {
8460         int cpu;
8461
8462         for_each_online_cpu(cpu)
8463                 perf_event_exit_cpu(cpu);
8464
8465         return NOTIFY_OK;
8466 }
8467
8468 /*
8469  * Run the perf reboot notifier at the very last possible moment so that
8470  * the generic watchdog code runs as long as possible.
8471  */
8472 static struct notifier_block perf_reboot_notifier = {
8473         .notifier_call = perf_reboot,
8474         .priority = INT_MIN,
8475 };
8476
8477 static int
8478 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
8479 {
8480         unsigned int cpu = (long)hcpu;
8481
8482         switch (action & ~CPU_TASKS_FROZEN) {
8483
8484         case CPU_UP_PREPARE:
8485         case CPU_DOWN_FAILED:
8486                 perf_event_init_cpu(cpu);
8487                 break;
8488
8489         case CPU_UP_CANCELED:
8490         case CPU_DOWN_PREPARE:
8491                 perf_event_exit_cpu(cpu);
8492                 break;
8493         default:
8494                 break;
8495         }
8496
8497         return NOTIFY_OK;
8498 }
8499
8500 void __init perf_event_init(void)
8501 {
8502         int ret;
8503
8504         idr_init(&pmu_idr);
8505
8506         perf_event_init_all_cpus();
8507         init_srcu_struct(&pmus_srcu);
8508         perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
8509         perf_pmu_register(&perf_cpu_clock, NULL, -1);
8510         perf_pmu_register(&perf_task_clock, NULL, -1);
8511         perf_tp_register();
8512         perf_cpu_notifier(perf_cpu_notify);
8513         register_reboot_notifier(&perf_reboot_notifier);
8514
8515         ret = init_hw_breakpoint();
8516         WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
8517
8518         /* do not patch jump label more than once per second */
8519         jump_label_rate_limit(&perf_sched_events, HZ);
8520
8521         /*
8522          * Build time assertion that we keep the data_head at the intended
8523          * location.  IOW, validation we got the __reserved[] size right.
8524          */
8525         BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
8526                      != 1024);
8527 }
8528
8529 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
8530                               char *page)
8531 {
8532         struct perf_pmu_events_attr *pmu_attr =
8533                 container_of(attr, struct perf_pmu_events_attr, attr);
8534
8535         if (pmu_attr->event_str)
8536                 return sprintf(page, "%s\n", pmu_attr->event_str);
8537
8538         return 0;
8539 }
8540
8541 static int __init perf_event_sysfs_init(void)
8542 {
8543         struct pmu *pmu;
8544         int ret;
8545
8546         mutex_lock(&pmus_lock);
8547
8548         ret = bus_register(&pmu_bus);
8549         if (ret)
8550                 goto unlock;
8551
8552         list_for_each_entry(pmu, &pmus, entry) {
8553                 if (!pmu->name || pmu->type < 0)
8554                         continue;
8555
8556                 ret = pmu_dev_alloc(pmu);
8557                 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
8558         }
8559         pmu_bus_running = 1;
8560         ret = 0;
8561
8562 unlock:
8563         mutex_unlock(&pmus_lock);
8564
8565         return ret;
8566 }
8567 device_initcall(perf_event_sysfs_init);
8568
8569 #ifdef CONFIG_CGROUP_PERF
8570 static struct cgroup_subsys_state *
8571 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
8572 {
8573         struct perf_cgroup *jc;
8574
8575         jc = kzalloc(sizeof(*jc), GFP_KERNEL);
8576         if (!jc)
8577                 return ERR_PTR(-ENOMEM);
8578
8579         jc->info = alloc_percpu(struct perf_cgroup_info);
8580         if (!jc->info) {
8581                 kfree(jc);
8582                 return ERR_PTR(-ENOMEM);
8583         }
8584
8585         return &jc->css;
8586 }
8587
8588 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
8589 {
8590         struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
8591
8592         free_percpu(jc->info);
8593         kfree(jc);
8594 }
8595
8596 static int __perf_cgroup_move(void *info)
8597 {
8598         struct task_struct *task = info;
8599         perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
8600         return 0;
8601 }
8602
8603 static void perf_cgroup_attach(struct cgroup_subsys_state *css,
8604                                struct cgroup_taskset *tset)
8605 {
8606         struct task_struct *task;
8607
8608         cgroup_taskset_for_each(task, tset)
8609                 task_function_call(task, __perf_cgroup_move, task);
8610 }
8611
8612 static void perf_cgroup_exit(struct cgroup_subsys_state *css,
8613                              struct cgroup_subsys_state *old_css,
8614                              struct task_struct *task)
8615 {
8616         /*
8617          * cgroup_exit() is called in the copy_process() failure path.
8618          * Ignore this case since the task hasn't ran yet, this avoids
8619          * trying to poke a half freed task state from generic code.
8620          */
8621         if (!(task->flags & PF_EXITING))
8622                 return;
8623
8624         task_function_call(task, __perf_cgroup_move, task);
8625 }
8626
8627 struct cgroup_subsys perf_event_cgrp_subsys = {
8628         .css_alloc      = perf_cgroup_css_alloc,
8629         .css_free       = perf_cgroup_css_free,
8630         .exit           = perf_cgroup_exit,
8631         .attach         = perf_cgroup_attach,
8632 };
8633 #endif /* CONFIG_CGROUP_PERF */