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