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