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