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