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