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