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