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