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