perf: Fix perf bug in fork()
[sfrench/cifs-2.6.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/module.h>
43 #include <linux/mman.h>
44 #include <linux/compat.h>
45
46 #include "internal.h"
47
48 #include <asm/irq_regs.h>
49
50 struct remote_function_call {
51         struct task_struct      *p;
52         int                     (*func)(void *info);
53         void                    *info;
54         int                     ret;
55 };
56
57 static void remote_function(void *data)
58 {
59         struct remote_function_call *tfc = data;
60         struct task_struct *p = tfc->p;
61
62         if (p) {
63                 tfc->ret = -EAGAIN;
64                 if (task_cpu(p) != smp_processor_id() || !task_curr(p))
65                         return;
66         }
67
68         tfc->ret = tfc->func(tfc->info);
69 }
70
71 /**
72  * task_function_call - call a function on the cpu on which a task runs
73  * @p:          the task to evaluate
74  * @func:       the function to be called
75  * @info:       the function call argument
76  *
77  * Calls the function @func when the task is currently running. This might
78  * be on the current CPU, which just calls the function directly
79  *
80  * returns: @func return value, or
81  *          -ESRCH  - when the process isn't running
82  *          -EAGAIN - when the process moved away
83  */
84 static int
85 task_function_call(struct task_struct *p, int (*func) (void *info), void *info)
86 {
87         struct remote_function_call data = {
88                 .p      = p,
89                 .func   = func,
90                 .info   = info,
91                 .ret    = -ESRCH, /* No such (running) process */
92         };
93
94         if (task_curr(p))
95                 smp_call_function_single(task_cpu(p), remote_function, &data, 1);
96
97         return data.ret;
98 }
99
100 /**
101  * cpu_function_call - call a function on the cpu
102  * @func:       the function to be called
103  * @info:       the function call argument
104  *
105  * Calls the function @func on the remote cpu.
106  *
107  * returns: @func return value or -ENXIO when the cpu is offline
108  */
109 static int cpu_function_call(int cpu, int (*func) (void *info), void *info)
110 {
111         struct remote_function_call data = {
112                 .p      = NULL,
113                 .func   = func,
114                 .info   = info,
115                 .ret    = -ENXIO, /* No such CPU */
116         };
117
118         smp_call_function_single(cpu, remote_function, &data, 1);
119
120         return data.ret;
121 }
122
123 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
124                        PERF_FLAG_FD_OUTPUT  |\
125                        PERF_FLAG_PID_CGROUP |\
126                        PERF_FLAG_FD_CLOEXEC)
127
128 /*
129  * branch priv levels that need permission checks
130  */
131 #define PERF_SAMPLE_BRANCH_PERM_PLM \
132         (PERF_SAMPLE_BRANCH_KERNEL |\
133          PERF_SAMPLE_BRANCH_HV)
134
135 enum event_type_t {
136         EVENT_FLEXIBLE = 0x1,
137         EVENT_PINNED = 0x2,
138         EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
139 };
140
141 /*
142  * perf_sched_events : >0 events exist
143  * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
144  */
145 struct static_key_deferred perf_sched_events __read_mostly;
146 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
147 static DEFINE_PER_CPU(atomic_t, perf_branch_stack_events);
148
149 static atomic_t nr_mmap_events __read_mostly;
150 static atomic_t nr_comm_events __read_mostly;
151 static atomic_t nr_task_events __read_mostly;
152 static atomic_t nr_freq_events __read_mostly;
153
154 static LIST_HEAD(pmus);
155 static DEFINE_MUTEX(pmus_lock);
156 static struct srcu_struct pmus_srcu;
157
158 /*
159  * perf event paranoia level:
160  *  -1 - not paranoid at all
161  *   0 - disallow raw tracepoint access for unpriv
162  *   1 - disallow cpu events for unpriv
163  *   2 - disallow kernel profiling for unpriv
164  */
165 int sysctl_perf_event_paranoid __read_mostly = 1;
166
167 /* Minimum for 512 kiB + 1 user control page */
168 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
169
170 /*
171  * max perf event sample rate
172  */
173 #define DEFAULT_MAX_SAMPLE_RATE         100000
174 #define DEFAULT_SAMPLE_PERIOD_NS        (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
175 #define DEFAULT_CPU_TIME_MAX_PERCENT    25
176
177 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
178
179 static int max_samples_per_tick __read_mostly   = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
180 static int perf_sample_period_ns __read_mostly  = DEFAULT_SAMPLE_PERIOD_NS;
181
182 static int perf_sample_allowed_ns __read_mostly =
183         DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
184
185 void update_perf_cpu_limits(void)
186 {
187         u64 tmp = perf_sample_period_ns;
188
189         tmp *= sysctl_perf_cpu_time_max_percent;
190         do_div(tmp, 100);
191         ACCESS_ONCE(perf_sample_allowed_ns) = tmp;
192 }
193
194 static int perf_rotate_context(struct perf_cpu_context *cpuctx);
195
196 int perf_proc_update_handler(struct ctl_table *table, int write,
197                 void __user *buffer, size_t *lenp,
198                 loff_t *ppos)
199 {
200         int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
201
202         if (ret || !write)
203                 return ret;
204
205         max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
206         perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
207         update_perf_cpu_limits();
208
209         return 0;
210 }
211
212 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
213
214 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
215                                 void __user *buffer, size_t *lenp,
216                                 loff_t *ppos)
217 {
218         int ret = proc_dointvec(table, write, buffer, lenp, ppos);
219
220         if (ret || !write)
221                 return ret;
222
223         update_perf_cpu_limits();
224
225         return 0;
226 }
227
228 /*
229  * perf samples are done in some very critical code paths (NMIs).
230  * If they take too much CPU time, the system can lock up and not
231  * get any real work done.  This will drop the sample rate when
232  * we detect that events are taking too long.
233  */
234 #define NR_ACCUMULATED_SAMPLES 128
235 static DEFINE_PER_CPU(u64, running_sample_length);
236
237 static void perf_duration_warn(struct irq_work *w)
238 {
239         u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
240         u64 avg_local_sample_len;
241         u64 local_samples_len;
242
243         local_samples_len = __get_cpu_var(running_sample_length);
244         avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
245
246         printk_ratelimited(KERN_WARNING
247                         "perf interrupt took too long (%lld > %lld), lowering "
248                         "kernel.perf_event_max_sample_rate to %d\n",
249                         avg_local_sample_len, allowed_ns >> 1,
250                         sysctl_perf_event_sample_rate);
251 }
252
253 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
254
255 void perf_sample_event_took(u64 sample_len_ns)
256 {
257         u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
258         u64 avg_local_sample_len;
259         u64 local_samples_len;
260
261         if (allowed_ns == 0)
262                 return;
263
264         /* decay the counter by 1 average sample */
265         local_samples_len = __get_cpu_var(running_sample_length);
266         local_samples_len -= local_samples_len/NR_ACCUMULATED_SAMPLES;
267         local_samples_len += sample_len_ns;
268         __get_cpu_var(running_sample_length) = local_samples_len;
269
270         /*
271          * note: this will be biased artifically low until we have
272          * seen NR_ACCUMULATED_SAMPLES.  Doing it this way keeps us
273          * from having to maintain a count.
274          */
275         avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
276
277         if (avg_local_sample_len <= allowed_ns)
278                 return;
279
280         if (max_samples_per_tick <= 1)
281                 return;
282
283         max_samples_per_tick = DIV_ROUND_UP(max_samples_per_tick, 2);
284         sysctl_perf_event_sample_rate = max_samples_per_tick * HZ;
285         perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
286
287         update_perf_cpu_limits();
288
289         if (!irq_work_queue(&perf_duration_work)) {
290                 early_printk("perf interrupt took too long (%lld > %lld), lowering "
291                              "kernel.perf_event_max_sample_rate to %d\n",
292                              avg_local_sample_len, allowed_ns >> 1,
293                              sysctl_perf_event_sample_rate);
294         }
295 }
296
297 static atomic64_t perf_event_id;
298
299 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
300                               enum event_type_t event_type);
301
302 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
303                              enum event_type_t event_type,
304                              struct task_struct *task);
305
306 static void update_context_time(struct perf_event_context *ctx);
307 static u64 perf_event_time(struct perf_event *event);
308
309 void __weak perf_event_print_debug(void)        { }
310
311 extern __weak const char *perf_pmu_name(void)
312 {
313         return "pmu";
314 }
315
316 static inline u64 perf_clock(void)
317 {
318         return local_clock();
319 }
320
321 static inline struct perf_cpu_context *
322 __get_cpu_context(struct perf_event_context *ctx)
323 {
324         return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
325 }
326
327 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
328                           struct perf_event_context *ctx)
329 {
330         raw_spin_lock(&cpuctx->ctx.lock);
331         if (ctx)
332                 raw_spin_lock(&ctx->lock);
333 }
334
335 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
336                             struct perf_event_context *ctx)
337 {
338         if (ctx)
339                 raw_spin_unlock(&ctx->lock);
340         raw_spin_unlock(&cpuctx->ctx.lock);
341 }
342
343 #ifdef CONFIG_CGROUP_PERF
344
345 /*
346  * perf_cgroup_info keeps track of time_enabled for a cgroup.
347  * This is a per-cpu dynamically allocated data structure.
348  */
349 struct perf_cgroup_info {
350         u64                             time;
351         u64                             timestamp;
352 };
353
354 struct perf_cgroup {
355         struct cgroup_subsys_state      css;
356         struct perf_cgroup_info __percpu *info;
357 };
358
359 /*
360  * Must ensure cgroup is pinned (css_get) before calling
361  * this function. In other words, we cannot call this function
362  * if there is no cgroup event for the current CPU context.
363  */
364 static inline struct perf_cgroup *
365 perf_cgroup_from_task(struct task_struct *task)
366 {
367         return container_of(task_css(task, perf_event_cgrp_id),
368                             struct perf_cgroup, css);
369 }
370
371 static inline bool
372 perf_cgroup_match(struct perf_event *event)
373 {
374         struct perf_event_context *ctx = event->ctx;
375         struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
376
377         /* @event doesn't care about cgroup */
378         if (!event->cgrp)
379                 return true;
380
381         /* wants specific cgroup scope but @cpuctx isn't associated with any */
382         if (!cpuctx->cgrp)
383                 return false;
384
385         /*
386          * Cgroup scoping is recursive.  An event enabled for a cgroup is
387          * also enabled for all its descendant cgroups.  If @cpuctx's
388          * cgroup is a descendant of @event's (the test covers identity
389          * case), it's a match.
390          */
391         return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
392                                     event->cgrp->css.cgroup);
393 }
394
395 static inline void perf_put_cgroup(struct perf_event *event)
396 {
397         css_put(&event->cgrp->css);
398 }
399
400 static inline void perf_detach_cgroup(struct perf_event *event)
401 {
402         perf_put_cgroup(event);
403         event->cgrp = NULL;
404 }
405
406 static inline int is_cgroup_event(struct perf_event *event)
407 {
408         return event->cgrp != NULL;
409 }
410
411 static inline u64 perf_cgroup_event_time(struct perf_event *event)
412 {
413         struct perf_cgroup_info *t;
414
415         t = per_cpu_ptr(event->cgrp->info, event->cpu);
416         return t->time;
417 }
418
419 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
420 {
421         struct perf_cgroup_info *info;
422         u64 now;
423
424         now = perf_clock();
425
426         info = this_cpu_ptr(cgrp->info);
427
428         info->time += now - info->timestamp;
429         info->timestamp = now;
430 }
431
432 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
433 {
434         struct perf_cgroup *cgrp_out = cpuctx->cgrp;
435         if (cgrp_out)
436                 __update_cgrp_time(cgrp_out);
437 }
438
439 static inline void update_cgrp_time_from_event(struct perf_event *event)
440 {
441         struct perf_cgroup *cgrp;
442
443         /*
444          * ensure we access cgroup data only when needed and
445          * when we know the cgroup is pinned (css_get)
446          */
447         if (!is_cgroup_event(event))
448                 return;
449
450         cgrp = perf_cgroup_from_task(current);
451         /*
452          * Do not update time when cgroup is not active
453          */
454         if (cgrp == event->cgrp)
455                 __update_cgrp_time(event->cgrp);
456 }
457
458 static inline void
459 perf_cgroup_set_timestamp(struct task_struct *task,
460                           struct perf_event_context *ctx)
461 {
462         struct perf_cgroup *cgrp;
463         struct perf_cgroup_info *info;
464
465         /*
466          * ctx->lock held by caller
467          * ensure we do not access cgroup data
468          * unless we have the cgroup pinned (css_get)
469          */
470         if (!task || !ctx->nr_cgroups)
471                 return;
472
473         cgrp = perf_cgroup_from_task(task);
474         info = this_cpu_ptr(cgrp->info);
475         info->timestamp = ctx->timestamp;
476 }
477
478 #define PERF_CGROUP_SWOUT       0x1 /* cgroup switch out every event */
479 #define PERF_CGROUP_SWIN        0x2 /* cgroup switch in events based on task */
480
481 /*
482  * reschedule events based on the cgroup constraint of task.
483  *
484  * mode SWOUT : schedule out everything
485  * mode SWIN : schedule in based on cgroup for next
486  */
487 void perf_cgroup_switch(struct task_struct *task, int mode)
488 {
489         struct perf_cpu_context *cpuctx;
490         struct pmu *pmu;
491         unsigned long flags;
492
493         /*
494          * disable interrupts to avoid geting nr_cgroup
495          * changes via __perf_event_disable(). Also
496          * avoids preemption.
497          */
498         local_irq_save(flags);
499
500         /*
501          * we reschedule only in the presence of cgroup
502          * constrained events.
503          */
504         rcu_read_lock();
505
506         list_for_each_entry_rcu(pmu, &pmus, entry) {
507                 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
508                 if (cpuctx->unique_pmu != pmu)
509                         continue; /* ensure we process each cpuctx once */
510
511                 /*
512                  * perf_cgroup_events says at least one
513                  * context on this CPU has cgroup events.
514                  *
515                  * ctx->nr_cgroups reports the number of cgroup
516                  * events for a context.
517                  */
518                 if (cpuctx->ctx.nr_cgroups > 0) {
519                         perf_ctx_lock(cpuctx, cpuctx->task_ctx);
520                         perf_pmu_disable(cpuctx->ctx.pmu);
521
522                         if (mode & PERF_CGROUP_SWOUT) {
523                                 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
524                                 /*
525                                  * must not be done before ctxswout due
526                                  * to event_filter_match() in event_sched_out()
527                                  */
528                                 cpuctx->cgrp = NULL;
529                         }
530
531                         if (mode & PERF_CGROUP_SWIN) {
532                                 WARN_ON_ONCE(cpuctx->cgrp);
533                                 /*
534                                  * set cgrp before ctxsw in to allow
535                                  * event_filter_match() to not have to pass
536                                  * task around
537                                  */
538                                 cpuctx->cgrp = perf_cgroup_from_task(task);
539                                 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
540                         }
541                         perf_pmu_enable(cpuctx->ctx.pmu);
542                         perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
543                 }
544         }
545
546         rcu_read_unlock();
547
548         local_irq_restore(flags);
549 }
550
551 static inline void perf_cgroup_sched_out(struct task_struct *task,
552                                          struct task_struct *next)
553 {
554         struct perf_cgroup *cgrp1;
555         struct perf_cgroup *cgrp2 = NULL;
556
557         /*
558          * we come here when we know perf_cgroup_events > 0
559          */
560         cgrp1 = perf_cgroup_from_task(task);
561
562         /*
563          * next is NULL when called from perf_event_enable_on_exec()
564          * that will systematically cause a cgroup_switch()
565          */
566         if (next)
567                 cgrp2 = perf_cgroup_from_task(next);
568
569         /*
570          * only schedule out current cgroup events if we know
571          * that we are switching to a different cgroup. Otherwise,
572          * do no touch the cgroup events.
573          */
574         if (cgrp1 != cgrp2)
575                 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
576 }
577
578 static inline void perf_cgroup_sched_in(struct task_struct *prev,
579                                         struct task_struct *task)
580 {
581         struct perf_cgroup *cgrp1;
582         struct perf_cgroup *cgrp2 = NULL;
583
584         /*
585          * we come here when we know perf_cgroup_events > 0
586          */
587         cgrp1 = perf_cgroup_from_task(task);
588
589         /* prev can never be NULL */
590         cgrp2 = perf_cgroup_from_task(prev);
591
592         /*
593          * only need to schedule in cgroup events if we are changing
594          * cgroup during ctxsw. Cgroup events were not scheduled
595          * out of ctxsw out if that was not the case.
596          */
597         if (cgrp1 != cgrp2)
598                 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
599 }
600
601 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
602                                       struct perf_event_attr *attr,
603                                       struct perf_event *group_leader)
604 {
605         struct perf_cgroup *cgrp;
606         struct cgroup_subsys_state *css;
607         struct fd f = fdget(fd);
608         int ret = 0;
609
610         if (!f.file)
611                 return -EBADF;
612
613         css = css_tryget_online_from_dir(f.file->f_dentry,
614                                          &perf_event_cgrp_subsys);
615         if (IS_ERR(css)) {
616                 ret = PTR_ERR(css);
617                 goto out;
618         }
619
620         cgrp = container_of(css, struct perf_cgroup, css);
621         event->cgrp = cgrp;
622
623         /*
624          * all events in a group must monitor
625          * the same cgroup because a task belongs
626          * to only one perf cgroup at a time
627          */
628         if (group_leader && group_leader->cgrp != cgrp) {
629                 perf_detach_cgroup(event);
630                 ret = -EINVAL;
631         }
632 out:
633         fdput(f);
634         return ret;
635 }
636
637 static inline void
638 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
639 {
640         struct perf_cgroup_info *t;
641         t = per_cpu_ptr(event->cgrp->info, event->cpu);
642         event->shadow_ctx_time = now - t->timestamp;
643 }
644
645 static inline void
646 perf_cgroup_defer_enabled(struct perf_event *event)
647 {
648         /*
649          * when the current task's perf cgroup does not match
650          * the event's, we need to remember to call the
651          * perf_mark_enable() function the first time a task with
652          * a matching perf cgroup is scheduled in.
653          */
654         if (is_cgroup_event(event) && !perf_cgroup_match(event))
655                 event->cgrp_defer_enabled = 1;
656 }
657
658 static inline void
659 perf_cgroup_mark_enabled(struct perf_event *event,
660                          struct perf_event_context *ctx)
661 {
662         struct perf_event *sub;
663         u64 tstamp = perf_event_time(event);
664
665         if (!event->cgrp_defer_enabled)
666                 return;
667
668         event->cgrp_defer_enabled = 0;
669
670         event->tstamp_enabled = tstamp - event->total_time_enabled;
671         list_for_each_entry(sub, &event->sibling_list, group_entry) {
672                 if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
673                         sub->tstamp_enabled = tstamp - sub->total_time_enabled;
674                         sub->cgrp_defer_enabled = 0;
675                 }
676         }
677 }
678 #else /* !CONFIG_CGROUP_PERF */
679
680 static inline bool
681 perf_cgroup_match(struct perf_event *event)
682 {
683         return true;
684 }
685
686 static inline void perf_detach_cgroup(struct perf_event *event)
687 {}
688
689 static inline int is_cgroup_event(struct perf_event *event)
690 {
691         return 0;
692 }
693
694 static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
695 {
696         return 0;
697 }
698
699 static inline void update_cgrp_time_from_event(struct perf_event *event)
700 {
701 }
702
703 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
704 {
705 }
706
707 static inline void perf_cgroup_sched_out(struct task_struct *task,
708                                          struct task_struct *next)
709 {
710 }
711
712 static inline void perf_cgroup_sched_in(struct task_struct *prev,
713                                         struct task_struct *task)
714 {
715 }
716
717 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
718                                       struct perf_event_attr *attr,
719                                       struct perf_event *group_leader)
720 {
721         return -EINVAL;
722 }
723
724 static inline void
725 perf_cgroup_set_timestamp(struct task_struct *task,
726                           struct perf_event_context *ctx)
727 {
728 }
729
730 void
731 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
732 {
733 }
734
735 static inline void
736 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
737 {
738 }
739
740 static inline u64 perf_cgroup_event_time(struct perf_event *event)
741 {
742         return 0;
743 }
744
745 static inline void
746 perf_cgroup_defer_enabled(struct perf_event *event)
747 {
748 }
749
750 static inline void
751 perf_cgroup_mark_enabled(struct perf_event *event,
752                          struct perf_event_context *ctx)
753 {
754 }
755 #endif
756
757 /*
758  * set default to be dependent on timer tick just
759  * like original code
760  */
761 #define PERF_CPU_HRTIMER (1000 / HZ)
762 /*
763  * function must be called with interrupts disbled
764  */
765 static enum hrtimer_restart perf_cpu_hrtimer_handler(struct hrtimer *hr)
766 {
767         struct perf_cpu_context *cpuctx;
768         enum hrtimer_restart ret = HRTIMER_NORESTART;
769         int rotations = 0;
770
771         WARN_ON(!irqs_disabled());
772
773         cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
774
775         rotations = perf_rotate_context(cpuctx);
776
777         /*
778          * arm timer if needed
779          */
780         if (rotations) {
781                 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
782                 ret = HRTIMER_RESTART;
783         }
784
785         return ret;
786 }
787
788 /* CPU is going down */
789 void perf_cpu_hrtimer_cancel(int cpu)
790 {
791         struct perf_cpu_context *cpuctx;
792         struct pmu *pmu;
793         unsigned long flags;
794
795         if (WARN_ON(cpu != smp_processor_id()))
796                 return;
797
798         local_irq_save(flags);
799
800         rcu_read_lock();
801
802         list_for_each_entry_rcu(pmu, &pmus, entry) {
803                 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
804
805                 if (pmu->task_ctx_nr == perf_sw_context)
806                         continue;
807
808                 hrtimer_cancel(&cpuctx->hrtimer);
809         }
810
811         rcu_read_unlock();
812
813         local_irq_restore(flags);
814 }
815
816 static void __perf_cpu_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
817 {
818         struct hrtimer *hr = &cpuctx->hrtimer;
819         struct pmu *pmu = cpuctx->ctx.pmu;
820         int timer;
821
822         /* no multiplexing needed for SW PMU */
823         if (pmu->task_ctx_nr == perf_sw_context)
824                 return;
825
826         /*
827          * check default is sane, if not set then force to
828          * default interval (1/tick)
829          */
830         timer = pmu->hrtimer_interval_ms;
831         if (timer < 1)
832                 timer = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
833
834         cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
835
836         hrtimer_init(hr, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
837         hr->function = perf_cpu_hrtimer_handler;
838 }
839
840 static void perf_cpu_hrtimer_restart(struct perf_cpu_context *cpuctx)
841 {
842         struct hrtimer *hr = &cpuctx->hrtimer;
843         struct pmu *pmu = cpuctx->ctx.pmu;
844
845         /* not for SW PMU */
846         if (pmu->task_ctx_nr == perf_sw_context)
847                 return;
848
849         if (hrtimer_active(hr))
850                 return;
851
852         if (!hrtimer_callback_running(hr))
853                 __hrtimer_start_range_ns(hr, cpuctx->hrtimer_interval,
854                                          0, HRTIMER_MODE_REL_PINNED, 0);
855 }
856
857 void perf_pmu_disable(struct pmu *pmu)
858 {
859         int *count = this_cpu_ptr(pmu->pmu_disable_count);
860         if (!(*count)++)
861                 pmu->pmu_disable(pmu);
862 }
863
864 void perf_pmu_enable(struct pmu *pmu)
865 {
866         int *count = this_cpu_ptr(pmu->pmu_disable_count);
867         if (!--(*count))
868                 pmu->pmu_enable(pmu);
869 }
870
871 static DEFINE_PER_CPU(struct list_head, rotation_list);
872
873 /*
874  * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
875  * because they're strictly cpu affine and rotate_start is called with IRQs
876  * disabled, while rotate_context is called from IRQ context.
877  */
878 static void perf_pmu_rotate_start(struct pmu *pmu)
879 {
880         struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
881         struct list_head *head = &__get_cpu_var(rotation_list);
882
883         WARN_ON(!irqs_disabled());
884
885         if (list_empty(&cpuctx->rotation_list))
886                 list_add(&cpuctx->rotation_list, head);
887 }
888
889 static void get_ctx(struct perf_event_context *ctx)
890 {
891         WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
892 }
893
894 static void put_ctx(struct perf_event_context *ctx)
895 {
896         if (atomic_dec_and_test(&ctx->refcount)) {
897                 if (ctx->parent_ctx)
898                         put_ctx(ctx->parent_ctx);
899                 if (ctx->task)
900                         put_task_struct(ctx->task);
901                 kfree_rcu(ctx, rcu_head);
902         }
903 }
904
905 /*
906  * This must be done under the ctx->lock, such as to serialize against
907  * context_equiv(), therefore we cannot call put_ctx() since that might end up
908  * calling scheduler related locks and ctx->lock nests inside those.
909  */
910 static __must_check struct perf_event_context *
911 unclone_ctx(struct perf_event_context *ctx)
912 {
913         struct perf_event_context *parent_ctx = ctx->parent_ctx;
914
915         lockdep_assert_held(&ctx->lock);
916
917         if (parent_ctx)
918                 ctx->parent_ctx = NULL;
919         ctx->generation++;
920
921         return parent_ctx;
922 }
923
924 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
925 {
926         /*
927          * only top level events have the pid namespace they were created in
928          */
929         if (event->parent)
930                 event = event->parent;
931
932         return task_tgid_nr_ns(p, event->ns);
933 }
934
935 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
936 {
937         /*
938          * only top level events have the pid namespace they were created in
939          */
940         if (event->parent)
941                 event = event->parent;
942
943         return task_pid_nr_ns(p, event->ns);
944 }
945
946 /*
947  * If we inherit events we want to return the parent event id
948  * to userspace.
949  */
950 static u64 primary_event_id(struct perf_event *event)
951 {
952         u64 id = event->id;
953
954         if (event->parent)
955                 id = event->parent->id;
956
957         return id;
958 }
959
960 /*
961  * Get the perf_event_context for a task and lock it.
962  * This has to cope with with the fact that until it is locked,
963  * the context could get moved to another task.
964  */
965 static struct perf_event_context *
966 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
967 {
968         struct perf_event_context *ctx;
969
970 retry:
971         /*
972          * One of the few rules of preemptible RCU is that one cannot do
973          * rcu_read_unlock() while holding a scheduler (or nested) lock when
974          * part of the read side critical section was preemptible -- see
975          * rcu_read_unlock_special().
976          *
977          * Since ctx->lock nests under rq->lock we must ensure the entire read
978          * side critical section is non-preemptible.
979          */
980         preempt_disable();
981         rcu_read_lock();
982         ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
983         if (ctx) {
984                 /*
985                  * If this context is a clone of another, it might
986                  * get swapped for another underneath us by
987                  * perf_event_task_sched_out, though the
988                  * rcu_read_lock() protects us from any context
989                  * getting freed.  Lock the context and check if it
990                  * got swapped before we could get the lock, and retry
991                  * if so.  If we locked the right context, then it
992                  * can't get swapped on us any more.
993                  */
994                 raw_spin_lock_irqsave(&ctx->lock, *flags);
995                 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
996                         raw_spin_unlock_irqrestore(&ctx->lock, *flags);
997                         rcu_read_unlock();
998                         preempt_enable();
999                         goto retry;
1000                 }
1001
1002                 if (!atomic_inc_not_zero(&ctx->refcount)) {
1003                         raw_spin_unlock_irqrestore(&ctx->lock, *flags);
1004                         ctx = NULL;
1005                 }
1006         }
1007         rcu_read_unlock();
1008         preempt_enable();
1009         return ctx;
1010 }
1011
1012 /*
1013  * Get the context for a task and increment its pin_count so it
1014  * can't get swapped to another task.  This also increments its
1015  * reference count so that the context can't get freed.
1016  */
1017 static struct perf_event_context *
1018 perf_pin_task_context(struct task_struct *task, int ctxn)
1019 {
1020         struct perf_event_context *ctx;
1021         unsigned long flags;
1022
1023         ctx = perf_lock_task_context(task, ctxn, &flags);
1024         if (ctx) {
1025                 ++ctx->pin_count;
1026                 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1027         }
1028         return ctx;
1029 }
1030
1031 static void perf_unpin_context(struct perf_event_context *ctx)
1032 {
1033         unsigned long flags;
1034
1035         raw_spin_lock_irqsave(&ctx->lock, flags);
1036         --ctx->pin_count;
1037         raw_spin_unlock_irqrestore(&ctx->lock, flags);
1038 }
1039
1040 /*
1041  * Update the record of the current time in a context.
1042  */
1043 static void update_context_time(struct perf_event_context *ctx)
1044 {
1045         u64 now = perf_clock();
1046
1047         ctx->time += now - ctx->timestamp;
1048         ctx->timestamp = now;
1049 }
1050
1051 static u64 perf_event_time(struct perf_event *event)
1052 {
1053         struct perf_event_context *ctx = event->ctx;
1054
1055         if (is_cgroup_event(event))
1056                 return perf_cgroup_event_time(event);
1057
1058         return ctx ? ctx->time : 0;
1059 }
1060
1061 /*
1062  * Update the total_time_enabled and total_time_running fields for a event.
1063  * The caller of this function needs to hold the ctx->lock.
1064  */
1065 static void update_event_times(struct perf_event *event)
1066 {
1067         struct perf_event_context *ctx = event->ctx;
1068         u64 run_end;
1069
1070         if (event->state < PERF_EVENT_STATE_INACTIVE ||
1071             event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
1072                 return;
1073         /*
1074          * in cgroup mode, time_enabled represents
1075          * the time the event was enabled AND active
1076          * tasks were in the monitored cgroup. This is
1077          * independent of the activity of the context as
1078          * there may be a mix of cgroup and non-cgroup events.
1079          *
1080          * That is why we treat cgroup events differently
1081          * here.
1082          */
1083         if (is_cgroup_event(event))
1084                 run_end = perf_cgroup_event_time(event);
1085         else if (ctx->is_active)
1086                 run_end = ctx->time;
1087         else
1088                 run_end = event->tstamp_stopped;
1089
1090         event->total_time_enabled = run_end - event->tstamp_enabled;
1091
1092         if (event->state == PERF_EVENT_STATE_INACTIVE)
1093                 run_end = event->tstamp_stopped;
1094         else
1095                 run_end = perf_event_time(event);
1096
1097         event->total_time_running = run_end - event->tstamp_running;
1098
1099 }
1100
1101 /*
1102  * Update total_time_enabled and total_time_running for all events in a group.
1103  */
1104 static void update_group_times(struct perf_event *leader)
1105 {
1106         struct perf_event *event;
1107
1108         update_event_times(leader);
1109         list_for_each_entry(event, &leader->sibling_list, group_entry)
1110                 update_event_times(event);
1111 }
1112
1113 static struct list_head *
1114 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
1115 {
1116         if (event->attr.pinned)
1117                 return &ctx->pinned_groups;
1118         else
1119                 return &ctx->flexible_groups;
1120 }
1121
1122 /*
1123  * Add a event from the lists for its context.
1124  * Must be called with ctx->mutex and ctx->lock held.
1125  */
1126 static void
1127 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1128 {
1129         WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1130         event->attach_state |= PERF_ATTACH_CONTEXT;
1131
1132         /*
1133          * If we're a stand alone event or group leader, we go to the context
1134          * list, group events are kept attached to the group so that
1135          * perf_group_detach can, at all times, locate all siblings.
1136          */
1137         if (event->group_leader == event) {
1138                 struct list_head *list;
1139
1140                 if (is_software_event(event))
1141                         event->group_flags |= PERF_GROUP_SOFTWARE;
1142
1143                 list = ctx_group_list(event, ctx);
1144                 list_add_tail(&event->group_entry, list);
1145         }
1146
1147         if (is_cgroup_event(event))
1148                 ctx->nr_cgroups++;
1149
1150         if (has_branch_stack(event))
1151                 ctx->nr_branch_stack++;
1152
1153         list_add_rcu(&event->event_entry, &ctx->event_list);
1154         if (!ctx->nr_events)
1155                 perf_pmu_rotate_start(ctx->pmu);
1156         ctx->nr_events++;
1157         if (event->attr.inherit_stat)
1158                 ctx->nr_stat++;
1159
1160         ctx->generation++;
1161 }
1162
1163 /*
1164  * Initialize event state based on the perf_event_attr::disabled.
1165  */
1166 static inline void perf_event__state_init(struct perf_event *event)
1167 {
1168         event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1169                                               PERF_EVENT_STATE_INACTIVE;
1170 }
1171
1172 /*
1173  * Called at perf_event creation and when events are attached/detached from a
1174  * group.
1175  */
1176 static void perf_event__read_size(struct perf_event *event)
1177 {
1178         int entry = sizeof(u64); /* value */
1179         int size = 0;
1180         int nr = 1;
1181
1182         if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1183                 size += sizeof(u64);
1184
1185         if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1186                 size += sizeof(u64);
1187
1188         if (event->attr.read_format & PERF_FORMAT_ID)
1189                 entry += sizeof(u64);
1190
1191         if (event->attr.read_format & PERF_FORMAT_GROUP) {
1192                 nr += event->group_leader->nr_siblings;
1193                 size += sizeof(u64);
1194         }
1195
1196         size += entry * nr;
1197         event->read_size = size;
1198 }
1199
1200 static void perf_event__header_size(struct perf_event *event)
1201 {
1202         struct perf_sample_data *data;
1203         u64 sample_type = event->attr.sample_type;
1204         u16 size = 0;
1205
1206         perf_event__read_size(event);
1207
1208         if (sample_type & PERF_SAMPLE_IP)
1209                 size += sizeof(data->ip);
1210
1211         if (sample_type & PERF_SAMPLE_ADDR)
1212                 size += sizeof(data->addr);
1213
1214         if (sample_type & PERF_SAMPLE_PERIOD)
1215                 size += sizeof(data->period);
1216
1217         if (sample_type & PERF_SAMPLE_WEIGHT)
1218                 size += sizeof(data->weight);
1219
1220         if (sample_type & PERF_SAMPLE_READ)
1221                 size += event->read_size;
1222
1223         if (sample_type & PERF_SAMPLE_DATA_SRC)
1224                 size += sizeof(data->data_src.val);
1225
1226         if (sample_type & PERF_SAMPLE_TRANSACTION)
1227                 size += sizeof(data->txn);
1228
1229         event->header_size = size;
1230 }
1231
1232 static void perf_event__id_header_size(struct perf_event *event)
1233 {
1234         struct perf_sample_data *data;
1235         u64 sample_type = event->attr.sample_type;
1236         u16 size = 0;
1237
1238         if (sample_type & PERF_SAMPLE_TID)
1239                 size += sizeof(data->tid_entry);
1240
1241         if (sample_type & PERF_SAMPLE_TIME)
1242                 size += sizeof(data->time);
1243
1244         if (sample_type & PERF_SAMPLE_IDENTIFIER)
1245                 size += sizeof(data->id);
1246
1247         if (sample_type & PERF_SAMPLE_ID)
1248                 size += sizeof(data->id);
1249
1250         if (sample_type & PERF_SAMPLE_STREAM_ID)
1251                 size += sizeof(data->stream_id);
1252
1253         if (sample_type & PERF_SAMPLE_CPU)
1254                 size += sizeof(data->cpu_entry);
1255
1256         event->id_header_size = size;
1257 }
1258
1259 static void perf_group_attach(struct perf_event *event)
1260 {
1261         struct perf_event *group_leader = event->group_leader, *pos;
1262
1263         /*
1264          * We can have double attach due to group movement in perf_event_open.
1265          */
1266         if (event->attach_state & PERF_ATTACH_GROUP)
1267                 return;
1268
1269         event->attach_state |= PERF_ATTACH_GROUP;
1270
1271         if (group_leader == event)
1272                 return;
1273
1274         if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
1275                         !is_software_event(event))
1276                 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
1277
1278         list_add_tail(&event->group_entry, &group_leader->sibling_list);
1279         group_leader->nr_siblings++;
1280
1281         perf_event__header_size(group_leader);
1282
1283         list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
1284                 perf_event__header_size(pos);
1285 }
1286
1287 /*
1288  * Remove a event from the lists for its context.
1289  * Must be called with ctx->mutex and ctx->lock held.
1290  */
1291 static void
1292 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1293 {
1294         struct perf_cpu_context *cpuctx;
1295         /*
1296          * We can have double detach due to exit/hot-unplug + close.
1297          */
1298         if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1299                 return;
1300
1301         event->attach_state &= ~PERF_ATTACH_CONTEXT;
1302
1303         if (is_cgroup_event(event)) {
1304                 ctx->nr_cgroups--;
1305                 cpuctx = __get_cpu_context(ctx);
1306                 /*
1307                  * if there are no more cgroup events
1308                  * then cler cgrp to avoid stale pointer
1309                  * in update_cgrp_time_from_cpuctx()
1310                  */
1311                 if (!ctx->nr_cgroups)
1312                         cpuctx->cgrp = NULL;
1313         }
1314
1315         if (has_branch_stack(event))
1316                 ctx->nr_branch_stack--;
1317
1318         ctx->nr_events--;
1319         if (event->attr.inherit_stat)
1320                 ctx->nr_stat--;
1321
1322         list_del_rcu(&event->event_entry);
1323
1324         if (event->group_leader == event)
1325                 list_del_init(&event->group_entry);
1326
1327         update_group_times(event);
1328
1329         /*
1330          * If event was in error state, then keep it
1331          * that way, otherwise bogus counts will be
1332          * returned on read(). The only way to get out
1333          * of error state is by explicit re-enabling
1334          * of the event
1335          */
1336         if (event->state > PERF_EVENT_STATE_OFF)
1337                 event->state = PERF_EVENT_STATE_OFF;
1338
1339         ctx->generation++;
1340 }
1341
1342 static void perf_group_detach(struct perf_event *event)
1343 {
1344         struct perf_event *sibling, *tmp;
1345         struct list_head *list = NULL;
1346
1347         /*
1348          * We can have double detach due to exit/hot-unplug + close.
1349          */
1350         if (!(event->attach_state & PERF_ATTACH_GROUP))
1351                 return;
1352
1353         event->attach_state &= ~PERF_ATTACH_GROUP;
1354
1355         /*
1356          * If this is a sibling, remove it from its group.
1357          */
1358         if (event->group_leader != event) {
1359                 list_del_init(&event->group_entry);
1360                 event->group_leader->nr_siblings--;
1361                 goto out;
1362         }
1363
1364         if (!list_empty(&event->group_entry))
1365                 list = &event->group_entry;
1366
1367         /*
1368          * If this was a group event with sibling events then
1369          * upgrade the siblings to singleton events by adding them
1370          * to whatever list we are on.
1371          */
1372         list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
1373                 if (list)
1374                         list_move_tail(&sibling->group_entry, list);
1375                 sibling->group_leader = sibling;
1376
1377                 /* Inherit group flags from the previous leader */
1378                 sibling->group_flags = event->group_flags;
1379         }
1380
1381 out:
1382         perf_event__header_size(event->group_leader);
1383
1384         list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
1385                 perf_event__header_size(tmp);
1386 }
1387
1388 static inline int
1389 event_filter_match(struct perf_event *event)
1390 {
1391         return (event->cpu == -1 || event->cpu == smp_processor_id())
1392             && perf_cgroup_match(event);
1393 }
1394
1395 static void
1396 event_sched_out(struct perf_event *event,
1397                   struct perf_cpu_context *cpuctx,
1398                   struct perf_event_context *ctx)
1399 {
1400         u64 tstamp = perf_event_time(event);
1401         u64 delta;
1402         /*
1403          * An event which could not be activated because of
1404          * filter mismatch still needs to have its timings
1405          * maintained, otherwise bogus information is return
1406          * via read() for time_enabled, time_running:
1407          */
1408         if (event->state == PERF_EVENT_STATE_INACTIVE
1409             && !event_filter_match(event)) {
1410                 delta = tstamp - event->tstamp_stopped;
1411                 event->tstamp_running += delta;
1412                 event->tstamp_stopped = tstamp;
1413         }
1414
1415         if (event->state != PERF_EVENT_STATE_ACTIVE)
1416                 return;
1417
1418         perf_pmu_disable(event->pmu);
1419
1420         event->state = PERF_EVENT_STATE_INACTIVE;
1421         if (event->pending_disable) {
1422                 event->pending_disable = 0;
1423                 event->state = PERF_EVENT_STATE_OFF;
1424         }
1425         event->tstamp_stopped = tstamp;
1426         event->pmu->del(event, 0);
1427         event->oncpu = -1;
1428
1429         if (!is_software_event(event))
1430                 cpuctx->active_oncpu--;
1431         ctx->nr_active--;
1432         if (event->attr.freq && event->attr.sample_freq)
1433                 ctx->nr_freq--;
1434         if (event->attr.exclusive || !cpuctx->active_oncpu)
1435                 cpuctx->exclusive = 0;
1436
1437         perf_pmu_enable(event->pmu);
1438 }
1439
1440 static void
1441 group_sched_out(struct perf_event *group_event,
1442                 struct perf_cpu_context *cpuctx,
1443                 struct perf_event_context *ctx)
1444 {
1445         struct perf_event *event;
1446         int state = group_event->state;
1447
1448         event_sched_out(group_event, cpuctx, ctx);
1449
1450         /*
1451          * Schedule out siblings (if any):
1452          */
1453         list_for_each_entry(event, &group_event->sibling_list, group_entry)
1454                 event_sched_out(event, cpuctx, ctx);
1455
1456         if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
1457                 cpuctx->exclusive = 0;
1458 }
1459
1460 struct remove_event {
1461         struct perf_event *event;
1462         bool detach_group;
1463 };
1464
1465 /*
1466  * Cross CPU call to remove a performance event
1467  *
1468  * We disable the event on the hardware level first. After that we
1469  * remove it from the context list.
1470  */
1471 static int __perf_remove_from_context(void *info)
1472 {
1473         struct remove_event *re = info;
1474         struct perf_event *event = re->event;
1475         struct perf_event_context *ctx = event->ctx;
1476         struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1477
1478         raw_spin_lock(&ctx->lock);
1479         event_sched_out(event, cpuctx, ctx);
1480         if (re->detach_group)
1481                 perf_group_detach(event);
1482         list_del_event(event, ctx);
1483         if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
1484                 ctx->is_active = 0;
1485                 cpuctx->task_ctx = NULL;
1486         }
1487         raw_spin_unlock(&ctx->lock);
1488
1489         return 0;
1490 }
1491
1492
1493 /*
1494  * Remove the event from a task's (or a CPU's) list of events.
1495  *
1496  * CPU events are removed with a smp call. For task events we only
1497  * call when the task is on a CPU.
1498  *
1499  * If event->ctx is a cloned context, callers must make sure that
1500  * every task struct that event->ctx->task could possibly point to
1501  * remains valid.  This is OK when called from perf_release since
1502  * that only calls us on the top-level context, which can't be a clone.
1503  * When called from perf_event_exit_task, it's OK because the
1504  * context has been detached from its task.
1505  */
1506 static void perf_remove_from_context(struct perf_event *event, bool detach_group)
1507 {
1508         struct perf_event_context *ctx = event->ctx;
1509         struct task_struct *task = ctx->task;
1510         struct remove_event re = {
1511                 .event = event,
1512                 .detach_group = detach_group,
1513         };
1514
1515         lockdep_assert_held(&ctx->mutex);
1516
1517         if (!task) {
1518                 /*
1519                  * Per cpu events are removed via an smp call and
1520                  * the removal is always successful.
1521                  */
1522                 cpu_function_call(event->cpu, __perf_remove_from_context, &re);
1523                 return;
1524         }
1525
1526 retry:
1527         if (!task_function_call(task, __perf_remove_from_context, &re))
1528                 return;
1529
1530         raw_spin_lock_irq(&ctx->lock);
1531         /*
1532          * If we failed to find a running task, but find the context active now
1533          * that we've acquired the ctx->lock, retry.
1534          */
1535         if (ctx->is_active) {
1536                 raw_spin_unlock_irq(&ctx->lock);
1537                 /*
1538                  * Reload the task pointer, it might have been changed by
1539                  * a concurrent perf_event_context_sched_out().
1540                  */
1541                 task = ctx->task;
1542                 goto retry;
1543         }
1544
1545         /*
1546          * Since the task isn't running, its safe to remove the event, us
1547          * holding the ctx->lock ensures the task won't get scheduled in.
1548          */
1549         if (detach_group)
1550                 perf_group_detach(event);
1551         list_del_event(event, ctx);
1552         raw_spin_unlock_irq(&ctx->lock);
1553 }
1554
1555 /*
1556  * Cross CPU call to disable a performance event
1557  */
1558 int __perf_event_disable(void *info)
1559 {
1560         struct perf_event *event = info;
1561         struct perf_event_context *ctx = event->ctx;
1562         struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1563
1564         /*
1565          * If this is a per-task event, need to check whether this
1566          * event's task is the current task on this cpu.
1567          *
1568          * Can trigger due to concurrent perf_event_context_sched_out()
1569          * flipping contexts around.
1570          */
1571         if (ctx->task && cpuctx->task_ctx != ctx)
1572                 return -EINVAL;
1573
1574         raw_spin_lock(&ctx->lock);
1575
1576         /*
1577          * If the event is on, turn it off.
1578          * If it is in error state, leave it in error state.
1579          */
1580         if (event->state >= PERF_EVENT_STATE_INACTIVE) {
1581                 update_context_time(ctx);
1582                 update_cgrp_time_from_event(event);
1583                 update_group_times(event);
1584                 if (event == event->group_leader)
1585                         group_sched_out(event, cpuctx, ctx);
1586                 else
1587                         event_sched_out(event, cpuctx, ctx);
1588                 event->state = PERF_EVENT_STATE_OFF;
1589         }
1590
1591         raw_spin_unlock(&ctx->lock);
1592
1593         return 0;
1594 }
1595
1596 /*
1597  * Disable a event.
1598  *
1599  * If event->ctx is a cloned context, callers must make sure that
1600  * every task struct that event->ctx->task could possibly point to
1601  * remains valid.  This condition is satisifed when called through
1602  * perf_event_for_each_child or perf_event_for_each because they
1603  * hold the top-level event's child_mutex, so any descendant that
1604  * goes to exit will block in sync_child_event.
1605  * When called from perf_pending_event it's OK because event->ctx
1606  * is the current context on this CPU and preemption is disabled,
1607  * hence we can't get into perf_event_task_sched_out for this context.
1608  */
1609 void perf_event_disable(struct perf_event *event)
1610 {
1611         struct perf_event_context *ctx = event->ctx;
1612         struct task_struct *task = ctx->task;
1613
1614         if (!task) {
1615                 /*
1616                  * Disable the event on the cpu that it's on
1617                  */
1618                 cpu_function_call(event->cpu, __perf_event_disable, event);
1619                 return;
1620         }
1621
1622 retry:
1623         if (!task_function_call(task, __perf_event_disable, event))
1624                 return;
1625
1626         raw_spin_lock_irq(&ctx->lock);
1627         /*
1628          * If the event is still active, we need to retry the cross-call.
1629          */
1630         if (event->state == PERF_EVENT_STATE_ACTIVE) {
1631                 raw_spin_unlock_irq(&ctx->lock);
1632                 /*
1633                  * Reload the task pointer, it might have been changed by
1634                  * a concurrent perf_event_context_sched_out().
1635                  */
1636                 task = ctx->task;
1637                 goto retry;
1638         }
1639
1640         /*
1641          * Since we have the lock this context can't be scheduled
1642          * in, so we can change the state safely.
1643          */
1644         if (event->state == PERF_EVENT_STATE_INACTIVE) {
1645                 update_group_times(event);
1646                 event->state = PERF_EVENT_STATE_OFF;
1647         }
1648         raw_spin_unlock_irq(&ctx->lock);
1649 }
1650 EXPORT_SYMBOL_GPL(perf_event_disable);
1651
1652 static void perf_set_shadow_time(struct perf_event *event,
1653                                  struct perf_event_context *ctx,
1654                                  u64 tstamp)
1655 {
1656         /*
1657          * use the correct time source for the time snapshot
1658          *
1659          * We could get by without this by leveraging the
1660          * fact that to get to this function, the caller
1661          * has most likely already called update_context_time()
1662          * and update_cgrp_time_xx() and thus both timestamp
1663          * are identical (or very close). Given that tstamp is,
1664          * already adjusted for cgroup, we could say that:
1665          *    tstamp - ctx->timestamp
1666          * is equivalent to
1667          *    tstamp - cgrp->timestamp.
1668          *
1669          * Then, in perf_output_read(), the calculation would
1670          * work with no changes because:
1671          * - event is guaranteed scheduled in
1672          * - no scheduled out in between
1673          * - thus the timestamp would be the same
1674          *
1675          * But this is a bit hairy.
1676          *
1677          * So instead, we have an explicit cgroup call to remain
1678          * within the time time source all along. We believe it
1679          * is cleaner and simpler to understand.
1680          */
1681         if (is_cgroup_event(event))
1682                 perf_cgroup_set_shadow_time(event, tstamp);
1683         else
1684                 event->shadow_ctx_time = tstamp - ctx->timestamp;
1685 }
1686
1687 #define MAX_INTERRUPTS (~0ULL)
1688
1689 static void perf_log_throttle(struct perf_event *event, int enable);
1690
1691 static int
1692 event_sched_in(struct perf_event *event,
1693                  struct perf_cpu_context *cpuctx,
1694                  struct perf_event_context *ctx)
1695 {
1696         u64 tstamp = perf_event_time(event);
1697         int ret = 0;
1698
1699         lockdep_assert_held(&ctx->lock);
1700
1701         if (event->state <= PERF_EVENT_STATE_OFF)
1702                 return 0;
1703
1704         event->state = PERF_EVENT_STATE_ACTIVE;
1705         event->oncpu = smp_processor_id();
1706
1707         /*
1708          * Unthrottle events, since we scheduled we might have missed several
1709          * ticks already, also for a heavily scheduling task there is little
1710          * guarantee it'll get a tick in a timely manner.
1711          */
1712         if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
1713                 perf_log_throttle(event, 1);
1714                 event->hw.interrupts = 0;
1715         }
1716
1717         /*
1718          * The new state must be visible before we turn it on in the hardware:
1719          */
1720         smp_wmb();
1721
1722         perf_pmu_disable(event->pmu);
1723
1724         if (event->pmu->add(event, PERF_EF_START)) {
1725                 event->state = PERF_EVENT_STATE_INACTIVE;
1726                 event->oncpu = -1;
1727                 ret = -EAGAIN;
1728                 goto out;
1729         }
1730
1731         event->tstamp_running += tstamp - event->tstamp_stopped;
1732
1733         perf_set_shadow_time(event, ctx, tstamp);
1734
1735         if (!is_software_event(event))
1736                 cpuctx->active_oncpu++;
1737         ctx->nr_active++;
1738         if (event->attr.freq && event->attr.sample_freq)
1739                 ctx->nr_freq++;
1740
1741         if (event->attr.exclusive)
1742                 cpuctx->exclusive = 1;
1743
1744 out:
1745         perf_pmu_enable(event->pmu);
1746
1747         return ret;
1748 }
1749
1750 static int
1751 group_sched_in(struct perf_event *group_event,
1752                struct perf_cpu_context *cpuctx,
1753                struct perf_event_context *ctx)
1754 {
1755         struct perf_event *event, *partial_group = NULL;
1756         struct pmu *pmu = ctx->pmu;
1757         u64 now = ctx->time;
1758         bool simulate = false;
1759
1760         if (group_event->state == PERF_EVENT_STATE_OFF)
1761                 return 0;
1762
1763         pmu->start_txn(pmu);
1764
1765         if (event_sched_in(group_event, cpuctx, ctx)) {
1766                 pmu->cancel_txn(pmu);
1767                 perf_cpu_hrtimer_restart(cpuctx);
1768                 return -EAGAIN;
1769         }
1770
1771         /*
1772          * Schedule in siblings as one group (if any):
1773          */
1774         list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1775                 if (event_sched_in(event, cpuctx, ctx)) {
1776                         partial_group = event;
1777                         goto group_error;
1778                 }
1779         }
1780
1781         if (!pmu->commit_txn(pmu))
1782                 return 0;
1783
1784 group_error:
1785         /*
1786          * Groups can be scheduled in as one unit only, so undo any
1787          * partial group before returning:
1788          * The events up to the failed event are scheduled out normally,
1789          * tstamp_stopped will be updated.
1790          *
1791          * The failed events and the remaining siblings need to have
1792          * their timings updated as if they had gone thru event_sched_in()
1793          * and event_sched_out(). This is required to get consistent timings
1794          * across the group. This also takes care of the case where the group
1795          * could never be scheduled by ensuring tstamp_stopped is set to mark
1796          * the time the event was actually stopped, such that time delta
1797          * calculation in update_event_times() is correct.
1798          */
1799         list_for_each_entry(event, &group_event->sibling_list, group_entry) {
1800                 if (event == partial_group)
1801                         simulate = true;
1802
1803                 if (simulate) {
1804                         event->tstamp_running += now - event->tstamp_stopped;
1805                         event->tstamp_stopped = now;
1806                 } else {
1807                         event_sched_out(event, cpuctx, ctx);
1808                 }
1809         }
1810         event_sched_out(group_event, cpuctx, ctx);
1811
1812         pmu->cancel_txn(pmu);
1813
1814         perf_cpu_hrtimer_restart(cpuctx);
1815
1816         return -EAGAIN;
1817 }
1818
1819 /*
1820  * Work out whether we can put this event group on the CPU now.
1821  */
1822 static int group_can_go_on(struct perf_event *event,
1823                            struct perf_cpu_context *cpuctx,
1824                            int can_add_hw)
1825 {
1826         /*
1827          * Groups consisting entirely of software events can always go on.
1828          */
1829         if (event->group_flags & PERF_GROUP_SOFTWARE)
1830                 return 1;
1831         /*
1832          * If an exclusive group is already on, no other hardware
1833          * events can go on.
1834          */
1835         if (cpuctx->exclusive)
1836                 return 0;
1837         /*
1838          * If this group is exclusive and there are already
1839          * events on the CPU, it can't go on.
1840          */
1841         if (event->attr.exclusive && cpuctx->active_oncpu)
1842                 return 0;
1843         /*
1844          * Otherwise, try to add it if all previous groups were able
1845          * to go on.
1846          */
1847         return can_add_hw;
1848 }
1849
1850 static void add_event_to_ctx(struct perf_event *event,
1851                                struct perf_event_context *ctx)
1852 {
1853         u64 tstamp = perf_event_time(event);
1854
1855         list_add_event(event, ctx);
1856         perf_group_attach(event);
1857         event->tstamp_enabled = tstamp;
1858         event->tstamp_running = tstamp;
1859         event->tstamp_stopped = tstamp;
1860 }
1861
1862 static void task_ctx_sched_out(struct perf_event_context *ctx);
1863 static void
1864 ctx_sched_in(struct perf_event_context *ctx,
1865              struct perf_cpu_context *cpuctx,
1866              enum event_type_t event_type,
1867              struct task_struct *task);
1868
1869 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
1870                                 struct perf_event_context *ctx,
1871                                 struct task_struct *task)
1872 {
1873         cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
1874         if (ctx)
1875                 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
1876         cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
1877         if (ctx)
1878                 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
1879 }
1880
1881 /*
1882  * Cross CPU call to install and enable a performance event
1883  *
1884  * Must be called with ctx->mutex held
1885  */
1886 static int  __perf_install_in_context(void *info)
1887 {
1888         struct perf_event *event = info;
1889         struct perf_event_context *ctx = event->ctx;
1890         struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1891         struct perf_event_context *task_ctx = cpuctx->task_ctx;
1892         struct task_struct *task = current;
1893
1894         perf_ctx_lock(cpuctx, task_ctx);
1895         perf_pmu_disable(cpuctx->ctx.pmu);
1896
1897         /*
1898          * If there was an active task_ctx schedule it out.
1899          */
1900         if (task_ctx)
1901                 task_ctx_sched_out(task_ctx);
1902
1903         /*
1904          * If the context we're installing events in is not the
1905          * active task_ctx, flip them.
1906          */
1907         if (ctx->task && task_ctx != ctx) {
1908                 if (task_ctx)
1909                         raw_spin_unlock(&task_ctx->lock);
1910                 raw_spin_lock(&ctx->lock);
1911                 task_ctx = ctx;
1912         }
1913
1914         if (task_ctx) {
1915                 cpuctx->task_ctx = task_ctx;
1916                 task = task_ctx->task;
1917         }
1918
1919         cpu_ctx_sched_out(cpuctx, EVENT_ALL);
1920
1921         update_context_time(ctx);
1922         /*
1923          * update cgrp time only if current cgrp
1924          * matches event->cgrp. Must be done before
1925          * calling add_event_to_ctx()
1926          */
1927         update_cgrp_time_from_event(event);
1928
1929         add_event_to_ctx(event, ctx);
1930
1931         /*
1932          * Schedule everything back in
1933          */
1934         perf_event_sched_in(cpuctx, task_ctx, task);
1935
1936         perf_pmu_enable(cpuctx->ctx.pmu);
1937         perf_ctx_unlock(cpuctx, task_ctx);
1938
1939         return 0;
1940 }
1941
1942 /*
1943  * Attach a performance event to a context
1944  *
1945  * First we add the event to the list with the hardware enable bit
1946  * in event->hw_config cleared.
1947  *
1948  * If the event is attached to a task which is on a CPU we use a smp
1949  * call to enable it in the task context. The task might have been
1950  * scheduled away, but we check this in the smp call again.
1951  */
1952 static void
1953 perf_install_in_context(struct perf_event_context *ctx,
1954                         struct perf_event *event,
1955                         int cpu)
1956 {
1957         struct task_struct *task = ctx->task;
1958
1959         lockdep_assert_held(&ctx->mutex);
1960
1961         event->ctx = ctx;
1962         if (event->cpu != -1)
1963                 event->cpu = cpu;
1964
1965         if (!task) {
1966                 /*
1967                  * Per cpu events are installed via an smp call and
1968                  * the install is always successful.
1969                  */
1970                 cpu_function_call(cpu, __perf_install_in_context, event);
1971                 return;
1972         }
1973
1974 retry:
1975         if (!task_function_call(task, __perf_install_in_context, event))
1976                 return;
1977
1978         raw_spin_lock_irq(&ctx->lock);
1979         /*
1980          * If we failed to find a running task, but find the context active now
1981          * that we've acquired the ctx->lock, retry.
1982          */
1983         if (ctx->is_active) {
1984                 raw_spin_unlock_irq(&ctx->lock);
1985                 /*
1986                  * Reload the task pointer, it might have been changed by
1987                  * a concurrent perf_event_context_sched_out().
1988                  */
1989                 task = ctx->task;
1990                 goto retry;
1991         }
1992
1993         /*
1994          * Since the task isn't running, its safe to add the event, us holding
1995          * the ctx->lock ensures the task won't get scheduled in.
1996          */
1997         add_event_to_ctx(event, ctx);
1998         raw_spin_unlock_irq(&ctx->lock);
1999 }
2000
2001 /*
2002  * Put a event into inactive state and update time fields.
2003  * Enabling the leader of a group effectively enables all
2004  * the group members that aren't explicitly disabled, so we
2005  * have to update their ->tstamp_enabled also.
2006  * Note: this works for group members as well as group leaders
2007  * since the non-leader members' sibling_lists will be empty.
2008  */
2009 static void __perf_event_mark_enabled(struct perf_event *event)
2010 {
2011         struct perf_event *sub;
2012         u64 tstamp = perf_event_time(event);
2013
2014         event->state = PERF_EVENT_STATE_INACTIVE;
2015         event->tstamp_enabled = tstamp - event->total_time_enabled;
2016         list_for_each_entry(sub, &event->sibling_list, group_entry) {
2017                 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
2018                         sub->tstamp_enabled = tstamp - sub->total_time_enabled;
2019         }
2020 }
2021
2022 /*
2023  * Cross CPU call to enable a performance event
2024  */
2025 static int __perf_event_enable(void *info)
2026 {
2027         struct perf_event *event = info;
2028         struct perf_event_context *ctx = event->ctx;
2029         struct perf_event *leader = event->group_leader;
2030         struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2031         int err;
2032
2033         /*
2034          * There's a time window between 'ctx->is_active' check
2035          * in perf_event_enable function and this place having:
2036          *   - IRQs on
2037          *   - ctx->lock unlocked
2038          *
2039          * where the task could be killed and 'ctx' deactivated
2040          * by perf_event_exit_task.
2041          */
2042         if (!ctx->is_active)
2043                 return -EINVAL;
2044
2045         raw_spin_lock(&ctx->lock);
2046         update_context_time(ctx);
2047
2048         if (event->state >= PERF_EVENT_STATE_INACTIVE)
2049                 goto unlock;
2050
2051         /*
2052          * set current task's cgroup time reference point
2053          */
2054         perf_cgroup_set_timestamp(current, ctx);
2055
2056         __perf_event_mark_enabled(event);
2057
2058         if (!event_filter_match(event)) {
2059                 if (is_cgroup_event(event))
2060                         perf_cgroup_defer_enabled(event);
2061                 goto unlock;
2062         }
2063
2064         /*
2065          * If the event is in a group and isn't the group leader,
2066          * then don't put it on unless the group is on.
2067          */
2068         if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
2069                 goto unlock;
2070
2071         if (!group_can_go_on(event, cpuctx, 1)) {
2072                 err = -EEXIST;
2073         } else {
2074                 if (event == leader)
2075                         err = group_sched_in(event, cpuctx, ctx);
2076                 else
2077                         err = event_sched_in(event, cpuctx, ctx);
2078         }
2079
2080         if (err) {
2081                 /*
2082                  * If this event can't go on and it's part of a
2083                  * group, then the whole group has to come off.
2084                  */
2085                 if (leader != event) {
2086                         group_sched_out(leader, cpuctx, ctx);
2087                         perf_cpu_hrtimer_restart(cpuctx);
2088                 }
2089                 if (leader->attr.pinned) {
2090                         update_group_times(leader);
2091                         leader->state = PERF_EVENT_STATE_ERROR;
2092                 }
2093         }
2094
2095 unlock:
2096         raw_spin_unlock(&ctx->lock);
2097
2098         return 0;
2099 }
2100
2101 /*
2102  * Enable a event.
2103  *
2104  * If event->ctx is a cloned context, callers must make sure that
2105  * every task struct that event->ctx->task could possibly point to
2106  * remains valid.  This condition is satisfied when called through
2107  * perf_event_for_each_child or perf_event_for_each as described
2108  * for perf_event_disable.
2109  */
2110 void perf_event_enable(struct perf_event *event)
2111 {
2112         struct perf_event_context *ctx = event->ctx;
2113         struct task_struct *task = ctx->task;
2114
2115         if (!task) {
2116                 /*
2117                  * Enable the event on the cpu that it's on
2118                  */
2119                 cpu_function_call(event->cpu, __perf_event_enable, event);
2120                 return;
2121         }
2122
2123         raw_spin_lock_irq(&ctx->lock);
2124         if (event->state >= PERF_EVENT_STATE_INACTIVE)
2125                 goto out;
2126
2127         /*
2128          * If the event is in error state, clear that first.
2129          * That way, if we see the event in error state below, we
2130          * know that it has gone back into error state, as distinct
2131          * from the task having been scheduled away before the
2132          * cross-call arrived.
2133          */
2134         if (event->state == PERF_EVENT_STATE_ERROR)
2135                 event->state = PERF_EVENT_STATE_OFF;
2136
2137 retry:
2138         if (!ctx->is_active) {
2139                 __perf_event_mark_enabled(event);
2140                 goto out;
2141         }
2142
2143         raw_spin_unlock_irq(&ctx->lock);
2144
2145         if (!task_function_call(task, __perf_event_enable, event))
2146                 return;
2147
2148         raw_spin_lock_irq(&ctx->lock);
2149
2150         /*
2151          * If the context is active and the event is still off,
2152          * we need to retry the cross-call.
2153          */
2154         if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
2155                 /*
2156                  * task could have been flipped by a concurrent
2157                  * perf_event_context_sched_out()
2158                  */
2159                 task = ctx->task;
2160                 goto retry;
2161         }
2162
2163 out:
2164         raw_spin_unlock_irq(&ctx->lock);
2165 }
2166 EXPORT_SYMBOL_GPL(perf_event_enable);
2167
2168 int perf_event_refresh(struct perf_event *event, int refresh)
2169 {
2170         /*
2171          * not supported on inherited events
2172          */
2173         if (event->attr.inherit || !is_sampling_event(event))
2174                 return -EINVAL;
2175
2176         atomic_add(refresh, &event->event_limit);
2177         perf_event_enable(event);
2178
2179         return 0;
2180 }
2181 EXPORT_SYMBOL_GPL(perf_event_refresh);
2182
2183 static void ctx_sched_out(struct perf_event_context *ctx,
2184                           struct perf_cpu_context *cpuctx,
2185                           enum event_type_t event_type)
2186 {
2187         struct perf_event *event;
2188         int is_active = ctx->is_active;
2189
2190         ctx->is_active &= ~event_type;
2191         if (likely(!ctx->nr_events))
2192                 return;
2193
2194         update_context_time(ctx);
2195         update_cgrp_time_from_cpuctx(cpuctx);
2196         if (!ctx->nr_active)
2197                 return;
2198
2199         perf_pmu_disable(ctx->pmu);
2200         if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
2201                 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
2202                         group_sched_out(event, cpuctx, ctx);
2203         }
2204
2205         if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
2206                 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
2207                         group_sched_out(event, cpuctx, ctx);
2208         }
2209         perf_pmu_enable(ctx->pmu);
2210 }
2211
2212 /*
2213  * Test whether two contexts are equivalent, i.e. whether they have both been
2214  * cloned from the same version of the same context.
2215  *
2216  * Equivalence is measured using a generation number in the context that is
2217  * incremented on each modification to it; see unclone_ctx(), list_add_event()
2218  * and list_del_event().
2219  */
2220 static int context_equiv(struct perf_event_context *ctx1,
2221                          struct perf_event_context *ctx2)
2222 {
2223         lockdep_assert_held(&ctx1->lock);
2224         lockdep_assert_held(&ctx2->lock);
2225
2226         /* Pinning disables the swap optimization */
2227         if (ctx1->pin_count || ctx2->pin_count)
2228                 return 0;
2229
2230         /* If ctx1 is the parent of ctx2 */
2231         if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
2232                 return 1;
2233
2234         /* If ctx2 is the parent of ctx1 */
2235         if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
2236                 return 1;
2237
2238         /*
2239          * If ctx1 and ctx2 have the same parent; we flatten the parent
2240          * hierarchy, see perf_event_init_context().
2241          */
2242         if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
2243                         ctx1->parent_gen == ctx2->parent_gen)
2244                 return 1;
2245
2246         /* Unmatched */
2247         return 0;
2248 }
2249
2250 static void __perf_event_sync_stat(struct perf_event *event,
2251                                      struct perf_event *next_event)
2252 {
2253         u64 value;
2254
2255         if (!event->attr.inherit_stat)
2256                 return;
2257
2258         /*
2259          * Update the event value, we cannot use perf_event_read()
2260          * because we're in the middle of a context switch and have IRQs
2261          * disabled, which upsets smp_call_function_single(), however
2262          * we know the event must be on the current CPU, therefore we
2263          * don't need to use it.
2264          */
2265         switch (event->state) {
2266         case PERF_EVENT_STATE_ACTIVE:
2267                 event->pmu->read(event);
2268                 /* fall-through */
2269
2270         case PERF_EVENT_STATE_INACTIVE:
2271                 update_event_times(event);
2272                 break;
2273
2274         default:
2275                 break;
2276         }
2277
2278         /*
2279          * In order to keep per-task stats reliable we need to flip the event
2280          * values when we flip the contexts.
2281          */
2282         value = local64_read(&next_event->count);
2283         value = local64_xchg(&event->count, value);
2284         local64_set(&next_event->count, value);
2285
2286         swap(event->total_time_enabled, next_event->total_time_enabled);
2287         swap(event->total_time_running, next_event->total_time_running);
2288
2289         /*
2290          * Since we swizzled the values, update the user visible data too.
2291          */
2292         perf_event_update_userpage(event);
2293         perf_event_update_userpage(next_event);
2294 }
2295
2296 static void perf_event_sync_stat(struct perf_event_context *ctx,
2297                                    struct perf_event_context *next_ctx)
2298 {
2299         struct perf_event *event, *next_event;
2300
2301         if (!ctx->nr_stat)
2302                 return;
2303
2304         update_context_time(ctx);
2305
2306         event = list_first_entry(&ctx->event_list,
2307                                    struct perf_event, event_entry);
2308
2309         next_event = list_first_entry(&next_ctx->event_list,
2310                                         struct perf_event, event_entry);
2311
2312         while (&event->event_entry != &ctx->event_list &&
2313                &next_event->event_entry != &next_ctx->event_list) {
2314
2315                 __perf_event_sync_stat(event, next_event);
2316
2317                 event = list_next_entry(event, event_entry);
2318                 next_event = list_next_entry(next_event, event_entry);
2319         }
2320 }
2321
2322 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
2323                                          struct task_struct *next)
2324 {
2325         struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
2326         struct perf_event_context *next_ctx;
2327         struct perf_event_context *parent, *next_parent;
2328         struct perf_cpu_context *cpuctx;
2329         int do_switch = 1;
2330
2331         if (likely(!ctx))
2332                 return;
2333
2334         cpuctx = __get_cpu_context(ctx);
2335         if (!cpuctx->task_ctx)
2336                 return;
2337
2338         rcu_read_lock();
2339         next_ctx = next->perf_event_ctxp[ctxn];
2340         if (!next_ctx)
2341                 goto unlock;
2342
2343         parent = rcu_dereference(ctx->parent_ctx);
2344         next_parent = rcu_dereference(next_ctx->parent_ctx);
2345
2346         /* If neither context have a parent context; they cannot be clones. */
2347         if (!parent || !next_parent)
2348                 goto unlock;
2349
2350         if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
2351                 /*
2352                  * Looks like the two contexts are clones, so we might be
2353                  * able to optimize the context switch.  We lock both
2354                  * contexts and check that they are clones under the
2355                  * lock (including re-checking that neither has been
2356                  * uncloned in the meantime).  It doesn't matter which
2357                  * order we take the locks because no other cpu could
2358                  * be trying to lock both of these tasks.
2359                  */
2360                 raw_spin_lock(&ctx->lock);
2361                 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
2362                 if (context_equiv(ctx, next_ctx)) {
2363                         /*
2364                          * XXX do we need a memory barrier of sorts
2365                          * wrt to rcu_dereference() of perf_event_ctxp
2366                          */
2367                         task->perf_event_ctxp[ctxn] = next_ctx;
2368                         next->perf_event_ctxp[ctxn] = ctx;
2369                         ctx->task = next;
2370                         next_ctx->task = task;
2371                         do_switch = 0;
2372
2373                         perf_event_sync_stat(ctx, next_ctx);
2374                 }
2375                 raw_spin_unlock(&next_ctx->lock);
2376                 raw_spin_unlock(&ctx->lock);
2377         }
2378 unlock:
2379         rcu_read_unlock();
2380
2381         if (do_switch) {
2382                 raw_spin_lock(&ctx->lock);
2383                 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2384                 cpuctx->task_ctx = NULL;
2385                 raw_spin_unlock(&ctx->lock);
2386         }
2387 }
2388
2389 #define for_each_task_context_nr(ctxn)                                  \
2390         for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
2391
2392 /*
2393  * Called from scheduler to remove the events of the current task,
2394  * with interrupts disabled.
2395  *
2396  * We stop each event and update the event value in event->count.
2397  *
2398  * This does not protect us against NMI, but disable()
2399  * sets the disabled bit in the control field of event _before_
2400  * accessing the event control register. If a NMI hits, then it will
2401  * not restart the event.
2402  */
2403 void __perf_event_task_sched_out(struct task_struct *task,
2404                                  struct task_struct *next)
2405 {
2406         int ctxn;
2407
2408         for_each_task_context_nr(ctxn)
2409                 perf_event_context_sched_out(task, ctxn, next);
2410
2411         /*
2412          * if cgroup events exist on this CPU, then we need
2413          * to check if we have to switch out PMU state.
2414          * cgroup event are system-wide mode only
2415          */
2416         if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2417                 perf_cgroup_sched_out(task, next);
2418 }
2419
2420 static void task_ctx_sched_out(struct perf_event_context *ctx)
2421 {
2422         struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2423
2424         if (!cpuctx->task_ctx)
2425                 return;
2426
2427         if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2428                 return;
2429
2430         ctx_sched_out(ctx, cpuctx, EVENT_ALL);
2431         cpuctx->task_ctx = NULL;
2432 }
2433
2434 /*
2435  * Called with IRQs disabled
2436  */
2437 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
2438                               enum event_type_t event_type)
2439 {
2440         ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
2441 }
2442
2443 static void
2444 ctx_pinned_sched_in(struct perf_event_context *ctx,
2445                     struct perf_cpu_context *cpuctx)
2446 {
2447         struct perf_event *event;
2448
2449         list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
2450                 if (event->state <= PERF_EVENT_STATE_OFF)
2451                         continue;
2452                 if (!event_filter_match(event))
2453                         continue;
2454
2455                 /* may need to reset tstamp_enabled */
2456                 if (is_cgroup_event(event))
2457                         perf_cgroup_mark_enabled(event, ctx);
2458
2459                 if (group_can_go_on(event, cpuctx, 1))
2460                         group_sched_in(event, cpuctx, ctx);
2461
2462                 /*
2463                  * If this pinned group hasn't been scheduled,
2464                  * put it in error state.
2465                  */
2466                 if (event->state == PERF_EVENT_STATE_INACTIVE) {
2467                         update_group_times(event);
2468                         event->state = PERF_EVENT_STATE_ERROR;
2469                 }
2470         }
2471 }
2472
2473 static void
2474 ctx_flexible_sched_in(struct perf_event_context *ctx,
2475                       struct perf_cpu_context *cpuctx)
2476 {
2477         struct perf_event *event;
2478         int can_add_hw = 1;
2479
2480         list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
2481                 /* Ignore events in OFF or ERROR state */
2482                 if (event->state <= PERF_EVENT_STATE_OFF)
2483                         continue;
2484                 /*
2485                  * Listen to the 'cpu' scheduling filter constraint
2486                  * of events:
2487                  */
2488                 if (!event_filter_match(event))
2489                         continue;
2490
2491                 /* may need to reset tstamp_enabled */
2492                 if (is_cgroup_event(event))
2493                         perf_cgroup_mark_enabled(event, ctx);
2494
2495                 if (group_can_go_on(event, cpuctx, can_add_hw)) {
2496                         if (group_sched_in(event, cpuctx, ctx))
2497                                 can_add_hw = 0;
2498                 }
2499         }
2500 }
2501
2502 static void
2503 ctx_sched_in(struct perf_event_context *ctx,
2504              struct perf_cpu_context *cpuctx,
2505              enum event_type_t event_type,
2506              struct task_struct *task)
2507 {
2508         u64 now;
2509         int is_active = ctx->is_active;
2510
2511         ctx->is_active |= event_type;
2512         if (likely(!ctx->nr_events))
2513                 return;
2514
2515         now = perf_clock();
2516         ctx->timestamp = now;
2517         perf_cgroup_set_timestamp(task, ctx);
2518         /*
2519          * First go through the list and put on any pinned groups
2520          * in order to give them the best chance of going on.
2521          */
2522         if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
2523                 ctx_pinned_sched_in(ctx, cpuctx);
2524
2525         /* Then walk through the lower prio flexible groups */
2526         if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
2527                 ctx_flexible_sched_in(ctx, cpuctx);
2528 }
2529
2530 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
2531                              enum event_type_t event_type,
2532                              struct task_struct *task)
2533 {
2534         struct perf_event_context *ctx = &cpuctx->ctx;
2535
2536         ctx_sched_in(ctx, cpuctx, event_type, task);
2537 }
2538
2539 static void perf_event_context_sched_in(struct perf_event_context *ctx,
2540                                         struct task_struct *task)
2541 {
2542         struct perf_cpu_context *cpuctx;
2543
2544         cpuctx = __get_cpu_context(ctx);
2545         if (cpuctx->task_ctx == ctx)
2546                 return;
2547
2548         perf_ctx_lock(cpuctx, ctx);
2549         perf_pmu_disable(ctx->pmu);
2550         /*
2551          * We want to keep the following priority order:
2552          * cpu pinned (that don't need to move), task pinned,
2553          * cpu flexible, task flexible.
2554          */
2555         cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2556
2557         if (ctx->nr_events)
2558                 cpuctx->task_ctx = ctx;
2559
2560         perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
2561
2562         perf_pmu_enable(ctx->pmu);
2563         perf_ctx_unlock(cpuctx, ctx);
2564
2565         /*
2566          * Since these rotations are per-cpu, we need to ensure the
2567          * cpu-context we got scheduled on is actually rotating.
2568          */
2569         perf_pmu_rotate_start(ctx->pmu);
2570 }
2571
2572 /*
2573  * When sampling the branck stack in system-wide, it may be necessary
2574  * to flush the stack on context switch. This happens when the branch
2575  * stack does not tag its entries with the pid of the current task.
2576  * Otherwise it becomes impossible to associate a branch entry with a
2577  * task. This ambiguity is more likely to appear when the branch stack
2578  * supports priv level filtering and the user sets it to monitor only
2579  * at the user level (which could be a useful measurement in system-wide
2580  * mode). In that case, the risk is high of having a branch stack with
2581  * branch from multiple tasks. Flushing may mean dropping the existing
2582  * entries or stashing them somewhere in the PMU specific code layer.
2583  *
2584  * This function provides the context switch callback to the lower code
2585  * layer. It is invoked ONLY when there is at least one system-wide context
2586  * with at least one active event using taken branch sampling.
2587  */
2588 static void perf_branch_stack_sched_in(struct task_struct *prev,
2589                                        struct task_struct *task)
2590 {
2591         struct perf_cpu_context *cpuctx;
2592         struct pmu *pmu;
2593         unsigned long flags;
2594
2595         /* no need to flush branch stack if not changing task */
2596         if (prev == task)
2597                 return;
2598
2599         local_irq_save(flags);
2600
2601         rcu_read_lock();
2602
2603         list_for_each_entry_rcu(pmu, &pmus, entry) {
2604                 cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2605
2606                 /*
2607                  * check if the context has at least one
2608                  * event using PERF_SAMPLE_BRANCH_STACK
2609                  */
2610                 if (cpuctx->ctx.nr_branch_stack > 0
2611                     && pmu->flush_branch_stack) {
2612
2613                         perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2614
2615                         perf_pmu_disable(pmu);
2616
2617                         pmu->flush_branch_stack();
2618
2619                         perf_pmu_enable(pmu);
2620
2621                         perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2622                 }
2623         }
2624
2625         rcu_read_unlock();
2626
2627         local_irq_restore(flags);
2628 }
2629
2630 /*
2631  * Called from scheduler to add the events of the current task
2632  * with interrupts disabled.
2633  *
2634  * We restore the event value and then enable it.
2635  *
2636  * This does not protect us against NMI, but enable()
2637  * sets the enabled bit in the control field of event _before_
2638  * accessing the event control register. If a NMI hits, then it will
2639  * keep the event running.
2640  */
2641 void __perf_event_task_sched_in(struct task_struct *prev,
2642                                 struct task_struct *task)
2643 {
2644         struct perf_event_context *ctx;
2645         int ctxn;
2646
2647         for_each_task_context_nr(ctxn) {
2648                 ctx = task->perf_event_ctxp[ctxn];
2649                 if (likely(!ctx))
2650                         continue;
2651
2652                 perf_event_context_sched_in(ctx, task);
2653         }
2654         /*
2655          * if cgroup events exist on this CPU, then we need
2656          * to check if we have to switch in PMU state.
2657          * cgroup event are system-wide mode only
2658          */
2659         if (atomic_read(&__get_cpu_var(perf_cgroup_events)))
2660                 perf_cgroup_sched_in(prev, task);
2661
2662         /* check for system-wide branch_stack events */
2663         if (atomic_read(&__get_cpu_var(perf_branch_stack_events)))
2664                 perf_branch_stack_sched_in(prev, task);
2665 }
2666
2667 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
2668 {
2669         u64 frequency = event->attr.sample_freq;
2670         u64 sec = NSEC_PER_SEC;
2671         u64 divisor, dividend;
2672
2673         int count_fls, nsec_fls, frequency_fls, sec_fls;
2674
2675         count_fls = fls64(count);
2676         nsec_fls = fls64(nsec);
2677         frequency_fls = fls64(frequency);
2678         sec_fls = 30;
2679
2680         /*
2681          * We got @count in @nsec, with a target of sample_freq HZ
2682          * the target period becomes:
2683          *
2684          *             @count * 10^9
2685          * period = -------------------
2686          *          @nsec * sample_freq
2687          *
2688          */
2689
2690         /*
2691          * Reduce accuracy by one bit such that @a and @b converge
2692          * to a similar magnitude.
2693          */
2694 #define REDUCE_FLS(a, b)                \
2695 do {                                    \
2696         if (a##_fls > b##_fls) {        \
2697                 a >>= 1;                \
2698                 a##_fls--;              \
2699         } else {                        \
2700                 b >>= 1;                \
2701                 b##_fls--;              \
2702         }                               \
2703 } while (0)
2704
2705         /*
2706          * Reduce accuracy until either term fits in a u64, then proceed with
2707          * the other, so that finally we can do a u64/u64 division.
2708          */
2709         while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
2710                 REDUCE_FLS(nsec, frequency);
2711                 REDUCE_FLS(sec, count);
2712         }
2713
2714         if (count_fls + sec_fls > 64) {
2715                 divisor = nsec * frequency;
2716
2717                 while (count_fls + sec_fls > 64) {
2718                         REDUCE_FLS(count, sec);
2719                         divisor >>= 1;
2720                 }
2721
2722                 dividend = count * sec;
2723         } else {
2724                 dividend = count * sec;
2725
2726                 while (nsec_fls + frequency_fls > 64) {
2727                         REDUCE_FLS(nsec, frequency);
2728                         dividend >>= 1;
2729                 }
2730
2731                 divisor = nsec * frequency;
2732         }
2733
2734         if (!divisor)
2735                 return dividend;
2736
2737         return div64_u64(dividend, divisor);
2738 }
2739
2740 static DEFINE_PER_CPU(int, perf_throttled_count);
2741 static DEFINE_PER_CPU(u64, perf_throttled_seq);
2742
2743 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
2744 {
2745         struct hw_perf_event *hwc = &event->hw;
2746         s64 period, sample_period;
2747         s64 delta;
2748
2749         period = perf_calculate_period(event, nsec, count);
2750
2751         delta = (s64)(period - hwc->sample_period);
2752         delta = (delta + 7) / 8; /* low pass filter */
2753
2754         sample_period = hwc->sample_period + delta;
2755
2756         if (!sample_period)
2757                 sample_period = 1;
2758
2759         hwc->sample_period = sample_period;
2760
2761         if (local64_read(&hwc->period_left) > 8*sample_period) {
2762                 if (disable)
2763                         event->pmu->stop(event, PERF_EF_UPDATE);
2764
2765                 local64_set(&hwc->period_left, 0);
2766
2767                 if (disable)
2768                         event->pmu->start(event, PERF_EF_RELOAD);
2769         }
2770 }
2771
2772 /*
2773  * combine freq adjustment with unthrottling to avoid two passes over the
2774  * events. At the same time, make sure, having freq events does not change
2775  * the rate of unthrottling as that would introduce bias.
2776  */
2777 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
2778                                            int needs_unthr)
2779 {
2780         struct perf_event *event;
2781         struct hw_perf_event *hwc;
2782         u64 now, period = TICK_NSEC;
2783         s64 delta;
2784
2785         /*
2786          * only need to iterate over all events iff:
2787          * - context have events in frequency mode (needs freq adjust)
2788          * - there are events to unthrottle on this cpu
2789          */
2790         if (!(ctx->nr_freq || needs_unthr))
2791                 return;
2792
2793         raw_spin_lock(&ctx->lock);
2794         perf_pmu_disable(ctx->pmu);
2795
2796         list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
2797                 if (event->state != PERF_EVENT_STATE_ACTIVE)
2798                         continue;
2799
2800                 if (!event_filter_match(event))
2801                         continue;
2802
2803                 perf_pmu_disable(event->pmu);
2804
2805                 hwc = &event->hw;
2806
2807                 if (hwc->interrupts == MAX_INTERRUPTS) {
2808                         hwc->interrupts = 0;
2809                         perf_log_throttle(event, 1);
2810                         event->pmu->start(event, 0);
2811                 }
2812
2813                 if (!event->attr.freq || !event->attr.sample_freq)
2814                         goto next;
2815
2816                 /*
2817                  * stop the event and update event->count
2818                  */
2819                 event->pmu->stop(event, PERF_EF_UPDATE);
2820
2821                 now = local64_read(&event->count);
2822                 delta = now - hwc->freq_count_stamp;
2823                 hwc->freq_count_stamp = now;
2824
2825                 /*
2826                  * restart the event
2827                  * reload only if value has changed
2828                  * we have stopped the event so tell that
2829                  * to perf_adjust_period() to avoid stopping it
2830                  * twice.
2831                  */
2832                 if (delta > 0)
2833                         perf_adjust_period(event, period, delta, false);
2834
2835                 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
2836         next:
2837                 perf_pmu_enable(event->pmu);
2838         }
2839
2840         perf_pmu_enable(ctx->pmu);
2841         raw_spin_unlock(&ctx->lock);
2842 }
2843
2844 /*
2845  * Round-robin a context's events:
2846  */
2847 static void rotate_ctx(struct perf_event_context *ctx)
2848 {
2849         /*
2850          * Rotate the first entry last of non-pinned groups. Rotation might be
2851          * disabled by the inheritance code.
2852          */
2853         if (!ctx->rotate_disable)
2854                 list_rotate_left(&ctx->flexible_groups);
2855 }
2856
2857 /*
2858  * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
2859  * because they're strictly cpu affine and rotate_start is called with IRQs
2860  * disabled, while rotate_context is called from IRQ context.
2861  */
2862 static int perf_rotate_context(struct perf_cpu_context *cpuctx)
2863 {
2864         struct perf_event_context *ctx = NULL;
2865         int rotate = 0, remove = 1;
2866
2867         if (cpuctx->ctx.nr_events) {
2868                 remove = 0;
2869                 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
2870                         rotate = 1;
2871         }
2872
2873         ctx = cpuctx->task_ctx;
2874         if (ctx && ctx->nr_events) {
2875                 remove = 0;
2876                 if (ctx->nr_events != ctx->nr_active)
2877                         rotate = 1;
2878         }
2879
2880         if (!rotate)
2881                 goto done;
2882
2883         perf_ctx_lock(cpuctx, cpuctx->task_ctx);
2884         perf_pmu_disable(cpuctx->ctx.pmu);
2885
2886         cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2887         if (ctx)
2888                 ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
2889
2890         rotate_ctx(&cpuctx->ctx);
2891         if (ctx)
2892                 rotate_ctx(ctx);
2893
2894         perf_event_sched_in(cpuctx, ctx, current);
2895
2896         perf_pmu_enable(cpuctx->ctx.pmu);
2897         perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
2898 done:
2899         if (remove)
2900                 list_del_init(&cpuctx->rotation_list);
2901
2902         return rotate;
2903 }
2904
2905 #ifdef CONFIG_NO_HZ_FULL
2906 bool perf_event_can_stop_tick(void)
2907 {
2908         if (atomic_read(&nr_freq_events) ||
2909             __this_cpu_read(perf_throttled_count))
2910                 return false;
2911         else
2912                 return true;
2913 }
2914 #endif
2915
2916 void perf_event_task_tick(void)
2917 {
2918         struct list_head *head = &__get_cpu_var(rotation_list);
2919         struct perf_cpu_context *cpuctx, *tmp;
2920         struct perf_event_context *ctx;
2921         int throttled;
2922
2923         WARN_ON(!irqs_disabled());
2924
2925         __this_cpu_inc(perf_throttled_seq);
2926         throttled = __this_cpu_xchg(perf_throttled_count, 0);
2927
2928         list_for_each_entry_safe(cpuctx, tmp, head, rotation_list) {
2929                 ctx = &cpuctx->ctx;
2930                 perf_adjust_freq_unthr_context(ctx, throttled);
2931
2932                 ctx = cpuctx->task_ctx;
2933                 if (ctx)
2934                         perf_adjust_freq_unthr_context(ctx, throttled);
2935         }
2936 }
2937
2938 static int event_enable_on_exec(struct perf_event *event,
2939                                 struct perf_event_context *ctx)
2940 {
2941         if (!event->attr.enable_on_exec)
2942                 return 0;
2943
2944         event->attr.enable_on_exec = 0;
2945         if (event->state >= PERF_EVENT_STATE_INACTIVE)
2946                 return 0;
2947
2948         __perf_event_mark_enabled(event);
2949
2950         return 1;
2951 }
2952
2953 /*
2954  * Enable all of a task's events that have been marked enable-on-exec.
2955  * This expects task == current.
2956  */
2957 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
2958 {
2959         struct perf_event_context *clone_ctx = NULL;
2960         struct perf_event *event;
2961         unsigned long flags;
2962         int enabled = 0;
2963         int ret;
2964
2965         local_irq_save(flags);
2966         if (!ctx || !ctx->nr_events)
2967                 goto out;
2968
2969         /*
2970          * We must ctxsw out cgroup events to avoid conflict
2971          * when invoking perf_task_event_sched_in() later on
2972          * in this function. Otherwise we end up trying to
2973          * ctxswin cgroup events which are already scheduled
2974          * in.
2975          */
2976         perf_cgroup_sched_out(current, NULL);
2977
2978         raw_spin_lock(&ctx->lock);
2979         task_ctx_sched_out(ctx);
2980
2981         list_for_each_entry(event, &ctx->event_list, event_entry) {
2982                 ret = event_enable_on_exec(event, ctx);
2983                 if (ret)
2984                         enabled = 1;
2985         }
2986
2987         /*
2988          * Unclone this context if we enabled any event.
2989          */
2990         if (enabled)
2991                 clone_ctx = unclone_ctx(ctx);
2992
2993         raw_spin_unlock(&ctx->lock);
2994
2995         /*
2996          * Also calls ctxswin for cgroup events, if any:
2997          */
2998         perf_event_context_sched_in(ctx, ctx->task);
2999 out:
3000         local_irq_restore(flags);
3001
3002         if (clone_ctx)
3003                 put_ctx(clone_ctx);
3004 }
3005
3006 void perf_event_exec(void)
3007 {
3008         struct perf_event_context *ctx;
3009         int ctxn;
3010
3011         rcu_read_lock();
3012         for_each_task_context_nr(ctxn) {
3013                 ctx = current->perf_event_ctxp[ctxn];
3014                 if (!ctx)
3015                         continue;
3016
3017                 perf_event_enable_on_exec(ctx);
3018         }
3019         rcu_read_unlock();
3020 }
3021
3022 /*
3023  * Cross CPU call to read the hardware event
3024  */
3025 static void __perf_event_read(void *info)
3026 {
3027         struct perf_event *event = info;
3028         struct perf_event_context *ctx = event->ctx;
3029         struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3030
3031         /*
3032          * If this is a task context, we need to check whether it is
3033          * the current task context of this cpu.  If not it has been
3034          * scheduled out before the smp call arrived.  In that case
3035          * event->count would have been updated to a recent sample
3036          * when the event was scheduled out.
3037          */
3038         if (ctx->task && cpuctx->task_ctx != ctx)
3039                 return;
3040
3041         raw_spin_lock(&ctx->lock);
3042         if (ctx->is_active) {
3043                 update_context_time(ctx);
3044                 update_cgrp_time_from_event(event);
3045         }
3046         update_event_times(event);
3047         if (event->state == PERF_EVENT_STATE_ACTIVE)
3048                 event->pmu->read(event);
3049         raw_spin_unlock(&ctx->lock);
3050 }
3051
3052 static inline u64 perf_event_count(struct perf_event *event)
3053 {
3054         return local64_read(&event->count) + atomic64_read(&event->child_count);
3055 }
3056
3057 static u64 perf_event_read(struct perf_event *event)
3058 {
3059         /*
3060          * If event is enabled and currently active on a CPU, update the
3061          * value in the event structure:
3062          */
3063         if (event->state == PERF_EVENT_STATE_ACTIVE) {
3064                 smp_call_function_single(event->oncpu,
3065                                          __perf_event_read, event, 1);
3066         } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
3067                 struct perf_event_context *ctx = event->ctx;
3068                 unsigned long flags;
3069
3070                 raw_spin_lock_irqsave(&ctx->lock, flags);
3071                 /*
3072                  * may read while context is not active
3073                  * (e.g., thread is blocked), in that case
3074                  * we cannot update context time
3075                  */
3076                 if (ctx->is_active) {
3077                         update_context_time(ctx);
3078                         update_cgrp_time_from_event(event);
3079                 }
3080                 update_event_times(event);
3081                 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3082         }
3083
3084         return perf_event_count(event);
3085 }
3086
3087 /*
3088  * Initialize the perf_event context in a task_struct:
3089  */
3090 static void __perf_event_init_context(struct perf_event_context *ctx)
3091 {
3092         raw_spin_lock_init(&ctx->lock);
3093         mutex_init(&ctx->mutex);
3094         INIT_LIST_HEAD(&ctx->pinned_groups);
3095         INIT_LIST_HEAD(&ctx->flexible_groups);
3096         INIT_LIST_HEAD(&ctx->event_list);
3097         atomic_set(&ctx->refcount, 1);
3098 }
3099
3100 static struct perf_event_context *
3101 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3102 {
3103         struct perf_event_context *ctx;
3104
3105         ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3106         if (!ctx)
3107                 return NULL;
3108
3109         __perf_event_init_context(ctx);
3110         if (task) {
3111                 ctx->task = task;
3112                 get_task_struct(task);
3113         }
3114         ctx->pmu = pmu;
3115
3116         return ctx;
3117 }
3118
3119 static struct task_struct *
3120 find_lively_task_by_vpid(pid_t vpid)
3121 {
3122         struct task_struct *task;
3123         int err;
3124
3125         rcu_read_lock();
3126         if (!vpid)
3127                 task = current;
3128         else
3129                 task = find_task_by_vpid(vpid);
3130         if (task)
3131                 get_task_struct(task);
3132         rcu_read_unlock();
3133
3134         if (!task)
3135                 return ERR_PTR(-ESRCH);
3136
3137         /* Reuse ptrace permission checks for now. */
3138         err = -EACCES;
3139         if (!ptrace_may_access(task, PTRACE_MODE_READ))
3140                 goto errout;
3141
3142         return task;
3143 errout:
3144         put_task_struct(task);
3145         return ERR_PTR(err);
3146
3147 }
3148
3149 /*
3150  * Returns a matching context with refcount and pincount.
3151  */
3152 static struct perf_event_context *
3153 find_get_context(struct pmu *pmu, struct task_struct *task, int cpu)
3154 {
3155         struct perf_event_context *ctx, *clone_ctx = NULL;
3156         struct perf_cpu_context *cpuctx;
3157         unsigned long flags;
3158         int ctxn, err;
3159
3160         if (!task) {
3161                 /* Must be root to operate on a CPU event: */
3162                 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
3163                         return ERR_PTR(-EACCES);
3164
3165                 /*
3166                  * We could be clever and allow to attach a event to an
3167                  * offline CPU and activate it when the CPU comes up, but
3168                  * that's for later.
3169                  */
3170                 if (!cpu_online(cpu))
3171                         return ERR_PTR(-ENODEV);
3172
3173                 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
3174                 ctx = &cpuctx->ctx;
3175                 get_ctx(ctx);
3176                 ++ctx->pin_count;
3177
3178                 return ctx;
3179         }
3180
3181         err = -EINVAL;
3182         ctxn = pmu->task_ctx_nr;
3183         if (ctxn < 0)
3184                 goto errout;
3185
3186 retry:
3187         ctx = perf_lock_task_context(task, ctxn, &flags);
3188         if (ctx) {
3189                 clone_ctx = unclone_ctx(ctx);
3190                 ++ctx->pin_count;
3191                 raw_spin_unlock_irqrestore(&ctx->lock, flags);
3192
3193                 if (clone_ctx)
3194                         put_ctx(clone_ctx);
3195         } else {
3196                 ctx = alloc_perf_context(pmu, task);
3197                 err = -ENOMEM;
3198                 if (!ctx)
3199                         goto errout;
3200
3201                 err = 0;
3202                 mutex_lock(&task->perf_event_mutex);
3203                 /*
3204                  * If it has already passed perf_event_exit_task().
3205                  * we must see PF_EXITING, it takes this mutex too.
3206                  */
3207                 if (task->flags & PF_EXITING)
3208                         err = -ESRCH;
3209                 else if (task->perf_event_ctxp[ctxn])
3210                         err = -EAGAIN;
3211                 else {
3212                         get_ctx(ctx);
3213                         ++ctx->pin_count;
3214                         rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
3215                 }
3216                 mutex_unlock(&task->perf_event_mutex);
3217
3218                 if (unlikely(err)) {
3219                         put_ctx(ctx);
3220
3221                         if (err == -EAGAIN)
3222                                 goto retry;
3223                         goto errout;
3224                 }
3225         }
3226
3227         return ctx;
3228
3229 errout:
3230         return ERR_PTR(err);
3231 }
3232
3233 static void perf_event_free_filter(struct perf_event *event);
3234
3235 static void free_event_rcu(struct rcu_head *head)
3236 {
3237         struct perf_event *event;
3238
3239         event = container_of(head, struct perf_event, rcu_head);
3240         if (event->ns)
3241                 put_pid_ns(event->ns);
3242         perf_event_free_filter(event);
3243         kfree(event);
3244 }
3245
3246 static void ring_buffer_put(struct ring_buffer *rb);
3247 static void ring_buffer_attach(struct perf_event *event,
3248                                struct ring_buffer *rb);
3249
3250 static void unaccount_event_cpu(struct perf_event *event, int cpu)
3251 {
3252         if (event->parent)
3253                 return;
3254
3255         if (has_branch_stack(event)) {
3256                 if (!(event->attach_state & PERF_ATTACH_TASK))
3257                         atomic_dec(&per_cpu(perf_branch_stack_events, cpu));
3258         }
3259         if (is_cgroup_event(event))
3260                 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3261 }
3262
3263 static void unaccount_event(struct perf_event *event)
3264 {
3265         if (event->parent)
3266                 return;
3267
3268         if (event->attach_state & PERF_ATTACH_TASK)
3269                 static_key_slow_dec_deferred(&perf_sched_events);
3270         if (event->attr.mmap || event->attr.mmap_data)
3271                 atomic_dec(&nr_mmap_events);
3272         if (event->attr.comm)
3273                 atomic_dec(&nr_comm_events);
3274         if (event->attr.task)
3275                 atomic_dec(&nr_task_events);
3276         if (event->attr.freq)
3277                 atomic_dec(&nr_freq_events);
3278         if (is_cgroup_event(event))
3279                 static_key_slow_dec_deferred(&perf_sched_events);
3280         if (has_branch_stack(event))
3281                 static_key_slow_dec_deferred(&perf_sched_events);
3282
3283         unaccount_event_cpu(event, event->cpu);
3284 }
3285
3286 static void __free_event(struct perf_event *event)
3287 {
3288         if (!event->parent) {
3289                 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3290                         put_callchain_buffers();
3291         }
3292
3293         if (event->destroy)
3294                 event->destroy(event);
3295
3296         if (event->ctx)
3297                 put_ctx(event->ctx);
3298
3299         if (event->pmu)
3300                 module_put(event->pmu->module);
3301
3302         call_rcu(&event->rcu_head, free_event_rcu);
3303 }
3304
3305 static void _free_event(struct perf_event *event)
3306 {
3307         irq_work_sync(&event->pending);
3308
3309         unaccount_event(event);
3310
3311         if (event->rb) {
3312                 /*
3313                  * Can happen when we close an event with re-directed output.
3314                  *
3315                  * Since we have a 0 refcount, perf_mmap_close() will skip
3316                  * over us; possibly making our ring_buffer_put() the last.
3317                  */
3318                 mutex_lock(&event->mmap_mutex);
3319                 ring_buffer_attach(event, NULL);
3320                 mutex_unlock(&event->mmap_mutex);
3321         }
3322
3323         if (is_cgroup_event(event))
3324                 perf_detach_cgroup(event);
3325
3326         __free_event(event);
3327 }
3328
3329 /*
3330  * Used to free events which have a known refcount of 1, such as in error paths
3331  * where the event isn't exposed yet and inherited events.
3332  */
3333 static void free_event(struct perf_event *event)
3334 {
3335         if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3336                                 "unexpected event refcount: %ld; ptr=%p\n",
3337                                 atomic_long_read(&event->refcount), event)) {
3338                 /* leak to avoid use-after-free */
3339                 return;
3340         }
3341
3342         _free_event(event);
3343 }
3344
3345 /*
3346  * Called when the last reference to the file is gone.
3347  */
3348 static void put_event(struct perf_event *event)
3349 {
3350         struct perf_event_context *ctx = event->ctx;
3351         struct task_struct *owner;
3352
3353         if (!atomic_long_dec_and_test(&event->refcount))
3354                 return;
3355
3356         rcu_read_lock();
3357         owner = ACCESS_ONCE(event->owner);
3358         /*
3359          * Matches the smp_wmb() in perf_event_exit_task(). If we observe
3360          * !owner it means the list deletion is complete and we can indeed
3361          * free this event, otherwise we need to serialize on
3362          * owner->perf_event_mutex.
3363          */
3364         smp_read_barrier_depends();
3365         if (owner) {
3366                 /*
3367                  * Since delayed_put_task_struct() also drops the last
3368                  * task reference we can safely take a new reference
3369                  * while holding the rcu_read_lock().
3370                  */
3371                 get_task_struct(owner);
3372         }
3373         rcu_read_unlock();
3374
3375         if (owner) {
3376                 mutex_lock(&owner->perf_event_mutex);
3377                 /*
3378                  * We have to re-check the event->owner field, if it is cleared
3379                  * we raced with perf_event_exit_task(), acquiring the mutex
3380                  * ensured they're done, and we can proceed with freeing the
3381                  * event.
3382                  */
3383                 if (event->owner)
3384                         list_del_init(&event->owner_entry);
3385                 mutex_unlock(&owner->perf_event_mutex);
3386                 put_task_struct(owner);
3387         }
3388
3389         WARN_ON_ONCE(ctx->parent_ctx);
3390         /*
3391          * There are two ways this annotation is useful:
3392          *
3393          *  1) there is a lock recursion from perf_event_exit_task
3394          *     see the comment there.
3395          *
3396          *  2) there is a lock-inversion with mmap_sem through
3397          *     perf_event_read_group(), which takes faults while
3398          *     holding ctx->mutex, however this is called after
3399          *     the last filedesc died, so there is no possibility
3400          *     to trigger the AB-BA case.
3401          */
3402         mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING);
3403         perf_remove_from_context(event, true);
3404         mutex_unlock(&ctx->mutex);
3405
3406         _free_event(event);
3407 }
3408
3409 int perf_event_release_kernel(struct perf_event *event)
3410 {
3411         put_event(event);
3412         return 0;
3413 }
3414 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3415
3416 static int perf_release(struct inode *inode, struct file *file)
3417 {
3418         put_event(file->private_data);
3419         return 0;
3420 }
3421
3422 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
3423 {
3424         struct perf_event *child;
3425         u64 total = 0;
3426