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