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