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