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