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