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