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