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