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