1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Performance events core code:
4 *
5 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
6 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
7 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
8 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
9 */
10
11 #include <linux/fs.h>
12 #include <linux/mm.h>
13 #include <linux/cpu.h>
14 #include <linux/smp.h>
15 #include <linux/idr.h>
16 #include <linux/file.h>
17 #include <linux/poll.h>
18 #include <linux/slab.h>
19 #include <linux/hash.h>
20 #include <linux/tick.h>
21 #include <linux/sysfs.h>
22 #include <linux/dcache.h>
23 #include <linux/percpu.h>
24 #include <linux/ptrace.h>
25 #include <linux/reboot.h>
26 #include <linux/vmstat.h>
27 #include <linux/device.h>
28 #include <linux/export.h>
29 #include <linux/vmalloc.h>
30 #include <linux/hardirq.h>
31 #include <linux/hugetlb.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 #include <linux/namei.h>
48 #include <linux/parser.h>
49 #include <linux/sched/clock.h>
50 #include <linux/sched/mm.h>
51 #include <linux/proc_ns.h>
52 #include <linux/mount.h>
53 #include <linux/min_heap.h>
54 #include <linux/highmem.h>
55 #include <linux/pgtable.h>
56 #include <linux/buildid.h>
57 #include <linux/task_work.h>
58 #include <linux/percpu-rwsem.h>
59
60 #include "internal.h"
61
62 #include <asm/irq_regs.h>
63
64 typedef int (*remote_function_f)(void *);
65
66 struct remote_function_call {
67 struct task_struct *p;
68 remote_function_f func;
69 void *info;
70 int ret;
71 };
72
remote_function(void * data)73 static void remote_function(void *data)
74 {
75 struct remote_function_call *tfc = data;
76 struct task_struct *p = tfc->p;
77
78 if (p) {
79 /* -EAGAIN */
80 if (task_cpu(p) != smp_processor_id())
81 return;
82
83 /*
84 * Now that we're on right CPU with IRQs disabled, we can test
85 * if we hit the right task without races.
86 */
87
88 tfc->ret = -ESRCH; /* No such (running) process */
89 if (p != current)
90 return;
91 }
92
93 tfc->ret = tfc->func(tfc->info);
94 }
95
96 /**
97 * task_function_call - call a function on the cpu on which a task runs
98 * @p: the task to evaluate
99 * @func: the function to be called
100 * @info: the function call argument
101 *
102 * Calls the function @func when the task is currently running. This might
103 * be on the current CPU, which just calls the function directly. This will
104 * retry due to any failures in smp_call_function_single(), such as if the
105 * task_cpu() goes offline concurrently.
106 *
107 * returns @func return value or -ESRCH or -ENXIO when the process isn't running
108 */
109 static int
task_function_call(struct task_struct * p,remote_function_f func,void * info)110 task_function_call(struct task_struct *p, remote_function_f func, void *info)
111 {
112 struct remote_function_call data = {
113 .p = p,
114 .func = func,
115 .info = info,
116 .ret = -EAGAIN,
117 };
118 int ret;
119
120 for (;;) {
121 ret = smp_call_function_single(task_cpu(p), remote_function,
122 &data, 1);
123 if (!ret)
124 ret = data.ret;
125
126 if (ret != -EAGAIN)
127 break;
128
129 cond_resched();
130 }
131
132 return ret;
133 }
134
135 /**
136 * cpu_function_call - call a function on the cpu
137 * @cpu: target cpu to queue this function
138 * @func: the function to be called
139 * @info: the function call argument
140 *
141 * Calls the function @func on the remote cpu.
142 *
143 * returns: @func return value or -ENXIO when the cpu is offline
144 */
cpu_function_call(int cpu,remote_function_f func,void * info)145 static int cpu_function_call(int cpu, remote_function_f func, void *info)
146 {
147 struct remote_function_call data = {
148 .p = NULL,
149 .func = func,
150 .info = info,
151 .ret = -ENXIO, /* No such CPU */
152 };
153
154 smp_call_function_single(cpu, remote_function, &data, 1);
155
156 return data.ret;
157 }
158
159 enum event_type_t {
160 EVENT_FLEXIBLE = 0x01,
161 EVENT_PINNED = 0x02,
162 EVENT_TIME = 0x04,
163 EVENT_FROZEN = 0x08,
164 /* see ctx_resched() for details */
165 EVENT_CPU = 0x10,
166 EVENT_CGROUP = 0x20,
167
168 /* compound helpers */
169 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
170 EVENT_TIME_FROZEN = EVENT_TIME | EVENT_FROZEN,
171 };
172
__perf_ctx_lock(struct perf_event_context * ctx)173 static inline void __perf_ctx_lock(struct perf_event_context *ctx)
174 {
175 raw_spin_lock(&ctx->lock);
176 WARN_ON_ONCE(ctx->is_active & EVENT_FROZEN);
177 }
178
perf_ctx_lock(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)179 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
180 struct perf_event_context *ctx)
181 {
182 __perf_ctx_lock(&cpuctx->ctx);
183 if (ctx)
184 __perf_ctx_lock(ctx);
185 }
186
__perf_ctx_unlock(struct perf_event_context * ctx)187 static inline void __perf_ctx_unlock(struct perf_event_context *ctx)
188 {
189 /*
190 * If ctx_sched_in() didn't again set any ALL flags, clean up
191 * after ctx_sched_out() by clearing is_active.
192 */
193 if (ctx->is_active & EVENT_FROZEN) {
194 if (!(ctx->is_active & EVENT_ALL))
195 ctx->is_active = 0;
196 else
197 ctx->is_active &= ~EVENT_FROZEN;
198 }
199 raw_spin_unlock(&ctx->lock);
200 }
201
perf_ctx_unlock(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)202 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
203 struct perf_event_context *ctx)
204 {
205 if (ctx)
206 __perf_ctx_unlock(ctx);
207 __perf_ctx_unlock(&cpuctx->ctx);
208 }
209
210 #define TASK_TOMBSTONE ((void *)-1L)
211
is_kernel_event(struct perf_event * event)212 static bool is_kernel_event(struct perf_event *event)
213 {
214 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
215 }
216
217 static DEFINE_PER_CPU(struct perf_cpu_context, perf_cpu_context);
218
perf_cpu_task_ctx(void)219 struct perf_event_context *perf_cpu_task_ctx(void)
220 {
221 lockdep_assert_irqs_disabled();
222 return this_cpu_ptr(&perf_cpu_context)->task_ctx;
223 }
224
225 /*
226 * On task ctx scheduling...
227 *
228 * When !ctx->nr_events a task context will not be scheduled. This means
229 * we can disable the scheduler hooks (for performance) without leaving
230 * pending task ctx state.
231 *
232 * This however results in two special cases:
233 *
234 * - removing the last event from a task ctx; this is relatively straight
235 * forward and is done in __perf_remove_from_context.
236 *
237 * - adding the first event to a task ctx; this is tricky because we cannot
238 * rely on ctx->is_active and therefore cannot use event_function_call().
239 * See perf_install_in_context().
240 *
241 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
242 */
243
244 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
245 struct perf_event_context *, void *);
246
247 struct event_function_struct {
248 struct perf_event *event;
249 event_f func;
250 void *data;
251 };
252
event_function(void * info)253 static int event_function(void *info)
254 {
255 struct event_function_struct *efs = info;
256 struct perf_event *event = efs->event;
257 struct perf_event_context *ctx = event->ctx;
258 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
259 struct perf_event_context *task_ctx = cpuctx->task_ctx;
260 int ret = 0;
261
262 lockdep_assert_irqs_disabled();
263
264 perf_ctx_lock(cpuctx, task_ctx);
265 /*
266 * Since we do the IPI call without holding ctx->lock things can have
267 * changed, double check we hit the task we set out to hit.
268 */
269 if (ctx->task) {
270 if (ctx->task != current) {
271 ret = -ESRCH;
272 goto unlock;
273 }
274
275 /*
276 * We only use event_function_call() on established contexts,
277 * and event_function() is only ever called when active (or
278 * rather, we'll have bailed in task_function_call() or the
279 * above ctx->task != current test), therefore we must have
280 * ctx->is_active here.
281 */
282 WARN_ON_ONCE(!ctx->is_active);
283 /*
284 * And since we have ctx->is_active, cpuctx->task_ctx must
285 * match.
286 */
287 WARN_ON_ONCE(task_ctx != ctx);
288 } else {
289 WARN_ON_ONCE(&cpuctx->ctx != ctx);
290 }
291
292 efs->func(event, cpuctx, ctx, efs->data);
293 unlock:
294 perf_ctx_unlock(cpuctx, task_ctx);
295
296 return ret;
297 }
298
event_function_call(struct perf_event * event,event_f func,void * data)299 static void event_function_call(struct perf_event *event, event_f func, void *data)
300 {
301 struct perf_event_context *ctx = event->ctx;
302 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
303 struct perf_cpu_context *cpuctx;
304 struct event_function_struct efs = {
305 .event = event,
306 .func = func,
307 .data = data,
308 };
309
310 if (!event->parent) {
311 /*
312 * If this is a !child event, we must hold ctx::mutex to
313 * stabilize the event->ctx relation. See
314 * perf_event_ctx_lock().
315 */
316 lockdep_assert_held(&ctx->mutex);
317 }
318
319 if (!task) {
320 cpu_function_call(event->cpu, event_function, &efs);
321 return;
322 }
323
324 if (task == TASK_TOMBSTONE)
325 return;
326
327 again:
328 if (!task_function_call(task, event_function, &efs))
329 return;
330
331 local_irq_disable();
332 cpuctx = this_cpu_ptr(&perf_cpu_context);
333 perf_ctx_lock(cpuctx, ctx);
334 /*
335 * Reload the task pointer, it might have been changed by
336 * a concurrent perf_event_context_sched_out().
337 */
338 task = ctx->task;
339 if (task == TASK_TOMBSTONE)
340 goto unlock;
341 if (ctx->is_active) {
342 perf_ctx_unlock(cpuctx, ctx);
343 local_irq_enable();
344 goto again;
345 }
346 func(event, NULL, ctx, data);
347 unlock:
348 perf_ctx_unlock(cpuctx, ctx);
349 local_irq_enable();
350 }
351
352 /*
353 * Similar to event_function_call() + event_function(), but hard assumes IRQs
354 * are already disabled and we're on the right CPU.
355 */
event_function_local(struct perf_event * event,event_f func,void * data)356 static void event_function_local(struct perf_event *event, event_f func, void *data)
357 {
358 struct perf_event_context *ctx = event->ctx;
359 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
360 struct task_struct *task = READ_ONCE(ctx->task);
361 struct perf_event_context *task_ctx = NULL;
362
363 lockdep_assert_irqs_disabled();
364
365 if (task) {
366 if (task == TASK_TOMBSTONE)
367 return;
368
369 task_ctx = ctx;
370 }
371
372 perf_ctx_lock(cpuctx, task_ctx);
373
374 task = ctx->task;
375 if (task == TASK_TOMBSTONE)
376 goto unlock;
377
378 if (task) {
379 /*
380 * We must be either inactive or active and the right task,
381 * otherwise we're screwed, since we cannot IPI to somewhere
382 * else.
383 */
384 if (ctx->is_active) {
385 if (WARN_ON_ONCE(task != current))
386 goto unlock;
387
388 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
389 goto unlock;
390 }
391 } else {
392 WARN_ON_ONCE(&cpuctx->ctx != ctx);
393 }
394
395 func(event, cpuctx, ctx, data);
396 unlock:
397 perf_ctx_unlock(cpuctx, task_ctx);
398 }
399
400 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
401 PERF_FLAG_FD_OUTPUT |\
402 PERF_FLAG_PID_CGROUP |\
403 PERF_FLAG_FD_CLOEXEC)
404
405 /*
406 * branch priv levels that need permission checks
407 */
408 #define PERF_SAMPLE_BRANCH_PERM_PLM \
409 (PERF_SAMPLE_BRANCH_KERNEL |\
410 PERF_SAMPLE_BRANCH_HV)
411
412 /*
413 * perf_sched_events : >0 events exist
414 */
415
416 static void perf_sched_delayed(struct work_struct *work);
417 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
418 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
419 static DEFINE_MUTEX(perf_sched_mutex);
420 static atomic_t perf_sched_count;
421
422 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
423
424 static atomic_t nr_mmap_events __read_mostly;
425 static atomic_t nr_comm_events __read_mostly;
426 static atomic_t nr_namespaces_events __read_mostly;
427 static atomic_t nr_task_events __read_mostly;
428 static atomic_t nr_freq_events __read_mostly;
429 static atomic_t nr_switch_events __read_mostly;
430 static atomic_t nr_ksymbol_events __read_mostly;
431 static atomic_t nr_bpf_events __read_mostly;
432 static atomic_t nr_cgroup_events __read_mostly;
433 static atomic_t nr_text_poke_events __read_mostly;
434 static atomic_t nr_build_id_events __read_mostly;
435
436 static LIST_HEAD(pmus);
437 static DEFINE_MUTEX(pmus_lock);
438 static struct srcu_struct pmus_srcu;
439 static cpumask_var_t perf_online_mask;
440 static cpumask_var_t perf_online_core_mask;
441 static cpumask_var_t perf_online_die_mask;
442 static cpumask_var_t perf_online_cluster_mask;
443 static cpumask_var_t perf_online_pkg_mask;
444 static cpumask_var_t perf_online_sys_mask;
445 static struct kmem_cache *perf_event_cache;
446
447 /*
448 * perf event paranoia level:
449 * -1 - not paranoid at all
450 * 0 - disallow raw tracepoint access for unpriv
451 * 1 - disallow cpu events for unpriv
452 * 2 - disallow kernel profiling for unpriv
453 */
454 int sysctl_perf_event_paranoid __read_mostly = 2;
455
456 /* Minimum for 512 kiB + 1 user control page. 'free' kiB per user. */
457 static int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024);
458
459 /*
460 * max perf event sample rate
461 */
462 #define DEFAULT_MAX_SAMPLE_RATE 100000
463 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
464 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
465
466 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
467 static int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
468
469 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
470 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
471
472 static int perf_sample_allowed_ns __read_mostly =
473 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
474
update_perf_cpu_limits(void)475 static void update_perf_cpu_limits(void)
476 {
477 u64 tmp = perf_sample_period_ns;
478
479 tmp *= sysctl_perf_cpu_time_max_percent;
480 tmp = div_u64(tmp, 100);
481 if (!tmp)
482 tmp = 1;
483
484 WRITE_ONCE(perf_sample_allowed_ns, tmp);
485 }
486
487 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc);
488
perf_event_max_sample_rate_handler(const struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)489 static int perf_event_max_sample_rate_handler(const struct ctl_table *table, int write,
490 void *buffer, size_t *lenp, loff_t *ppos)
491 {
492 int ret;
493 int perf_cpu = sysctl_perf_cpu_time_max_percent;
494 /*
495 * If throttling is disabled don't allow the write:
496 */
497 if (write && (perf_cpu == 100 || perf_cpu == 0))
498 return -EINVAL;
499
500 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
501 if (ret || !write)
502 return ret;
503
504 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
505 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
506 update_perf_cpu_limits();
507
508 return 0;
509 }
510
perf_cpu_time_max_percent_handler(const struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)511 static int perf_cpu_time_max_percent_handler(const struct ctl_table *table, int write,
512 void *buffer, size_t *lenp, loff_t *ppos)
513 {
514 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
515
516 if (ret || !write)
517 return ret;
518
519 if (sysctl_perf_cpu_time_max_percent == 100 ||
520 sysctl_perf_cpu_time_max_percent == 0) {
521 printk(KERN_WARNING
522 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
523 WRITE_ONCE(perf_sample_allowed_ns, 0);
524 } else {
525 update_perf_cpu_limits();
526 }
527
528 return 0;
529 }
530
531 static const struct ctl_table events_core_sysctl_table[] = {
532 /*
533 * User-space relies on this file as a feature check for
534 * perf_events being enabled. It's an ABI, do not remove!
535 */
536 {
537 .procname = "perf_event_paranoid",
538 .data = &sysctl_perf_event_paranoid,
539 .maxlen = sizeof(sysctl_perf_event_paranoid),
540 .mode = 0644,
541 .proc_handler = proc_dointvec,
542 },
543 {
544 .procname = "perf_event_mlock_kb",
545 .data = &sysctl_perf_event_mlock,
546 .maxlen = sizeof(sysctl_perf_event_mlock),
547 .mode = 0644,
548 .proc_handler = proc_dointvec,
549 },
550 {
551 .procname = "perf_event_max_sample_rate",
552 .data = &sysctl_perf_event_sample_rate,
553 .maxlen = sizeof(sysctl_perf_event_sample_rate),
554 .mode = 0644,
555 .proc_handler = perf_event_max_sample_rate_handler,
556 .extra1 = SYSCTL_ONE,
557 },
558 {
559 .procname = "perf_cpu_time_max_percent",
560 .data = &sysctl_perf_cpu_time_max_percent,
561 .maxlen = sizeof(sysctl_perf_cpu_time_max_percent),
562 .mode = 0644,
563 .proc_handler = perf_cpu_time_max_percent_handler,
564 .extra1 = SYSCTL_ZERO,
565 .extra2 = SYSCTL_ONE_HUNDRED,
566 },
567 };
568
init_events_core_sysctls(void)569 static int __init init_events_core_sysctls(void)
570 {
571 register_sysctl_init("kernel", events_core_sysctl_table);
572 return 0;
573 }
574 core_initcall(init_events_core_sysctls);
575
576
577 /*
578 * perf samples are done in some very critical code paths (NMIs).
579 * If they take too much CPU time, the system can lock up and not
580 * get any real work done. This will drop the sample rate when
581 * we detect that events are taking too long.
582 */
583 #define NR_ACCUMULATED_SAMPLES 128
584 static DEFINE_PER_CPU(u64, running_sample_length);
585
586 static u64 __report_avg;
587 static u64 __report_allowed;
588
perf_duration_warn(struct irq_work * w)589 static void perf_duration_warn(struct irq_work *w)
590 {
591 printk_ratelimited(KERN_INFO
592 "perf: interrupt took too long (%lld > %lld), lowering "
593 "kernel.perf_event_max_sample_rate to %d\n",
594 __report_avg, __report_allowed,
595 sysctl_perf_event_sample_rate);
596 }
597
598 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
599
perf_sample_event_took(u64 sample_len_ns)600 void perf_sample_event_took(u64 sample_len_ns)
601 {
602 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
603 u64 running_len;
604 u64 avg_len;
605 u32 max;
606
607 if (max_len == 0)
608 return;
609
610 /* Decay the counter by 1 average sample. */
611 running_len = __this_cpu_read(running_sample_length);
612 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
613 running_len += sample_len_ns;
614 __this_cpu_write(running_sample_length, running_len);
615
616 /*
617 * Note: this will be biased artificially low until we have
618 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
619 * from having to maintain a count.
620 */
621 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
622 if (avg_len <= max_len)
623 return;
624
625 __report_avg = avg_len;
626 __report_allowed = max_len;
627
628 /*
629 * Compute a throttle threshold 25% below the current duration.
630 */
631 avg_len += avg_len / 4;
632 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
633 if (avg_len < max)
634 max /= (u32)avg_len;
635 else
636 max = 1;
637
638 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
639 WRITE_ONCE(max_samples_per_tick, max);
640
641 sysctl_perf_event_sample_rate = max * HZ;
642 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
643
644 if (!irq_work_queue(&perf_duration_work)) {
645 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
646 "kernel.perf_event_max_sample_rate to %d\n",
647 __report_avg, __report_allowed,
648 sysctl_perf_event_sample_rate);
649 }
650 }
651
652 static atomic64_t perf_event_id;
653
654 static void update_context_time(struct perf_event_context *ctx);
655 static u64 perf_event_time(struct perf_event *event);
656
perf_event_print_debug(void)657 void __weak perf_event_print_debug(void) { }
658
perf_clock(void)659 static inline u64 perf_clock(void)
660 {
661 return local_clock();
662 }
663
perf_event_clock(struct perf_event * event)664 static inline u64 perf_event_clock(struct perf_event *event)
665 {
666 return event->clock();
667 }
668
669 /*
670 * State based event timekeeping...
671 *
672 * The basic idea is to use event->state to determine which (if any) time
673 * fields to increment with the current delta. This means we only need to
674 * update timestamps when we change state or when they are explicitly requested
675 * (read).
676 *
677 * Event groups make things a little more complicated, but not terribly so. The
678 * rules for a group are that if the group leader is OFF the entire group is
679 * OFF, irrespective of what the group member states are. This results in
680 * __perf_effective_state().
681 *
682 * A further ramification is that when a group leader flips between OFF and
683 * !OFF, we need to update all group member times.
684 *
685 *
686 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
687 * need to make sure the relevant context time is updated before we try and
688 * update our timestamps.
689 */
690
691 static __always_inline enum perf_event_state
__perf_effective_state(struct perf_event * event)692 __perf_effective_state(struct perf_event *event)
693 {
694 struct perf_event *leader = event->group_leader;
695
696 if (leader->state <= PERF_EVENT_STATE_OFF)
697 return leader->state;
698
699 return event->state;
700 }
701
702 static __always_inline void
__perf_update_times(struct perf_event * event,u64 now,u64 * enabled,u64 * running)703 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
704 {
705 enum perf_event_state state = __perf_effective_state(event);
706 u64 delta = now - event->tstamp;
707
708 *enabled = event->total_time_enabled;
709 if (state >= PERF_EVENT_STATE_INACTIVE)
710 *enabled += delta;
711
712 *running = event->total_time_running;
713 if (state >= PERF_EVENT_STATE_ACTIVE)
714 *running += delta;
715 }
716
perf_event_update_time(struct perf_event * event)717 static void perf_event_update_time(struct perf_event *event)
718 {
719 u64 now = perf_event_time(event);
720
721 __perf_update_times(event, now, &event->total_time_enabled,
722 &event->total_time_running);
723 event->tstamp = now;
724 }
725
perf_event_update_sibling_time(struct perf_event * leader)726 static void perf_event_update_sibling_time(struct perf_event *leader)
727 {
728 struct perf_event *sibling;
729
730 for_each_sibling_event(sibling, leader)
731 perf_event_update_time(sibling);
732 }
733
734 static void
perf_event_set_state(struct perf_event * event,enum perf_event_state state)735 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
736 {
737 if (event->state == state)
738 return;
739
740 perf_event_update_time(event);
741 /*
742 * If a group leader gets enabled/disabled all its siblings
743 * are affected too.
744 */
745 if ((event->state < 0) ^ (state < 0))
746 perf_event_update_sibling_time(event);
747
748 WRITE_ONCE(event->state, state);
749 }
750
751 /*
752 * UP store-release, load-acquire
753 */
754
755 #define __store_release(ptr, val) \
756 do { \
757 barrier(); \
758 WRITE_ONCE(*(ptr), (val)); \
759 } while (0)
760
761 #define __load_acquire(ptr) \
762 ({ \
763 __unqual_scalar_typeof(*(ptr)) ___p = READ_ONCE(*(ptr)); \
764 barrier(); \
765 ___p; \
766 })
767
768 #define for_each_epc(_epc, _ctx, _pmu, _cgroup) \
769 list_for_each_entry(_epc, &((_ctx)->pmu_ctx_list), pmu_ctx_entry) \
770 if (_cgroup && !_epc->nr_cgroups) \
771 continue; \
772 else if (_pmu && _epc->pmu != _pmu) \
773 continue; \
774 else
775
perf_ctx_disable(struct perf_event_context * ctx,bool cgroup)776 static void perf_ctx_disable(struct perf_event_context *ctx, bool cgroup)
777 {
778 struct perf_event_pmu_context *pmu_ctx;
779
780 for_each_epc(pmu_ctx, ctx, NULL, cgroup)
781 perf_pmu_disable(pmu_ctx->pmu);
782 }
783
perf_ctx_enable(struct perf_event_context * ctx,bool cgroup)784 static void perf_ctx_enable(struct perf_event_context *ctx, bool cgroup)
785 {
786 struct perf_event_pmu_context *pmu_ctx;
787
788 for_each_epc(pmu_ctx, ctx, NULL, cgroup)
789 perf_pmu_enable(pmu_ctx->pmu);
790 }
791
792 static void ctx_sched_out(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type);
793 static void ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type);
794
795 #ifdef CONFIG_CGROUP_PERF
796
797 static inline bool
perf_cgroup_match(struct perf_event * event)798 perf_cgroup_match(struct perf_event *event)
799 {
800 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
801
802 /* @event doesn't care about cgroup */
803 if (!event->cgrp)
804 return true;
805
806 /* wants specific cgroup scope but @cpuctx isn't associated with any */
807 if (!cpuctx->cgrp)
808 return false;
809
810 /*
811 * Cgroup scoping is recursive. An event enabled for a cgroup is
812 * also enabled for all its descendant cgroups. If @cpuctx's
813 * cgroup is a descendant of @event's (the test covers identity
814 * case), it's a match.
815 */
816 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
817 event->cgrp->css.cgroup);
818 }
819
perf_detach_cgroup(struct perf_event * event)820 static inline void perf_detach_cgroup(struct perf_event *event)
821 {
822 css_put(&event->cgrp->css);
823 event->cgrp = NULL;
824 }
825
is_cgroup_event(struct perf_event * event)826 static inline int is_cgroup_event(struct perf_event *event)
827 {
828 return event->cgrp != NULL;
829 }
830
perf_cgroup_event_time(struct perf_event * event)831 static inline u64 perf_cgroup_event_time(struct perf_event *event)
832 {
833 struct perf_cgroup_info *t;
834
835 t = per_cpu_ptr(event->cgrp->info, event->cpu);
836 return t->time;
837 }
838
perf_cgroup_event_time_now(struct perf_event * event,u64 now)839 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
840 {
841 struct perf_cgroup_info *t;
842
843 t = per_cpu_ptr(event->cgrp->info, event->cpu);
844 if (!__load_acquire(&t->active))
845 return t->time;
846 now += READ_ONCE(t->timeoffset);
847 return now;
848 }
849
__update_cgrp_time(struct perf_cgroup_info * info,u64 now,bool adv)850 static inline void __update_cgrp_time(struct perf_cgroup_info *info, u64 now, bool adv)
851 {
852 if (adv)
853 info->time += now - info->timestamp;
854 info->timestamp = now;
855 /*
856 * see update_context_time()
857 */
858 WRITE_ONCE(info->timeoffset, info->time - info->timestamp);
859 }
860
update_cgrp_time_from_cpuctx(struct perf_cpu_context * cpuctx,bool final)861 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx, bool final)
862 {
863 struct perf_cgroup *cgrp = cpuctx->cgrp;
864 struct cgroup_subsys_state *css;
865 struct perf_cgroup_info *info;
866
867 if (cgrp) {
868 u64 now = perf_clock();
869
870 for (css = &cgrp->css; css; css = css->parent) {
871 cgrp = container_of(css, struct perf_cgroup, css);
872 info = this_cpu_ptr(cgrp->info);
873
874 __update_cgrp_time(info, now, true);
875 if (final)
876 __store_release(&info->active, 0);
877 }
878 }
879 }
880
update_cgrp_time_from_event(struct perf_event * event)881 static inline void update_cgrp_time_from_event(struct perf_event *event)
882 {
883 struct perf_cgroup_info *info;
884
885 /*
886 * ensure we access cgroup data only when needed and
887 * when we know the cgroup is pinned (css_get)
888 */
889 if (!is_cgroup_event(event))
890 return;
891
892 info = this_cpu_ptr(event->cgrp->info);
893 /*
894 * Do not update time when cgroup is not active
895 */
896 if (info->active)
897 __update_cgrp_time(info, perf_clock(), true);
898 }
899
900 static inline void
perf_cgroup_set_timestamp(struct perf_cpu_context * cpuctx)901 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx)
902 {
903 struct perf_event_context *ctx = &cpuctx->ctx;
904 struct perf_cgroup *cgrp = cpuctx->cgrp;
905 struct perf_cgroup_info *info;
906 struct cgroup_subsys_state *css;
907
908 /*
909 * ctx->lock held by caller
910 * ensure we do not access cgroup data
911 * unless we have the cgroup pinned (css_get)
912 */
913 if (!cgrp)
914 return;
915
916 WARN_ON_ONCE(!ctx->nr_cgroups);
917
918 for (css = &cgrp->css; css; css = css->parent) {
919 cgrp = container_of(css, struct perf_cgroup, css);
920 info = this_cpu_ptr(cgrp->info);
921 __update_cgrp_time(info, ctx->timestamp, false);
922 __store_release(&info->active, 1);
923 }
924 }
925
926 /*
927 * reschedule events based on the cgroup constraint of task.
928 */
perf_cgroup_switch(struct task_struct * task)929 static void perf_cgroup_switch(struct task_struct *task)
930 {
931 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
932 struct perf_cgroup *cgrp;
933
934 /*
935 * cpuctx->cgrp is set when the first cgroup event enabled,
936 * and is cleared when the last cgroup event disabled.
937 */
938 if (READ_ONCE(cpuctx->cgrp) == NULL)
939 return;
940
941 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
942
943 cgrp = perf_cgroup_from_task(task, NULL);
944 if (READ_ONCE(cpuctx->cgrp) == cgrp)
945 return;
946
947 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
948 perf_ctx_disable(&cpuctx->ctx, true);
949
950 ctx_sched_out(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP);
951 /*
952 * must not be done before ctxswout due
953 * to update_cgrp_time_from_cpuctx() in
954 * ctx_sched_out()
955 */
956 cpuctx->cgrp = cgrp;
957 /*
958 * set cgrp before ctxsw in to allow
959 * perf_cgroup_set_timestamp() in ctx_sched_in()
960 * to not have to pass task around
961 */
962 ctx_sched_in(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP);
963
964 perf_ctx_enable(&cpuctx->ctx, true);
965 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
966 }
967
perf_cgroup_ensure_storage(struct perf_event * event,struct cgroup_subsys_state * css)968 static int perf_cgroup_ensure_storage(struct perf_event *event,
969 struct cgroup_subsys_state *css)
970 {
971 struct perf_cpu_context *cpuctx;
972 struct perf_event **storage;
973 int cpu, heap_size, ret = 0;
974
975 /*
976 * Allow storage to have sufficient space for an iterator for each
977 * possibly nested cgroup plus an iterator for events with no cgroup.
978 */
979 for (heap_size = 1; css; css = css->parent)
980 heap_size++;
981
982 for_each_possible_cpu(cpu) {
983 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
984 if (heap_size <= cpuctx->heap_size)
985 continue;
986
987 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
988 GFP_KERNEL, cpu_to_node(cpu));
989 if (!storage) {
990 ret = -ENOMEM;
991 break;
992 }
993
994 raw_spin_lock_irq(&cpuctx->ctx.lock);
995 if (cpuctx->heap_size < heap_size) {
996 swap(cpuctx->heap, storage);
997 if (storage == cpuctx->heap_default)
998 storage = NULL;
999 cpuctx->heap_size = heap_size;
1000 }
1001 raw_spin_unlock_irq(&cpuctx->ctx.lock);
1002
1003 kfree(storage);
1004 }
1005
1006 return ret;
1007 }
1008
perf_cgroup_connect(int fd,struct perf_event * event,struct perf_event_attr * attr,struct perf_event * group_leader)1009 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
1010 struct perf_event_attr *attr,
1011 struct perf_event *group_leader)
1012 {
1013 struct perf_cgroup *cgrp;
1014 struct cgroup_subsys_state *css;
1015 CLASS(fd, f)(fd);
1016 int ret = 0;
1017
1018 if (fd_empty(f))
1019 return -EBADF;
1020
1021 css = css_tryget_online_from_dir(fd_file(f)->f_path.dentry,
1022 &perf_event_cgrp_subsys);
1023 if (IS_ERR(css))
1024 return PTR_ERR(css);
1025
1026 ret = perf_cgroup_ensure_storage(event, css);
1027 if (ret)
1028 return ret;
1029
1030 cgrp = container_of(css, struct perf_cgroup, css);
1031 event->cgrp = cgrp;
1032
1033 /*
1034 * all events in a group must monitor
1035 * the same cgroup because a task belongs
1036 * to only one perf cgroup at a time
1037 */
1038 if (group_leader && group_leader->cgrp != cgrp) {
1039 perf_detach_cgroup(event);
1040 ret = -EINVAL;
1041 }
1042 return ret;
1043 }
1044
1045 static inline void
perf_cgroup_event_enable(struct perf_event * event,struct perf_event_context * ctx)1046 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1047 {
1048 struct perf_cpu_context *cpuctx;
1049
1050 if (!is_cgroup_event(event))
1051 return;
1052
1053 event->pmu_ctx->nr_cgroups++;
1054
1055 /*
1056 * Because cgroup events are always per-cpu events,
1057 * @ctx == &cpuctx->ctx.
1058 */
1059 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1060
1061 if (ctx->nr_cgroups++)
1062 return;
1063
1064 cpuctx->cgrp = perf_cgroup_from_task(current, ctx);
1065 }
1066
1067 static inline void
perf_cgroup_event_disable(struct perf_event * event,struct perf_event_context * ctx)1068 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1069 {
1070 struct perf_cpu_context *cpuctx;
1071
1072 if (!is_cgroup_event(event))
1073 return;
1074
1075 event->pmu_ctx->nr_cgroups--;
1076
1077 /*
1078 * Because cgroup events are always per-cpu events,
1079 * @ctx == &cpuctx->ctx.
1080 */
1081 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1082
1083 if (--ctx->nr_cgroups)
1084 return;
1085
1086 cpuctx->cgrp = NULL;
1087 }
1088
1089 #else /* !CONFIG_CGROUP_PERF */
1090
1091 static inline bool
perf_cgroup_match(struct perf_event * event)1092 perf_cgroup_match(struct perf_event *event)
1093 {
1094 return true;
1095 }
1096
perf_detach_cgroup(struct perf_event * event)1097 static inline void perf_detach_cgroup(struct perf_event *event)
1098 {}
1099
is_cgroup_event(struct perf_event * event)1100 static inline int is_cgroup_event(struct perf_event *event)
1101 {
1102 return 0;
1103 }
1104
update_cgrp_time_from_event(struct perf_event * event)1105 static inline void update_cgrp_time_from_event(struct perf_event *event)
1106 {
1107 }
1108
update_cgrp_time_from_cpuctx(struct perf_cpu_context * cpuctx,bool final)1109 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx,
1110 bool final)
1111 {
1112 }
1113
perf_cgroup_connect(pid_t pid,struct perf_event * event,struct perf_event_attr * attr,struct perf_event * group_leader)1114 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1115 struct perf_event_attr *attr,
1116 struct perf_event *group_leader)
1117 {
1118 return -EINVAL;
1119 }
1120
1121 static inline void
perf_cgroup_set_timestamp(struct perf_cpu_context * cpuctx)1122 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx)
1123 {
1124 }
1125
perf_cgroup_event_time(struct perf_event * event)1126 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1127 {
1128 return 0;
1129 }
1130
perf_cgroup_event_time_now(struct perf_event * event,u64 now)1131 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
1132 {
1133 return 0;
1134 }
1135
1136 static inline void
perf_cgroup_event_enable(struct perf_event * event,struct perf_event_context * ctx)1137 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1138 {
1139 }
1140
1141 static inline void
perf_cgroup_event_disable(struct perf_event * event,struct perf_event_context * ctx)1142 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1143 {
1144 }
1145
perf_cgroup_switch(struct task_struct * task)1146 static void perf_cgroup_switch(struct task_struct *task)
1147 {
1148 }
1149 #endif
1150
1151 /*
1152 * set default to be dependent on timer tick just
1153 * like original code
1154 */
1155 #define PERF_CPU_HRTIMER (1000 / HZ)
1156 /*
1157 * function must be called with interrupts disabled
1158 */
perf_mux_hrtimer_handler(struct hrtimer * hr)1159 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1160 {
1161 struct perf_cpu_pmu_context *cpc;
1162 bool rotations;
1163
1164 lockdep_assert_irqs_disabled();
1165
1166 cpc = container_of(hr, struct perf_cpu_pmu_context, hrtimer);
1167 rotations = perf_rotate_context(cpc);
1168
1169 raw_spin_lock(&cpc->hrtimer_lock);
1170 if (rotations)
1171 hrtimer_forward_now(hr, cpc->hrtimer_interval);
1172 else
1173 cpc->hrtimer_active = 0;
1174 raw_spin_unlock(&cpc->hrtimer_lock);
1175
1176 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1177 }
1178
__perf_mux_hrtimer_init(struct perf_cpu_pmu_context * cpc,int cpu)1179 static void __perf_mux_hrtimer_init(struct perf_cpu_pmu_context *cpc, int cpu)
1180 {
1181 struct hrtimer *timer = &cpc->hrtimer;
1182 struct pmu *pmu = cpc->epc.pmu;
1183 u64 interval;
1184
1185 /*
1186 * check default is sane, if not set then force to
1187 * default interval (1/tick)
1188 */
1189 interval = pmu->hrtimer_interval_ms;
1190 if (interval < 1)
1191 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1192
1193 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1194
1195 raw_spin_lock_init(&cpc->hrtimer_lock);
1196 hrtimer_setup(timer, perf_mux_hrtimer_handler, CLOCK_MONOTONIC,
1197 HRTIMER_MODE_ABS_PINNED_HARD);
1198 }
1199
perf_mux_hrtimer_restart(struct perf_cpu_pmu_context * cpc)1200 static int perf_mux_hrtimer_restart(struct perf_cpu_pmu_context *cpc)
1201 {
1202 struct hrtimer *timer = &cpc->hrtimer;
1203 unsigned long flags;
1204
1205 raw_spin_lock_irqsave(&cpc->hrtimer_lock, flags);
1206 if (!cpc->hrtimer_active) {
1207 cpc->hrtimer_active = 1;
1208 hrtimer_forward_now(timer, cpc->hrtimer_interval);
1209 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1210 }
1211 raw_spin_unlock_irqrestore(&cpc->hrtimer_lock, flags);
1212
1213 return 0;
1214 }
1215
perf_mux_hrtimer_restart_ipi(void * arg)1216 static int perf_mux_hrtimer_restart_ipi(void *arg)
1217 {
1218 return perf_mux_hrtimer_restart(arg);
1219 }
1220
this_cpc(struct pmu * pmu)1221 static __always_inline struct perf_cpu_pmu_context *this_cpc(struct pmu *pmu)
1222 {
1223 return *this_cpu_ptr(pmu->cpu_pmu_context);
1224 }
1225
perf_pmu_disable(struct pmu * pmu)1226 void perf_pmu_disable(struct pmu *pmu)
1227 {
1228 int *count = &this_cpc(pmu)->pmu_disable_count;
1229 if (!(*count)++)
1230 pmu->pmu_disable(pmu);
1231 }
1232
perf_pmu_enable(struct pmu * pmu)1233 void perf_pmu_enable(struct pmu *pmu)
1234 {
1235 int *count = &this_cpc(pmu)->pmu_disable_count;
1236 if (!--(*count))
1237 pmu->pmu_enable(pmu);
1238 }
1239
perf_assert_pmu_disabled(struct pmu * pmu)1240 static void perf_assert_pmu_disabled(struct pmu *pmu)
1241 {
1242 int *count = &this_cpc(pmu)->pmu_disable_count;
1243 WARN_ON_ONCE(*count == 0);
1244 }
1245
perf_pmu_read(struct perf_event * event)1246 static inline void perf_pmu_read(struct perf_event *event)
1247 {
1248 if (event->state == PERF_EVENT_STATE_ACTIVE)
1249 event->pmu->read(event);
1250 }
1251
get_ctx(struct perf_event_context * ctx)1252 static void get_ctx(struct perf_event_context *ctx)
1253 {
1254 refcount_inc(&ctx->refcount);
1255 }
1256
free_ctx(struct rcu_head * head)1257 static void free_ctx(struct rcu_head *head)
1258 {
1259 struct perf_event_context *ctx;
1260
1261 ctx = container_of(head, struct perf_event_context, rcu_head);
1262 kfree(ctx);
1263 }
1264
put_ctx(struct perf_event_context * ctx)1265 static void put_ctx(struct perf_event_context *ctx)
1266 {
1267 if (refcount_dec_and_test(&ctx->refcount)) {
1268 if (ctx->parent_ctx)
1269 put_ctx(ctx->parent_ctx);
1270 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1271 put_task_struct(ctx->task);
1272 call_rcu(&ctx->rcu_head, free_ctx);
1273 }
1274 }
1275
1276 /*
1277 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1278 * perf_pmu_migrate_context() we need some magic.
1279 *
1280 * Those places that change perf_event::ctx will hold both
1281 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1282 *
1283 * Lock ordering is by mutex address. There are two other sites where
1284 * perf_event_context::mutex nests and those are:
1285 *
1286 * - perf_event_exit_task_context() [ child , 0 ]
1287 * perf_event_exit_event()
1288 * put_event() [ parent, 1 ]
1289 *
1290 * - perf_event_init_context() [ parent, 0 ]
1291 * inherit_task_group()
1292 * inherit_group()
1293 * inherit_event()
1294 * perf_event_alloc()
1295 * perf_init_event()
1296 * perf_try_init_event() [ child , 1 ]
1297 *
1298 * While it appears there is an obvious deadlock here -- the parent and child
1299 * nesting levels are inverted between the two. This is in fact safe because
1300 * life-time rules separate them. That is an exiting task cannot fork, and a
1301 * spawning task cannot (yet) exit.
1302 *
1303 * But remember that these are parent<->child context relations, and
1304 * migration does not affect children, therefore these two orderings should not
1305 * interact.
1306 *
1307 * The change in perf_event::ctx does not affect children (as claimed above)
1308 * because the sys_perf_event_open() case will install a new event and break
1309 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1310 * concerned with cpuctx and that doesn't have children.
1311 *
1312 * The places that change perf_event::ctx will issue:
1313 *
1314 * perf_remove_from_context();
1315 * synchronize_rcu();
1316 * perf_install_in_context();
1317 *
1318 * to affect the change. The remove_from_context() + synchronize_rcu() should
1319 * quiesce the event, after which we can install it in the new location. This
1320 * means that only external vectors (perf_fops, prctl) can perturb the event
1321 * while in transit. Therefore all such accessors should also acquire
1322 * perf_event_context::mutex to serialize against this.
1323 *
1324 * However; because event->ctx can change while we're waiting to acquire
1325 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1326 * function.
1327 *
1328 * Lock order:
1329 * exec_update_lock
1330 * task_struct::perf_event_mutex
1331 * perf_event_context::mutex
1332 * perf_event::child_mutex;
1333 * perf_event_context::lock
1334 * mmap_lock
1335 * perf_event::mmap_mutex
1336 * perf_buffer::aux_mutex
1337 * perf_addr_filters_head::lock
1338 *
1339 * cpu_hotplug_lock
1340 * pmus_lock
1341 * cpuctx->mutex / perf_event_context::mutex
1342 */
1343 static struct perf_event_context *
perf_event_ctx_lock_nested(struct perf_event * event,int nesting)1344 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1345 {
1346 struct perf_event_context *ctx;
1347
1348 again:
1349 rcu_read_lock();
1350 ctx = READ_ONCE(event->ctx);
1351 if (!refcount_inc_not_zero(&ctx->refcount)) {
1352 rcu_read_unlock();
1353 goto again;
1354 }
1355 rcu_read_unlock();
1356
1357 mutex_lock_nested(&ctx->mutex, nesting);
1358 if (event->ctx != ctx) {
1359 mutex_unlock(&ctx->mutex);
1360 put_ctx(ctx);
1361 goto again;
1362 }
1363
1364 return ctx;
1365 }
1366
1367 static inline struct perf_event_context *
perf_event_ctx_lock(struct perf_event * event)1368 perf_event_ctx_lock(struct perf_event *event)
1369 {
1370 return perf_event_ctx_lock_nested(event, 0);
1371 }
1372
perf_event_ctx_unlock(struct perf_event * event,struct perf_event_context * ctx)1373 static void perf_event_ctx_unlock(struct perf_event *event,
1374 struct perf_event_context *ctx)
1375 {
1376 mutex_unlock(&ctx->mutex);
1377 put_ctx(ctx);
1378 }
1379
1380 /*
1381 * This must be done under the ctx->lock, such as to serialize against
1382 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1383 * calling scheduler related locks and ctx->lock nests inside those.
1384 */
1385 static __must_check struct perf_event_context *
unclone_ctx(struct perf_event_context * ctx)1386 unclone_ctx(struct perf_event_context *ctx)
1387 {
1388 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1389
1390 lockdep_assert_held(&ctx->lock);
1391
1392 if (parent_ctx)
1393 ctx->parent_ctx = NULL;
1394 ctx->generation++;
1395
1396 return parent_ctx;
1397 }
1398
perf_event_pid_type(struct perf_event * event,struct task_struct * p,enum pid_type type)1399 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1400 enum pid_type type)
1401 {
1402 u32 nr;
1403 /*
1404 * only top level events have the pid namespace they were created in
1405 */
1406 if (event->parent)
1407 event = event->parent;
1408
1409 nr = __task_pid_nr_ns(p, type, event->ns);
1410 /* avoid -1 if it is idle thread or runs in another ns */
1411 if (!nr && !pid_alive(p))
1412 nr = -1;
1413 return nr;
1414 }
1415
perf_event_pid(struct perf_event * event,struct task_struct * p)1416 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1417 {
1418 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1419 }
1420
perf_event_tid(struct perf_event * event,struct task_struct * p)1421 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1422 {
1423 return perf_event_pid_type(event, p, PIDTYPE_PID);
1424 }
1425
1426 /*
1427 * If we inherit events we want to return the parent event id
1428 * to userspace.
1429 */
primary_event_id(struct perf_event * event)1430 static u64 primary_event_id(struct perf_event *event)
1431 {
1432 u64 id = event->id;
1433
1434 if (event->parent)
1435 id = event->parent->id;
1436
1437 return id;
1438 }
1439
1440 /*
1441 * Get the perf_event_context for a task and lock it.
1442 *
1443 * This has to cope with the fact that until it is locked,
1444 * the context could get moved to another task.
1445 */
1446 static struct perf_event_context *
perf_lock_task_context(struct task_struct * task,unsigned long * flags)1447 perf_lock_task_context(struct task_struct *task, unsigned long *flags)
1448 {
1449 struct perf_event_context *ctx;
1450
1451 retry:
1452 /*
1453 * One of the few rules of preemptible RCU is that one cannot do
1454 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1455 * part of the read side critical section was irqs-enabled -- see
1456 * rcu_read_unlock_special().
1457 *
1458 * Since ctx->lock nests under rq->lock we must ensure the entire read
1459 * side critical section has interrupts disabled.
1460 */
1461 local_irq_save(*flags);
1462 rcu_read_lock();
1463 ctx = rcu_dereference(task->perf_event_ctxp);
1464 if (ctx) {
1465 /*
1466 * If this context is a clone of another, it might
1467 * get swapped for another underneath us by
1468 * perf_event_task_sched_out, though the
1469 * rcu_read_lock() protects us from any context
1470 * getting freed. Lock the context and check if it
1471 * got swapped before we could get the lock, and retry
1472 * if so. If we locked the right context, then it
1473 * can't get swapped on us any more.
1474 */
1475 raw_spin_lock(&ctx->lock);
1476 if (ctx != rcu_dereference(task->perf_event_ctxp)) {
1477 raw_spin_unlock(&ctx->lock);
1478 rcu_read_unlock();
1479 local_irq_restore(*flags);
1480 goto retry;
1481 }
1482
1483 if (ctx->task == TASK_TOMBSTONE ||
1484 !refcount_inc_not_zero(&ctx->refcount)) {
1485 raw_spin_unlock(&ctx->lock);
1486 ctx = NULL;
1487 } else {
1488 WARN_ON_ONCE(ctx->task != task);
1489 }
1490 }
1491 rcu_read_unlock();
1492 if (!ctx)
1493 local_irq_restore(*flags);
1494 return ctx;
1495 }
1496
1497 /*
1498 * Get the context for a task and increment its pin_count so it
1499 * can't get swapped to another task. This also increments its
1500 * reference count so that the context can't get freed.
1501 */
1502 static struct perf_event_context *
perf_pin_task_context(struct task_struct * task)1503 perf_pin_task_context(struct task_struct *task)
1504 {
1505 struct perf_event_context *ctx;
1506 unsigned long flags;
1507
1508 ctx = perf_lock_task_context(task, &flags);
1509 if (ctx) {
1510 ++ctx->pin_count;
1511 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1512 }
1513 return ctx;
1514 }
1515
perf_unpin_context(struct perf_event_context * ctx)1516 static void perf_unpin_context(struct perf_event_context *ctx)
1517 {
1518 unsigned long flags;
1519
1520 raw_spin_lock_irqsave(&ctx->lock, flags);
1521 --ctx->pin_count;
1522 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1523 }
1524
1525 /*
1526 * Update the record of the current time in a context.
1527 */
__update_context_time(struct perf_event_context * ctx,bool adv)1528 static void __update_context_time(struct perf_event_context *ctx, bool adv)
1529 {
1530 u64 now = perf_clock();
1531
1532 lockdep_assert_held(&ctx->lock);
1533
1534 if (adv)
1535 ctx->time += now - ctx->timestamp;
1536 ctx->timestamp = now;
1537
1538 /*
1539 * The above: time' = time + (now - timestamp), can be re-arranged
1540 * into: time` = now + (time - timestamp), which gives a single value
1541 * offset to compute future time without locks on.
1542 *
1543 * See perf_event_time_now(), which can be used from NMI context where
1544 * it's (obviously) not possible to acquire ctx->lock in order to read
1545 * both the above values in a consistent manner.
1546 */
1547 WRITE_ONCE(ctx->timeoffset, ctx->time - ctx->timestamp);
1548 }
1549
update_context_time(struct perf_event_context * ctx)1550 static void update_context_time(struct perf_event_context *ctx)
1551 {
1552 __update_context_time(ctx, true);
1553 }
1554
perf_event_time(struct perf_event * event)1555 static u64 perf_event_time(struct perf_event *event)
1556 {
1557 struct perf_event_context *ctx = event->ctx;
1558
1559 if (unlikely(!ctx))
1560 return 0;
1561
1562 if (is_cgroup_event(event))
1563 return perf_cgroup_event_time(event);
1564
1565 return ctx->time;
1566 }
1567
perf_event_time_now(struct perf_event * event,u64 now)1568 static u64 perf_event_time_now(struct perf_event *event, u64 now)
1569 {
1570 struct perf_event_context *ctx = event->ctx;
1571
1572 if (unlikely(!ctx))
1573 return 0;
1574
1575 if (is_cgroup_event(event))
1576 return perf_cgroup_event_time_now(event, now);
1577
1578 if (!(__load_acquire(&ctx->is_active) & EVENT_TIME))
1579 return ctx->time;
1580
1581 now += READ_ONCE(ctx->timeoffset);
1582 return now;
1583 }
1584
get_event_type(struct perf_event * event)1585 static enum event_type_t get_event_type(struct perf_event *event)
1586 {
1587 struct perf_event_context *ctx = event->ctx;
1588 enum event_type_t event_type;
1589
1590 lockdep_assert_held(&ctx->lock);
1591
1592 /*
1593 * It's 'group type', really, because if our group leader is
1594 * pinned, so are we.
1595 */
1596 if (event->group_leader != event)
1597 event = event->group_leader;
1598
1599 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1600 if (!ctx->task)
1601 event_type |= EVENT_CPU;
1602
1603 return event_type;
1604 }
1605
1606 /*
1607 * Helper function to initialize event group nodes.
1608 */
init_event_group(struct perf_event * event)1609 static void init_event_group(struct perf_event *event)
1610 {
1611 RB_CLEAR_NODE(&event->group_node);
1612 event->group_index = 0;
1613 }
1614
1615 /*
1616 * Extract pinned or flexible groups from the context
1617 * based on event attrs bits.
1618 */
1619 static struct perf_event_groups *
get_event_groups(struct perf_event * event,struct perf_event_context * ctx)1620 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1621 {
1622 if (event->attr.pinned)
1623 return &ctx->pinned_groups;
1624 else
1625 return &ctx->flexible_groups;
1626 }
1627
1628 /*
1629 * Helper function to initializes perf_event_group trees.
1630 */
perf_event_groups_init(struct perf_event_groups * groups)1631 static void perf_event_groups_init(struct perf_event_groups *groups)
1632 {
1633 groups->tree = RB_ROOT;
1634 groups->index = 0;
1635 }
1636
event_cgroup(const struct perf_event * event)1637 static inline struct cgroup *event_cgroup(const struct perf_event *event)
1638 {
1639 struct cgroup *cgroup = NULL;
1640
1641 #ifdef CONFIG_CGROUP_PERF
1642 if (event->cgrp)
1643 cgroup = event->cgrp->css.cgroup;
1644 #endif
1645
1646 return cgroup;
1647 }
1648
1649 /*
1650 * Compare function for event groups;
1651 *
1652 * Implements complex key that first sorts by CPU and then by virtual index
1653 * which provides ordering when rotating groups for the same CPU.
1654 */
1655 static __always_inline int
perf_event_groups_cmp(const int left_cpu,const struct pmu * left_pmu,const struct cgroup * left_cgroup,const u64 left_group_index,const struct perf_event * right)1656 perf_event_groups_cmp(const int left_cpu, const struct pmu *left_pmu,
1657 const struct cgroup *left_cgroup, const u64 left_group_index,
1658 const struct perf_event *right)
1659 {
1660 if (left_cpu < right->cpu)
1661 return -1;
1662 if (left_cpu > right->cpu)
1663 return 1;
1664
1665 if (left_pmu) {
1666 if (left_pmu < right->pmu_ctx->pmu)
1667 return -1;
1668 if (left_pmu > right->pmu_ctx->pmu)
1669 return 1;
1670 }
1671
1672 #ifdef CONFIG_CGROUP_PERF
1673 {
1674 const struct cgroup *right_cgroup = event_cgroup(right);
1675
1676 if (left_cgroup != right_cgroup) {
1677 if (!left_cgroup) {
1678 /*
1679 * Left has no cgroup but right does, no
1680 * cgroups come first.
1681 */
1682 return -1;
1683 }
1684 if (!right_cgroup) {
1685 /*
1686 * Right has no cgroup but left does, no
1687 * cgroups come first.
1688 */
1689 return 1;
1690 }
1691 /* Two dissimilar cgroups, order by id. */
1692 if (cgroup_id(left_cgroup) < cgroup_id(right_cgroup))
1693 return -1;
1694
1695 return 1;
1696 }
1697 }
1698 #endif
1699
1700 if (left_group_index < right->group_index)
1701 return -1;
1702 if (left_group_index > right->group_index)
1703 return 1;
1704
1705 return 0;
1706 }
1707
1708 #define __node_2_pe(node) \
1709 rb_entry((node), struct perf_event, group_node)
1710
__group_less(struct rb_node * a,const struct rb_node * b)1711 static inline bool __group_less(struct rb_node *a, const struct rb_node *b)
1712 {
1713 struct perf_event *e = __node_2_pe(a);
1714 return perf_event_groups_cmp(e->cpu, e->pmu_ctx->pmu, event_cgroup(e),
1715 e->group_index, __node_2_pe(b)) < 0;
1716 }
1717
1718 struct __group_key {
1719 int cpu;
1720 struct pmu *pmu;
1721 struct cgroup *cgroup;
1722 };
1723
__group_cmp(const void * key,const struct rb_node * node)1724 static inline int __group_cmp(const void *key, const struct rb_node *node)
1725 {
1726 const struct __group_key *a = key;
1727 const struct perf_event *b = __node_2_pe(node);
1728
1729 /* partial/subtree match: @cpu, @pmu, @cgroup; ignore: @group_index */
1730 return perf_event_groups_cmp(a->cpu, a->pmu, a->cgroup, b->group_index, b);
1731 }
1732
1733 static inline int
__group_cmp_ignore_cgroup(const void * key,const struct rb_node * node)1734 __group_cmp_ignore_cgroup(const void *key, const struct rb_node *node)
1735 {
1736 const struct __group_key *a = key;
1737 const struct perf_event *b = __node_2_pe(node);
1738
1739 /* partial/subtree match: @cpu, @pmu, ignore: @cgroup, @group_index */
1740 return perf_event_groups_cmp(a->cpu, a->pmu, event_cgroup(b),
1741 b->group_index, b);
1742 }
1743
1744 /*
1745 * Insert @event into @groups' tree; using
1746 * {@event->cpu, @event->pmu_ctx->pmu, event_cgroup(@event), ++@groups->index}
1747 * as key. This places it last inside the {cpu,pmu,cgroup} subtree.
1748 */
1749 static void
perf_event_groups_insert(struct perf_event_groups * groups,struct perf_event * event)1750 perf_event_groups_insert(struct perf_event_groups *groups,
1751 struct perf_event *event)
1752 {
1753 event->group_index = ++groups->index;
1754
1755 rb_add(&event->group_node, &groups->tree, __group_less);
1756 }
1757
1758 /*
1759 * Helper function to insert event into the pinned or flexible groups.
1760 */
1761 static void
add_event_to_groups(struct perf_event * event,struct perf_event_context * ctx)1762 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1763 {
1764 struct perf_event_groups *groups;
1765
1766 groups = get_event_groups(event, ctx);
1767 perf_event_groups_insert(groups, event);
1768 }
1769
1770 /*
1771 * Delete a group from a tree.
1772 */
1773 static void
perf_event_groups_delete(struct perf_event_groups * groups,struct perf_event * event)1774 perf_event_groups_delete(struct perf_event_groups *groups,
1775 struct perf_event *event)
1776 {
1777 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1778 RB_EMPTY_ROOT(&groups->tree));
1779
1780 rb_erase(&event->group_node, &groups->tree);
1781 init_event_group(event);
1782 }
1783
1784 /*
1785 * Helper function to delete event from its groups.
1786 */
1787 static void
del_event_from_groups(struct perf_event * event,struct perf_event_context * ctx)1788 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1789 {
1790 struct perf_event_groups *groups;
1791
1792 groups = get_event_groups(event, ctx);
1793 perf_event_groups_delete(groups, event);
1794 }
1795
1796 /*
1797 * Get the leftmost event in the {cpu,pmu,cgroup} subtree.
1798 */
1799 static struct perf_event *
perf_event_groups_first(struct perf_event_groups * groups,int cpu,struct pmu * pmu,struct cgroup * cgrp)1800 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1801 struct pmu *pmu, struct cgroup *cgrp)
1802 {
1803 struct __group_key key = {
1804 .cpu = cpu,
1805 .pmu = pmu,
1806 .cgroup = cgrp,
1807 };
1808 struct rb_node *node;
1809
1810 node = rb_find_first(&key, &groups->tree, __group_cmp);
1811 if (node)
1812 return __node_2_pe(node);
1813
1814 return NULL;
1815 }
1816
1817 static struct perf_event *
perf_event_groups_next(struct perf_event * event,struct pmu * pmu)1818 perf_event_groups_next(struct perf_event *event, struct pmu *pmu)
1819 {
1820 struct __group_key key = {
1821 .cpu = event->cpu,
1822 .pmu = pmu,
1823 .cgroup = event_cgroup(event),
1824 };
1825 struct rb_node *next;
1826
1827 next = rb_next_match(&key, &event->group_node, __group_cmp);
1828 if (next)
1829 return __node_2_pe(next);
1830
1831 return NULL;
1832 }
1833
1834 #define perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) \
1835 for (event = perf_event_groups_first(groups, cpu, pmu, NULL); \
1836 event; event = perf_event_groups_next(event, pmu))
1837
1838 /*
1839 * Iterate through the whole groups tree.
1840 */
1841 #define perf_event_groups_for_each(event, groups) \
1842 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1843 typeof(*event), group_node); event; \
1844 event = rb_entry_safe(rb_next(&event->group_node), \
1845 typeof(*event), group_node))
1846
1847 /*
1848 * Does the event attribute request inherit with PERF_SAMPLE_READ
1849 */
has_inherit_and_sample_read(struct perf_event_attr * attr)1850 static inline bool has_inherit_and_sample_read(struct perf_event_attr *attr)
1851 {
1852 return attr->inherit && (attr->sample_type & PERF_SAMPLE_READ);
1853 }
1854
1855 /*
1856 * Add an event from the lists for its context.
1857 * Must be called with ctx->mutex and ctx->lock held.
1858 */
1859 static void
list_add_event(struct perf_event * event,struct perf_event_context * ctx)1860 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1861 {
1862 lockdep_assert_held(&ctx->lock);
1863
1864 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1865 event->attach_state |= PERF_ATTACH_CONTEXT;
1866
1867 event->tstamp = perf_event_time(event);
1868
1869 /*
1870 * If we're a stand alone event or group leader, we go to the context
1871 * list, group events are kept attached to the group so that
1872 * perf_group_detach can, at all times, locate all siblings.
1873 */
1874 if (event->group_leader == event) {
1875 event->group_caps = event->event_caps;
1876 add_event_to_groups(event, ctx);
1877 }
1878
1879 list_add_rcu(&event->event_entry, &ctx->event_list);
1880 ctx->nr_events++;
1881 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
1882 ctx->nr_user++;
1883 if (event->attr.inherit_stat)
1884 ctx->nr_stat++;
1885 if (has_inherit_and_sample_read(&event->attr))
1886 local_inc(&ctx->nr_no_switch_fast);
1887
1888 if (event->state > PERF_EVENT_STATE_OFF)
1889 perf_cgroup_event_enable(event, ctx);
1890
1891 ctx->generation++;
1892 event->pmu_ctx->nr_events++;
1893 }
1894
1895 /*
1896 * Initialize event state based on the perf_event_attr::disabled.
1897 */
perf_event__state_init(struct perf_event * event)1898 static inline void perf_event__state_init(struct perf_event *event)
1899 {
1900 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1901 PERF_EVENT_STATE_INACTIVE;
1902 }
1903
__perf_event_read_size(u64 read_format,int nr_siblings)1904 static int __perf_event_read_size(u64 read_format, int nr_siblings)
1905 {
1906 int entry = sizeof(u64); /* value */
1907 int size = 0;
1908 int nr = 1;
1909
1910 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1911 size += sizeof(u64);
1912
1913 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1914 size += sizeof(u64);
1915
1916 if (read_format & PERF_FORMAT_ID)
1917 entry += sizeof(u64);
1918
1919 if (read_format & PERF_FORMAT_LOST)
1920 entry += sizeof(u64);
1921
1922 if (read_format & PERF_FORMAT_GROUP) {
1923 nr += nr_siblings;
1924 size += sizeof(u64);
1925 }
1926
1927 /*
1928 * Since perf_event_validate_size() limits this to 16k and inhibits
1929 * adding more siblings, this will never overflow.
1930 */
1931 return size + nr * entry;
1932 }
1933
__perf_event_header_size(struct perf_event * event,u64 sample_type)1934 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1935 {
1936 struct perf_sample_data *data;
1937 u16 size = 0;
1938
1939 if (sample_type & PERF_SAMPLE_IP)
1940 size += sizeof(data->ip);
1941
1942 if (sample_type & PERF_SAMPLE_ADDR)
1943 size += sizeof(data->addr);
1944
1945 if (sample_type & PERF_SAMPLE_PERIOD)
1946 size += sizeof(data->period);
1947
1948 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
1949 size += sizeof(data->weight.full);
1950
1951 if (sample_type & PERF_SAMPLE_READ)
1952 size += event->read_size;
1953
1954 if (sample_type & PERF_SAMPLE_DATA_SRC)
1955 size += sizeof(data->data_src.val);
1956
1957 if (sample_type & PERF_SAMPLE_TRANSACTION)
1958 size += sizeof(data->txn);
1959
1960 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1961 size += sizeof(data->phys_addr);
1962
1963 if (sample_type & PERF_SAMPLE_CGROUP)
1964 size += sizeof(data->cgroup);
1965
1966 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
1967 size += sizeof(data->data_page_size);
1968
1969 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
1970 size += sizeof(data->code_page_size);
1971
1972 event->header_size = size;
1973 }
1974
1975 /*
1976 * Called at perf_event creation and when events are attached/detached from a
1977 * group.
1978 */
perf_event__header_size(struct perf_event * event)1979 static void perf_event__header_size(struct perf_event *event)
1980 {
1981 event->read_size =
1982 __perf_event_read_size(event->attr.read_format,
1983 event->group_leader->nr_siblings);
1984 __perf_event_header_size(event, event->attr.sample_type);
1985 }
1986
perf_event__id_header_size(struct perf_event * event)1987 static void perf_event__id_header_size(struct perf_event *event)
1988 {
1989 struct perf_sample_data *data;
1990 u64 sample_type = event->attr.sample_type;
1991 u16 size = 0;
1992
1993 if (sample_type & PERF_SAMPLE_TID)
1994 size += sizeof(data->tid_entry);
1995
1996 if (sample_type & PERF_SAMPLE_TIME)
1997 size += sizeof(data->time);
1998
1999 if (sample_type & PERF_SAMPLE_IDENTIFIER)
2000 size += sizeof(data->id);
2001
2002 if (sample_type & PERF_SAMPLE_ID)
2003 size += sizeof(data->id);
2004
2005 if (sample_type & PERF_SAMPLE_STREAM_ID)
2006 size += sizeof(data->stream_id);
2007
2008 if (sample_type & PERF_SAMPLE_CPU)
2009 size += sizeof(data->cpu_entry);
2010
2011 event->id_header_size = size;
2012 }
2013
2014 /*
2015 * Check that adding an event to the group does not result in anybody
2016 * overflowing the 64k event limit imposed by the output buffer.
2017 *
2018 * Specifically, check that the read_size for the event does not exceed 16k,
2019 * read_size being the one term that grows with groups size. Since read_size
2020 * depends on per-event read_format, also (re)check the existing events.
2021 *
2022 * This leaves 48k for the constant size fields and things like callchains,
2023 * branch stacks and register sets.
2024 */
perf_event_validate_size(struct perf_event * event)2025 static bool perf_event_validate_size(struct perf_event *event)
2026 {
2027 struct perf_event *sibling, *group_leader = event->group_leader;
2028
2029 if (__perf_event_read_size(event->attr.read_format,
2030 group_leader->nr_siblings + 1) > 16*1024)
2031 return false;
2032
2033 if (__perf_event_read_size(group_leader->attr.read_format,
2034 group_leader->nr_siblings + 1) > 16*1024)
2035 return false;
2036
2037 /*
2038 * When creating a new group leader, group_leader->ctx is initialized
2039 * after the size has been validated, but we cannot safely use
2040 * for_each_sibling_event() until group_leader->ctx is set. A new group
2041 * leader cannot have any siblings yet, so we can safely skip checking
2042 * the non-existent siblings.
2043 */
2044 if (event == group_leader)
2045 return true;
2046
2047 for_each_sibling_event(sibling, group_leader) {
2048 if (__perf_event_read_size(sibling->attr.read_format,
2049 group_leader->nr_siblings + 1) > 16*1024)
2050 return false;
2051 }
2052
2053 return true;
2054 }
2055
perf_group_attach(struct perf_event * event)2056 static void perf_group_attach(struct perf_event *event)
2057 {
2058 struct perf_event *group_leader = event->group_leader, *pos;
2059
2060 lockdep_assert_held(&event->ctx->lock);
2061
2062 /*
2063 * We can have double attach due to group movement (move_group) in
2064 * perf_event_open().
2065 */
2066 if (event->attach_state & PERF_ATTACH_GROUP)
2067 return;
2068
2069 event->attach_state |= PERF_ATTACH_GROUP;
2070
2071 if (group_leader == event)
2072 return;
2073
2074 WARN_ON_ONCE(group_leader->ctx != event->ctx);
2075
2076 group_leader->group_caps &= event->event_caps;
2077
2078 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
2079 group_leader->nr_siblings++;
2080 group_leader->group_generation++;
2081
2082 perf_event__header_size(group_leader);
2083
2084 for_each_sibling_event(pos, group_leader)
2085 perf_event__header_size(pos);
2086 }
2087
2088 /*
2089 * Remove an event from the lists for its context.
2090 * Must be called with ctx->mutex and ctx->lock held.
2091 */
2092 static void
list_del_event(struct perf_event * event,struct perf_event_context * ctx)2093 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
2094 {
2095 WARN_ON_ONCE(event->ctx != ctx);
2096 lockdep_assert_held(&ctx->lock);
2097
2098 /*
2099 * We can have double detach due to exit/hot-unplug + close.
2100 */
2101 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
2102 return;
2103
2104 event->attach_state &= ~PERF_ATTACH_CONTEXT;
2105
2106 ctx->nr_events--;
2107 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
2108 ctx->nr_user--;
2109 if (event->attr.inherit_stat)
2110 ctx->nr_stat--;
2111 if (has_inherit_and_sample_read(&event->attr))
2112 local_dec(&ctx->nr_no_switch_fast);
2113
2114 list_del_rcu(&event->event_entry);
2115
2116 if (event->group_leader == event)
2117 del_event_from_groups(event, ctx);
2118
2119 /*
2120 * If event was in error state, then keep it
2121 * that way, otherwise bogus counts will be
2122 * returned on read(). The only way to get out
2123 * of error state is by explicit re-enabling
2124 * of the event
2125 */
2126 if (event->state > PERF_EVENT_STATE_OFF) {
2127 perf_cgroup_event_disable(event, ctx);
2128 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2129 }
2130
2131 ctx->generation++;
2132 event->pmu_ctx->nr_events--;
2133 }
2134
2135 static int
perf_aux_output_match(struct perf_event * event,struct perf_event * aux_event)2136 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2137 {
2138 if (!has_aux(aux_event))
2139 return 0;
2140
2141 if (!event->pmu->aux_output_match)
2142 return 0;
2143
2144 return event->pmu->aux_output_match(aux_event);
2145 }
2146
2147 static void put_event(struct perf_event *event);
2148 static void event_sched_out(struct perf_event *event,
2149 struct perf_event_context *ctx);
2150
perf_put_aux_event(struct perf_event * event)2151 static void perf_put_aux_event(struct perf_event *event)
2152 {
2153 struct perf_event_context *ctx = event->ctx;
2154 struct perf_event *iter;
2155
2156 /*
2157 * If event uses aux_event tear down the link
2158 */
2159 if (event->aux_event) {
2160 iter = event->aux_event;
2161 event->aux_event = NULL;
2162 put_event(iter);
2163 return;
2164 }
2165
2166 /*
2167 * If the event is an aux_event, tear down all links to
2168 * it from other events.
2169 */
2170 for_each_sibling_event(iter, event->group_leader) {
2171 if (iter->aux_event != event)
2172 continue;
2173
2174 iter->aux_event = NULL;
2175 put_event(event);
2176
2177 /*
2178 * If it's ACTIVE, schedule it out and put it into ERROR
2179 * state so that we don't try to schedule it again. Note
2180 * that perf_event_enable() will clear the ERROR status.
2181 */
2182 event_sched_out(iter, ctx);
2183 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2184 }
2185 }
2186
perf_need_aux_event(struct perf_event * event)2187 static bool perf_need_aux_event(struct perf_event *event)
2188 {
2189 return event->attr.aux_output || has_aux_action(event);
2190 }
2191
perf_get_aux_event(struct perf_event * event,struct perf_event * group_leader)2192 static int perf_get_aux_event(struct perf_event *event,
2193 struct perf_event *group_leader)
2194 {
2195 /*
2196 * Our group leader must be an aux event if we want to be
2197 * an aux_output. This way, the aux event will precede its
2198 * aux_output events in the group, and therefore will always
2199 * schedule first.
2200 */
2201 if (!group_leader)
2202 return 0;
2203
2204 /*
2205 * aux_output and aux_sample_size are mutually exclusive.
2206 */
2207 if (event->attr.aux_output && event->attr.aux_sample_size)
2208 return 0;
2209
2210 if (event->attr.aux_output &&
2211 !perf_aux_output_match(event, group_leader))
2212 return 0;
2213
2214 if ((event->attr.aux_pause || event->attr.aux_resume) &&
2215 !(group_leader->pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE))
2216 return 0;
2217
2218 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2219 return 0;
2220
2221 if (!atomic_long_inc_not_zero(&group_leader->refcount))
2222 return 0;
2223
2224 /*
2225 * Link aux_outputs to their aux event; this is undone in
2226 * perf_group_detach() by perf_put_aux_event(). When the
2227 * group in torn down, the aux_output events loose their
2228 * link to the aux_event and can't schedule any more.
2229 */
2230 event->aux_event = group_leader;
2231
2232 return 1;
2233 }
2234
get_event_list(struct perf_event * event)2235 static inline struct list_head *get_event_list(struct perf_event *event)
2236 {
2237 return event->attr.pinned ? &event->pmu_ctx->pinned_active :
2238 &event->pmu_ctx->flexible_active;
2239 }
2240
2241 /*
2242 * Events that have PERF_EV_CAP_SIBLING require being part of a group and
2243 * cannot exist on their own, schedule them out and move them into the ERROR
2244 * state. Also see _perf_event_enable(), it will not be able to recover
2245 * this ERROR state.
2246 */
perf_remove_sibling_event(struct perf_event * event)2247 static inline void perf_remove_sibling_event(struct perf_event *event)
2248 {
2249 event_sched_out(event, event->ctx);
2250 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2251 }
2252
perf_group_detach(struct perf_event * event)2253 static void perf_group_detach(struct perf_event *event)
2254 {
2255 struct perf_event *leader = event->group_leader;
2256 struct perf_event *sibling, *tmp;
2257 struct perf_event_context *ctx = event->ctx;
2258
2259 lockdep_assert_held(&ctx->lock);
2260
2261 /*
2262 * We can have double detach due to exit/hot-unplug + close.
2263 */
2264 if (!(event->attach_state & PERF_ATTACH_GROUP))
2265 return;
2266
2267 event->attach_state &= ~PERF_ATTACH_GROUP;
2268
2269 perf_put_aux_event(event);
2270
2271 /*
2272 * If this is a sibling, remove it from its group.
2273 */
2274 if (leader != event) {
2275 list_del_init(&event->sibling_list);
2276 event->group_leader->nr_siblings--;
2277 event->group_leader->group_generation++;
2278 goto out;
2279 }
2280
2281 /*
2282 * If this was a group event with sibling events then
2283 * upgrade the siblings to singleton events by adding them
2284 * to whatever list we are on.
2285 */
2286 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2287
2288 if (sibling->event_caps & PERF_EV_CAP_SIBLING)
2289 perf_remove_sibling_event(sibling);
2290
2291 sibling->group_leader = sibling;
2292 list_del_init(&sibling->sibling_list);
2293
2294 /* Inherit group flags from the previous leader */
2295 sibling->group_caps = event->group_caps;
2296
2297 if (sibling->attach_state & PERF_ATTACH_CONTEXT) {
2298 add_event_to_groups(sibling, event->ctx);
2299
2300 if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2301 list_add_tail(&sibling->active_list, get_event_list(sibling));
2302 }
2303
2304 WARN_ON_ONCE(sibling->ctx != event->ctx);
2305 }
2306
2307 out:
2308 for_each_sibling_event(tmp, leader)
2309 perf_event__header_size(tmp);
2310
2311 perf_event__header_size(leader);
2312 }
2313
2314 static void sync_child_event(struct perf_event *child_event);
2315
perf_child_detach(struct perf_event * event)2316 static void perf_child_detach(struct perf_event *event)
2317 {
2318 struct perf_event *parent_event = event->parent;
2319
2320 if (!(event->attach_state & PERF_ATTACH_CHILD))
2321 return;
2322
2323 event->attach_state &= ~PERF_ATTACH_CHILD;
2324
2325 if (WARN_ON_ONCE(!parent_event))
2326 return;
2327
2328 lockdep_assert_held(&parent_event->child_mutex);
2329
2330 sync_child_event(event);
2331 list_del_init(&event->child_list);
2332 }
2333
is_orphaned_event(struct perf_event * event)2334 static bool is_orphaned_event(struct perf_event *event)
2335 {
2336 return event->state == PERF_EVENT_STATE_DEAD;
2337 }
2338
2339 static inline int
event_filter_match(struct perf_event * event)2340 event_filter_match(struct perf_event *event)
2341 {
2342 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2343 perf_cgroup_match(event);
2344 }
2345
2346 static void
event_sched_out(struct perf_event * event,struct perf_event_context * ctx)2347 event_sched_out(struct perf_event *event, struct perf_event_context *ctx)
2348 {
2349 struct perf_event_pmu_context *epc = event->pmu_ctx;
2350 struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu);
2351 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2352
2353 // XXX cpc serialization, probably per-cpu IRQ disabled
2354
2355 WARN_ON_ONCE(event->ctx != ctx);
2356 lockdep_assert_held(&ctx->lock);
2357
2358 if (event->state != PERF_EVENT_STATE_ACTIVE)
2359 return;
2360
2361 /*
2362 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2363 * we can schedule events _OUT_ individually through things like
2364 * __perf_remove_from_context().
2365 */
2366 list_del_init(&event->active_list);
2367
2368 perf_pmu_disable(event->pmu);
2369
2370 event->pmu->del(event, 0);
2371 event->oncpu = -1;
2372
2373 if (event->pending_disable) {
2374 event->pending_disable = 0;
2375 perf_cgroup_event_disable(event, ctx);
2376 state = PERF_EVENT_STATE_OFF;
2377 }
2378
2379 perf_event_set_state(event, state);
2380
2381 if (!is_software_event(event))
2382 cpc->active_oncpu--;
2383 if (event->attr.freq && event->attr.sample_freq) {
2384 ctx->nr_freq--;
2385 epc->nr_freq--;
2386 }
2387 if (event->attr.exclusive || !cpc->active_oncpu)
2388 cpc->exclusive = 0;
2389
2390 perf_pmu_enable(event->pmu);
2391 }
2392
2393 static void
group_sched_out(struct perf_event * group_event,struct perf_event_context * ctx)2394 group_sched_out(struct perf_event *group_event, struct perf_event_context *ctx)
2395 {
2396 struct perf_event *event;
2397
2398 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2399 return;
2400
2401 perf_assert_pmu_disabled(group_event->pmu_ctx->pmu);
2402
2403 event_sched_out(group_event, ctx);
2404
2405 /*
2406 * Schedule out siblings (if any):
2407 */
2408 for_each_sibling_event(event, group_event)
2409 event_sched_out(event, ctx);
2410 }
2411
2412 static inline void
__ctx_time_update(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,bool final)2413 __ctx_time_update(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx, bool final)
2414 {
2415 if (ctx->is_active & EVENT_TIME) {
2416 if (ctx->is_active & EVENT_FROZEN)
2417 return;
2418 update_context_time(ctx);
2419 update_cgrp_time_from_cpuctx(cpuctx, final);
2420 }
2421 }
2422
2423 static inline void
ctx_time_update(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)2424 ctx_time_update(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx)
2425 {
2426 __ctx_time_update(cpuctx, ctx, false);
2427 }
2428
2429 /*
2430 * To be used inside perf_ctx_lock() / perf_ctx_unlock(). Lasts until perf_ctx_unlock().
2431 */
2432 static inline void
ctx_time_freeze(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)2433 ctx_time_freeze(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx)
2434 {
2435 ctx_time_update(cpuctx, ctx);
2436 if (ctx->is_active & EVENT_TIME)
2437 ctx->is_active |= EVENT_FROZEN;
2438 }
2439
2440 static inline void
ctx_time_update_event(struct perf_event_context * ctx,struct perf_event * event)2441 ctx_time_update_event(struct perf_event_context *ctx, struct perf_event *event)
2442 {
2443 if (ctx->is_active & EVENT_TIME) {
2444 if (ctx->is_active & EVENT_FROZEN)
2445 return;
2446 update_context_time(ctx);
2447 update_cgrp_time_from_event(event);
2448 }
2449 }
2450
2451 #define DETACH_GROUP 0x01UL
2452 #define DETACH_CHILD 0x02UL
2453 #define DETACH_DEAD 0x04UL
2454
2455 /*
2456 * Cross CPU call to remove a performance event
2457 *
2458 * We disable the event on the hardware level first. After that we
2459 * remove it from the context list.
2460 */
2461 static void
__perf_remove_from_context(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)2462 __perf_remove_from_context(struct perf_event *event,
2463 struct perf_cpu_context *cpuctx,
2464 struct perf_event_context *ctx,
2465 void *info)
2466 {
2467 struct perf_event_pmu_context *pmu_ctx = event->pmu_ctx;
2468 unsigned long flags = (unsigned long)info;
2469
2470 ctx_time_update(cpuctx, ctx);
2471
2472 /*
2473 * Ensure event_sched_out() switches to OFF, at the very least
2474 * this avoids raising perf_pending_task() at this time.
2475 */
2476 if (flags & DETACH_DEAD)
2477 event->pending_disable = 1;
2478 event_sched_out(event, ctx);
2479 if (flags & DETACH_GROUP)
2480 perf_group_detach(event);
2481 if (flags & DETACH_CHILD)
2482 perf_child_detach(event);
2483 list_del_event(event, ctx);
2484 if (flags & DETACH_DEAD)
2485 event->state = PERF_EVENT_STATE_DEAD;
2486
2487 if (!pmu_ctx->nr_events) {
2488 pmu_ctx->rotate_necessary = 0;
2489
2490 if (ctx->task && ctx->is_active) {
2491 struct perf_cpu_pmu_context *cpc = this_cpc(pmu_ctx->pmu);
2492
2493 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
2494 cpc->task_epc = NULL;
2495 }
2496 }
2497
2498 if (!ctx->nr_events && ctx->is_active) {
2499 if (ctx == &cpuctx->ctx)
2500 update_cgrp_time_from_cpuctx(cpuctx, true);
2501
2502 ctx->is_active = 0;
2503 if (ctx->task) {
2504 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2505 cpuctx->task_ctx = NULL;
2506 }
2507 }
2508 }
2509
2510 /*
2511 * Remove the event from a task's (or a CPU's) list of events.
2512 *
2513 * If event->ctx is a cloned context, callers must make sure that
2514 * every task struct that event->ctx->task could possibly point to
2515 * remains valid. This is OK when called from perf_release since
2516 * that only calls us on the top-level context, which can't be a clone.
2517 * When called from perf_event_exit_task, it's OK because the
2518 * context has been detached from its task.
2519 */
perf_remove_from_context(struct perf_event * event,unsigned long flags)2520 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2521 {
2522 struct perf_event_context *ctx = event->ctx;
2523
2524 lockdep_assert_held(&ctx->mutex);
2525
2526 /*
2527 * Because of perf_event_exit_task(), perf_remove_from_context() ought
2528 * to work in the face of TASK_TOMBSTONE, unlike every other
2529 * event_function_call() user.
2530 */
2531 raw_spin_lock_irq(&ctx->lock);
2532 if (!ctx->is_active) {
2533 __perf_remove_from_context(event, this_cpu_ptr(&perf_cpu_context),
2534 ctx, (void *)flags);
2535 raw_spin_unlock_irq(&ctx->lock);
2536 return;
2537 }
2538 raw_spin_unlock_irq(&ctx->lock);
2539
2540 event_function_call(event, __perf_remove_from_context, (void *)flags);
2541 }
2542
2543 /*
2544 * Cross CPU call to disable a performance event
2545 */
__perf_event_disable(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)2546 static void __perf_event_disable(struct perf_event *event,
2547 struct perf_cpu_context *cpuctx,
2548 struct perf_event_context *ctx,
2549 void *info)
2550 {
2551 if (event->state < PERF_EVENT_STATE_INACTIVE)
2552 return;
2553
2554 perf_pmu_disable(event->pmu_ctx->pmu);
2555 ctx_time_update_event(ctx, event);
2556
2557 if (event == event->group_leader)
2558 group_sched_out(event, ctx);
2559 else
2560 event_sched_out(event, ctx);
2561
2562 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2563 perf_cgroup_event_disable(event, ctx);
2564
2565 perf_pmu_enable(event->pmu_ctx->pmu);
2566 }
2567
2568 /*
2569 * Disable an event.
2570 *
2571 * If event->ctx is a cloned context, callers must make sure that
2572 * every task struct that event->ctx->task could possibly point to
2573 * remains valid. This condition is satisfied when called through
2574 * perf_event_for_each_child or perf_event_for_each because they
2575 * hold the top-level event's child_mutex, so any descendant that
2576 * goes to exit will block in perf_event_exit_event().
2577 *
2578 * When called from perf_pending_disable it's OK because event->ctx
2579 * is the current context on this CPU and preemption is disabled,
2580 * hence we can't get into perf_event_task_sched_out for this context.
2581 */
_perf_event_disable(struct perf_event * event)2582 static void _perf_event_disable(struct perf_event *event)
2583 {
2584 struct perf_event_context *ctx = event->ctx;
2585
2586 raw_spin_lock_irq(&ctx->lock);
2587 if (event->state <= PERF_EVENT_STATE_OFF) {
2588 raw_spin_unlock_irq(&ctx->lock);
2589 return;
2590 }
2591 raw_spin_unlock_irq(&ctx->lock);
2592
2593 event_function_call(event, __perf_event_disable, NULL);
2594 }
2595
perf_event_disable_local(struct perf_event * event)2596 void perf_event_disable_local(struct perf_event *event)
2597 {
2598 event_function_local(event, __perf_event_disable, NULL);
2599 }
2600
2601 /*
2602 * Strictly speaking kernel users cannot create groups and therefore this
2603 * interface does not need the perf_event_ctx_lock() magic.
2604 */
perf_event_disable(struct perf_event * event)2605 void perf_event_disable(struct perf_event *event)
2606 {
2607 struct perf_event_context *ctx;
2608
2609 ctx = perf_event_ctx_lock(event);
2610 _perf_event_disable(event);
2611 perf_event_ctx_unlock(event, ctx);
2612 }
2613 EXPORT_SYMBOL_GPL(perf_event_disable);
2614
perf_event_disable_inatomic(struct perf_event * event)2615 void perf_event_disable_inatomic(struct perf_event *event)
2616 {
2617 event->pending_disable = 1;
2618 irq_work_queue(&event->pending_disable_irq);
2619 }
2620
2621 #define MAX_INTERRUPTS (~0ULL)
2622
2623 static void perf_log_throttle(struct perf_event *event, int enable);
2624 static void perf_log_itrace_start(struct perf_event *event);
2625
2626 static int
event_sched_in(struct perf_event * event,struct perf_event_context * ctx)2627 event_sched_in(struct perf_event *event, struct perf_event_context *ctx)
2628 {
2629 struct perf_event_pmu_context *epc = event->pmu_ctx;
2630 struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu);
2631 int ret = 0;
2632
2633 WARN_ON_ONCE(event->ctx != ctx);
2634
2635 lockdep_assert_held(&ctx->lock);
2636
2637 if (event->state <= PERF_EVENT_STATE_OFF)
2638 return 0;
2639
2640 WRITE_ONCE(event->oncpu, smp_processor_id());
2641 /*
2642 * Order event::oncpu write to happen before the ACTIVE state is
2643 * visible. This allows perf_event_{stop,read}() to observe the correct
2644 * ->oncpu if it sees ACTIVE.
2645 */
2646 smp_wmb();
2647 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2648
2649 /*
2650 * Unthrottle events, since we scheduled we might have missed several
2651 * ticks already, also for a heavily scheduling task there is little
2652 * guarantee it'll get a tick in a timely manner.
2653 */
2654 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2655 perf_log_throttle(event, 1);
2656 event->hw.interrupts = 0;
2657 }
2658
2659 perf_pmu_disable(event->pmu);
2660
2661 perf_log_itrace_start(event);
2662
2663 if (event->pmu->add(event, PERF_EF_START)) {
2664 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2665 event->oncpu = -1;
2666 ret = -EAGAIN;
2667 goto out;
2668 }
2669
2670 if (!is_software_event(event))
2671 cpc->active_oncpu++;
2672 if (event->attr.freq && event->attr.sample_freq) {
2673 ctx->nr_freq++;
2674 epc->nr_freq++;
2675 }
2676 if (event->attr.exclusive)
2677 cpc->exclusive = 1;
2678
2679 out:
2680 perf_pmu_enable(event->pmu);
2681
2682 return ret;
2683 }
2684
2685 static int
group_sched_in(struct perf_event * group_event,struct perf_event_context * ctx)2686 group_sched_in(struct perf_event *group_event, struct perf_event_context *ctx)
2687 {
2688 struct perf_event *event, *partial_group = NULL;
2689 struct pmu *pmu = group_event->pmu_ctx->pmu;
2690
2691 if (group_event->state == PERF_EVENT_STATE_OFF)
2692 return 0;
2693
2694 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2695
2696 if (event_sched_in(group_event, ctx))
2697 goto error;
2698
2699 /*
2700 * Schedule in siblings as one group (if any):
2701 */
2702 for_each_sibling_event(event, group_event) {
2703 if (event_sched_in(event, ctx)) {
2704 partial_group = event;
2705 goto group_error;
2706 }
2707 }
2708
2709 if (!pmu->commit_txn(pmu))
2710 return 0;
2711
2712 group_error:
2713 /*
2714 * Groups can be scheduled in as one unit only, so undo any
2715 * partial group before returning:
2716 * The events up to the failed event are scheduled out normally.
2717 */
2718 for_each_sibling_event(event, group_event) {
2719 if (event == partial_group)
2720 break;
2721
2722 event_sched_out(event, ctx);
2723 }
2724 event_sched_out(group_event, ctx);
2725
2726 error:
2727 pmu->cancel_txn(pmu);
2728 return -EAGAIN;
2729 }
2730
2731 /*
2732 * Work out whether we can put this event group on the CPU now.
2733 */
group_can_go_on(struct perf_event * event,int can_add_hw)2734 static int group_can_go_on(struct perf_event *event, int can_add_hw)
2735 {
2736 struct perf_event_pmu_context *epc = event->pmu_ctx;
2737 struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu);
2738
2739 /*
2740 * Groups consisting entirely of software events can always go on.
2741 */
2742 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2743 return 1;
2744 /*
2745 * If an exclusive group is already on, no other hardware
2746 * events can go on.
2747 */
2748 if (cpc->exclusive)
2749 return 0;
2750 /*
2751 * If this group is exclusive and there are already
2752 * events on the CPU, it can't go on.
2753 */
2754 if (event->attr.exclusive && !list_empty(get_event_list(event)))
2755 return 0;
2756 /*
2757 * Otherwise, try to add it if all previous groups were able
2758 * to go on.
2759 */
2760 return can_add_hw;
2761 }
2762
add_event_to_ctx(struct perf_event * event,struct perf_event_context * ctx)2763 static void add_event_to_ctx(struct perf_event *event,
2764 struct perf_event_context *ctx)
2765 {
2766 list_add_event(event, ctx);
2767 perf_group_attach(event);
2768 }
2769
task_ctx_sched_out(struct perf_event_context * ctx,struct pmu * pmu,enum event_type_t event_type)2770 static void task_ctx_sched_out(struct perf_event_context *ctx,
2771 struct pmu *pmu,
2772 enum event_type_t event_type)
2773 {
2774 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2775
2776 if (!cpuctx->task_ctx)
2777 return;
2778
2779 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2780 return;
2781
2782 ctx_sched_out(ctx, pmu, event_type);
2783 }
2784
perf_event_sched_in(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,struct pmu * pmu)2785 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2786 struct perf_event_context *ctx,
2787 struct pmu *pmu)
2788 {
2789 ctx_sched_in(&cpuctx->ctx, pmu, EVENT_PINNED);
2790 if (ctx)
2791 ctx_sched_in(ctx, pmu, EVENT_PINNED);
2792 ctx_sched_in(&cpuctx->ctx, pmu, EVENT_FLEXIBLE);
2793 if (ctx)
2794 ctx_sched_in(ctx, pmu, EVENT_FLEXIBLE);
2795 }
2796
2797 /*
2798 * We want to maintain the following priority of scheduling:
2799 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2800 * - task pinned (EVENT_PINNED)
2801 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2802 * - task flexible (EVENT_FLEXIBLE).
2803 *
2804 * In order to avoid unscheduling and scheduling back in everything every
2805 * time an event is added, only do it for the groups of equal priority and
2806 * below.
2807 *
2808 * This can be called after a batch operation on task events, in which case
2809 * event_type is a bit mask of the types of events involved. For CPU events,
2810 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2811 */
ctx_resched(struct perf_cpu_context * cpuctx,struct perf_event_context * task_ctx,struct pmu * pmu,enum event_type_t event_type)2812 static void ctx_resched(struct perf_cpu_context *cpuctx,
2813 struct perf_event_context *task_ctx,
2814 struct pmu *pmu, enum event_type_t event_type)
2815 {
2816 bool cpu_event = !!(event_type & EVENT_CPU);
2817 struct perf_event_pmu_context *epc;
2818
2819 /*
2820 * If pinned groups are involved, flexible groups also need to be
2821 * scheduled out.
2822 */
2823 if (event_type & EVENT_PINNED)
2824 event_type |= EVENT_FLEXIBLE;
2825
2826 event_type &= EVENT_ALL;
2827
2828 for_each_epc(epc, &cpuctx->ctx, pmu, false)
2829 perf_pmu_disable(epc->pmu);
2830
2831 if (task_ctx) {
2832 for_each_epc(epc, task_ctx, pmu, false)
2833 perf_pmu_disable(epc->pmu);
2834
2835 task_ctx_sched_out(task_ctx, pmu, event_type);
2836 }
2837
2838 /*
2839 * Decide which cpu ctx groups to schedule out based on the types
2840 * of events that caused rescheduling:
2841 * - EVENT_CPU: schedule out corresponding groups;
2842 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2843 * - otherwise, do nothing more.
2844 */
2845 if (cpu_event)
2846 ctx_sched_out(&cpuctx->ctx, pmu, event_type);
2847 else if (event_type & EVENT_PINNED)
2848 ctx_sched_out(&cpuctx->ctx, pmu, EVENT_FLEXIBLE);
2849
2850 perf_event_sched_in(cpuctx, task_ctx, pmu);
2851
2852 for_each_epc(epc, &cpuctx->ctx, pmu, false)
2853 perf_pmu_enable(epc->pmu);
2854
2855 if (task_ctx) {
2856 for_each_epc(epc, task_ctx, pmu, false)
2857 perf_pmu_enable(epc->pmu);
2858 }
2859 }
2860
perf_pmu_resched(struct pmu * pmu)2861 void perf_pmu_resched(struct pmu *pmu)
2862 {
2863 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2864 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2865
2866 perf_ctx_lock(cpuctx, task_ctx);
2867 ctx_resched(cpuctx, task_ctx, pmu, EVENT_ALL|EVENT_CPU);
2868 perf_ctx_unlock(cpuctx, task_ctx);
2869 }
2870
2871 /*
2872 * Cross CPU call to install and enable a performance event
2873 *
2874 * Very similar to remote_function() + event_function() but cannot assume that
2875 * things like ctx->is_active and cpuctx->task_ctx are set.
2876 */
__perf_install_in_context(void * info)2877 static int __perf_install_in_context(void *info)
2878 {
2879 struct perf_event *event = info;
2880 struct perf_event_context *ctx = event->ctx;
2881 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2882 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2883 bool reprogram = true;
2884 int ret = 0;
2885
2886 raw_spin_lock(&cpuctx->ctx.lock);
2887 if (ctx->task) {
2888 raw_spin_lock(&ctx->lock);
2889 task_ctx = ctx;
2890
2891 reprogram = (ctx->task == current);
2892
2893 /*
2894 * If the task is running, it must be running on this CPU,
2895 * otherwise we cannot reprogram things.
2896 *
2897 * If its not running, we don't care, ctx->lock will
2898 * serialize against it becoming runnable.
2899 */
2900 if (task_curr(ctx->task) && !reprogram) {
2901 ret = -ESRCH;
2902 goto unlock;
2903 }
2904
2905 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2906 } else if (task_ctx) {
2907 raw_spin_lock(&task_ctx->lock);
2908 }
2909
2910 #ifdef CONFIG_CGROUP_PERF
2911 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
2912 /*
2913 * If the current cgroup doesn't match the event's
2914 * cgroup, we should not try to schedule it.
2915 */
2916 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2917 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2918 event->cgrp->css.cgroup);
2919 }
2920 #endif
2921
2922 if (reprogram) {
2923 ctx_time_freeze(cpuctx, ctx);
2924 add_event_to_ctx(event, ctx);
2925 ctx_resched(cpuctx, task_ctx, event->pmu_ctx->pmu,
2926 get_event_type(event));
2927 } else {
2928 add_event_to_ctx(event, ctx);
2929 }
2930
2931 unlock:
2932 perf_ctx_unlock(cpuctx, task_ctx);
2933
2934 return ret;
2935 }
2936
2937 static bool exclusive_event_installable(struct perf_event *event,
2938 struct perf_event_context *ctx);
2939
2940 /*
2941 * Attach a performance event to a context.
2942 *
2943 * Very similar to event_function_call, see comment there.
2944 */
2945 static void
perf_install_in_context(struct perf_event_context * ctx,struct perf_event * event,int cpu)2946 perf_install_in_context(struct perf_event_context *ctx,
2947 struct perf_event *event,
2948 int cpu)
2949 {
2950 struct task_struct *task = READ_ONCE(ctx->task);
2951
2952 lockdep_assert_held(&ctx->mutex);
2953
2954 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2955
2956 if (event->cpu != -1)
2957 WARN_ON_ONCE(event->cpu != cpu);
2958
2959 /*
2960 * Ensures that if we can observe event->ctx, both the event and ctx
2961 * will be 'complete'. See perf_iterate_sb_cpu().
2962 */
2963 smp_store_release(&event->ctx, ctx);
2964
2965 /*
2966 * perf_event_attr::disabled events will not run and can be initialized
2967 * without IPI. Except when this is the first event for the context, in
2968 * that case we need the magic of the IPI to set ctx->is_active.
2969 *
2970 * The IOC_ENABLE that is sure to follow the creation of a disabled
2971 * event will issue the IPI and reprogram the hardware.
2972 */
2973 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF &&
2974 ctx->nr_events && !is_cgroup_event(event)) {
2975 raw_spin_lock_irq(&ctx->lock);
2976 if (ctx->task == TASK_TOMBSTONE) {
2977 raw_spin_unlock_irq(&ctx->lock);
2978 return;
2979 }
2980 add_event_to_ctx(event, ctx);
2981 raw_spin_unlock_irq(&ctx->lock);
2982 return;
2983 }
2984
2985 if (!task) {
2986 cpu_function_call(cpu, __perf_install_in_context, event);
2987 return;
2988 }
2989
2990 /*
2991 * Should not happen, we validate the ctx is still alive before calling.
2992 */
2993 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2994 return;
2995
2996 /*
2997 * Installing events is tricky because we cannot rely on ctx->is_active
2998 * to be set in case this is the nr_events 0 -> 1 transition.
2999 *
3000 * Instead we use task_curr(), which tells us if the task is running.
3001 * However, since we use task_curr() outside of rq::lock, we can race
3002 * against the actual state. This means the result can be wrong.
3003 *
3004 * If we get a false positive, we retry, this is harmless.
3005 *
3006 * If we get a false negative, things are complicated. If we are after
3007 * perf_event_context_sched_in() ctx::lock will serialize us, and the
3008 * value must be correct. If we're before, it doesn't matter since
3009 * perf_event_context_sched_in() will program the counter.
3010 *
3011 * However, this hinges on the remote context switch having observed
3012 * our task->perf_event_ctxp[] store, such that it will in fact take
3013 * ctx::lock in perf_event_context_sched_in().
3014 *
3015 * We do this by task_function_call(), if the IPI fails to hit the task
3016 * we know any future context switch of task must see the
3017 * perf_event_ctpx[] store.
3018 */
3019
3020 /*
3021 * This smp_mb() orders the task->perf_event_ctxp[] store with the
3022 * task_cpu() load, such that if the IPI then does not find the task
3023 * running, a future context switch of that task must observe the
3024 * store.
3025 */
3026 smp_mb();
3027 again:
3028 if (!task_function_call(task, __perf_install_in_context, event))
3029 return;
3030
3031 raw_spin_lock_irq(&ctx->lock);
3032 task = ctx->task;
3033 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
3034 /*
3035 * Cannot happen because we already checked above (which also
3036 * cannot happen), and we hold ctx->mutex, which serializes us
3037 * against perf_event_exit_task_context().
3038 */
3039 raw_spin_unlock_irq(&ctx->lock);
3040 return;
3041 }
3042 /*
3043 * If the task is not running, ctx->lock will avoid it becoming so,
3044 * thus we can safely install the event.
3045 */
3046 if (task_curr(task)) {
3047 raw_spin_unlock_irq(&ctx->lock);
3048 goto again;
3049 }
3050 add_event_to_ctx(event, ctx);
3051 raw_spin_unlock_irq(&ctx->lock);
3052 }
3053
3054 /*
3055 * Cross CPU call to enable a performance event
3056 */
__perf_event_enable(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)3057 static void __perf_event_enable(struct perf_event *event,
3058 struct perf_cpu_context *cpuctx,
3059 struct perf_event_context *ctx,
3060 void *info)
3061 {
3062 struct perf_event *leader = event->group_leader;
3063 struct perf_event_context *task_ctx;
3064
3065 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
3066 event->state <= PERF_EVENT_STATE_ERROR)
3067 return;
3068
3069 ctx_time_freeze(cpuctx, ctx);
3070
3071 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
3072 perf_cgroup_event_enable(event, ctx);
3073
3074 if (!ctx->is_active)
3075 return;
3076
3077 if (!event_filter_match(event))
3078 return;
3079
3080 /*
3081 * If the event is in a group and isn't the group leader,
3082 * then don't put it on unless the group is on.
3083 */
3084 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
3085 return;
3086
3087 task_ctx = cpuctx->task_ctx;
3088 if (ctx->task)
3089 WARN_ON_ONCE(task_ctx != ctx);
3090
3091 ctx_resched(cpuctx, task_ctx, event->pmu_ctx->pmu, get_event_type(event));
3092 }
3093
3094 /*
3095 * Enable an event.
3096 *
3097 * If event->ctx is a cloned context, callers must make sure that
3098 * every task struct that event->ctx->task could possibly point to
3099 * remains valid. This condition is satisfied when called through
3100 * perf_event_for_each_child or perf_event_for_each as described
3101 * for perf_event_disable.
3102 */
_perf_event_enable(struct perf_event * event)3103 static void _perf_event_enable(struct perf_event *event)
3104 {
3105 struct perf_event_context *ctx = event->ctx;
3106
3107 raw_spin_lock_irq(&ctx->lock);
3108 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
3109 event->state < PERF_EVENT_STATE_ERROR) {
3110 out:
3111 raw_spin_unlock_irq(&ctx->lock);
3112 return;
3113 }
3114
3115 /*
3116 * If the event is in error state, clear that first.
3117 *
3118 * That way, if we see the event in error state below, we know that it
3119 * has gone back into error state, as distinct from the task having
3120 * been scheduled away before the cross-call arrived.
3121 */
3122 if (event->state == PERF_EVENT_STATE_ERROR) {
3123 /*
3124 * Detached SIBLING events cannot leave ERROR state.
3125 */
3126 if (event->event_caps & PERF_EV_CAP_SIBLING &&
3127 event->group_leader == event)
3128 goto out;
3129
3130 event->state = PERF_EVENT_STATE_OFF;
3131 }
3132 raw_spin_unlock_irq(&ctx->lock);
3133
3134 event_function_call(event, __perf_event_enable, NULL);
3135 }
3136
3137 /*
3138 * See perf_event_disable();
3139 */
perf_event_enable(struct perf_event * event)3140 void perf_event_enable(struct perf_event *event)
3141 {
3142 struct perf_event_context *ctx;
3143
3144 ctx = perf_event_ctx_lock(event);
3145 _perf_event_enable(event);
3146 perf_event_ctx_unlock(event, ctx);
3147 }
3148 EXPORT_SYMBOL_GPL(perf_event_enable);
3149
3150 struct stop_event_data {
3151 struct perf_event *event;
3152 unsigned int restart;
3153 };
3154
__perf_event_stop(void * info)3155 static int __perf_event_stop(void *info)
3156 {
3157 struct stop_event_data *sd = info;
3158 struct perf_event *event = sd->event;
3159
3160 /* if it's already INACTIVE, do nothing */
3161 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3162 return 0;
3163
3164 /* matches smp_wmb() in event_sched_in() */
3165 smp_rmb();
3166
3167 /*
3168 * There is a window with interrupts enabled before we get here,
3169 * so we need to check again lest we try to stop another CPU's event.
3170 */
3171 if (READ_ONCE(event->oncpu) != smp_processor_id())
3172 return -EAGAIN;
3173
3174 event->pmu->stop(event, PERF_EF_UPDATE);
3175
3176 /*
3177 * May race with the actual stop (through perf_pmu_output_stop()),
3178 * but it is only used for events with AUX ring buffer, and such
3179 * events will refuse to restart because of rb::aux_mmap_count==0,
3180 * see comments in perf_aux_output_begin().
3181 *
3182 * Since this is happening on an event-local CPU, no trace is lost
3183 * while restarting.
3184 */
3185 if (sd->restart)
3186 event->pmu->start(event, 0);
3187
3188 return 0;
3189 }
3190
perf_event_stop(struct perf_event * event,int restart)3191 static int perf_event_stop(struct perf_event *event, int restart)
3192 {
3193 struct stop_event_data sd = {
3194 .event = event,
3195 .restart = restart,
3196 };
3197 int ret = 0;
3198
3199 do {
3200 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3201 return 0;
3202
3203 /* matches smp_wmb() in event_sched_in() */
3204 smp_rmb();
3205
3206 /*
3207 * We only want to restart ACTIVE events, so if the event goes
3208 * inactive here (event->oncpu==-1), there's nothing more to do;
3209 * fall through with ret==-ENXIO.
3210 */
3211 ret = cpu_function_call(READ_ONCE(event->oncpu),
3212 __perf_event_stop, &sd);
3213 } while (ret == -EAGAIN);
3214
3215 return ret;
3216 }
3217
3218 /*
3219 * In order to contain the amount of racy and tricky in the address filter
3220 * configuration management, it is a two part process:
3221 *
3222 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3223 * we update the addresses of corresponding vmas in
3224 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3225 * (p2) when an event is scheduled in (pmu::add), it calls
3226 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3227 * if the generation has changed since the previous call.
3228 *
3229 * If (p1) happens while the event is active, we restart it to force (p2).
3230 *
3231 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3232 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3233 * ioctl;
3234 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3235 * registered mapping, called for every new mmap(), with mm::mmap_lock down
3236 * for reading;
3237 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3238 * of exec.
3239 */
perf_event_addr_filters_sync(struct perf_event * event)3240 void perf_event_addr_filters_sync(struct perf_event *event)
3241 {
3242 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3243
3244 if (!has_addr_filter(event))
3245 return;
3246
3247 raw_spin_lock(&ifh->lock);
3248 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3249 event->pmu->addr_filters_sync(event);
3250 event->hw.addr_filters_gen = event->addr_filters_gen;
3251 }
3252 raw_spin_unlock(&ifh->lock);
3253 }
3254 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3255
_perf_event_refresh(struct perf_event * event,int refresh)3256 static int _perf_event_refresh(struct perf_event *event, int refresh)
3257 {
3258 /*
3259 * not supported on inherited events
3260 */
3261 if (event->attr.inherit || !is_sampling_event(event))
3262 return -EINVAL;
3263
3264 atomic_add(refresh, &event->event_limit);
3265 _perf_event_enable(event);
3266
3267 return 0;
3268 }
3269
3270 /*
3271 * See perf_event_disable()
3272 */
perf_event_refresh(struct perf_event * event,int refresh)3273 int perf_event_refresh(struct perf_event *event, int refresh)
3274 {
3275 struct perf_event_context *ctx;
3276 int ret;
3277
3278 ctx = perf_event_ctx_lock(event);
3279 ret = _perf_event_refresh(event, refresh);
3280 perf_event_ctx_unlock(event, ctx);
3281
3282 return ret;
3283 }
3284 EXPORT_SYMBOL_GPL(perf_event_refresh);
3285
perf_event_modify_breakpoint(struct perf_event * bp,struct perf_event_attr * attr)3286 static int perf_event_modify_breakpoint(struct perf_event *bp,
3287 struct perf_event_attr *attr)
3288 {
3289 int err;
3290
3291 _perf_event_disable(bp);
3292
3293 err = modify_user_hw_breakpoint_check(bp, attr, true);
3294
3295 if (!bp->attr.disabled)
3296 _perf_event_enable(bp);
3297
3298 return err;
3299 }
3300
3301 /*
3302 * Copy event-type-independent attributes that may be modified.
3303 */
perf_event_modify_copy_attr(struct perf_event_attr * to,const struct perf_event_attr * from)3304 static void perf_event_modify_copy_attr(struct perf_event_attr *to,
3305 const struct perf_event_attr *from)
3306 {
3307 to->sig_data = from->sig_data;
3308 }
3309
perf_event_modify_attr(struct perf_event * event,struct perf_event_attr * attr)3310 static int perf_event_modify_attr(struct perf_event *event,
3311 struct perf_event_attr *attr)
3312 {
3313 int (*func)(struct perf_event *, struct perf_event_attr *);
3314 struct perf_event *child;
3315 int err;
3316
3317 if (event->attr.type != attr->type)
3318 return -EINVAL;
3319
3320 switch (event->attr.type) {
3321 case PERF_TYPE_BREAKPOINT:
3322 func = perf_event_modify_breakpoint;
3323 break;
3324 default:
3325 /* Place holder for future additions. */
3326 return -EOPNOTSUPP;
3327 }
3328
3329 WARN_ON_ONCE(event->ctx->parent_ctx);
3330
3331 mutex_lock(&event->child_mutex);
3332 /*
3333 * Event-type-independent attributes must be copied before event-type
3334 * modification, which will validate that final attributes match the
3335 * source attributes after all relevant attributes have been copied.
3336 */
3337 perf_event_modify_copy_attr(&event->attr, attr);
3338 err = func(event, attr);
3339 if (err)
3340 goto out;
3341 list_for_each_entry(child, &event->child_list, child_list) {
3342 perf_event_modify_copy_attr(&child->attr, attr);
3343 err = func(child, attr);
3344 if (err)
3345 goto out;
3346 }
3347 out:
3348 mutex_unlock(&event->child_mutex);
3349 return err;
3350 }
3351
__pmu_ctx_sched_out(struct perf_event_pmu_context * pmu_ctx,enum event_type_t event_type)3352 static void __pmu_ctx_sched_out(struct perf_event_pmu_context *pmu_ctx,
3353 enum event_type_t event_type)
3354 {
3355 struct perf_event_context *ctx = pmu_ctx->ctx;
3356 struct perf_event *event, *tmp;
3357 struct pmu *pmu = pmu_ctx->pmu;
3358
3359 if (ctx->task && !(ctx->is_active & EVENT_ALL)) {
3360 struct perf_cpu_pmu_context *cpc = this_cpc(pmu);
3361
3362 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
3363 cpc->task_epc = NULL;
3364 }
3365
3366 if (!(event_type & EVENT_ALL))
3367 return;
3368
3369 perf_pmu_disable(pmu);
3370 if (event_type & EVENT_PINNED) {
3371 list_for_each_entry_safe(event, tmp,
3372 &pmu_ctx->pinned_active,
3373 active_list)
3374 group_sched_out(event, ctx);
3375 }
3376
3377 if (event_type & EVENT_FLEXIBLE) {
3378 list_for_each_entry_safe(event, tmp,
3379 &pmu_ctx->flexible_active,
3380 active_list)
3381 group_sched_out(event, ctx);
3382 /*
3383 * Since we cleared EVENT_FLEXIBLE, also clear
3384 * rotate_necessary, is will be reset by
3385 * ctx_flexible_sched_in() when needed.
3386 */
3387 pmu_ctx->rotate_necessary = 0;
3388 }
3389 perf_pmu_enable(pmu);
3390 }
3391
3392 /*
3393 * Be very careful with the @pmu argument since this will change ctx state.
3394 * The @pmu argument works for ctx_resched(), because that is symmetric in
3395 * ctx_sched_out() / ctx_sched_in() usage and the ctx state ends up invariant.
3396 *
3397 * However, if you were to be asymmetrical, you could end up with messed up
3398 * state, eg. ctx->is_active cleared even though most EPCs would still actually
3399 * be active.
3400 */
3401 static void
ctx_sched_out(struct perf_event_context * ctx,struct pmu * pmu,enum event_type_t event_type)3402 ctx_sched_out(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type)
3403 {
3404 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3405 struct perf_event_pmu_context *pmu_ctx;
3406 int is_active = ctx->is_active;
3407 bool cgroup = event_type & EVENT_CGROUP;
3408
3409 event_type &= ~EVENT_CGROUP;
3410
3411 lockdep_assert_held(&ctx->lock);
3412
3413 if (likely(!ctx->nr_events)) {
3414 /*
3415 * See __perf_remove_from_context().
3416 */
3417 WARN_ON_ONCE(ctx->is_active);
3418 if (ctx->task)
3419 WARN_ON_ONCE(cpuctx->task_ctx);
3420 return;
3421 }
3422
3423 /*
3424 * Always update time if it was set; not only when it changes.
3425 * Otherwise we can 'forget' to update time for any but the last
3426 * context we sched out. For example:
3427 *
3428 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3429 * ctx_sched_out(.event_type = EVENT_PINNED)
3430 *
3431 * would only update time for the pinned events.
3432 */
3433 __ctx_time_update(cpuctx, ctx, ctx == &cpuctx->ctx);
3434
3435 /*
3436 * CPU-release for the below ->is_active store,
3437 * see __load_acquire() in perf_event_time_now()
3438 */
3439 barrier();
3440 ctx->is_active &= ~event_type;
3441
3442 if (!(ctx->is_active & EVENT_ALL)) {
3443 /*
3444 * For FROZEN, preserve TIME|FROZEN such that perf_event_time_now()
3445 * does not observe a hole. perf_ctx_unlock() will clean up.
3446 */
3447 if (ctx->is_active & EVENT_FROZEN)
3448 ctx->is_active &= EVENT_TIME_FROZEN;
3449 else
3450 ctx->is_active = 0;
3451 }
3452
3453 if (ctx->task) {
3454 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3455 if (!(ctx->is_active & EVENT_ALL))
3456 cpuctx->task_ctx = NULL;
3457 }
3458
3459 is_active ^= ctx->is_active; /* changed bits */
3460
3461 for_each_epc(pmu_ctx, ctx, pmu, cgroup)
3462 __pmu_ctx_sched_out(pmu_ctx, is_active);
3463 }
3464
3465 /*
3466 * Test whether two contexts are equivalent, i.e. whether they have both been
3467 * cloned from the same version of the same context.
3468 *
3469 * Equivalence is measured using a generation number in the context that is
3470 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3471 * and list_del_event().
3472 */
context_equiv(struct perf_event_context * ctx1,struct perf_event_context * ctx2)3473 static int context_equiv(struct perf_event_context *ctx1,
3474 struct perf_event_context *ctx2)
3475 {
3476 lockdep_assert_held(&ctx1->lock);
3477 lockdep_assert_held(&ctx2->lock);
3478
3479 /* Pinning disables the swap optimization */
3480 if (ctx1->pin_count || ctx2->pin_count)
3481 return 0;
3482
3483 /* If ctx1 is the parent of ctx2 */
3484 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3485 return 1;
3486
3487 /* If ctx2 is the parent of ctx1 */
3488 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3489 return 1;
3490
3491 /*
3492 * If ctx1 and ctx2 have the same parent; we flatten the parent
3493 * hierarchy, see perf_event_init_context().
3494 */
3495 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3496 ctx1->parent_gen == ctx2->parent_gen)
3497 return 1;
3498
3499 /* Unmatched */
3500 return 0;
3501 }
3502
__perf_event_sync_stat(struct perf_event * event,struct perf_event * next_event)3503 static void __perf_event_sync_stat(struct perf_event *event,
3504 struct perf_event *next_event)
3505 {
3506 u64 value;
3507
3508 if (!event->attr.inherit_stat)
3509 return;
3510
3511 /*
3512 * Update the event value, we cannot use perf_event_read()
3513 * because we're in the middle of a context switch and have IRQs
3514 * disabled, which upsets smp_call_function_single(), however
3515 * we know the event must be on the current CPU, therefore we
3516 * don't need to use it.
3517 */
3518 perf_pmu_read(event);
3519
3520 perf_event_update_time(event);
3521
3522 /*
3523 * In order to keep per-task stats reliable we need to flip the event
3524 * values when we flip the contexts.
3525 */
3526 value = local64_read(&next_event->count);
3527 value = local64_xchg(&event->count, value);
3528 local64_set(&next_event->count, value);
3529
3530 swap(event->total_time_enabled, next_event->total_time_enabled);
3531 swap(event->total_time_running, next_event->total_time_running);
3532
3533 /*
3534 * Since we swizzled the values, update the user visible data too.
3535 */
3536 perf_event_update_userpage(event);
3537 perf_event_update_userpage(next_event);
3538 }
3539
perf_event_sync_stat(struct perf_event_context * ctx,struct perf_event_context * next_ctx)3540 static void perf_event_sync_stat(struct perf_event_context *ctx,
3541 struct perf_event_context *next_ctx)
3542 {
3543 struct perf_event *event, *next_event;
3544
3545 if (!ctx->nr_stat)
3546 return;
3547
3548 update_context_time(ctx);
3549
3550 event = list_first_entry(&ctx->event_list,
3551 struct perf_event, event_entry);
3552
3553 next_event = list_first_entry(&next_ctx->event_list,
3554 struct perf_event, event_entry);
3555
3556 while (&event->event_entry != &ctx->event_list &&
3557 &next_event->event_entry != &next_ctx->event_list) {
3558
3559 __perf_event_sync_stat(event, next_event);
3560
3561 event = list_next_entry(event, event_entry);
3562 next_event = list_next_entry(next_event, event_entry);
3563 }
3564 }
3565
perf_ctx_sched_task_cb(struct perf_event_context * ctx,struct task_struct * task,bool sched_in)3566 static void perf_ctx_sched_task_cb(struct perf_event_context *ctx,
3567 struct task_struct *task, bool sched_in)
3568 {
3569 struct perf_event_pmu_context *pmu_ctx;
3570 struct perf_cpu_pmu_context *cpc;
3571
3572 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
3573 cpc = this_cpc(pmu_ctx->pmu);
3574
3575 if (cpc->sched_cb_usage && pmu_ctx->pmu->sched_task)
3576 pmu_ctx->pmu->sched_task(pmu_ctx, task, sched_in);
3577 }
3578 }
3579
3580 static void
perf_event_context_sched_out(struct task_struct * task,struct task_struct * next)3581 perf_event_context_sched_out(struct task_struct *task, struct task_struct *next)
3582 {
3583 struct perf_event_context *ctx = task->perf_event_ctxp;
3584 struct perf_event_context *next_ctx;
3585 struct perf_event_context *parent, *next_parent;
3586 int do_switch = 1;
3587
3588 if (likely(!ctx))
3589 return;
3590
3591 rcu_read_lock();
3592 next_ctx = rcu_dereference(next->perf_event_ctxp);
3593 if (!next_ctx)
3594 goto unlock;
3595
3596 parent = rcu_dereference(ctx->parent_ctx);
3597 next_parent = rcu_dereference(next_ctx->parent_ctx);
3598
3599 /* If neither context have a parent context; they cannot be clones. */
3600 if (!parent && !next_parent)
3601 goto unlock;
3602
3603 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3604 /*
3605 * Looks like the two contexts are clones, so we might be
3606 * able to optimize the context switch. We lock both
3607 * contexts and check that they are clones under the
3608 * lock (including re-checking that neither has been
3609 * uncloned in the meantime). It doesn't matter which
3610 * order we take the locks because no other cpu could
3611 * be trying to lock both of these tasks.
3612 */
3613 raw_spin_lock(&ctx->lock);
3614 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3615 if (context_equiv(ctx, next_ctx)) {
3616
3617 perf_ctx_disable(ctx, false);
3618
3619 /* PMIs are disabled; ctx->nr_no_switch_fast is stable. */
3620 if (local_read(&ctx->nr_no_switch_fast) ||
3621 local_read(&next_ctx->nr_no_switch_fast)) {
3622 /*
3623 * Must not swap out ctx when there's pending
3624 * events that rely on the ctx->task relation.
3625 *
3626 * Likewise, when a context contains inherit +
3627 * SAMPLE_READ events they should be switched
3628 * out using the slow path so that they are
3629 * treated as if they were distinct contexts.
3630 */
3631 raw_spin_unlock(&next_ctx->lock);
3632 rcu_read_unlock();
3633 goto inside_switch;
3634 }
3635
3636 WRITE_ONCE(ctx->task, next);
3637 WRITE_ONCE(next_ctx->task, task);
3638
3639 perf_ctx_sched_task_cb(ctx, task, false);
3640
3641 perf_ctx_enable(ctx, false);
3642
3643 /*
3644 * RCU_INIT_POINTER here is safe because we've not
3645 * modified the ctx and the above modification of
3646 * ctx->task is immaterial since this value is
3647 * always verified under ctx->lock which we're now
3648 * holding.
3649 */
3650 RCU_INIT_POINTER(task->perf_event_ctxp, next_ctx);
3651 RCU_INIT_POINTER(next->perf_event_ctxp, ctx);
3652
3653 do_switch = 0;
3654
3655 perf_event_sync_stat(ctx, next_ctx);
3656 }
3657 raw_spin_unlock(&next_ctx->lock);
3658 raw_spin_unlock(&ctx->lock);
3659 }
3660 unlock:
3661 rcu_read_unlock();
3662
3663 if (do_switch) {
3664 raw_spin_lock(&ctx->lock);
3665 perf_ctx_disable(ctx, false);
3666
3667 inside_switch:
3668 perf_ctx_sched_task_cb(ctx, task, false);
3669 task_ctx_sched_out(ctx, NULL, EVENT_ALL);
3670
3671 perf_ctx_enable(ctx, false);
3672 raw_spin_unlock(&ctx->lock);
3673 }
3674 }
3675
3676 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3677 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
3678
perf_sched_cb_dec(struct pmu * pmu)3679 void perf_sched_cb_dec(struct pmu *pmu)
3680 {
3681 struct perf_cpu_pmu_context *cpc = this_cpc(pmu);
3682
3683 this_cpu_dec(perf_sched_cb_usages);
3684 barrier();
3685
3686 if (!--cpc->sched_cb_usage)
3687 list_del(&cpc->sched_cb_entry);
3688 }
3689
3690
perf_sched_cb_inc(struct pmu * pmu)3691 void perf_sched_cb_inc(struct pmu *pmu)
3692 {
3693 struct perf_cpu_pmu_context *cpc = this_cpc(pmu);
3694
3695 if (!cpc->sched_cb_usage++)
3696 list_add(&cpc->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3697
3698 barrier();
3699 this_cpu_inc(perf_sched_cb_usages);
3700 }
3701
3702 /*
3703 * This function provides the context switch callback to the lower code
3704 * layer. It is invoked ONLY when the context switch callback is enabled.
3705 *
3706 * This callback is relevant even to per-cpu events; for example multi event
3707 * PEBS requires this to provide PID/TID information. This requires we flush
3708 * all queued PEBS records before we context switch to a new task.
3709 */
__perf_pmu_sched_task(struct perf_cpu_pmu_context * cpc,struct task_struct * task,bool sched_in)3710 static void __perf_pmu_sched_task(struct perf_cpu_pmu_context *cpc,
3711 struct task_struct *task, bool sched_in)
3712 {
3713 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3714 struct pmu *pmu;
3715
3716 pmu = cpc->epc.pmu;
3717
3718 /* software PMUs will not have sched_task */
3719 if (WARN_ON_ONCE(!pmu->sched_task))
3720 return;
3721
3722 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3723 perf_pmu_disable(pmu);
3724
3725 pmu->sched_task(cpc->task_epc, task, sched_in);
3726
3727 perf_pmu_enable(pmu);
3728 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3729 }
3730
perf_pmu_sched_task(struct task_struct * prev,struct task_struct * next,bool sched_in)3731 static void perf_pmu_sched_task(struct task_struct *prev,
3732 struct task_struct *next,
3733 bool sched_in)
3734 {
3735 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3736 struct perf_cpu_pmu_context *cpc;
3737
3738 /* cpuctx->task_ctx will be handled in perf_event_context_sched_in/out */
3739 if (prev == next || cpuctx->task_ctx)
3740 return;
3741
3742 list_for_each_entry(cpc, this_cpu_ptr(&sched_cb_list), sched_cb_entry)
3743 __perf_pmu_sched_task(cpc, sched_in ? next : prev, sched_in);
3744 }
3745
3746 static void perf_event_switch(struct task_struct *task,
3747 struct task_struct *next_prev, bool sched_in);
3748
3749 /*
3750 * Called from scheduler to remove the events of the current task,
3751 * with interrupts disabled.
3752 *
3753 * We stop each event and update the event value in event->count.
3754 *
3755 * This does not protect us against NMI, but disable()
3756 * sets the disabled bit in the control field of event _before_
3757 * accessing the event control register. If a NMI hits, then it will
3758 * not restart the event.
3759 */
__perf_event_task_sched_out(struct task_struct * task,struct task_struct * next)3760 void __perf_event_task_sched_out(struct task_struct *task,
3761 struct task_struct *next)
3762 {
3763 if (__this_cpu_read(perf_sched_cb_usages))
3764 perf_pmu_sched_task(task, next, false);
3765
3766 if (atomic_read(&nr_switch_events))
3767 perf_event_switch(task, next, false);
3768
3769 perf_event_context_sched_out(task, next);
3770
3771 /*
3772 * if cgroup events exist on this CPU, then we need
3773 * to check if we have to switch out PMU state.
3774 * cgroup event are system-wide mode only
3775 */
3776 perf_cgroup_switch(next);
3777 }
3778
perf_less_group_idx(const void * l,const void * r,void __always_unused * args)3779 static bool perf_less_group_idx(const void *l, const void *r, void __always_unused *args)
3780 {
3781 const struct perf_event *le = *(const struct perf_event **)l;
3782 const struct perf_event *re = *(const struct perf_event **)r;
3783
3784 return le->group_index < re->group_index;
3785 }
3786
3787 DEFINE_MIN_HEAP(struct perf_event *, perf_event_min_heap);
3788
3789 static const struct min_heap_callbacks perf_min_heap = {
3790 .less = perf_less_group_idx,
3791 .swp = NULL,
3792 };
3793
__heap_add(struct perf_event_min_heap * heap,struct perf_event * event)3794 static void __heap_add(struct perf_event_min_heap *heap, struct perf_event *event)
3795 {
3796 struct perf_event **itrs = heap->data;
3797
3798 if (event) {
3799 itrs[heap->nr] = event;
3800 heap->nr++;
3801 }
3802 }
3803
__link_epc(struct perf_event_pmu_context * pmu_ctx)3804 static void __link_epc(struct perf_event_pmu_context *pmu_ctx)
3805 {
3806 struct perf_cpu_pmu_context *cpc;
3807
3808 if (!pmu_ctx->ctx->task)
3809 return;
3810
3811 cpc = this_cpc(pmu_ctx->pmu);
3812 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
3813 cpc->task_epc = pmu_ctx;
3814 }
3815
visit_groups_merge(struct perf_event_context * ctx,struct perf_event_groups * groups,int cpu,struct pmu * pmu,int (* func)(struct perf_event *,void *),void * data)3816 static noinline int visit_groups_merge(struct perf_event_context *ctx,
3817 struct perf_event_groups *groups, int cpu,
3818 struct pmu *pmu,
3819 int (*func)(struct perf_event *, void *),
3820 void *data)
3821 {
3822 #ifdef CONFIG_CGROUP_PERF
3823 struct cgroup_subsys_state *css = NULL;
3824 #endif
3825 struct perf_cpu_context *cpuctx = NULL;
3826 /* Space for per CPU and/or any CPU event iterators. */
3827 struct perf_event *itrs[2];
3828 struct perf_event_min_heap event_heap;
3829 struct perf_event **evt;
3830 int ret;
3831
3832 if (pmu->filter && pmu->filter(pmu, cpu))
3833 return 0;
3834
3835 if (!ctx->task) {
3836 cpuctx = this_cpu_ptr(&perf_cpu_context);
3837 event_heap = (struct perf_event_min_heap){
3838 .data = cpuctx->heap,
3839 .nr = 0,
3840 .size = cpuctx->heap_size,
3841 };
3842
3843 lockdep_assert_held(&cpuctx->ctx.lock);
3844
3845 #ifdef CONFIG_CGROUP_PERF
3846 if (cpuctx->cgrp)
3847 css = &cpuctx->cgrp->css;
3848 #endif
3849 } else {
3850 event_heap = (struct perf_event_min_heap){
3851 .data = itrs,
3852 .nr = 0,
3853 .size = ARRAY_SIZE(itrs),
3854 };
3855 /* Events not within a CPU context may be on any CPU. */
3856 __heap_add(&event_heap, perf_event_groups_first(groups, -1, pmu, NULL));
3857 }
3858 evt = event_heap.data;
3859
3860 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, NULL));
3861
3862 #ifdef CONFIG_CGROUP_PERF
3863 for (; css; css = css->parent)
3864 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, css->cgroup));
3865 #endif
3866
3867 if (event_heap.nr) {
3868 __link_epc((*evt)->pmu_ctx);
3869 perf_assert_pmu_disabled((*evt)->pmu_ctx->pmu);
3870 }
3871
3872 min_heapify_all_inline(&event_heap, &perf_min_heap, NULL);
3873
3874 while (event_heap.nr) {
3875 ret = func(*evt, data);
3876 if (ret)
3877 return ret;
3878
3879 *evt = perf_event_groups_next(*evt, pmu);
3880 if (*evt)
3881 min_heap_sift_down_inline(&event_heap, 0, &perf_min_heap, NULL);
3882 else
3883 min_heap_pop_inline(&event_heap, &perf_min_heap, NULL);
3884 }
3885
3886 return 0;
3887 }
3888
3889 /*
3890 * Because the userpage is strictly per-event (there is no concept of context,
3891 * so there cannot be a context indirection), every userpage must be updated
3892 * when context time starts :-(
3893 *
3894 * IOW, we must not miss EVENT_TIME edges.
3895 */
event_update_userpage(struct perf_event * event)3896 static inline bool event_update_userpage(struct perf_event *event)
3897 {
3898 if (likely(!atomic_read(&event->mmap_count)))
3899 return false;
3900
3901 perf_event_update_time(event);
3902 perf_event_update_userpage(event);
3903
3904 return true;
3905 }
3906
group_update_userpage(struct perf_event * group_event)3907 static inline void group_update_userpage(struct perf_event *group_event)
3908 {
3909 struct perf_event *event;
3910
3911 if (!event_update_userpage(group_event))
3912 return;
3913
3914 for_each_sibling_event(event, group_event)
3915 event_update_userpage(event);
3916 }
3917
merge_sched_in(struct perf_event * event,void * data)3918 static int merge_sched_in(struct perf_event *event, void *data)
3919 {
3920 struct perf_event_context *ctx = event->ctx;
3921 int *can_add_hw = data;
3922
3923 if (event->state <= PERF_EVENT_STATE_OFF)
3924 return 0;
3925
3926 if (!event_filter_match(event))
3927 return 0;
3928
3929 if (group_can_go_on(event, *can_add_hw)) {
3930 if (!group_sched_in(event, ctx))
3931 list_add_tail(&event->active_list, get_event_list(event));
3932 }
3933
3934 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3935 *can_add_hw = 0;
3936 if (event->attr.pinned) {
3937 perf_cgroup_event_disable(event, ctx);
3938 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3939
3940 if (*perf_event_fasync(event))
3941 event->pending_kill = POLL_HUP;
3942
3943 perf_event_wakeup(event);
3944 } else {
3945 struct perf_cpu_pmu_context *cpc = this_cpc(event->pmu_ctx->pmu);
3946
3947 event->pmu_ctx->rotate_necessary = 1;
3948 perf_mux_hrtimer_restart(cpc);
3949 group_update_userpage(event);
3950 }
3951 }
3952
3953 return 0;
3954 }
3955
pmu_groups_sched_in(struct perf_event_context * ctx,struct perf_event_groups * groups,struct pmu * pmu)3956 static void pmu_groups_sched_in(struct perf_event_context *ctx,
3957 struct perf_event_groups *groups,
3958 struct pmu *pmu)
3959 {
3960 int can_add_hw = 1;
3961 visit_groups_merge(ctx, groups, smp_processor_id(), pmu,
3962 merge_sched_in, &can_add_hw);
3963 }
3964
__pmu_ctx_sched_in(struct perf_event_pmu_context * pmu_ctx,enum event_type_t event_type)3965 static void __pmu_ctx_sched_in(struct perf_event_pmu_context *pmu_ctx,
3966 enum event_type_t event_type)
3967 {
3968 struct perf_event_context *ctx = pmu_ctx->ctx;
3969
3970 if (event_type & EVENT_PINNED)
3971 pmu_groups_sched_in(ctx, &ctx->pinned_groups, pmu_ctx->pmu);
3972 if (event_type & EVENT_FLEXIBLE)
3973 pmu_groups_sched_in(ctx, &ctx->flexible_groups, pmu_ctx->pmu);
3974 }
3975
3976 static void
ctx_sched_in(struct perf_event_context * ctx,struct pmu * pmu,enum event_type_t event_type)3977 ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type)
3978 {
3979 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3980 struct perf_event_pmu_context *pmu_ctx;
3981 int is_active = ctx->is_active;
3982 bool cgroup = event_type & EVENT_CGROUP;
3983
3984 event_type &= ~EVENT_CGROUP;
3985
3986 lockdep_assert_held(&ctx->lock);
3987
3988 if (likely(!ctx->nr_events))
3989 return;
3990
3991 if (!(is_active & EVENT_TIME)) {
3992 /* start ctx time */
3993 __update_context_time(ctx, false);
3994 perf_cgroup_set_timestamp(cpuctx);
3995 /*
3996 * CPU-release for the below ->is_active store,
3997 * see __load_acquire() in perf_event_time_now()
3998 */
3999 barrier();
4000 }
4001
4002 ctx->is_active |= (event_type | EVENT_TIME);
4003 if (ctx->task) {
4004 if (!(is_active & EVENT_ALL))
4005 cpuctx->task_ctx = ctx;
4006 else
4007 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
4008 }
4009
4010 is_active ^= ctx->is_active; /* changed bits */
4011
4012 /*
4013 * First go through the list and put on any pinned groups
4014 * in order to give them the best chance of going on.
4015 */
4016 if (is_active & EVENT_PINNED) {
4017 for_each_epc(pmu_ctx, ctx, pmu, cgroup)
4018 __pmu_ctx_sched_in(pmu_ctx, EVENT_PINNED);
4019 }
4020
4021 /* Then walk through the lower prio flexible groups */
4022 if (is_active & EVENT_FLEXIBLE) {
4023 for_each_epc(pmu_ctx, ctx, pmu, cgroup)
4024 __pmu_ctx_sched_in(pmu_ctx, EVENT_FLEXIBLE);
4025 }
4026 }
4027
perf_event_context_sched_in(struct task_struct * task)4028 static void perf_event_context_sched_in(struct task_struct *task)
4029 {
4030 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4031 struct perf_event_context *ctx;
4032
4033 rcu_read_lock();
4034 ctx = rcu_dereference(task->perf_event_ctxp);
4035 if (!ctx)
4036 goto rcu_unlock;
4037
4038 if (cpuctx->task_ctx == ctx) {
4039 perf_ctx_lock(cpuctx, ctx);
4040 perf_ctx_disable(ctx, false);
4041
4042 perf_ctx_sched_task_cb(ctx, task, true);
4043
4044 perf_ctx_enable(ctx, false);
4045 perf_ctx_unlock(cpuctx, ctx);
4046 goto rcu_unlock;
4047 }
4048
4049 perf_ctx_lock(cpuctx, ctx);
4050 /*
4051 * We must check ctx->nr_events while holding ctx->lock, such
4052 * that we serialize against perf_install_in_context().
4053 */
4054 if (!ctx->nr_events)
4055 goto unlock;
4056
4057 perf_ctx_disable(ctx, false);
4058 /*
4059 * We want to keep the following priority order:
4060 * cpu pinned (that don't need to move), task pinned,
4061 * cpu flexible, task flexible.
4062 *
4063 * However, if task's ctx is not carrying any pinned
4064 * events, no need to flip the cpuctx's events around.
4065 */
4066 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree)) {
4067 perf_ctx_disable(&cpuctx->ctx, false);
4068 ctx_sched_out(&cpuctx->ctx, NULL, EVENT_FLEXIBLE);
4069 }
4070
4071 perf_event_sched_in(cpuctx, ctx, NULL);
4072
4073 perf_ctx_sched_task_cb(cpuctx->task_ctx, task, true);
4074
4075 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
4076 perf_ctx_enable(&cpuctx->ctx, false);
4077
4078 perf_ctx_enable(ctx, false);
4079
4080 unlock:
4081 perf_ctx_unlock(cpuctx, ctx);
4082 rcu_unlock:
4083 rcu_read_unlock();
4084 }
4085
4086 /*
4087 * Called from scheduler to add the events of the current task
4088 * with interrupts disabled.
4089 *
4090 * We restore the event value and then enable it.
4091 *
4092 * This does not protect us against NMI, but enable()
4093 * sets the enabled bit in the control field of event _before_
4094 * accessing the event control register. If a NMI hits, then it will
4095 * keep the event running.
4096 */
__perf_event_task_sched_in(struct task_struct * prev,struct task_struct * task)4097 void __perf_event_task_sched_in(struct task_struct *prev,
4098 struct task_struct *task)
4099 {
4100 perf_event_context_sched_in(task);
4101
4102 if (atomic_read(&nr_switch_events))
4103 perf_event_switch(task, prev, true);
4104
4105 if (__this_cpu_read(perf_sched_cb_usages))
4106 perf_pmu_sched_task(prev, task, true);
4107 }
4108
perf_calculate_period(struct perf_event * event,u64 nsec,u64 count)4109 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
4110 {
4111 u64 frequency = event->attr.sample_freq;
4112 u64 sec = NSEC_PER_SEC;
4113 u64 divisor, dividend;
4114
4115 int count_fls, nsec_fls, frequency_fls, sec_fls;
4116
4117 count_fls = fls64(count);
4118 nsec_fls = fls64(nsec);
4119 frequency_fls = fls64(frequency);
4120 sec_fls = 30;
4121
4122 /*
4123 * We got @count in @nsec, with a target of sample_freq HZ
4124 * the target period becomes:
4125 *
4126 * @count * 10^9
4127 * period = -------------------
4128 * @nsec * sample_freq
4129 *
4130 */
4131
4132 /*
4133 * Reduce accuracy by one bit such that @a and @b converge
4134 * to a similar magnitude.
4135 */
4136 #define REDUCE_FLS(a, b) \
4137 do { \
4138 if (a##_fls > b##_fls) { \
4139 a >>= 1; \
4140 a##_fls--; \
4141 } else { \
4142 b >>= 1; \
4143 b##_fls--; \
4144 } \
4145 } while (0)
4146
4147 /*
4148 * Reduce accuracy until either term fits in a u64, then proceed with
4149 * the other, so that finally we can do a u64/u64 division.
4150 */
4151 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
4152 REDUCE_FLS(nsec, frequency);
4153 REDUCE_FLS(sec, count);
4154 }
4155
4156 if (count_fls + sec_fls > 64) {
4157 divisor = nsec * frequency;
4158
4159 while (count_fls + sec_fls > 64) {
4160 REDUCE_FLS(count, sec);
4161 divisor >>= 1;
4162 }
4163
4164 dividend = count * sec;
4165 } else {
4166 dividend = count * sec;
4167
4168 while (nsec_fls + frequency_fls > 64) {
4169 REDUCE_FLS(nsec, frequency);
4170 dividend >>= 1;
4171 }
4172
4173 divisor = nsec * frequency;
4174 }
4175
4176 if (!divisor)
4177 return dividend;
4178
4179 return div64_u64(dividend, divisor);
4180 }
4181
4182 static DEFINE_PER_CPU(int, perf_throttled_count);
4183 static DEFINE_PER_CPU(u64, perf_throttled_seq);
4184
perf_adjust_period(struct perf_event * event,u64 nsec,u64 count,bool disable)4185 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
4186 {
4187 struct hw_perf_event *hwc = &event->hw;
4188 s64 period, sample_period;
4189 s64 delta;
4190
4191 period = perf_calculate_period(event, nsec, count);
4192
4193 delta = (s64)(period - hwc->sample_period);
4194 if (delta >= 0)
4195 delta += 7;
4196 else
4197 delta -= 7;
4198 delta /= 8; /* low pass filter */
4199
4200 sample_period = hwc->sample_period + delta;
4201
4202 if (!sample_period)
4203 sample_period = 1;
4204
4205 hwc->sample_period = sample_period;
4206
4207 if (local64_read(&hwc->period_left) > 8*sample_period) {
4208 if (disable)
4209 event->pmu->stop(event, PERF_EF_UPDATE);
4210
4211 local64_set(&hwc->period_left, 0);
4212
4213 if (disable)
4214 event->pmu->start(event, PERF_EF_RELOAD);
4215 }
4216 }
4217
perf_adjust_freq_unthr_events(struct list_head * event_list)4218 static void perf_adjust_freq_unthr_events(struct list_head *event_list)
4219 {
4220 struct perf_event *event;
4221 struct hw_perf_event *hwc;
4222 u64 now, period = TICK_NSEC;
4223 s64 delta;
4224
4225 list_for_each_entry(event, event_list, active_list) {
4226 if (event->state != PERF_EVENT_STATE_ACTIVE)
4227 continue;
4228
4229 // XXX use visit thingy to avoid the -1,cpu match
4230 if (!event_filter_match(event))
4231 continue;
4232
4233 hwc = &event->hw;
4234
4235 if (hwc->interrupts == MAX_INTERRUPTS) {
4236 hwc->interrupts = 0;
4237 perf_log_throttle(event, 1);
4238 if (!event->attr.freq || !event->attr.sample_freq)
4239 event->pmu->start(event, 0);
4240 }
4241
4242 if (!event->attr.freq || !event->attr.sample_freq)
4243 continue;
4244
4245 /*
4246 * stop the event and update event->count
4247 */
4248 event->pmu->stop(event, PERF_EF_UPDATE);
4249
4250 now = local64_read(&event->count);
4251 delta = now - hwc->freq_count_stamp;
4252 hwc->freq_count_stamp = now;
4253
4254 /*
4255 * restart the event
4256 * reload only if value has changed
4257 * we have stopped the event so tell that
4258 * to perf_adjust_period() to avoid stopping it
4259 * twice.
4260 */
4261 if (delta > 0)
4262 perf_adjust_period(event, period, delta, false);
4263
4264 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
4265 }
4266 }
4267
4268 /*
4269 * combine freq adjustment with unthrottling to avoid two passes over the
4270 * events. At the same time, make sure, having freq events does not change
4271 * the rate of unthrottling as that would introduce bias.
4272 */
4273 static void
perf_adjust_freq_unthr_context(struct perf_event_context * ctx,bool unthrottle)4274 perf_adjust_freq_unthr_context(struct perf_event_context *ctx, bool unthrottle)
4275 {
4276 struct perf_event_pmu_context *pmu_ctx;
4277
4278 /*
4279 * only need to iterate over all events iff:
4280 * - context have events in frequency mode (needs freq adjust)
4281 * - there are events to unthrottle on this cpu
4282 */
4283 if (!(ctx->nr_freq || unthrottle))
4284 return;
4285
4286 raw_spin_lock(&ctx->lock);
4287
4288 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
4289 if (!(pmu_ctx->nr_freq || unthrottle))
4290 continue;
4291 if (!perf_pmu_ctx_is_active(pmu_ctx))
4292 continue;
4293 if (pmu_ctx->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT)
4294 continue;
4295
4296 perf_pmu_disable(pmu_ctx->pmu);
4297 perf_adjust_freq_unthr_events(&pmu_ctx->pinned_active);
4298 perf_adjust_freq_unthr_events(&pmu_ctx->flexible_active);
4299 perf_pmu_enable(pmu_ctx->pmu);
4300 }
4301
4302 raw_spin_unlock(&ctx->lock);
4303 }
4304
4305 /*
4306 * Move @event to the tail of the @ctx's elegible events.
4307 */
rotate_ctx(struct perf_event_context * ctx,struct perf_event * event)4308 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4309 {
4310 /*
4311 * Rotate the first entry last of non-pinned groups. Rotation might be
4312 * disabled by the inheritance code.
4313 */
4314 if (ctx->rotate_disable)
4315 return;
4316
4317 perf_event_groups_delete(&ctx->flexible_groups, event);
4318 perf_event_groups_insert(&ctx->flexible_groups, event);
4319 }
4320
4321 /* pick an event from the flexible_groups to rotate */
4322 static inline struct perf_event *
ctx_event_to_rotate(struct perf_event_pmu_context * pmu_ctx)4323 ctx_event_to_rotate(struct perf_event_pmu_context *pmu_ctx)
4324 {
4325 struct perf_event *event;
4326 struct rb_node *node;
4327 struct rb_root *tree;
4328 struct __group_key key = {
4329 .pmu = pmu_ctx->pmu,
4330 };
4331
4332 /* pick the first active flexible event */
4333 event = list_first_entry_or_null(&pmu_ctx->flexible_active,
4334 struct perf_event, active_list);
4335 if (event)
4336 goto out;
4337
4338 /* if no active flexible event, pick the first event */
4339 tree = &pmu_ctx->ctx->flexible_groups.tree;
4340
4341 if (!pmu_ctx->ctx->task) {
4342 key.cpu = smp_processor_id();
4343
4344 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4345 if (node)
4346 event = __node_2_pe(node);
4347 goto out;
4348 }
4349
4350 key.cpu = -1;
4351 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4352 if (node) {
4353 event = __node_2_pe(node);
4354 goto out;
4355 }
4356
4357 key.cpu = smp_processor_id();
4358 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4359 if (node)
4360 event = __node_2_pe(node);
4361
4362 out:
4363 /*
4364 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4365 * finds there are unschedulable events, it will set it again.
4366 */
4367 pmu_ctx->rotate_necessary = 0;
4368
4369 return event;
4370 }
4371
perf_rotate_context(struct perf_cpu_pmu_context * cpc)4372 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc)
4373 {
4374 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4375 struct perf_event_pmu_context *cpu_epc, *task_epc = NULL;
4376 struct perf_event *cpu_event = NULL, *task_event = NULL;
4377 int cpu_rotate, task_rotate;
4378 struct pmu *pmu;
4379
4380 /*
4381 * Since we run this from IRQ context, nobody can install new
4382 * events, thus the event count values are stable.
4383 */
4384
4385 cpu_epc = &cpc->epc;
4386 pmu = cpu_epc->pmu;
4387 task_epc = cpc->task_epc;
4388
4389 cpu_rotate = cpu_epc->rotate_necessary;
4390 task_rotate = task_epc ? task_epc->rotate_necessary : 0;
4391
4392 if (!(cpu_rotate || task_rotate))
4393 return false;
4394
4395 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4396 perf_pmu_disable(pmu);
4397
4398 if (task_rotate)
4399 task_event = ctx_event_to_rotate(task_epc);
4400 if (cpu_rotate)
4401 cpu_event = ctx_event_to_rotate(cpu_epc);
4402
4403 /*
4404 * As per the order given at ctx_resched() first 'pop' task flexible
4405 * and then, if needed CPU flexible.
4406 */
4407 if (task_event || (task_epc && cpu_event)) {
4408 update_context_time(task_epc->ctx);
4409 __pmu_ctx_sched_out(task_epc, EVENT_FLEXIBLE);
4410 }
4411
4412 if (cpu_event) {
4413 update_context_time(&cpuctx->ctx);
4414 __pmu_ctx_sched_out(cpu_epc, EVENT_FLEXIBLE);
4415 rotate_ctx(&cpuctx->ctx, cpu_event);
4416 __pmu_ctx_sched_in(cpu_epc, EVENT_FLEXIBLE);
4417 }
4418
4419 if (task_event)
4420 rotate_ctx(task_epc->ctx, task_event);
4421
4422 if (task_event || (task_epc && cpu_event))
4423 __pmu_ctx_sched_in(task_epc, EVENT_FLEXIBLE);
4424
4425 perf_pmu_enable(pmu);
4426 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4427
4428 return true;
4429 }
4430
perf_event_task_tick(void)4431 void perf_event_task_tick(void)
4432 {
4433 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4434 struct perf_event_context *ctx;
4435 int throttled;
4436
4437 lockdep_assert_irqs_disabled();
4438
4439 __this_cpu_inc(perf_throttled_seq);
4440 throttled = __this_cpu_xchg(perf_throttled_count, 0);
4441 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4442
4443 perf_adjust_freq_unthr_context(&cpuctx->ctx, !!throttled);
4444
4445 rcu_read_lock();
4446 ctx = rcu_dereference(current->perf_event_ctxp);
4447 if (ctx)
4448 perf_adjust_freq_unthr_context(ctx, !!throttled);
4449 rcu_read_unlock();
4450 }
4451
event_enable_on_exec(struct perf_event * event,struct perf_event_context * ctx)4452 static int event_enable_on_exec(struct perf_event *event,
4453 struct perf_event_context *ctx)
4454 {
4455 if (!event->attr.enable_on_exec)
4456 return 0;
4457
4458 event->attr.enable_on_exec = 0;
4459 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4460 return 0;
4461
4462 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4463
4464 return 1;
4465 }
4466
4467 /*
4468 * Enable all of a task's events that have been marked enable-on-exec.
4469 * This expects task == current.
4470 */
perf_event_enable_on_exec(struct perf_event_context * ctx)4471 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
4472 {
4473 struct perf_event_context *clone_ctx = NULL;
4474 enum event_type_t event_type = 0;
4475 struct perf_cpu_context *cpuctx;
4476 struct perf_event *event;
4477 unsigned long flags;
4478 int enabled = 0;
4479
4480 local_irq_save(flags);
4481 if (WARN_ON_ONCE(current->perf_event_ctxp != ctx))
4482 goto out;
4483
4484 if (!ctx->nr_events)
4485 goto out;
4486
4487 cpuctx = this_cpu_ptr(&perf_cpu_context);
4488 perf_ctx_lock(cpuctx, ctx);
4489 ctx_time_freeze(cpuctx, ctx);
4490
4491 list_for_each_entry(event, &ctx->event_list, event_entry) {
4492 enabled |= event_enable_on_exec(event, ctx);
4493 event_type |= get_event_type(event);
4494 }
4495
4496 /*
4497 * Unclone and reschedule this context if we enabled any event.
4498 */
4499 if (enabled) {
4500 clone_ctx = unclone_ctx(ctx);
4501 ctx_resched(cpuctx, ctx, NULL, event_type);
4502 }
4503 perf_ctx_unlock(cpuctx, ctx);
4504
4505 out:
4506 local_irq_restore(flags);
4507
4508 if (clone_ctx)
4509 put_ctx(clone_ctx);
4510 }
4511
4512 static void perf_remove_from_owner(struct perf_event *event);
4513 static void perf_event_exit_event(struct perf_event *event,
4514 struct perf_event_context *ctx);
4515
4516 /*
4517 * Removes all events from the current task that have been marked
4518 * remove-on-exec, and feeds their values back to parent events.
4519 */
perf_event_remove_on_exec(struct perf_event_context * ctx)4520 static void perf_event_remove_on_exec(struct perf_event_context *ctx)
4521 {
4522 struct perf_event_context *clone_ctx = NULL;
4523 struct perf_event *event, *next;
4524 unsigned long flags;
4525 bool modified = false;
4526
4527 mutex_lock(&ctx->mutex);
4528
4529 if (WARN_ON_ONCE(ctx->task != current))
4530 goto unlock;
4531
4532 list_for_each_entry_safe(event, next, &ctx->event_list, event_entry) {
4533 if (!event->attr.remove_on_exec)
4534 continue;
4535
4536 if (!is_kernel_event(event))
4537 perf_remove_from_owner(event);
4538
4539 modified = true;
4540
4541 perf_event_exit_event(event, ctx);
4542 }
4543
4544 raw_spin_lock_irqsave(&ctx->lock, flags);
4545 if (modified)
4546 clone_ctx = unclone_ctx(ctx);
4547 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4548
4549 unlock:
4550 mutex_unlock(&ctx->mutex);
4551
4552 if (clone_ctx)
4553 put_ctx(clone_ctx);
4554 }
4555
4556 struct perf_read_data {
4557 struct perf_event *event;
4558 bool group;
4559 int ret;
4560 };
4561
4562 static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu);
4563
__perf_event_read_cpu(struct perf_event * event,int event_cpu)4564 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4565 {
4566 int local_cpu = smp_processor_id();
4567 u16 local_pkg, event_pkg;
4568
4569 if ((unsigned)event_cpu >= nr_cpu_ids)
4570 return event_cpu;
4571
4572 if (event->group_caps & PERF_EV_CAP_READ_SCOPE) {
4573 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(event->pmu->scope, event_cpu);
4574
4575 if (cpumask && cpumask_test_cpu(local_cpu, cpumask))
4576 return local_cpu;
4577 }
4578
4579 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4580 event_pkg = topology_physical_package_id(event_cpu);
4581 local_pkg = topology_physical_package_id(local_cpu);
4582
4583 if (event_pkg == local_pkg)
4584 return local_cpu;
4585 }
4586
4587 return event_cpu;
4588 }
4589
4590 /*
4591 * Cross CPU call to read the hardware event
4592 */
__perf_event_read(void * info)4593 static void __perf_event_read(void *info)
4594 {
4595 struct perf_read_data *data = info;
4596 struct perf_event *sub, *event = data->event;
4597 struct perf_event_context *ctx = event->ctx;
4598 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4599 struct pmu *pmu = event->pmu;
4600
4601 /*
4602 * If this is a task context, we need to check whether it is
4603 * the current task context of this cpu. If not it has been
4604 * scheduled out before the smp call arrived. In that case
4605 * event->count would have been updated to a recent sample
4606 * when the event was scheduled out.
4607 */
4608 if (ctx->task && cpuctx->task_ctx != ctx)
4609 return;
4610
4611 raw_spin_lock(&ctx->lock);
4612 ctx_time_update_event(ctx, event);
4613
4614 perf_event_update_time(event);
4615 if (data->group)
4616 perf_event_update_sibling_time(event);
4617
4618 if (event->state != PERF_EVENT_STATE_ACTIVE)
4619 goto unlock;
4620
4621 if (!data->group) {
4622 pmu->read(event);
4623 data->ret = 0;
4624 goto unlock;
4625 }
4626
4627 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4628
4629 pmu->read(event);
4630
4631 for_each_sibling_event(sub, event)
4632 perf_pmu_read(sub);
4633
4634 data->ret = pmu->commit_txn(pmu);
4635
4636 unlock:
4637 raw_spin_unlock(&ctx->lock);
4638 }
4639
perf_event_count(struct perf_event * event,bool self)4640 static inline u64 perf_event_count(struct perf_event *event, bool self)
4641 {
4642 if (self)
4643 return local64_read(&event->count);
4644
4645 return local64_read(&event->count) + atomic64_read(&event->child_count);
4646 }
4647
calc_timer_values(struct perf_event * event,u64 * now,u64 * enabled,u64 * running)4648 static void calc_timer_values(struct perf_event *event,
4649 u64 *now,
4650 u64 *enabled,
4651 u64 *running)
4652 {
4653 u64 ctx_time;
4654
4655 *now = perf_clock();
4656 ctx_time = perf_event_time_now(event, *now);
4657 __perf_update_times(event, ctx_time, enabled, running);
4658 }
4659
4660 /*
4661 * NMI-safe method to read a local event, that is an event that
4662 * is:
4663 * - either for the current task, or for this CPU
4664 * - does not have inherit set, for inherited task events
4665 * will not be local and we cannot read them atomically
4666 * - must not have a pmu::count method
4667 */
perf_event_read_local(struct perf_event * event,u64 * value,u64 * enabled,u64 * running)4668 int perf_event_read_local(struct perf_event *event, u64 *value,
4669 u64 *enabled, u64 *running)
4670 {
4671 unsigned long flags;
4672 int event_oncpu;
4673 int event_cpu;
4674 int ret = 0;
4675
4676 /*
4677 * Disabling interrupts avoids all counter scheduling (context
4678 * switches, timer based rotation and IPIs).
4679 */
4680 local_irq_save(flags);
4681
4682 /*
4683 * It must not be an event with inherit set, we cannot read
4684 * all child counters from atomic context.
4685 */
4686 if (event->attr.inherit) {
4687 ret = -EOPNOTSUPP;
4688 goto out;
4689 }
4690
4691 /* If this is a per-task event, it must be for current */
4692 if ((event->attach_state & PERF_ATTACH_TASK) &&
4693 event->hw.target != current) {
4694 ret = -EINVAL;
4695 goto out;
4696 }
4697
4698 /*
4699 * Get the event CPU numbers, and adjust them to local if the event is
4700 * a per-package event that can be read locally
4701 */
4702 event_oncpu = __perf_event_read_cpu(event, event->oncpu);
4703 event_cpu = __perf_event_read_cpu(event, event->cpu);
4704
4705 /* If this is a per-CPU event, it must be for this CPU */
4706 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4707 event_cpu != smp_processor_id()) {
4708 ret = -EINVAL;
4709 goto out;
4710 }
4711
4712 /* If this is a pinned event it must be running on this CPU */
4713 if (event->attr.pinned && event_oncpu != smp_processor_id()) {
4714 ret = -EBUSY;
4715 goto out;
4716 }
4717
4718 /*
4719 * If the event is currently on this CPU, its either a per-task event,
4720 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4721 * oncpu == -1).
4722 */
4723 if (event_oncpu == smp_processor_id())
4724 event->pmu->read(event);
4725
4726 *value = local64_read(&event->count);
4727 if (enabled || running) {
4728 u64 __enabled, __running, __now;
4729
4730 calc_timer_values(event, &__now, &__enabled, &__running);
4731 if (enabled)
4732 *enabled = __enabled;
4733 if (running)
4734 *running = __running;
4735 }
4736 out:
4737 local_irq_restore(flags);
4738
4739 return ret;
4740 }
4741
perf_event_read(struct perf_event * event,bool group)4742 static int perf_event_read(struct perf_event *event, bool group)
4743 {
4744 enum perf_event_state state = READ_ONCE(event->state);
4745 int event_cpu, ret = 0;
4746
4747 /*
4748 * If event is enabled and currently active on a CPU, update the
4749 * value in the event structure:
4750 */
4751 again:
4752 if (state == PERF_EVENT_STATE_ACTIVE) {
4753 struct perf_read_data data;
4754
4755 /*
4756 * Orders the ->state and ->oncpu loads such that if we see
4757 * ACTIVE we must also see the right ->oncpu.
4758 *
4759 * Matches the smp_wmb() from event_sched_in().
4760 */
4761 smp_rmb();
4762
4763 event_cpu = READ_ONCE(event->oncpu);
4764 if ((unsigned)event_cpu >= nr_cpu_ids)
4765 return 0;
4766
4767 data = (struct perf_read_data){
4768 .event = event,
4769 .group = group,
4770 .ret = 0,
4771 };
4772
4773 preempt_disable();
4774 event_cpu = __perf_event_read_cpu(event, event_cpu);
4775
4776 /*
4777 * Purposely ignore the smp_call_function_single() return
4778 * value.
4779 *
4780 * If event_cpu isn't a valid CPU it means the event got
4781 * scheduled out and that will have updated the event count.
4782 *
4783 * Therefore, either way, we'll have an up-to-date event count
4784 * after this.
4785 */
4786 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4787 preempt_enable();
4788 ret = data.ret;
4789
4790 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4791 struct perf_event_context *ctx = event->ctx;
4792 unsigned long flags;
4793
4794 raw_spin_lock_irqsave(&ctx->lock, flags);
4795 state = event->state;
4796 if (state != PERF_EVENT_STATE_INACTIVE) {
4797 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4798 goto again;
4799 }
4800
4801 /*
4802 * May read while context is not active (e.g., thread is
4803 * blocked), in that case we cannot update context time
4804 */
4805 ctx_time_update_event(ctx, event);
4806
4807 perf_event_update_time(event);
4808 if (group)
4809 perf_event_update_sibling_time(event);
4810 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4811 }
4812
4813 return ret;
4814 }
4815
4816 /*
4817 * Initialize the perf_event context in a task_struct:
4818 */
__perf_event_init_context(struct perf_event_context * ctx)4819 static void __perf_event_init_context(struct perf_event_context *ctx)
4820 {
4821 raw_spin_lock_init(&ctx->lock);
4822 mutex_init(&ctx->mutex);
4823 INIT_LIST_HEAD(&ctx->pmu_ctx_list);
4824 perf_event_groups_init(&ctx->pinned_groups);
4825 perf_event_groups_init(&ctx->flexible_groups);
4826 INIT_LIST_HEAD(&ctx->event_list);
4827 refcount_set(&ctx->refcount, 1);
4828 }
4829
4830 static void
__perf_init_event_pmu_context(struct perf_event_pmu_context * epc,struct pmu * pmu)4831 __perf_init_event_pmu_context(struct perf_event_pmu_context *epc, struct pmu *pmu)
4832 {
4833 epc->pmu = pmu;
4834 INIT_LIST_HEAD(&epc->pmu_ctx_entry);
4835 INIT_LIST_HEAD(&epc->pinned_active);
4836 INIT_LIST_HEAD(&epc->flexible_active);
4837 atomic_set(&epc->refcount, 1);
4838 }
4839
4840 static struct perf_event_context *
alloc_perf_context(struct task_struct * task)4841 alloc_perf_context(struct task_struct *task)
4842 {
4843 struct perf_event_context *ctx;
4844
4845 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4846 if (!ctx)
4847 return NULL;
4848
4849 __perf_event_init_context(ctx);
4850 if (task)
4851 ctx->task = get_task_struct(task);
4852
4853 return ctx;
4854 }
4855
4856 static struct task_struct *
find_lively_task_by_vpid(pid_t vpid)4857 find_lively_task_by_vpid(pid_t vpid)
4858 {
4859 struct task_struct *task;
4860
4861 rcu_read_lock();
4862 if (!vpid)
4863 task = current;
4864 else
4865 task = find_task_by_vpid(vpid);
4866 if (task)
4867 get_task_struct(task);
4868 rcu_read_unlock();
4869
4870 if (!task)
4871 return ERR_PTR(-ESRCH);
4872
4873 return task;
4874 }
4875
4876 /*
4877 * Returns a matching context with refcount and pincount.
4878 */
4879 static struct perf_event_context *
find_get_context(struct task_struct * task,struct perf_event * event)4880 find_get_context(struct task_struct *task, struct perf_event *event)
4881 {
4882 struct perf_event_context *ctx, *clone_ctx = NULL;
4883 struct perf_cpu_context *cpuctx;
4884 unsigned long flags;
4885 int err;
4886
4887 if (!task) {
4888 /* Must be root to operate on a CPU event: */
4889 err = perf_allow_cpu();
4890 if (err)
4891 return ERR_PTR(err);
4892
4893 cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
4894 ctx = &cpuctx->ctx;
4895 get_ctx(ctx);
4896 raw_spin_lock_irqsave(&ctx->lock, flags);
4897 ++ctx->pin_count;
4898 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4899
4900 return ctx;
4901 }
4902
4903 err = -EINVAL;
4904 retry:
4905 ctx = perf_lock_task_context(task, &flags);
4906 if (ctx) {
4907 clone_ctx = unclone_ctx(ctx);
4908 ++ctx->pin_count;
4909
4910 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4911
4912 if (clone_ctx)
4913 put_ctx(clone_ctx);
4914 } else {
4915 ctx = alloc_perf_context(task);
4916 err = -ENOMEM;
4917 if (!ctx)
4918 goto errout;
4919
4920 err = 0;
4921 mutex_lock(&task->perf_event_mutex);
4922 /*
4923 * If it has already passed perf_event_exit_task().
4924 * we must see PF_EXITING, it takes this mutex too.
4925 */
4926 if (task->flags & PF_EXITING)
4927 err = -ESRCH;
4928 else if (task->perf_event_ctxp)
4929 err = -EAGAIN;
4930 else {
4931 get_ctx(ctx);
4932 ++ctx->pin_count;
4933 rcu_assign_pointer(task->perf_event_ctxp, ctx);
4934 }
4935 mutex_unlock(&task->perf_event_mutex);
4936
4937 if (unlikely(err)) {
4938 put_ctx(ctx);
4939
4940 if (err == -EAGAIN)
4941 goto retry;
4942 goto errout;
4943 }
4944 }
4945
4946 return ctx;
4947
4948 errout:
4949 return ERR_PTR(err);
4950 }
4951
4952 static struct perf_event_pmu_context *
find_get_pmu_context(struct pmu * pmu,struct perf_event_context * ctx,struct perf_event * event)4953 find_get_pmu_context(struct pmu *pmu, struct perf_event_context *ctx,
4954 struct perf_event *event)
4955 {
4956 struct perf_event_pmu_context *new = NULL, *pos = NULL, *epc;
4957
4958 if (!ctx->task) {
4959 /*
4960 * perf_pmu_migrate_context() / __perf_pmu_install_event()
4961 * relies on the fact that find_get_pmu_context() cannot fail
4962 * for CPU contexts.
4963 */
4964 struct perf_cpu_pmu_context *cpc;
4965
4966 cpc = *per_cpu_ptr(pmu->cpu_pmu_context, event->cpu);
4967 epc = &cpc->epc;
4968 raw_spin_lock_irq(&ctx->lock);
4969 if (!epc->ctx) {
4970 /*
4971 * One extra reference for the pmu; see perf_pmu_free().
4972 */
4973 atomic_set(&epc->refcount, 2);
4974 epc->embedded = 1;
4975 list_add(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
4976 epc->ctx = ctx;
4977 } else {
4978 WARN_ON_ONCE(epc->ctx != ctx);
4979 atomic_inc(&epc->refcount);
4980 }
4981 raw_spin_unlock_irq(&ctx->lock);
4982 return epc;
4983 }
4984
4985 new = kzalloc(sizeof(*epc), GFP_KERNEL);
4986 if (!new)
4987 return ERR_PTR(-ENOMEM);
4988
4989 __perf_init_event_pmu_context(new, pmu);
4990
4991 /*
4992 * XXX
4993 *
4994 * lockdep_assert_held(&ctx->mutex);
4995 *
4996 * can't because perf_event_init_task() doesn't actually hold the
4997 * child_ctx->mutex.
4998 */
4999
5000 raw_spin_lock_irq(&ctx->lock);
5001 list_for_each_entry(epc, &ctx->pmu_ctx_list, pmu_ctx_entry) {
5002 if (epc->pmu == pmu) {
5003 WARN_ON_ONCE(epc->ctx != ctx);
5004 atomic_inc(&epc->refcount);
5005 goto found_epc;
5006 }
5007 /* Make sure the pmu_ctx_list is sorted by PMU type: */
5008 if (!pos && epc->pmu->type > pmu->type)
5009 pos = epc;
5010 }
5011
5012 epc = new;
5013 new = NULL;
5014
5015 if (!pos)
5016 list_add_tail(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
5017 else
5018 list_add(&epc->pmu_ctx_entry, pos->pmu_ctx_entry.prev);
5019
5020 epc->ctx = ctx;
5021
5022 found_epc:
5023 raw_spin_unlock_irq(&ctx->lock);
5024 kfree(new);
5025
5026 return epc;
5027 }
5028
get_pmu_ctx(struct perf_event_pmu_context * epc)5029 static void get_pmu_ctx(struct perf_event_pmu_context *epc)
5030 {
5031 WARN_ON_ONCE(!atomic_inc_not_zero(&epc->refcount));
5032 }
5033
free_cpc_rcu(struct rcu_head * head)5034 static void free_cpc_rcu(struct rcu_head *head)
5035 {
5036 struct perf_cpu_pmu_context *cpc =
5037 container_of(head, typeof(*cpc), epc.rcu_head);
5038
5039 kfree(cpc);
5040 }
5041
free_epc_rcu(struct rcu_head * head)5042 static void free_epc_rcu(struct rcu_head *head)
5043 {
5044 struct perf_event_pmu_context *epc = container_of(head, typeof(*epc), rcu_head);
5045
5046 kfree(epc);
5047 }
5048
put_pmu_ctx(struct perf_event_pmu_context * epc)5049 static void put_pmu_ctx(struct perf_event_pmu_context *epc)
5050 {
5051 struct perf_event_context *ctx = epc->ctx;
5052 unsigned long flags;
5053
5054 /*
5055 * XXX
5056 *
5057 * lockdep_assert_held(&ctx->mutex);
5058 *
5059 * can't because of the call-site in _free_event()/put_event()
5060 * which isn't always called under ctx->mutex.
5061 */
5062 if (!atomic_dec_and_raw_lock_irqsave(&epc->refcount, &ctx->lock, flags))
5063 return;
5064
5065 WARN_ON_ONCE(list_empty(&epc->pmu_ctx_entry));
5066
5067 list_del_init(&epc->pmu_ctx_entry);
5068 epc->ctx = NULL;
5069
5070 WARN_ON_ONCE(!list_empty(&epc->pinned_active));
5071 WARN_ON_ONCE(!list_empty(&epc->flexible_active));
5072
5073 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5074
5075 if (epc->embedded) {
5076 call_rcu(&epc->rcu_head, free_cpc_rcu);
5077 return;
5078 }
5079
5080 call_rcu(&epc->rcu_head, free_epc_rcu);
5081 }
5082
5083 static void perf_event_free_filter(struct perf_event *event);
5084
free_event_rcu(struct rcu_head * head)5085 static void free_event_rcu(struct rcu_head *head)
5086 {
5087 struct perf_event *event = container_of(head, typeof(*event), rcu_head);
5088
5089 if (event->ns)
5090 put_pid_ns(event->ns);
5091 perf_event_free_filter(event);
5092 kmem_cache_free(perf_event_cache, event);
5093 }
5094
5095 static void ring_buffer_attach(struct perf_event *event,
5096 struct perf_buffer *rb);
5097
detach_sb_event(struct perf_event * event)5098 static void detach_sb_event(struct perf_event *event)
5099 {
5100 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
5101
5102 raw_spin_lock(&pel->lock);
5103 list_del_rcu(&event->sb_list);
5104 raw_spin_unlock(&pel->lock);
5105 }
5106
is_sb_event(struct perf_event * event)5107 static bool is_sb_event(struct perf_event *event)
5108 {
5109 struct perf_event_attr *attr = &event->attr;
5110
5111 if (event->parent)
5112 return false;
5113
5114 if (event->attach_state & PERF_ATTACH_TASK)
5115 return false;
5116
5117 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
5118 attr->comm || attr->comm_exec ||
5119 attr->task || attr->ksymbol ||
5120 attr->context_switch || attr->text_poke ||
5121 attr->bpf_event)
5122 return true;
5123 return false;
5124 }
5125
unaccount_pmu_sb_event(struct perf_event * event)5126 static void unaccount_pmu_sb_event(struct perf_event *event)
5127 {
5128 if (is_sb_event(event))
5129 detach_sb_event(event);
5130 }
5131
5132 #ifdef CONFIG_NO_HZ_FULL
5133 static DEFINE_SPINLOCK(nr_freq_lock);
5134 #endif
5135
unaccount_freq_event_nohz(void)5136 static void unaccount_freq_event_nohz(void)
5137 {
5138 #ifdef CONFIG_NO_HZ_FULL
5139 spin_lock(&nr_freq_lock);
5140 if (atomic_dec_and_test(&nr_freq_events))
5141 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
5142 spin_unlock(&nr_freq_lock);
5143 #endif
5144 }
5145
unaccount_freq_event(void)5146 static void unaccount_freq_event(void)
5147 {
5148 if (tick_nohz_full_enabled())
5149 unaccount_freq_event_nohz();
5150 else
5151 atomic_dec(&nr_freq_events);
5152 }
5153
5154
5155 static struct perf_ctx_data *
alloc_perf_ctx_data(struct kmem_cache * ctx_cache,bool global)5156 alloc_perf_ctx_data(struct kmem_cache *ctx_cache, bool global)
5157 {
5158 struct perf_ctx_data *cd;
5159
5160 cd = kzalloc(sizeof(*cd), GFP_KERNEL);
5161 if (!cd)
5162 return NULL;
5163
5164 cd->data = kmem_cache_zalloc(ctx_cache, GFP_KERNEL);
5165 if (!cd->data) {
5166 kfree(cd);
5167 return NULL;
5168 }
5169
5170 cd->global = global;
5171 cd->ctx_cache = ctx_cache;
5172 refcount_set(&cd->refcount, 1);
5173
5174 return cd;
5175 }
5176
free_perf_ctx_data(struct perf_ctx_data * cd)5177 static void free_perf_ctx_data(struct perf_ctx_data *cd)
5178 {
5179 kmem_cache_free(cd->ctx_cache, cd->data);
5180 kfree(cd);
5181 }
5182
__free_perf_ctx_data_rcu(struct rcu_head * rcu_head)5183 static void __free_perf_ctx_data_rcu(struct rcu_head *rcu_head)
5184 {
5185 struct perf_ctx_data *cd;
5186
5187 cd = container_of(rcu_head, struct perf_ctx_data, rcu_head);
5188 free_perf_ctx_data(cd);
5189 }
5190
perf_free_ctx_data_rcu(struct perf_ctx_data * cd)5191 static inline void perf_free_ctx_data_rcu(struct perf_ctx_data *cd)
5192 {
5193 call_rcu(&cd->rcu_head, __free_perf_ctx_data_rcu);
5194 }
5195
5196 static int
attach_task_ctx_data(struct task_struct * task,struct kmem_cache * ctx_cache,bool global)5197 attach_task_ctx_data(struct task_struct *task, struct kmem_cache *ctx_cache,
5198 bool global)
5199 {
5200 struct perf_ctx_data *cd, *old = NULL;
5201
5202 cd = alloc_perf_ctx_data(ctx_cache, global);
5203 if (!cd)
5204 return -ENOMEM;
5205
5206 for (;;) {
5207 if (try_cmpxchg((struct perf_ctx_data **)&task->perf_ctx_data, &old, cd)) {
5208 if (old)
5209 perf_free_ctx_data_rcu(old);
5210 return 0;
5211 }
5212
5213 if (!old) {
5214 /*
5215 * After seeing a dead @old, we raced with
5216 * removal and lost, try again to install @cd.
5217 */
5218 continue;
5219 }
5220
5221 if (refcount_inc_not_zero(&old->refcount)) {
5222 free_perf_ctx_data(cd); /* unused */
5223 return 0;
5224 }
5225
5226 /*
5227 * @old is a dead object, refcount==0 is stable, try and
5228 * replace it with @cd.
5229 */
5230 }
5231 return 0;
5232 }
5233
5234 static void __detach_global_ctx_data(void);
5235 DEFINE_STATIC_PERCPU_RWSEM(global_ctx_data_rwsem);
5236 static refcount_t global_ctx_data_ref;
5237
5238 static int
attach_global_ctx_data(struct kmem_cache * ctx_cache)5239 attach_global_ctx_data(struct kmem_cache *ctx_cache)
5240 {
5241 struct task_struct *g, *p;
5242 struct perf_ctx_data *cd;
5243 int ret;
5244
5245 if (refcount_inc_not_zero(&global_ctx_data_ref))
5246 return 0;
5247
5248 guard(percpu_write)(&global_ctx_data_rwsem);
5249 if (refcount_inc_not_zero(&global_ctx_data_ref))
5250 return 0;
5251 again:
5252 /* Allocate everything */
5253 scoped_guard (rcu) {
5254 for_each_process_thread(g, p) {
5255 cd = rcu_dereference(p->perf_ctx_data);
5256 if (cd && !cd->global) {
5257 cd->global = 1;
5258 if (!refcount_inc_not_zero(&cd->refcount))
5259 cd = NULL;
5260 }
5261 if (!cd) {
5262 get_task_struct(p);
5263 goto alloc;
5264 }
5265 }
5266 }
5267
5268 refcount_set(&global_ctx_data_ref, 1);
5269
5270 return 0;
5271 alloc:
5272 ret = attach_task_ctx_data(p, ctx_cache, true);
5273 put_task_struct(p);
5274 if (ret) {
5275 __detach_global_ctx_data();
5276 return ret;
5277 }
5278 goto again;
5279 }
5280
5281 static int
attach_perf_ctx_data(struct perf_event * event)5282 attach_perf_ctx_data(struct perf_event *event)
5283 {
5284 struct task_struct *task = event->hw.target;
5285 struct kmem_cache *ctx_cache = event->pmu->task_ctx_cache;
5286 int ret;
5287
5288 if (!ctx_cache)
5289 return -ENOMEM;
5290
5291 if (task)
5292 return attach_task_ctx_data(task, ctx_cache, false);
5293
5294 ret = attach_global_ctx_data(ctx_cache);
5295 if (ret)
5296 return ret;
5297
5298 event->attach_state |= PERF_ATTACH_GLOBAL_DATA;
5299 return 0;
5300 }
5301
5302 static void
detach_task_ctx_data(struct task_struct * p)5303 detach_task_ctx_data(struct task_struct *p)
5304 {
5305 struct perf_ctx_data *cd;
5306
5307 scoped_guard (rcu) {
5308 cd = rcu_dereference(p->perf_ctx_data);
5309 if (!cd || !refcount_dec_and_test(&cd->refcount))
5310 return;
5311 }
5312
5313 /*
5314 * The old ctx_data may be lost because of the race.
5315 * Nothing is required to do for the case.
5316 * See attach_task_ctx_data().
5317 */
5318 if (try_cmpxchg((struct perf_ctx_data **)&p->perf_ctx_data, &cd, NULL))
5319 perf_free_ctx_data_rcu(cd);
5320 }
5321
__detach_global_ctx_data(void)5322 static void __detach_global_ctx_data(void)
5323 {
5324 struct task_struct *g, *p;
5325 struct perf_ctx_data *cd;
5326
5327 again:
5328 scoped_guard (rcu) {
5329 for_each_process_thread(g, p) {
5330 cd = rcu_dereference(p->perf_ctx_data);
5331 if (!cd || !cd->global)
5332 continue;
5333 cd->global = 0;
5334 get_task_struct(p);
5335 goto detach;
5336 }
5337 }
5338 return;
5339 detach:
5340 detach_task_ctx_data(p);
5341 put_task_struct(p);
5342 goto again;
5343 }
5344
detach_global_ctx_data(void)5345 static void detach_global_ctx_data(void)
5346 {
5347 if (refcount_dec_not_one(&global_ctx_data_ref))
5348 return;
5349
5350 guard(percpu_write)(&global_ctx_data_rwsem);
5351 if (!refcount_dec_and_test(&global_ctx_data_ref))
5352 return;
5353
5354 /* remove everything */
5355 __detach_global_ctx_data();
5356 }
5357
detach_perf_ctx_data(struct perf_event * event)5358 static void detach_perf_ctx_data(struct perf_event *event)
5359 {
5360 struct task_struct *task = event->hw.target;
5361
5362 event->attach_state &= ~PERF_ATTACH_TASK_DATA;
5363
5364 if (task)
5365 return detach_task_ctx_data(task);
5366
5367 if (event->attach_state & PERF_ATTACH_GLOBAL_DATA) {
5368 detach_global_ctx_data();
5369 event->attach_state &= ~PERF_ATTACH_GLOBAL_DATA;
5370 }
5371 }
5372
unaccount_event(struct perf_event * event)5373 static void unaccount_event(struct perf_event *event)
5374 {
5375 bool dec = false;
5376
5377 if (event->parent)
5378 return;
5379
5380 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
5381 dec = true;
5382 if (event->attr.mmap || event->attr.mmap_data)
5383 atomic_dec(&nr_mmap_events);
5384 if (event->attr.build_id)
5385 atomic_dec(&nr_build_id_events);
5386 if (event->attr.comm)
5387 atomic_dec(&nr_comm_events);
5388 if (event->attr.namespaces)
5389 atomic_dec(&nr_namespaces_events);
5390 if (event->attr.cgroup)
5391 atomic_dec(&nr_cgroup_events);
5392 if (event->attr.task)
5393 atomic_dec(&nr_task_events);
5394 if (event->attr.freq)
5395 unaccount_freq_event();
5396 if (event->attr.context_switch) {
5397 dec = true;
5398 atomic_dec(&nr_switch_events);
5399 }
5400 if (is_cgroup_event(event))
5401 dec = true;
5402 if (has_branch_stack(event))
5403 dec = true;
5404 if (event->attr.ksymbol)
5405 atomic_dec(&nr_ksymbol_events);
5406 if (event->attr.bpf_event)
5407 atomic_dec(&nr_bpf_events);
5408 if (event->attr.text_poke)
5409 atomic_dec(&nr_text_poke_events);
5410
5411 if (dec) {
5412 if (!atomic_add_unless(&perf_sched_count, -1, 1))
5413 schedule_delayed_work(&perf_sched_work, HZ);
5414 }
5415
5416 unaccount_pmu_sb_event(event);
5417 }
5418
perf_sched_delayed(struct work_struct * work)5419 static void perf_sched_delayed(struct work_struct *work)
5420 {
5421 mutex_lock(&perf_sched_mutex);
5422 if (atomic_dec_and_test(&perf_sched_count))
5423 static_branch_disable(&perf_sched_events);
5424 mutex_unlock(&perf_sched_mutex);
5425 }
5426
5427 /*
5428 * The following implement mutual exclusion of events on "exclusive" pmus
5429 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
5430 * at a time, so we disallow creating events that might conflict, namely:
5431 *
5432 * 1) cpu-wide events in the presence of per-task events,
5433 * 2) per-task events in the presence of cpu-wide events,
5434 * 3) two matching events on the same perf_event_context.
5435 *
5436 * The former two cases are handled in the allocation path (perf_event_alloc(),
5437 * _free_event()), the latter -- before the first perf_install_in_context().
5438 */
exclusive_event_init(struct perf_event * event)5439 static int exclusive_event_init(struct perf_event *event)
5440 {
5441 struct pmu *pmu = event->pmu;
5442
5443 if (!is_exclusive_pmu(pmu))
5444 return 0;
5445
5446 /*
5447 * Prevent co-existence of per-task and cpu-wide events on the
5448 * same exclusive pmu.
5449 *
5450 * Negative pmu::exclusive_cnt means there are cpu-wide
5451 * events on this "exclusive" pmu, positive means there are
5452 * per-task events.
5453 *
5454 * Since this is called in perf_event_alloc() path, event::ctx
5455 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
5456 * to mean "per-task event", because unlike other attach states it
5457 * never gets cleared.
5458 */
5459 if (event->attach_state & PERF_ATTACH_TASK) {
5460 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
5461 return -EBUSY;
5462 } else {
5463 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
5464 return -EBUSY;
5465 }
5466
5467 event->attach_state |= PERF_ATTACH_EXCLUSIVE;
5468
5469 return 0;
5470 }
5471
exclusive_event_destroy(struct perf_event * event)5472 static void exclusive_event_destroy(struct perf_event *event)
5473 {
5474 struct pmu *pmu = event->pmu;
5475
5476 /* see comment in exclusive_event_init() */
5477 if (event->attach_state & PERF_ATTACH_TASK)
5478 atomic_dec(&pmu->exclusive_cnt);
5479 else
5480 atomic_inc(&pmu->exclusive_cnt);
5481
5482 event->attach_state &= ~PERF_ATTACH_EXCLUSIVE;
5483 }
5484
exclusive_event_match(struct perf_event * e1,struct perf_event * e2)5485 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
5486 {
5487 if ((e1->pmu == e2->pmu) &&
5488 (e1->cpu == e2->cpu ||
5489 e1->cpu == -1 ||
5490 e2->cpu == -1))
5491 return true;
5492 return false;
5493 }
5494
exclusive_event_installable(struct perf_event * event,struct perf_event_context * ctx)5495 static bool exclusive_event_installable(struct perf_event *event,
5496 struct perf_event_context *ctx)
5497 {
5498 struct perf_event *iter_event;
5499 struct pmu *pmu = event->pmu;
5500
5501 lockdep_assert_held(&ctx->mutex);
5502
5503 if (!is_exclusive_pmu(pmu))
5504 return true;
5505
5506 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
5507 if (exclusive_event_match(iter_event, event))
5508 return false;
5509 }
5510
5511 return true;
5512 }
5513
5514 static void perf_free_addr_filters(struct perf_event *event);
5515
perf_pending_task_sync(struct perf_event * event)5516 static void perf_pending_task_sync(struct perf_event *event)
5517 {
5518 struct callback_head *head = &event->pending_task;
5519
5520 if (!event->pending_work)
5521 return;
5522 /*
5523 * If the task is queued to the current task's queue, we
5524 * obviously can't wait for it to complete. Simply cancel it.
5525 */
5526 if (task_work_cancel(current, head)) {
5527 event->pending_work = 0;
5528 local_dec(&event->ctx->nr_no_switch_fast);
5529 return;
5530 }
5531
5532 /*
5533 * All accesses related to the event are within the same RCU section in
5534 * perf_pending_task(). The RCU grace period before the event is freed
5535 * will make sure all those accesses are complete by then.
5536 */
5537 rcuwait_wait_event(&event->pending_work_wait, !event->pending_work, TASK_UNINTERRUPTIBLE);
5538 }
5539
5540 /* vs perf_event_alloc() error */
__free_event(struct perf_event * event)5541 static void __free_event(struct perf_event *event)
5542 {
5543 if (event->attach_state & PERF_ATTACH_CALLCHAIN)
5544 put_callchain_buffers();
5545
5546 kfree(event->addr_filter_ranges);
5547
5548 if (event->attach_state & PERF_ATTACH_EXCLUSIVE)
5549 exclusive_event_destroy(event);
5550
5551 if (is_cgroup_event(event))
5552 perf_detach_cgroup(event);
5553
5554 if (event->attach_state & PERF_ATTACH_TASK_DATA)
5555 detach_perf_ctx_data(event);
5556
5557 if (event->destroy)
5558 event->destroy(event);
5559
5560 /*
5561 * Must be after ->destroy(), due to uprobe_perf_close() using
5562 * hw.target.
5563 */
5564 if (event->hw.target)
5565 put_task_struct(event->hw.target);
5566
5567 if (event->pmu_ctx) {
5568 /*
5569 * put_pmu_ctx() needs an event->ctx reference, because of
5570 * epc->ctx.
5571 */
5572 WARN_ON_ONCE(!event->ctx);
5573 WARN_ON_ONCE(event->pmu_ctx->ctx != event->ctx);
5574 put_pmu_ctx(event->pmu_ctx);
5575 }
5576
5577 /*
5578 * perf_event_free_task() relies on put_ctx() being 'last', in
5579 * particular all task references must be cleaned up.
5580 */
5581 if (event->ctx)
5582 put_ctx(event->ctx);
5583
5584 if (event->pmu)
5585 module_put(event->pmu->module);
5586
5587 call_rcu(&event->rcu_head, free_event_rcu);
5588 }
5589
DEFINE_FREE(__free_event,struct perf_event *,if (_T)__free_event (_T))5590 DEFINE_FREE(__free_event, struct perf_event *, if (_T) __free_event(_T))
5591
5592 /* vs perf_event_alloc() success */
5593 static void _free_event(struct perf_event *event)
5594 {
5595 irq_work_sync(&event->pending_irq);
5596 irq_work_sync(&event->pending_disable_irq);
5597 perf_pending_task_sync(event);
5598
5599 unaccount_event(event);
5600
5601 security_perf_event_free(event);
5602
5603 if (event->rb) {
5604 /*
5605 * Can happen when we close an event with re-directed output.
5606 *
5607 * Since we have a 0 refcount, perf_mmap_close() will skip
5608 * over us; possibly making our ring_buffer_put() the last.
5609 */
5610 mutex_lock(&event->mmap_mutex);
5611 ring_buffer_attach(event, NULL);
5612 mutex_unlock(&event->mmap_mutex);
5613 }
5614
5615 perf_event_free_bpf_prog(event);
5616 perf_free_addr_filters(event);
5617
5618 __free_event(event);
5619 }
5620
5621 /*
5622 * Used to free events which have a known refcount of 1, such as in error paths
5623 * where the event isn't exposed yet and inherited events.
5624 */
free_event(struct perf_event * event)5625 static void free_event(struct perf_event *event)
5626 {
5627 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
5628 "unexpected event refcount: %ld; ptr=%p\n",
5629 atomic_long_read(&event->refcount), event)) {
5630 /* leak to avoid use-after-free */
5631 return;
5632 }
5633
5634 _free_event(event);
5635 }
5636
5637 /*
5638 * Remove user event from the owner task.
5639 */
perf_remove_from_owner(struct perf_event * event)5640 static void perf_remove_from_owner(struct perf_event *event)
5641 {
5642 struct task_struct *owner;
5643
5644 rcu_read_lock();
5645 /*
5646 * Matches the smp_store_release() in perf_event_exit_task(). If we
5647 * observe !owner it means the list deletion is complete and we can
5648 * indeed free this event, otherwise we need to serialize on
5649 * owner->perf_event_mutex.
5650 */
5651 owner = READ_ONCE(event->owner);
5652 if (owner) {
5653 /*
5654 * Since delayed_put_task_struct() also drops the last
5655 * task reference we can safely take a new reference
5656 * while holding the rcu_read_lock().
5657 */
5658 get_task_struct(owner);
5659 }
5660 rcu_read_unlock();
5661
5662 if (owner) {
5663 /*
5664 * If we're here through perf_event_exit_task() we're already
5665 * holding ctx->mutex which would be an inversion wrt. the
5666 * normal lock order.
5667 *
5668 * However we can safely take this lock because its the child
5669 * ctx->mutex.
5670 */
5671 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
5672
5673 /*
5674 * We have to re-check the event->owner field, if it is cleared
5675 * we raced with perf_event_exit_task(), acquiring the mutex
5676 * ensured they're done, and we can proceed with freeing the
5677 * event.
5678 */
5679 if (event->owner) {
5680 list_del_init(&event->owner_entry);
5681 smp_store_release(&event->owner, NULL);
5682 }
5683 mutex_unlock(&owner->perf_event_mutex);
5684 put_task_struct(owner);
5685 }
5686 }
5687
put_event(struct perf_event * event)5688 static void put_event(struct perf_event *event)
5689 {
5690 if (!atomic_long_dec_and_test(&event->refcount))
5691 return;
5692
5693 _free_event(event);
5694 }
5695
5696 /*
5697 * Kill an event dead; while event:refcount will preserve the event
5698 * object, it will not preserve its functionality. Once the last 'user'
5699 * gives up the object, we'll destroy the thing.
5700 */
perf_event_release_kernel(struct perf_event * event)5701 int perf_event_release_kernel(struct perf_event *event)
5702 {
5703 struct perf_event_context *ctx = event->ctx;
5704 struct perf_event *child, *tmp;
5705 LIST_HEAD(free_list);
5706
5707 /*
5708 * If we got here through err_alloc: free_event(event); we will not
5709 * have attached to a context yet.
5710 */
5711 if (!ctx) {
5712 WARN_ON_ONCE(event->attach_state &
5713 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
5714 goto no_ctx;
5715 }
5716
5717 if (!is_kernel_event(event))
5718 perf_remove_from_owner(event);
5719
5720 ctx = perf_event_ctx_lock(event);
5721 WARN_ON_ONCE(ctx->parent_ctx);
5722
5723 /*
5724 * Mark this event as STATE_DEAD, there is no external reference to it
5725 * anymore.
5726 *
5727 * Anybody acquiring event->child_mutex after the below loop _must_
5728 * also see this, most importantly inherit_event() which will avoid
5729 * placing more children on the list.
5730 *
5731 * Thus this guarantees that we will in fact observe and kill _ALL_
5732 * child events.
5733 */
5734 perf_remove_from_context(event, DETACH_GROUP|DETACH_DEAD);
5735
5736 perf_event_ctx_unlock(event, ctx);
5737
5738 again:
5739 mutex_lock(&event->child_mutex);
5740 list_for_each_entry(child, &event->child_list, child_list) {
5741 void *var = NULL;
5742
5743 /*
5744 * Cannot change, child events are not migrated, see the
5745 * comment with perf_event_ctx_lock_nested().
5746 */
5747 ctx = READ_ONCE(child->ctx);
5748 /*
5749 * Since child_mutex nests inside ctx::mutex, we must jump
5750 * through hoops. We start by grabbing a reference on the ctx.
5751 *
5752 * Since the event cannot get freed while we hold the
5753 * child_mutex, the context must also exist and have a !0
5754 * reference count.
5755 */
5756 get_ctx(ctx);
5757
5758 /*
5759 * Now that we have a ctx ref, we can drop child_mutex, and
5760 * acquire ctx::mutex without fear of it going away. Then we
5761 * can re-acquire child_mutex.
5762 */
5763 mutex_unlock(&event->child_mutex);
5764 mutex_lock(&ctx->mutex);
5765 mutex_lock(&event->child_mutex);
5766
5767 /*
5768 * Now that we hold ctx::mutex and child_mutex, revalidate our
5769 * state, if child is still the first entry, it didn't get freed
5770 * and we can continue doing so.
5771 */
5772 tmp = list_first_entry_or_null(&event->child_list,
5773 struct perf_event, child_list);
5774 if (tmp == child) {
5775 perf_remove_from_context(child, DETACH_GROUP);
5776 list_move(&child->child_list, &free_list);
5777 /*
5778 * This matches the refcount bump in inherit_event();
5779 * this can't be the last reference.
5780 */
5781 put_event(event);
5782 } else {
5783 var = &ctx->refcount;
5784 }
5785
5786 mutex_unlock(&event->child_mutex);
5787 mutex_unlock(&ctx->mutex);
5788 put_ctx(ctx);
5789
5790 if (var) {
5791 /*
5792 * If perf_event_free_task() has deleted all events from the
5793 * ctx while the child_mutex got released above, make sure to
5794 * notify about the preceding put_ctx().
5795 */
5796 smp_mb(); /* pairs with wait_var_event() */
5797 wake_up_var(var);
5798 }
5799 goto again;
5800 }
5801 mutex_unlock(&event->child_mutex);
5802
5803 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
5804 void *var = &child->ctx->refcount;
5805
5806 list_del(&child->child_list);
5807 free_event(child);
5808
5809 /*
5810 * Wake any perf_event_free_task() waiting for this event to be
5811 * freed.
5812 */
5813 smp_mb(); /* pairs with wait_var_event() */
5814 wake_up_var(var);
5815 }
5816
5817 no_ctx:
5818 put_event(event); /* Must be the 'last' reference */
5819 return 0;
5820 }
5821 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5822
5823 /*
5824 * Called when the last reference to the file is gone.
5825 */
perf_release(struct inode * inode,struct file * file)5826 static int perf_release(struct inode *inode, struct file *file)
5827 {
5828 perf_event_release_kernel(file->private_data);
5829 return 0;
5830 }
5831
__perf_event_read_value(struct perf_event * event,u64 * enabled,u64 * running)5832 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5833 {
5834 struct perf_event *child;
5835 u64 total = 0;
5836
5837 *enabled = 0;
5838 *running = 0;
5839
5840 mutex_lock(&event->child_mutex);
5841
5842 (void)perf_event_read(event, false);
5843 total += perf_event_count(event, false);
5844
5845 *enabled += event->total_time_enabled +
5846 atomic64_read(&event->child_total_time_enabled);
5847 *running += event->total_time_running +
5848 atomic64_read(&event->child_total_time_running);
5849
5850 list_for_each_entry(child, &event->child_list, child_list) {
5851 (void)perf_event_read(child, false);
5852 total += perf_event_count(child, false);
5853 *enabled += child->total_time_enabled;
5854 *running += child->total_time_running;
5855 }
5856 mutex_unlock(&event->child_mutex);
5857
5858 return total;
5859 }
5860
perf_event_read_value(struct perf_event * event,u64 * enabled,u64 * running)5861 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5862 {
5863 struct perf_event_context *ctx;
5864 u64 count;
5865
5866 ctx = perf_event_ctx_lock(event);
5867 count = __perf_event_read_value(event, enabled, running);
5868 perf_event_ctx_unlock(event, ctx);
5869
5870 return count;
5871 }
5872 EXPORT_SYMBOL_GPL(perf_event_read_value);
5873
__perf_read_group_add(struct perf_event * leader,u64 read_format,u64 * values)5874 static int __perf_read_group_add(struct perf_event *leader,
5875 u64 read_format, u64 *values)
5876 {
5877 struct perf_event_context *ctx = leader->ctx;
5878 struct perf_event *sub, *parent;
5879 unsigned long flags;
5880 int n = 1; /* skip @nr */
5881 int ret;
5882
5883 ret = perf_event_read(leader, true);
5884 if (ret)
5885 return ret;
5886
5887 raw_spin_lock_irqsave(&ctx->lock, flags);
5888 /*
5889 * Verify the grouping between the parent and child (inherited)
5890 * events is still in tact.
5891 *
5892 * Specifically:
5893 * - leader->ctx->lock pins leader->sibling_list
5894 * - parent->child_mutex pins parent->child_list
5895 * - parent->ctx->mutex pins parent->sibling_list
5896 *
5897 * Because parent->ctx != leader->ctx (and child_list nests inside
5898 * ctx->mutex), group destruction is not atomic between children, also
5899 * see perf_event_release_kernel(). Additionally, parent can grow the
5900 * group.
5901 *
5902 * Therefore it is possible to have parent and child groups in a
5903 * different configuration and summing over such a beast makes no sense
5904 * what so ever.
5905 *
5906 * Reject this.
5907 */
5908 parent = leader->parent;
5909 if (parent &&
5910 (parent->group_generation != leader->group_generation ||
5911 parent->nr_siblings != leader->nr_siblings)) {
5912 ret = -ECHILD;
5913 goto unlock;
5914 }
5915
5916 /*
5917 * Since we co-schedule groups, {enabled,running} times of siblings
5918 * will be identical to those of the leader, so we only publish one
5919 * set.
5920 */
5921 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5922 values[n++] += leader->total_time_enabled +
5923 atomic64_read(&leader->child_total_time_enabled);
5924 }
5925
5926 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5927 values[n++] += leader->total_time_running +
5928 atomic64_read(&leader->child_total_time_running);
5929 }
5930
5931 /*
5932 * Write {count,id} tuples for every sibling.
5933 */
5934 values[n++] += perf_event_count(leader, false);
5935 if (read_format & PERF_FORMAT_ID)
5936 values[n++] = primary_event_id(leader);
5937 if (read_format & PERF_FORMAT_LOST)
5938 values[n++] = atomic64_read(&leader->lost_samples);
5939
5940 for_each_sibling_event(sub, leader) {
5941 values[n++] += perf_event_count(sub, false);
5942 if (read_format & PERF_FORMAT_ID)
5943 values[n++] = primary_event_id(sub);
5944 if (read_format & PERF_FORMAT_LOST)
5945 values[n++] = atomic64_read(&sub->lost_samples);
5946 }
5947
5948 unlock:
5949 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5950 return ret;
5951 }
5952
perf_read_group(struct perf_event * event,u64 read_format,char __user * buf)5953 static int perf_read_group(struct perf_event *event,
5954 u64 read_format, char __user *buf)
5955 {
5956 struct perf_event *leader = event->group_leader, *child;
5957 struct perf_event_context *ctx = leader->ctx;
5958 int ret;
5959 u64 *values;
5960
5961 lockdep_assert_held(&ctx->mutex);
5962
5963 values = kzalloc(event->read_size, GFP_KERNEL);
5964 if (!values)
5965 return -ENOMEM;
5966
5967 values[0] = 1 + leader->nr_siblings;
5968
5969 mutex_lock(&leader->child_mutex);
5970
5971 ret = __perf_read_group_add(leader, read_format, values);
5972 if (ret)
5973 goto unlock;
5974
5975 list_for_each_entry(child, &leader->child_list, child_list) {
5976 ret = __perf_read_group_add(child, read_format, values);
5977 if (ret)
5978 goto unlock;
5979 }
5980
5981 mutex_unlock(&leader->child_mutex);
5982
5983 ret = event->read_size;
5984 if (copy_to_user(buf, values, event->read_size))
5985 ret = -EFAULT;
5986 goto out;
5987
5988 unlock:
5989 mutex_unlock(&leader->child_mutex);
5990 out:
5991 kfree(values);
5992 return ret;
5993 }
5994
perf_read_one(struct perf_event * event,u64 read_format,char __user * buf)5995 static int perf_read_one(struct perf_event *event,
5996 u64 read_format, char __user *buf)
5997 {
5998 u64 enabled, running;
5999 u64 values[5];
6000 int n = 0;
6001
6002 values[n++] = __perf_event_read_value(event, &enabled, &running);
6003 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6004 values[n++] = enabled;
6005 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6006 values[n++] = running;
6007 if (read_format & PERF_FORMAT_ID)
6008 values[n++] = primary_event_id(event);
6009 if (read_format & PERF_FORMAT_LOST)
6010 values[n++] = atomic64_read(&event->lost_samples);
6011
6012 if (copy_to_user(buf, values, n * sizeof(u64)))
6013 return -EFAULT;
6014
6015 return n * sizeof(u64);
6016 }
6017
is_event_hup(struct perf_event * event)6018 static bool is_event_hup(struct perf_event *event)
6019 {
6020 bool no_children;
6021
6022 if (event->state > PERF_EVENT_STATE_EXIT)
6023 return false;
6024
6025 mutex_lock(&event->child_mutex);
6026 no_children = list_empty(&event->child_list);
6027 mutex_unlock(&event->child_mutex);
6028 return no_children;
6029 }
6030
6031 /*
6032 * Read the performance event - simple non blocking version for now
6033 */
6034 static ssize_t
__perf_read(struct perf_event * event,char __user * buf,size_t count)6035 __perf_read(struct perf_event *event, char __user *buf, size_t count)
6036 {
6037 u64 read_format = event->attr.read_format;
6038 int ret;
6039
6040 /*
6041 * Return end-of-file for a read on an event that is in
6042 * error state (i.e. because it was pinned but it couldn't be
6043 * scheduled on to the CPU at some point).
6044 */
6045 if (event->state == PERF_EVENT_STATE_ERROR)
6046 return 0;
6047
6048 if (count < event->read_size)
6049 return -ENOSPC;
6050
6051 WARN_ON_ONCE(event->ctx->parent_ctx);
6052 if (read_format & PERF_FORMAT_GROUP)
6053 ret = perf_read_group(event, read_format, buf);
6054 else
6055 ret = perf_read_one(event, read_format, buf);
6056
6057 return ret;
6058 }
6059
6060 static ssize_t
perf_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)6061 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
6062 {
6063 struct perf_event *event = file->private_data;
6064 struct perf_event_context *ctx;
6065 int ret;
6066
6067 ret = security_perf_event_read(event);
6068 if (ret)
6069 return ret;
6070
6071 ctx = perf_event_ctx_lock(event);
6072 ret = __perf_read(event, buf, count);
6073 perf_event_ctx_unlock(event, ctx);
6074
6075 return ret;
6076 }
6077
perf_poll(struct file * file,poll_table * wait)6078 static __poll_t perf_poll(struct file *file, poll_table *wait)
6079 {
6080 struct perf_event *event = file->private_data;
6081 struct perf_buffer *rb;
6082 __poll_t events = EPOLLHUP;
6083
6084 poll_wait(file, &event->waitq, wait);
6085
6086 if (is_event_hup(event))
6087 return events;
6088
6089 if (unlikely(READ_ONCE(event->state) == PERF_EVENT_STATE_ERROR &&
6090 event->attr.pinned))
6091 return events;
6092
6093 /*
6094 * Pin the event->rb by taking event->mmap_mutex; otherwise
6095 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
6096 */
6097 mutex_lock(&event->mmap_mutex);
6098 rb = event->rb;
6099 if (rb)
6100 events = atomic_xchg(&rb->poll, 0);
6101 mutex_unlock(&event->mmap_mutex);
6102 return events;
6103 }
6104
_perf_event_reset(struct perf_event * event)6105 static void _perf_event_reset(struct perf_event *event)
6106 {
6107 (void)perf_event_read(event, false);
6108 local64_set(&event->count, 0);
6109 perf_event_update_userpage(event);
6110 }
6111
6112 /* Assume it's not an event with inherit set. */
perf_event_pause(struct perf_event * event,bool reset)6113 u64 perf_event_pause(struct perf_event *event, bool reset)
6114 {
6115 struct perf_event_context *ctx;
6116 u64 count;
6117
6118 ctx = perf_event_ctx_lock(event);
6119 WARN_ON_ONCE(event->attr.inherit);
6120 _perf_event_disable(event);
6121 count = local64_read(&event->count);
6122 if (reset)
6123 local64_set(&event->count, 0);
6124 perf_event_ctx_unlock(event, ctx);
6125
6126 return count;
6127 }
6128 EXPORT_SYMBOL_GPL(perf_event_pause);
6129
6130 /*
6131 * Holding the top-level event's child_mutex means that any
6132 * descendant process that has inherited this event will block
6133 * in perf_event_exit_event() if it goes to exit, thus satisfying the
6134 * task existence requirements of perf_event_enable/disable.
6135 */
perf_event_for_each_child(struct perf_event * event,void (* func)(struct perf_event *))6136 static void perf_event_for_each_child(struct perf_event *event,
6137 void (*func)(struct perf_event *))
6138 {
6139 struct perf_event *child;
6140
6141 WARN_ON_ONCE(event->ctx->parent_ctx);
6142
6143 mutex_lock(&event->child_mutex);
6144 func(event);
6145 list_for_each_entry(child, &event->child_list, child_list)
6146 func(child);
6147 mutex_unlock(&event->child_mutex);
6148 }
6149
perf_event_for_each(struct perf_event * event,void (* func)(struct perf_event *))6150 static void perf_event_for_each(struct perf_event *event,
6151 void (*func)(struct perf_event *))
6152 {
6153 struct perf_event_context *ctx = event->ctx;
6154 struct perf_event *sibling;
6155
6156 lockdep_assert_held(&ctx->mutex);
6157
6158 event = event->group_leader;
6159
6160 perf_event_for_each_child(event, func);
6161 for_each_sibling_event(sibling, event)
6162 perf_event_for_each_child(sibling, func);
6163 }
6164
__perf_event_period(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)6165 static void __perf_event_period(struct perf_event *event,
6166 struct perf_cpu_context *cpuctx,
6167 struct perf_event_context *ctx,
6168 void *info)
6169 {
6170 u64 value = *((u64 *)info);
6171 bool active;
6172
6173 if (event->attr.freq) {
6174 event->attr.sample_freq = value;
6175 } else {
6176 event->attr.sample_period = value;
6177 event->hw.sample_period = value;
6178 }
6179
6180 active = (event->state == PERF_EVENT_STATE_ACTIVE);
6181 if (active) {
6182 perf_pmu_disable(event->pmu);
6183 /*
6184 * We could be throttled; unthrottle now to avoid the tick
6185 * trying to unthrottle while we already re-started the event.
6186 */
6187 if (event->hw.interrupts == MAX_INTERRUPTS) {
6188 event->hw.interrupts = 0;
6189 perf_log_throttle(event, 1);
6190 }
6191 event->pmu->stop(event, PERF_EF_UPDATE);
6192 }
6193
6194 local64_set(&event->hw.period_left, 0);
6195
6196 if (active) {
6197 event->pmu->start(event, PERF_EF_RELOAD);
6198 perf_pmu_enable(event->pmu);
6199 }
6200 }
6201
perf_event_check_period(struct perf_event * event,u64 value)6202 static int perf_event_check_period(struct perf_event *event, u64 value)
6203 {
6204 return event->pmu->check_period(event, value);
6205 }
6206
_perf_event_period(struct perf_event * event,u64 value)6207 static int _perf_event_period(struct perf_event *event, u64 value)
6208 {
6209 if (!is_sampling_event(event))
6210 return -EINVAL;
6211
6212 if (!value)
6213 return -EINVAL;
6214
6215 if (event->attr.freq) {
6216 if (value > sysctl_perf_event_sample_rate)
6217 return -EINVAL;
6218 } else {
6219 if (perf_event_check_period(event, value))
6220 return -EINVAL;
6221 if (value & (1ULL << 63))
6222 return -EINVAL;
6223 }
6224
6225 event_function_call(event, __perf_event_period, &value);
6226
6227 return 0;
6228 }
6229
perf_event_period(struct perf_event * event,u64 value)6230 int perf_event_period(struct perf_event *event, u64 value)
6231 {
6232 struct perf_event_context *ctx;
6233 int ret;
6234
6235 ctx = perf_event_ctx_lock(event);
6236 ret = _perf_event_period(event, value);
6237 perf_event_ctx_unlock(event, ctx);
6238
6239 return ret;
6240 }
6241 EXPORT_SYMBOL_GPL(perf_event_period);
6242
6243 static const struct file_operations perf_fops;
6244
is_perf_file(struct fd f)6245 static inline bool is_perf_file(struct fd f)
6246 {
6247 return !fd_empty(f) && fd_file(f)->f_op == &perf_fops;
6248 }
6249
6250 static int perf_event_set_output(struct perf_event *event,
6251 struct perf_event *output_event);
6252 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
6253 static int perf_copy_attr(struct perf_event_attr __user *uattr,
6254 struct perf_event_attr *attr);
6255
_perf_ioctl(struct perf_event * event,unsigned int cmd,unsigned long arg)6256 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
6257 {
6258 void (*func)(struct perf_event *);
6259 u32 flags = arg;
6260
6261 switch (cmd) {
6262 case PERF_EVENT_IOC_ENABLE:
6263 func = _perf_event_enable;
6264 break;
6265 case PERF_EVENT_IOC_DISABLE:
6266 func = _perf_event_disable;
6267 break;
6268 case PERF_EVENT_IOC_RESET:
6269 func = _perf_event_reset;
6270 break;
6271
6272 case PERF_EVENT_IOC_REFRESH:
6273 return _perf_event_refresh(event, arg);
6274
6275 case PERF_EVENT_IOC_PERIOD:
6276 {
6277 u64 value;
6278
6279 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
6280 return -EFAULT;
6281
6282 return _perf_event_period(event, value);
6283 }
6284 case PERF_EVENT_IOC_ID:
6285 {
6286 u64 id = primary_event_id(event);
6287
6288 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
6289 return -EFAULT;
6290 return 0;
6291 }
6292
6293 case PERF_EVENT_IOC_SET_OUTPUT:
6294 {
6295 CLASS(fd, output)(arg); // arg == -1 => empty
6296 struct perf_event *output_event = NULL;
6297 if (arg != -1) {
6298 if (!is_perf_file(output))
6299 return -EBADF;
6300 output_event = fd_file(output)->private_data;
6301 }
6302 return perf_event_set_output(event, output_event);
6303 }
6304
6305 case PERF_EVENT_IOC_SET_FILTER:
6306 return perf_event_set_filter(event, (void __user *)arg);
6307
6308 case PERF_EVENT_IOC_SET_BPF:
6309 {
6310 struct bpf_prog *prog;
6311 int err;
6312
6313 prog = bpf_prog_get(arg);
6314 if (IS_ERR(prog))
6315 return PTR_ERR(prog);
6316
6317 err = perf_event_set_bpf_prog(event, prog, 0);
6318 if (err) {
6319 bpf_prog_put(prog);
6320 return err;
6321 }
6322
6323 return 0;
6324 }
6325
6326 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
6327 struct perf_buffer *rb;
6328
6329 rcu_read_lock();
6330 rb = rcu_dereference(event->rb);
6331 if (!rb || !rb->nr_pages) {
6332 rcu_read_unlock();
6333 return -EINVAL;
6334 }
6335 rb_toggle_paused(rb, !!arg);
6336 rcu_read_unlock();
6337 return 0;
6338 }
6339
6340 case PERF_EVENT_IOC_QUERY_BPF:
6341 return perf_event_query_prog_array(event, (void __user *)arg);
6342
6343 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
6344 struct perf_event_attr new_attr;
6345 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
6346 &new_attr);
6347
6348 if (err)
6349 return err;
6350
6351 return perf_event_modify_attr(event, &new_attr);
6352 }
6353 default:
6354 return -ENOTTY;
6355 }
6356
6357 if (flags & PERF_IOC_FLAG_GROUP)
6358 perf_event_for_each(event, func);
6359 else
6360 perf_event_for_each_child(event, func);
6361
6362 return 0;
6363 }
6364
perf_ioctl(struct file * file,unsigned int cmd,unsigned long arg)6365 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
6366 {
6367 struct perf_event *event = file->private_data;
6368 struct perf_event_context *ctx;
6369 long ret;
6370
6371 /* Treat ioctl like writes as it is likely a mutating operation. */
6372 ret = security_perf_event_write(event);
6373 if (ret)
6374 return ret;
6375
6376 ctx = perf_event_ctx_lock(event);
6377 ret = _perf_ioctl(event, cmd, arg);
6378 perf_event_ctx_unlock(event, ctx);
6379
6380 return ret;
6381 }
6382
6383 #ifdef CONFIG_COMPAT
perf_compat_ioctl(struct file * file,unsigned int cmd,unsigned long arg)6384 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
6385 unsigned long arg)
6386 {
6387 switch (_IOC_NR(cmd)) {
6388 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
6389 case _IOC_NR(PERF_EVENT_IOC_ID):
6390 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
6391 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
6392 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
6393 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
6394 cmd &= ~IOCSIZE_MASK;
6395 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
6396 }
6397 break;
6398 }
6399 return perf_ioctl(file, cmd, arg);
6400 }
6401 #else
6402 # define perf_compat_ioctl NULL
6403 #endif
6404
perf_event_task_enable(void)6405 int perf_event_task_enable(void)
6406 {
6407 struct perf_event_context *ctx;
6408 struct perf_event *event;
6409
6410 mutex_lock(¤t->perf_event_mutex);
6411 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
6412 ctx = perf_event_ctx_lock(event);
6413 perf_event_for_each_child(event, _perf_event_enable);
6414 perf_event_ctx_unlock(event, ctx);
6415 }
6416 mutex_unlock(¤t->perf_event_mutex);
6417
6418 return 0;
6419 }
6420
perf_event_task_disable(void)6421 int perf_event_task_disable(void)
6422 {
6423 struct perf_event_context *ctx;
6424 struct perf_event *event;
6425
6426 mutex_lock(¤t->perf_event_mutex);
6427 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
6428 ctx = perf_event_ctx_lock(event);
6429 perf_event_for_each_child(event, _perf_event_disable);
6430 perf_event_ctx_unlock(event, ctx);
6431 }
6432 mutex_unlock(¤t->perf_event_mutex);
6433
6434 return 0;
6435 }
6436
perf_event_index(struct perf_event * event)6437 static int perf_event_index(struct perf_event *event)
6438 {
6439 if (event->hw.state & PERF_HES_STOPPED)
6440 return 0;
6441
6442 if (event->state != PERF_EVENT_STATE_ACTIVE)
6443 return 0;
6444
6445 return event->pmu->event_idx(event);
6446 }
6447
perf_event_init_userpage(struct perf_event * event)6448 static void perf_event_init_userpage(struct perf_event *event)
6449 {
6450 struct perf_event_mmap_page *userpg;
6451 struct perf_buffer *rb;
6452
6453 rcu_read_lock();
6454 rb = rcu_dereference(event->rb);
6455 if (!rb)
6456 goto unlock;
6457
6458 userpg = rb->user_page;
6459
6460 /* Allow new userspace to detect that bit 0 is deprecated */
6461 userpg->cap_bit0_is_deprecated = 1;
6462 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
6463 userpg->data_offset = PAGE_SIZE;
6464 userpg->data_size = perf_data_size(rb);
6465
6466 unlock:
6467 rcu_read_unlock();
6468 }
6469
arch_perf_update_userpage(struct perf_event * event,struct perf_event_mmap_page * userpg,u64 now)6470 void __weak arch_perf_update_userpage(
6471 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
6472 {
6473 }
6474
6475 /*
6476 * Callers need to ensure there can be no nesting of this function, otherwise
6477 * the seqlock logic goes bad. We can not serialize this because the arch
6478 * code calls this from NMI context.
6479 */
perf_event_update_userpage(struct perf_event * event)6480 void perf_event_update_userpage(struct perf_event *event)
6481 {
6482 struct perf_event_mmap_page *userpg;
6483 struct perf_buffer *rb;
6484 u64 enabled, running, now;
6485
6486 rcu_read_lock();
6487 rb = rcu_dereference(event->rb);
6488 if (!rb)
6489 goto unlock;
6490
6491 /*
6492 * compute total_time_enabled, total_time_running
6493 * based on snapshot values taken when the event
6494 * was last scheduled in.
6495 *
6496 * we cannot simply called update_context_time()
6497 * because of locking issue as we can be called in
6498 * NMI context
6499 */
6500 calc_timer_values(event, &now, &enabled, &running);
6501
6502 userpg = rb->user_page;
6503 /*
6504 * Disable preemption to guarantee consistent time stamps are stored to
6505 * the user page.
6506 */
6507 preempt_disable();
6508 ++userpg->lock;
6509 barrier();
6510 userpg->index = perf_event_index(event);
6511 userpg->offset = perf_event_count(event, false);
6512 if (userpg->index)
6513 userpg->offset -= local64_read(&event->hw.prev_count);
6514
6515 userpg->time_enabled = enabled +
6516 atomic64_read(&event->child_total_time_enabled);
6517
6518 userpg->time_running = running +
6519 atomic64_read(&event->child_total_time_running);
6520
6521 arch_perf_update_userpage(event, userpg, now);
6522
6523 barrier();
6524 ++userpg->lock;
6525 preempt_enable();
6526 unlock:
6527 rcu_read_unlock();
6528 }
6529 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
6530
ring_buffer_attach(struct perf_event * event,struct perf_buffer * rb)6531 static void ring_buffer_attach(struct perf_event *event,
6532 struct perf_buffer *rb)
6533 {
6534 struct perf_buffer *old_rb = NULL;
6535 unsigned long flags;
6536
6537 WARN_ON_ONCE(event->parent);
6538
6539 if (event->rb) {
6540 /*
6541 * Should be impossible, we set this when removing
6542 * event->rb_entry and wait/clear when adding event->rb_entry.
6543 */
6544 WARN_ON_ONCE(event->rcu_pending);
6545
6546 old_rb = event->rb;
6547 spin_lock_irqsave(&old_rb->event_lock, flags);
6548 list_del_rcu(&event->rb_entry);
6549 spin_unlock_irqrestore(&old_rb->event_lock, flags);
6550
6551 event->rcu_batches = get_state_synchronize_rcu();
6552 event->rcu_pending = 1;
6553 }
6554
6555 if (rb) {
6556 if (event->rcu_pending) {
6557 cond_synchronize_rcu(event->rcu_batches);
6558 event->rcu_pending = 0;
6559 }
6560
6561 spin_lock_irqsave(&rb->event_lock, flags);
6562 list_add_rcu(&event->rb_entry, &rb->event_list);
6563 spin_unlock_irqrestore(&rb->event_lock, flags);
6564 }
6565
6566 /*
6567 * Avoid racing with perf_mmap_close(AUX): stop the event
6568 * before swizzling the event::rb pointer; if it's getting
6569 * unmapped, its aux_mmap_count will be 0 and it won't
6570 * restart. See the comment in __perf_pmu_output_stop().
6571 *
6572 * Data will inevitably be lost when set_output is done in
6573 * mid-air, but then again, whoever does it like this is
6574 * not in for the data anyway.
6575 */
6576 if (has_aux(event))
6577 perf_event_stop(event, 0);
6578
6579 rcu_assign_pointer(event->rb, rb);
6580
6581 if (old_rb) {
6582 ring_buffer_put(old_rb);
6583 /*
6584 * Since we detached before setting the new rb, so that we
6585 * could attach the new rb, we could have missed a wakeup.
6586 * Provide it now.
6587 */
6588 wake_up_all(&event->waitq);
6589 }
6590 }
6591
ring_buffer_wakeup(struct perf_event * event)6592 static void ring_buffer_wakeup(struct perf_event *event)
6593 {
6594 struct perf_buffer *rb;
6595
6596 if (event->parent)
6597 event = event->parent;
6598
6599 rcu_read_lock();
6600 rb = rcu_dereference(event->rb);
6601 if (rb) {
6602 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
6603 wake_up_all(&event->waitq);
6604 }
6605 rcu_read_unlock();
6606 }
6607
ring_buffer_get(struct perf_event * event)6608 struct perf_buffer *ring_buffer_get(struct perf_event *event)
6609 {
6610 struct perf_buffer *rb;
6611
6612 if (event->parent)
6613 event = event->parent;
6614
6615 rcu_read_lock();
6616 rb = rcu_dereference(event->rb);
6617 if (rb) {
6618 if (!refcount_inc_not_zero(&rb->refcount))
6619 rb = NULL;
6620 }
6621 rcu_read_unlock();
6622
6623 return rb;
6624 }
6625
ring_buffer_put(struct perf_buffer * rb)6626 void ring_buffer_put(struct perf_buffer *rb)
6627 {
6628 if (!refcount_dec_and_test(&rb->refcount))
6629 return;
6630
6631 WARN_ON_ONCE(!list_empty(&rb->event_list));
6632
6633 call_rcu(&rb->rcu_head, rb_free_rcu);
6634 }
6635
perf_mmap_open(struct vm_area_struct * vma)6636 static void perf_mmap_open(struct vm_area_struct *vma)
6637 {
6638 struct perf_event *event = vma->vm_file->private_data;
6639
6640 atomic_inc(&event->mmap_count);
6641 atomic_inc(&event->rb->mmap_count);
6642
6643 if (vma->vm_pgoff)
6644 atomic_inc(&event->rb->aux_mmap_count);
6645
6646 if (event->pmu->event_mapped)
6647 event->pmu->event_mapped(event, vma->vm_mm);
6648 }
6649
6650 static void perf_pmu_output_stop(struct perf_event *event);
6651
6652 /*
6653 * A buffer can be mmap()ed multiple times; either directly through the same
6654 * event, or through other events by use of perf_event_set_output().
6655 *
6656 * In order to undo the VM accounting done by perf_mmap() we need to destroy
6657 * the buffer here, where we still have a VM context. This means we need
6658 * to detach all events redirecting to us.
6659 */
perf_mmap_close(struct vm_area_struct * vma)6660 static void perf_mmap_close(struct vm_area_struct *vma)
6661 {
6662 struct perf_event *event = vma->vm_file->private_data;
6663 struct perf_buffer *rb = ring_buffer_get(event);
6664 struct user_struct *mmap_user = rb->mmap_user;
6665 int mmap_locked = rb->mmap_locked;
6666 unsigned long size = perf_data_size(rb);
6667 bool detach_rest = false;
6668
6669 if (event->pmu->event_unmapped)
6670 event->pmu->event_unmapped(event, vma->vm_mm);
6671
6672 /*
6673 * The AUX buffer is strictly a sub-buffer, serialize using aux_mutex
6674 * to avoid complications.
6675 */
6676 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
6677 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &rb->aux_mutex)) {
6678 /*
6679 * Stop all AUX events that are writing to this buffer,
6680 * so that we can free its AUX pages and corresponding PMU
6681 * data. Note that after rb::aux_mmap_count dropped to zero,
6682 * they won't start any more (see perf_aux_output_begin()).
6683 */
6684 perf_pmu_output_stop(event);
6685
6686 /* now it's safe to free the pages */
6687 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
6688 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
6689
6690 /* this has to be the last one */
6691 rb_free_aux(rb);
6692 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
6693
6694 mutex_unlock(&rb->aux_mutex);
6695 }
6696
6697 if (atomic_dec_and_test(&rb->mmap_count))
6698 detach_rest = true;
6699
6700 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
6701 goto out_put;
6702
6703 ring_buffer_attach(event, NULL);
6704 mutex_unlock(&event->mmap_mutex);
6705
6706 /* If there's still other mmap()s of this buffer, we're done. */
6707 if (!detach_rest)
6708 goto out_put;
6709
6710 /*
6711 * No other mmap()s, detach from all other events that might redirect
6712 * into the now unreachable buffer. Somewhat complicated by the
6713 * fact that rb::event_lock otherwise nests inside mmap_mutex.
6714 */
6715 again:
6716 rcu_read_lock();
6717 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
6718 if (!atomic_long_inc_not_zero(&event->refcount)) {
6719 /*
6720 * This event is en-route to free_event() which will
6721 * detach it and remove it from the list.
6722 */
6723 continue;
6724 }
6725 rcu_read_unlock();
6726
6727 mutex_lock(&event->mmap_mutex);
6728 /*
6729 * Check we didn't race with perf_event_set_output() which can
6730 * swizzle the rb from under us while we were waiting to
6731 * acquire mmap_mutex.
6732 *
6733 * If we find a different rb; ignore this event, a next
6734 * iteration will no longer find it on the list. We have to
6735 * still restart the iteration to make sure we're not now
6736 * iterating the wrong list.
6737 */
6738 if (event->rb == rb)
6739 ring_buffer_attach(event, NULL);
6740
6741 mutex_unlock(&event->mmap_mutex);
6742 put_event(event);
6743
6744 /*
6745 * Restart the iteration; either we're on the wrong list or
6746 * destroyed its integrity by doing a deletion.
6747 */
6748 goto again;
6749 }
6750 rcu_read_unlock();
6751
6752 /*
6753 * It could be there's still a few 0-ref events on the list; they'll
6754 * get cleaned up by free_event() -- they'll also still have their
6755 * ref on the rb and will free it whenever they are done with it.
6756 *
6757 * Aside from that, this buffer is 'fully' detached and unmapped,
6758 * undo the VM accounting.
6759 */
6760
6761 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
6762 &mmap_user->locked_vm);
6763 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
6764 free_uid(mmap_user);
6765
6766 out_put:
6767 ring_buffer_put(rb); /* could be last */
6768 }
6769
perf_mmap_pfn_mkwrite(struct vm_fault * vmf)6770 static vm_fault_t perf_mmap_pfn_mkwrite(struct vm_fault *vmf)
6771 {
6772 /* The first page is the user control page, others are read-only. */
6773 return vmf->pgoff == 0 ? 0 : VM_FAULT_SIGBUS;
6774 }
6775
6776 static const struct vm_operations_struct perf_mmap_vmops = {
6777 .open = perf_mmap_open,
6778 .close = perf_mmap_close, /* non mergeable */
6779 .pfn_mkwrite = perf_mmap_pfn_mkwrite,
6780 };
6781
map_range(struct perf_buffer * rb,struct vm_area_struct * vma)6782 static int map_range(struct perf_buffer *rb, struct vm_area_struct *vma)
6783 {
6784 unsigned long nr_pages = vma_pages(vma);
6785 int err = 0;
6786 unsigned long pagenum;
6787
6788 /*
6789 * We map this as a VM_PFNMAP VMA.
6790 *
6791 * This is not ideal as this is designed broadly for mappings of PFNs
6792 * referencing memory-mapped I/O ranges or non-system RAM i.e. for which
6793 * !pfn_valid(pfn).
6794 *
6795 * We are mapping kernel-allocated memory (memory we manage ourselves)
6796 * which would more ideally be mapped using vm_insert_page() or a
6797 * similar mechanism, that is as a VM_MIXEDMAP mapping.
6798 *
6799 * However this won't work here, because:
6800 *
6801 * 1. It uses vma->vm_page_prot, but this field has not been completely
6802 * setup at the point of the f_op->mmp() hook, so we are unable to
6803 * indicate that this should be mapped CoW in order that the
6804 * mkwrite() hook can be invoked to make the first page R/W and the
6805 * rest R/O as desired.
6806 *
6807 * 2. Anything other than a VM_PFNMAP of valid PFNs will result in
6808 * vm_normal_page() returning a struct page * pointer, which means
6809 * vm_ops->page_mkwrite() will be invoked rather than
6810 * vm_ops->pfn_mkwrite(), and this means we have to set page->mapping
6811 * to work around retry logic in the fault handler, however this
6812 * field is no longer allowed to be used within struct page.
6813 *
6814 * 3. Having a struct page * made available in the fault logic also
6815 * means that the page gets put on the rmap and becomes
6816 * inappropriately accessible and subject to map and ref counting.
6817 *
6818 * Ideally we would have a mechanism that could explicitly express our
6819 * desires, but this is not currently the case, so we instead use
6820 * VM_PFNMAP.
6821 *
6822 * We manage the lifetime of these mappings with internal refcounts (see
6823 * perf_mmap_open() and perf_mmap_close()) so we ensure the lifetime of
6824 * this mapping is maintained correctly.
6825 */
6826 for (pagenum = 0; pagenum < nr_pages; pagenum++) {
6827 unsigned long va = vma->vm_start + PAGE_SIZE * pagenum;
6828 struct page *page = perf_mmap_to_page(rb, vma->vm_pgoff + pagenum);
6829
6830 if (page == NULL) {
6831 err = -EINVAL;
6832 break;
6833 }
6834
6835 /* Map readonly, perf_mmap_pfn_mkwrite() called on write fault. */
6836 err = remap_pfn_range(vma, va, page_to_pfn(page), PAGE_SIZE,
6837 vm_get_page_prot(vma->vm_flags & ~VM_SHARED));
6838 if (err)
6839 break;
6840 }
6841
6842 #ifdef CONFIG_MMU
6843 /* Clear any partial mappings on error. */
6844 if (err)
6845 zap_page_range_single(vma, vma->vm_start, nr_pages * PAGE_SIZE, NULL);
6846 #endif
6847
6848 return err;
6849 }
6850
perf_mmap(struct file * file,struct vm_area_struct * vma)6851 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
6852 {
6853 struct perf_event *event = file->private_data;
6854 unsigned long user_locked, user_lock_limit;
6855 struct user_struct *user = current_user();
6856 struct mutex *aux_mutex = NULL;
6857 struct perf_buffer *rb = NULL;
6858 unsigned long locked, lock_limit;
6859 unsigned long vma_size;
6860 unsigned long nr_pages;
6861 long user_extra = 0, extra = 0;
6862 int ret, flags = 0;
6863
6864 /*
6865 * Don't allow mmap() of inherited per-task counters. This would
6866 * create a performance issue due to all children writing to the
6867 * same rb.
6868 */
6869 if (event->cpu == -1 && event->attr.inherit)
6870 return -EINVAL;
6871
6872 if (!(vma->vm_flags & VM_SHARED))
6873 return -EINVAL;
6874
6875 ret = security_perf_event_read(event);
6876 if (ret)
6877 return ret;
6878
6879 vma_size = vma->vm_end - vma->vm_start;
6880 nr_pages = vma_size / PAGE_SIZE;
6881
6882 if (nr_pages > INT_MAX)
6883 return -ENOMEM;
6884
6885 if (vma_size != PAGE_SIZE * nr_pages)
6886 return -EINVAL;
6887
6888 user_extra = nr_pages;
6889
6890 mutex_lock(&event->mmap_mutex);
6891 ret = -EINVAL;
6892
6893 if (vma->vm_pgoff == 0) {
6894 nr_pages -= 1;
6895
6896 /*
6897 * If we have rb pages ensure they're a power-of-two number, so we
6898 * can do bitmasks instead of modulo.
6899 */
6900 if (nr_pages != 0 && !is_power_of_2(nr_pages))
6901 goto unlock;
6902
6903 WARN_ON_ONCE(event->ctx->parent_ctx);
6904
6905 if (event->rb) {
6906 if (data_page_nr(event->rb) != nr_pages)
6907 goto unlock;
6908
6909 if (atomic_inc_not_zero(&event->rb->mmap_count)) {
6910 /*
6911 * Success -- managed to mmap() the same buffer
6912 * multiple times.
6913 */
6914 ret = 0;
6915 /* We need the rb to map pages. */
6916 rb = event->rb;
6917 goto unlock;
6918 }
6919
6920 /*
6921 * Raced against perf_mmap_close()'s
6922 * atomic_dec_and_mutex_lock() remove the
6923 * event and continue as if !event->rb
6924 */
6925 ring_buffer_attach(event, NULL);
6926 }
6927
6928 } else {
6929 /*
6930 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
6931 * mapped, all subsequent mappings should have the same size
6932 * and offset. Must be above the normal perf buffer.
6933 */
6934 u64 aux_offset, aux_size;
6935
6936 rb = event->rb;
6937 if (!rb)
6938 goto aux_unlock;
6939
6940 aux_mutex = &rb->aux_mutex;
6941 mutex_lock(aux_mutex);
6942
6943 aux_offset = READ_ONCE(rb->user_page->aux_offset);
6944 aux_size = READ_ONCE(rb->user_page->aux_size);
6945
6946 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6947 goto aux_unlock;
6948
6949 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6950 goto aux_unlock;
6951
6952 /* already mapped with a different offset */
6953 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6954 goto aux_unlock;
6955
6956 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6957 goto aux_unlock;
6958
6959 /* already mapped with a different size */
6960 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6961 goto aux_unlock;
6962
6963 if (!is_power_of_2(nr_pages))
6964 goto aux_unlock;
6965
6966 if (!atomic_inc_not_zero(&rb->mmap_count))
6967 goto aux_unlock;
6968
6969 if (rb_has_aux(rb)) {
6970 atomic_inc(&rb->aux_mmap_count);
6971 ret = 0;
6972 goto unlock;
6973 }
6974
6975 atomic_set(&rb->aux_mmap_count, 1);
6976 }
6977
6978 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
6979
6980 /*
6981 * Increase the limit linearly with more CPUs:
6982 */
6983 user_lock_limit *= num_online_cpus();
6984
6985 user_locked = atomic_long_read(&user->locked_vm);
6986
6987 /*
6988 * sysctl_perf_event_mlock may have changed, so that
6989 * user->locked_vm > user_lock_limit
6990 */
6991 if (user_locked > user_lock_limit)
6992 user_locked = user_lock_limit;
6993 user_locked += user_extra;
6994
6995 if (user_locked > user_lock_limit) {
6996 /*
6997 * charge locked_vm until it hits user_lock_limit;
6998 * charge the rest from pinned_vm
6999 */
7000 extra = user_locked - user_lock_limit;
7001 user_extra -= extra;
7002 }
7003
7004 lock_limit = rlimit(RLIMIT_MEMLOCK);
7005 lock_limit >>= PAGE_SHIFT;
7006 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
7007
7008 if ((locked > lock_limit) && perf_is_paranoid() &&
7009 !capable(CAP_IPC_LOCK)) {
7010 ret = -EPERM;
7011 goto unlock;
7012 }
7013
7014 WARN_ON(!rb && event->rb);
7015
7016 if (vma->vm_flags & VM_WRITE)
7017 flags |= RING_BUFFER_WRITABLE;
7018
7019 if (!rb) {
7020 rb = rb_alloc(nr_pages,
7021 event->attr.watermark ? event->attr.wakeup_watermark : 0,
7022 event->cpu, flags);
7023
7024 if (!rb) {
7025 ret = -ENOMEM;
7026 goto unlock;
7027 }
7028
7029 atomic_set(&rb->mmap_count, 1);
7030 rb->mmap_user = get_current_user();
7031 rb->mmap_locked = extra;
7032
7033 ring_buffer_attach(event, rb);
7034
7035 perf_event_update_time(event);
7036 perf_event_init_userpage(event);
7037 perf_event_update_userpage(event);
7038 } else {
7039 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
7040 event->attr.aux_watermark, flags);
7041 if (!ret)
7042 rb->aux_mmap_locked = extra;
7043 }
7044
7045 ret = 0;
7046
7047 unlock:
7048 if (!ret) {
7049 atomic_long_add(user_extra, &user->locked_vm);
7050 atomic64_add(extra, &vma->vm_mm->pinned_vm);
7051
7052 atomic_inc(&event->mmap_count);
7053 } else if (rb) {
7054 atomic_dec(&rb->mmap_count);
7055 }
7056 aux_unlock:
7057 if (aux_mutex)
7058 mutex_unlock(aux_mutex);
7059 mutex_unlock(&event->mmap_mutex);
7060
7061 /*
7062 * Since pinned accounting is per vm we cannot allow fork() to copy our
7063 * vma.
7064 */
7065 vm_flags_set(vma, VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP);
7066 vma->vm_ops = &perf_mmap_vmops;
7067
7068 if (!ret)
7069 ret = map_range(rb, vma);
7070
7071 if (!ret && event->pmu->event_mapped)
7072 event->pmu->event_mapped(event, vma->vm_mm);
7073
7074 return ret;
7075 }
7076
perf_fasync(int fd,struct file * filp,int on)7077 static int perf_fasync(int fd, struct file *filp, int on)
7078 {
7079 struct inode *inode = file_inode(filp);
7080 struct perf_event *event = filp->private_data;
7081 int retval;
7082
7083 inode_lock(inode);
7084 retval = fasync_helper(fd, filp, on, &event->fasync);
7085 inode_unlock(inode);
7086
7087 if (retval < 0)
7088 return retval;
7089
7090 return 0;
7091 }
7092
7093 static const struct file_operations perf_fops = {
7094 .release = perf_release,
7095 .read = perf_read,
7096 .poll = perf_poll,
7097 .unlocked_ioctl = perf_ioctl,
7098 .compat_ioctl = perf_compat_ioctl,
7099 .mmap = perf_mmap,
7100 .fasync = perf_fasync,
7101 };
7102
7103 /*
7104 * Perf event wakeup
7105 *
7106 * If there's data, ensure we set the poll() state and publish everything
7107 * to user-space before waking everybody up.
7108 */
7109
perf_event_wakeup(struct perf_event * event)7110 void perf_event_wakeup(struct perf_event *event)
7111 {
7112 ring_buffer_wakeup(event);
7113
7114 if (event->pending_kill) {
7115 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
7116 event->pending_kill = 0;
7117 }
7118 }
7119
perf_sigtrap(struct perf_event * event)7120 static void perf_sigtrap(struct perf_event *event)
7121 {
7122 /*
7123 * We'd expect this to only occur if the irq_work is delayed and either
7124 * ctx->task or current has changed in the meantime. This can be the
7125 * case on architectures that do not implement arch_irq_work_raise().
7126 */
7127 if (WARN_ON_ONCE(event->ctx->task != current))
7128 return;
7129
7130 /*
7131 * Both perf_pending_task() and perf_pending_irq() can race with the
7132 * task exiting.
7133 */
7134 if (current->flags & PF_EXITING)
7135 return;
7136
7137 send_sig_perf((void __user *)event->pending_addr,
7138 event->orig_type, event->attr.sig_data);
7139 }
7140
7141 /*
7142 * Deliver the pending work in-event-context or follow the context.
7143 */
__perf_pending_disable(struct perf_event * event)7144 static void __perf_pending_disable(struct perf_event *event)
7145 {
7146 int cpu = READ_ONCE(event->oncpu);
7147
7148 /*
7149 * If the event isn't running; we done. event_sched_out() will have
7150 * taken care of things.
7151 */
7152 if (cpu < 0)
7153 return;
7154
7155 /*
7156 * Yay, we hit home and are in the context of the event.
7157 */
7158 if (cpu == smp_processor_id()) {
7159 if (event->pending_disable) {
7160 event->pending_disable = 0;
7161 perf_event_disable_local(event);
7162 }
7163 return;
7164 }
7165
7166 /*
7167 * CPU-A CPU-B
7168 *
7169 * perf_event_disable_inatomic()
7170 * @pending_disable = CPU-A;
7171 * irq_work_queue();
7172 *
7173 * sched-out
7174 * @pending_disable = -1;
7175 *
7176 * sched-in
7177 * perf_event_disable_inatomic()
7178 * @pending_disable = CPU-B;
7179 * irq_work_queue(); // FAILS
7180 *
7181 * irq_work_run()
7182 * perf_pending_disable()
7183 *
7184 * But the event runs on CPU-B and wants disabling there.
7185 */
7186 irq_work_queue_on(&event->pending_disable_irq, cpu);
7187 }
7188
perf_pending_disable(struct irq_work * entry)7189 static void perf_pending_disable(struct irq_work *entry)
7190 {
7191 struct perf_event *event = container_of(entry, struct perf_event, pending_disable_irq);
7192 int rctx;
7193
7194 /*
7195 * If we 'fail' here, that's OK, it means recursion is already disabled
7196 * and we won't recurse 'further'.
7197 */
7198 rctx = perf_swevent_get_recursion_context();
7199 __perf_pending_disable(event);
7200 if (rctx >= 0)
7201 perf_swevent_put_recursion_context(rctx);
7202 }
7203
perf_pending_irq(struct irq_work * entry)7204 static void perf_pending_irq(struct irq_work *entry)
7205 {
7206 struct perf_event *event = container_of(entry, struct perf_event, pending_irq);
7207 int rctx;
7208
7209 /*
7210 * If we 'fail' here, that's OK, it means recursion is already disabled
7211 * and we won't recurse 'further'.
7212 */
7213 rctx = perf_swevent_get_recursion_context();
7214
7215 /*
7216 * The wakeup isn't bound to the context of the event -- it can happen
7217 * irrespective of where the event is.
7218 */
7219 if (event->pending_wakeup) {
7220 event->pending_wakeup = 0;
7221 perf_event_wakeup(event);
7222 }
7223
7224 if (rctx >= 0)
7225 perf_swevent_put_recursion_context(rctx);
7226 }
7227
perf_pending_task(struct callback_head * head)7228 static void perf_pending_task(struct callback_head *head)
7229 {
7230 struct perf_event *event = container_of(head, struct perf_event, pending_task);
7231 int rctx;
7232
7233 /*
7234 * All accesses to the event must belong to the same implicit RCU read-side
7235 * critical section as the ->pending_work reset. See comment in
7236 * perf_pending_task_sync().
7237 */
7238 rcu_read_lock();
7239 /*
7240 * If we 'fail' here, that's OK, it means recursion is already disabled
7241 * and we won't recurse 'further'.
7242 */
7243 rctx = perf_swevent_get_recursion_context();
7244
7245 if (event->pending_work) {
7246 event->pending_work = 0;
7247 perf_sigtrap(event);
7248 local_dec(&event->ctx->nr_no_switch_fast);
7249 rcuwait_wake_up(&event->pending_work_wait);
7250 }
7251 rcu_read_unlock();
7252
7253 if (rctx >= 0)
7254 perf_swevent_put_recursion_context(rctx);
7255 }
7256
7257 #ifdef CONFIG_GUEST_PERF_EVENTS
7258 struct perf_guest_info_callbacks __rcu *perf_guest_cbs;
7259
7260 DEFINE_STATIC_CALL_RET0(__perf_guest_state, *perf_guest_cbs->state);
7261 DEFINE_STATIC_CALL_RET0(__perf_guest_get_ip, *perf_guest_cbs->get_ip);
7262 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr);
7263
perf_register_guest_info_callbacks(struct perf_guest_info_callbacks * cbs)7264 void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
7265 {
7266 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs)))
7267 return;
7268
7269 rcu_assign_pointer(perf_guest_cbs, cbs);
7270 static_call_update(__perf_guest_state, cbs->state);
7271 static_call_update(__perf_guest_get_ip, cbs->get_ip);
7272
7273 /* Implementing ->handle_intel_pt_intr is optional. */
7274 if (cbs->handle_intel_pt_intr)
7275 static_call_update(__perf_guest_handle_intel_pt_intr,
7276 cbs->handle_intel_pt_intr);
7277 }
7278 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
7279
perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks * cbs)7280 void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
7281 {
7282 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs) != cbs))
7283 return;
7284
7285 rcu_assign_pointer(perf_guest_cbs, NULL);
7286 static_call_update(__perf_guest_state, (void *)&__static_call_return0);
7287 static_call_update(__perf_guest_get_ip, (void *)&__static_call_return0);
7288 static_call_update(__perf_guest_handle_intel_pt_intr,
7289 (void *)&__static_call_return0);
7290 synchronize_rcu();
7291 }
7292 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
7293 #endif
7294
should_sample_guest(struct perf_event * event)7295 static bool should_sample_guest(struct perf_event *event)
7296 {
7297 return !event->attr.exclude_guest && perf_guest_state();
7298 }
7299
perf_misc_flags(struct perf_event * event,struct pt_regs * regs)7300 unsigned long perf_misc_flags(struct perf_event *event,
7301 struct pt_regs *regs)
7302 {
7303 if (should_sample_guest(event))
7304 return perf_arch_guest_misc_flags(regs);
7305
7306 return perf_arch_misc_flags(regs);
7307 }
7308
perf_instruction_pointer(struct perf_event * event,struct pt_regs * regs)7309 unsigned long perf_instruction_pointer(struct perf_event *event,
7310 struct pt_regs *regs)
7311 {
7312 if (should_sample_guest(event))
7313 return perf_guest_get_ip();
7314
7315 return perf_arch_instruction_pointer(regs);
7316 }
7317
7318 static void
perf_output_sample_regs(struct perf_output_handle * handle,struct pt_regs * regs,u64 mask)7319 perf_output_sample_regs(struct perf_output_handle *handle,
7320 struct pt_regs *regs, u64 mask)
7321 {
7322 int bit;
7323 DECLARE_BITMAP(_mask, 64);
7324
7325 bitmap_from_u64(_mask, mask);
7326 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
7327 u64 val;
7328
7329 val = perf_reg_value(regs, bit);
7330 perf_output_put(handle, val);
7331 }
7332 }
7333
perf_sample_regs_user(struct perf_regs * regs_user,struct pt_regs * regs)7334 static void perf_sample_regs_user(struct perf_regs *regs_user,
7335 struct pt_regs *regs)
7336 {
7337 if (user_mode(regs)) {
7338 regs_user->abi = perf_reg_abi(current);
7339 regs_user->regs = regs;
7340 } else if (!(current->flags & PF_KTHREAD)) {
7341 perf_get_regs_user(regs_user, regs);
7342 } else {
7343 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
7344 regs_user->regs = NULL;
7345 }
7346 }
7347
perf_sample_regs_intr(struct perf_regs * regs_intr,struct pt_regs * regs)7348 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
7349 struct pt_regs *regs)
7350 {
7351 regs_intr->regs = regs;
7352 regs_intr->abi = perf_reg_abi(current);
7353 }
7354
7355
7356 /*
7357 * Get remaining task size from user stack pointer.
7358 *
7359 * It'd be better to take stack vma map and limit this more
7360 * precisely, but there's no way to get it safely under interrupt,
7361 * so using TASK_SIZE as limit.
7362 */
perf_ustack_task_size(struct pt_regs * regs)7363 static u64 perf_ustack_task_size(struct pt_regs *regs)
7364 {
7365 unsigned long addr = perf_user_stack_pointer(regs);
7366
7367 if (!addr || addr >= TASK_SIZE)
7368 return 0;
7369
7370 return TASK_SIZE - addr;
7371 }
7372
7373 static u16
perf_sample_ustack_size(u16 stack_size,u16 header_size,struct pt_regs * regs)7374 perf_sample_ustack_size(u16 stack_size, u16 header_size,
7375 struct pt_regs *regs)
7376 {
7377 u64 task_size;
7378
7379 /* No regs, no stack pointer, no dump. */
7380 if (!regs)
7381 return 0;
7382
7383 /*
7384 * Check if we fit in with the requested stack size into the:
7385 * - TASK_SIZE
7386 * If we don't, we limit the size to the TASK_SIZE.
7387 *
7388 * - remaining sample size
7389 * If we don't, we customize the stack size to
7390 * fit in to the remaining sample size.
7391 */
7392
7393 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
7394 stack_size = min(stack_size, (u16) task_size);
7395
7396 /* Current header size plus static size and dynamic size. */
7397 header_size += 2 * sizeof(u64);
7398
7399 /* Do we fit in with the current stack dump size? */
7400 if ((u16) (header_size + stack_size) < header_size) {
7401 /*
7402 * If we overflow the maximum size for the sample,
7403 * we customize the stack dump size to fit in.
7404 */
7405 stack_size = USHRT_MAX - header_size - sizeof(u64);
7406 stack_size = round_up(stack_size, sizeof(u64));
7407 }
7408
7409 return stack_size;
7410 }
7411
7412 static void
perf_output_sample_ustack(struct perf_output_handle * handle,u64 dump_size,struct pt_regs * regs)7413 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
7414 struct pt_regs *regs)
7415 {
7416 /* Case of a kernel thread, nothing to dump */
7417 if (!regs) {
7418 u64 size = 0;
7419 perf_output_put(handle, size);
7420 } else {
7421 unsigned long sp;
7422 unsigned int rem;
7423 u64 dyn_size;
7424
7425 /*
7426 * We dump:
7427 * static size
7428 * - the size requested by user or the best one we can fit
7429 * in to the sample max size
7430 * data
7431 * - user stack dump data
7432 * dynamic size
7433 * - the actual dumped size
7434 */
7435
7436 /* Static size. */
7437 perf_output_put(handle, dump_size);
7438
7439 /* Data. */
7440 sp = perf_user_stack_pointer(regs);
7441 rem = __output_copy_user(handle, (void *) sp, dump_size);
7442 dyn_size = dump_size - rem;
7443
7444 perf_output_skip(handle, rem);
7445
7446 /* Dynamic size. */
7447 perf_output_put(handle, dyn_size);
7448 }
7449 }
7450
perf_prepare_sample_aux(struct perf_event * event,struct perf_sample_data * data,size_t size)7451 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
7452 struct perf_sample_data *data,
7453 size_t size)
7454 {
7455 struct perf_event *sampler = event->aux_event;
7456 struct perf_buffer *rb;
7457
7458 data->aux_size = 0;
7459
7460 if (!sampler)
7461 goto out;
7462
7463 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
7464 goto out;
7465
7466 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
7467 goto out;
7468
7469 rb = ring_buffer_get(sampler);
7470 if (!rb)
7471 goto out;
7472
7473 /*
7474 * If this is an NMI hit inside sampling code, don't take
7475 * the sample. See also perf_aux_sample_output().
7476 */
7477 if (READ_ONCE(rb->aux_in_sampling)) {
7478 data->aux_size = 0;
7479 } else {
7480 size = min_t(size_t, size, perf_aux_size(rb));
7481 data->aux_size = ALIGN(size, sizeof(u64));
7482 }
7483 ring_buffer_put(rb);
7484
7485 out:
7486 return data->aux_size;
7487 }
7488
perf_pmu_snapshot_aux(struct perf_buffer * rb,struct perf_event * event,struct perf_output_handle * handle,unsigned long size)7489 static long perf_pmu_snapshot_aux(struct perf_buffer *rb,
7490 struct perf_event *event,
7491 struct perf_output_handle *handle,
7492 unsigned long size)
7493 {
7494 unsigned long flags;
7495 long ret;
7496
7497 /*
7498 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
7499 * paths. If we start calling them in NMI context, they may race with
7500 * the IRQ ones, that is, for example, re-starting an event that's just
7501 * been stopped, which is why we're using a separate callback that
7502 * doesn't change the event state.
7503 *
7504 * IRQs need to be disabled to prevent IPIs from racing with us.
7505 */
7506 local_irq_save(flags);
7507 /*
7508 * Guard against NMI hits inside the critical section;
7509 * see also perf_prepare_sample_aux().
7510 */
7511 WRITE_ONCE(rb->aux_in_sampling, 1);
7512 barrier();
7513
7514 ret = event->pmu->snapshot_aux(event, handle, size);
7515
7516 barrier();
7517 WRITE_ONCE(rb->aux_in_sampling, 0);
7518 local_irq_restore(flags);
7519
7520 return ret;
7521 }
7522
perf_aux_sample_output(struct perf_event * event,struct perf_output_handle * handle,struct perf_sample_data * data)7523 static void perf_aux_sample_output(struct perf_event *event,
7524 struct perf_output_handle *handle,
7525 struct perf_sample_data *data)
7526 {
7527 struct perf_event *sampler = event->aux_event;
7528 struct perf_buffer *rb;
7529 unsigned long pad;
7530 long size;
7531
7532 if (WARN_ON_ONCE(!sampler || !data->aux_size))
7533 return;
7534
7535 rb = ring_buffer_get(sampler);
7536 if (!rb)
7537 return;
7538
7539 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
7540
7541 /*
7542 * An error here means that perf_output_copy() failed (returned a
7543 * non-zero surplus that it didn't copy), which in its current
7544 * enlightened implementation is not possible. If that changes, we'd
7545 * like to know.
7546 */
7547 if (WARN_ON_ONCE(size < 0))
7548 goto out_put;
7549
7550 /*
7551 * The pad comes from ALIGN()ing data->aux_size up to u64 in
7552 * perf_prepare_sample_aux(), so should not be more than that.
7553 */
7554 pad = data->aux_size - size;
7555 if (WARN_ON_ONCE(pad >= sizeof(u64)))
7556 pad = 8;
7557
7558 if (pad) {
7559 u64 zero = 0;
7560 perf_output_copy(handle, &zero, pad);
7561 }
7562
7563 out_put:
7564 ring_buffer_put(rb);
7565 }
7566
7567 /*
7568 * A set of common sample data types saved even for non-sample records
7569 * when event->attr.sample_id_all is set.
7570 */
7571 #define PERF_SAMPLE_ID_ALL (PERF_SAMPLE_TID | PERF_SAMPLE_TIME | \
7572 PERF_SAMPLE_ID | PERF_SAMPLE_STREAM_ID | \
7573 PERF_SAMPLE_CPU | PERF_SAMPLE_IDENTIFIER)
7574
__perf_event_header__init_id(struct perf_sample_data * data,struct perf_event * event,u64 sample_type)7575 static void __perf_event_header__init_id(struct perf_sample_data *data,
7576 struct perf_event *event,
7577 u64 sample_type)
7578 {
7579 data->type = event->attr.sample_type;
7580 data->sample_flags |= data->type & PERF_SAMPLE_ID_ALL;
7581
7582 if (sample_type & PERF_SAMPLE_TID) {
7583 /* namespace issues */
7584 data->tid_entry.pid = perf_event_pid(event, current);
7585 data->tid_entry.tid = perf_event_tid(event, current);
7586 }
7587
7588 if (sample_type & PERF_SAMPLE_TIME)
7589 data->time = perf_event_clock(event);
7590
7591 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
7592 data->id = primary_event_id(event);
7593
7594 if (sample_type & PERF_SAMPLE_STREAM_ID)
7595 data->stream_id = event->id;
7596
7597 if (sample_type & PERF_SAMPLE_CPU) {
7598 data->cpu_entry.cpu = raw_smp_processor_id();
7599 data->cpu_entry.reserved = 0;
7600 }
7601 }
7602
perf_event_header__init_id(struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event)7603 void perf_event_header__init_id(struct perf_event_header *header,
7604 struct perf_sample_data *data,
7605 struct perf_event *event)
7606 {
7607 if (event->attr.sample_id_all) {
7608 header->size += event->id_header_size;
7609 __perf_event_header__init_id(data, event, event->attr.sample_type);
7610 }
7611 }
7612
__perf_event__output_id_sample(struct perf_output_handle * handle,struct perf_sample_data * data)7613 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
7614 struct perf_sample_data *data)
7615 {
7616 u64 sample_type = data->type;
7617
7618 if (sample_type & PERF_SAMPLE_TID)
7619 perf_output_put(handle, data->tid_entry);
7620
7621 if (sample_type & PERF_SAMPLE_TIME)
7622 perf_output_put(handle, data->time);
7623
7624 if (sample_type & PERF_SAMPLE_ID)
7625 perf_output_put(handle, data->id);
7626
7627 if (sample_type & PERF_SAMPLE_STREAM_ID)
7628 perf_output_put(handle, data->stream_id);
7629
7630 if (sample_type & PERF_SAMPLE_CPU)
7631 perf_output_put(handle, data->cpu_entry);
7632
7633 if (sample_type & PERF_SAMPLE_IDENTIFIER)
7634 perf_output_put(handle, data->id);
7635 }
7636
perf_event__output_id_sample(struct perf_event * event,struct perf_output_handle * handle,struct perf_sample_data * sample)7637 void perf_event__output_id_sample(struct perf_event *event,
7638 struct perf_output_handle *handle,
7639 struct perf_sample_data *sample)
7640 {
7641 if (event->attr.sample_id_all)
7642 __perf_event__output_id_sample(handle, sample);
7643 }
7644
perf_output_read_one(struct perf_output_handle * handle,struct perf_event * event,u64 enabled,u64 running)7645 static void perf_output_read_one(struct perf_output_handle *handle,
7646 struct perf_event *event,
7647 u64 enabled, u64 running)
7648 {
7649 u64 read_format = event->attr.read_format;
7650 u64 values[5];
7651 int n = 0;
7652
7653 values[n++] = perf_event_count(event, has_inherit_and_sample_read(&event->attr));
7654 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
7655 values[n++] = enabled +
7656 atomic64_read(&event->child_total_time_enabled);
7657 }
7658 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
7659 values[n++] = running +
7660 atomic64_read(&event->child_total_time_running);
7661 }
7662 if (read_format & PERF_FORMAT_ID)
7663 values[n++] = primary_event_id(event);
7664 if (read_format & PERF_FORMAT_LOST)
7665 values[n++] = atomic64_read(&event->lost_samples);
7666
7667 __output_copy(handle, values, n * sizeof(u64));
7668 }
7669
perf_output_read_group(struct perf_output_handle * handle,struct perf_event * event,u64 enabled,u64 running)7670 static void perf_output_read_group(struct perf_output_handle *handle,
7671 struct perf_event *event,
7672 u64 enabled, u64 running)
7673 {
7674 struct perf_event *leader = event->group_leader, *sub;
7675 u64 read_format = event->attr.read_format;
7676 unsigned long flags;
7677 u64 values[6];
7678 int n = 0;
7679 bool self = has_inherit_and_sample_read(&event->attr);
7680
7681 /*
7682 * Disabling interrupts avoids all counter scheduling
7683 * (context switches, timer based rotation and IPIs).
7684 */
7685 local_irq_save(flags);
7686
7687 values[n++] = 1 + leader->nr_siblings;
7688
7689 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
7690 values[n++] = enabled;
7691
7692 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
7693 values[n++] = running;
7694
7695 if ((leader != event) && !handle->skip_read)
7696 perf_pmu_read(leader);
7697
7698 values[n++] = perf_event_count(leader, self);
7699 if (read_format & PERF_FORMAT_ID)
7700 values[n++] = primary_event_id(leader);
7701 if (read_format & PERF_FORMAT_LOST)
7702 values[n++] = atomic64_read(&leader->lost_samples);
7703
7704 __output_copy(handle, values, n * sizeof(u64));
7705
7706 for_each_sibling_event(sub, leader) {
7707 n = 0;
7708
7709 if ((sub != event) && !handle->skip_read)
7710 perf_pmu_read(sub);
7711
7712 values[n++] = perf_event_count(sub, self);
7713 if (read_format & PERF_FORMAT_ID)
7714 values[n++] = primary_event_id(sub);
7715 if (read_format & PERF_FORMAT_LOST)
7716 values[n++] = atomic64_read(&sub->lost_samples);
7717
7718 __output_copy(handle, values, n * sizeof(u64));
7719 }
7720
7721 local_irq_restore(flags);
7722 }
7723
7724 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
7725 PERF_FORMAT_TOTAL_TIME_RUNNING)
7726
7727 /*
7728 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
7729 *
7730 * The problem is that its both hard and excessively expensive to iterate the
7731 * child list, not to mention that its impossible to IPI the children running
7732 * on another CPU, from interrupt/NMI context.
7733 *
7734 * Instead the combination of PERF_SAMPLE_READ and inherit will track per-thread
7735 * counts rather than attempting to accumulate some value across all children on
7736 * all cores.
7737 */
perf_output_read(struct perf_output_handle * handle,struct perf_event * event)7738 static void perf_output_read(struct perf_output_handle *handle,
7739 struct perf_event *event)
7740 {
7741 u64 enabled = 0, running = 0, now;
7742 u64 read_format = event->attr.read_format;
7743
7744 /*
7745 * compute total_time_enabled, total_time_running
7746 * based on snapshot values taken when the event
7747 * was last scheduled in.
7748 *
7749 * we cannot simply called update_context_time()
7750 * because of locking issue as we are called in
7751 * NMI context
7752 */
7753 if (read_format & PERF_FORMAT_TOTAL_TIMES)
7754 calc_timer_values(event, &now, &enabled, &running);
7755
7756 if (event->attr.read_format & PERF_FORMAT_GROUP)
7757 perf_output_read_group(handle, event, enabled, running);
7758 else
7759 perf_output_read_one(handle, event, enabled, running);
7760 }
7761
perf_output_sample(struct perf_output_handle * handle,struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event)7762 void perf_output_sample(struct perf_output_handle *handle,
7763 struct perf_event_header *header,
7764 struct perf_sample_data *data,
7765 struct perf_event *event)
7766 {
7767 u64 sample_type = data->type;
7768
7769 if (data->sample_flags & PERF_SAMPLE_READ)
7770 handle->skip_read = 1;
7771
7772 perf_output_put(handle, *header);
7773
7774 if (sample_type & PERF_SAMPLE_IDENTIFIER)
7775 perf_output_put(handle, data->id);
7776
7777 if (sample_type & PERF_SAMPLE_IP)
7778 perf_output_put(handle, data->ip);
7779
7780 if (sample_type & PERF_SAMPLE_TID)
7781 perf_output_put(handle, data->tid_entry);
7782
7783 if (sample_type & PERF_SAMPLE_TIME)
7784 perf_output_put(handle, data->time);
7785
7786 if (sample_type & PERF_SAMPLE_ADDR)
7787 perf_output_put(handle, data->addr);
7788
7789 if (sample_type & PERF_SAMPLE_ID)
7790 perf_output_put(handle, data->id);
7791
7792 if (sample_type & PERF_SAMPLE_STREAM_ID)
7793 perf_output_put(handle, data->stream_id);
7794
7795 if (sample_type & PERF_SAMPLE_CPU)
7796 perf_output_put(handle, data->cpu_entry);
7797
7798 if (sample_type & PERF_SAMPLE_PERIOD)
7799 perf_output_put(handle, data->period);
7800
7801 if (sample_type & PERF_SAMPLE_READ)
7802 perf_output_read(handle, event);
7803
7804 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7805 int size = 1;
7806
7807 size += data->callchain->nr;
7808 size *= sizeof(u64);
7809 __output_copy(handle, data->callchain, size);
7810 }
7811
7812 if (sample_type & PERF_SAMPLE_RAW) {
7813 struct perf_raw_record *raw = data->raw;
7814
7815 if (raw) {
7816 struct perf_raw_frag *frag = &raw->frag;
7817
7818 perf_output_put(handle, raw->size);
7819 do {
7820 if (frag->copy) {
7821 __output_custom(handle, frag->copy,
7822 frag->data, frag->size);
7823 } else {
7824 __output_copy(handle, frag->data,
7825 frag->size);
7826 }
7827 if (perf_raw_frag_last(frag))
7828 break;
7829 frag = frag->next;
7830 } while (1);
7831 if (frag->pad)
7832 __output_skip(handle, NULL, frag->pad);
7833 } else {
7834 struct {
7835 u32 size;
7836 u32 data;
7837 } raw = {
7838 .size = sizeof(u32),
7839 .data = 0,
7840 };
7841 perf_output_put(handle, raw);
7842 }
7843 }
7844
7845 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7846 if (data->br_stack) {
7847 size_t size;
7848
7849 size = data->br_stack->nr
7850 * sizeof(struct perf_branch_entry);
7851
7852 perf_output_put(handle, data->br_stack->nr);
7853 if (branch_sample_hw_index(event))
7854 perf_output_put(handle, data->br_stack->hw_idx);
7855 perf_output_copy(handle, data->br_stack->entries, size);
7856 /*
7857 * Add the extension space which is appended
7858 * right after the struct perf_branch_stack.
7859 */
7860 if (data->br_stack_cntr) {
7861 size = data->br_stack->nr * sizeof(u64);
7862 perf_output_copy(handle, data->br_stack_cntr, size);
7863 }
7864 } else {
7865 /*
7866 * we always store at least the value of nr
7867 */
7868 u64 nr = 0;
7869 perf_output_put(handle, nr);
7870 }
7871 }
7872
7873 if (sample_type & PERF_SAMPLE_REGS_USER) {
7874 u64 abi = data->regs_user.abi;
7875
7876 /*
7877 * If there are no regs to dump, notice it through
7878 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7879 */
7880 perf_output_put(handle, abi);
7881
7882 if (abi) {
7883 u64 mask = event->attr.sample_regs_user;
7884 perf_output_sample_regs(handle,
7885 data->regs_user.regs,
7886 mask);
7887 }
7888 }
7889
7890 if (sample_type & PERF_SAMPLE_STACK_USER) {
7891 perf_output_sample_ustack(handle,
7892 data->stack_user_size,
7893 data->regs_user.regs);
7894 }
7895
7896 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
7897 perf_output_put(handle, data->weight.full);
7898
7899 if (sample_type & PERF_SAMPLE_DATA_SRC)
7900 perf_output_put(handle, data->data_src.val);
7901
7902 if (sample_type & PERF_SAMPLE_TRANSACTION)
7903 perf_output_put(handle, data->txn);
7904
7905 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7906 u64 abi = data->regs_intr.abi;
7907 /*
7908 * If there are no regs to dump, notice it through
7909 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7910 */
7911 perf_output_put(handle, abi);
7912
7913 if (abi) {
7914 u64 mask = event->attr.sample_regs_intr;
7915
7916 perf_output_sample_regs(handle,
7917 data->regs_intr.regs,
7918 mask);
7919 }
7920 }
7921
7922 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7923 perf_output_put(handle, data->phys_addr);
7924
7925 if (sample_type & PERF_SAMPLE_CGROUP)
7926 perf_output_put(handle, data->cgroup);
7927
7928 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
7929 perf_output_put(handle, data->data_page_size);
7930
7931 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
7932 perf_output_put(handle, data->code_page_size);
7933
7934 if (sample_type & PERF_SAMPLE_AUX) {
7935 perf_output_put(handle, data->aux_size);
7936
7937 if (data->aux_size)
7938 perf_aux_sample_output(event, handle, data);
7939 }
7940
7941 if (!event->attr.watermark) {
7942 int wakeup_events = event->attr.wakeup_events;
7943
7944 if (wakeup_events) {
7945 struct perf_buffer *rb = handle->rb;
7946 int events = local_inc_return(&rb->events);
7947
7948 if (events >= wakeup_events) {
7949 local_sub(wakeup_events, &rb->events);
7950 local_inc(&rb->wakeup);
7951 }
7952 }
7953 }
7954 }
7955
perf_virt_to_phys(u64 virt)7956 static u64 perf_virt_to_phys(u64 virt)
7957 {
7958 u64 phys_addr = 0;
7959
7960 if (!virt)
7961 return 0;
7962
7963 if (virt >= TASK_SIZE) {
7964 /* If it's vmalloc()d memory, leave phys_addr as 0 */
7965 if (virt_addr_valid((void *)(uintptr_t)virt) &&
7966 !(virt >= VMALLOC_START && virt < VMALLOC_END))
7967 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
7968 } else {
7969 /*
7970 * Walking the pages tables for user address.
7971 * Interrupts are disabled, so it prevents any tear down
7972 * of the page tables.
7973 * Try IRQ-safe get_user_page_fast_only first.
7974 * If failed, leave phys_addr as 0.
7975 */
7976 if (current->mm != NULL) {
7977 struct page *p;
7978
7979 pagefault_disable();
7980 if (get_user_page_fast_only(virt, 0, &p)) {
7981 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
7982 put_page(p);
7983 }
7984 pagefault_enable();
7985 }
7986 }
7987
7988 return phys_addr;
7989 }
7990
7991 /*
7992 * Return the pagetable size of a given virtual address.
7993 */
perf_get_pgtable_size(struct mm_struct * mm,unsigned long addr)7994 static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
7995 {
7996 u64 size = 0;
7997
7998 #ifdef CONFIG_HAVE_GUP_FAST
7999 pgd_t *pgdp, pgd;
8000 p4d_t *p4dp, p4d;
8001 pud_t *pudp, pud;
8002 pmd_t *pmdp, pmd;
8003 pte_t *ptep, pte;
8004
8005 pgdp = pgd_offset(mm, addr);
8006 pgd = READ_ONCE(*pgdp);
8007 if (pgd_none(pgd))
8008 return 0;
8009
8010 if (pgd_leaf(pgd))
8011 return pgd_leaf_size(pgd);
8012
8013 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
8014 p4d = READ_ONCE(*p4dp);
8015 if (!p4d_present(p4d))
8016 return 0;
8017
8018 if (p4d_leaf(p4d))
8019 return p4d_leaf_size(p4d);
8020
8021 pudp = pud_offset_lockless(p4dp, p4d, addr);
8022 pud = READ_ONCE(*pudp);
8023 if (!pud_present(pud))
8024 return 0;
8025
8026 if (pud_leaf(pud))
8027 return pud_leaf_size(pud);
8028
8029 pmdp = pmd_offset_lockless(pudp, pud, addr);
8030 again:
8031 pmd = pmdp_get_lockless(pmdp);
8032 if (!pmd_present(pmd))
8033 return 0;
8034
8035 if (pmd_leaf(pmd))
8036 return pmd_leaf_size(pmd);
8037
8038 ptep = pte_offset_map(&pmd, addr);
8039 if (!ptep)
8040 goto again;
8041
8042 pte = ptep_get_lockless(ptep);
8043 if (pte_present(pte))
8044 size = __pte_leaf_size(pmd, pte);
8045 pte_unmap(ptep);
8046 #endif /* CONFIG_HAVE_GUP_FAST */
8047
8048 return size;
8049 }
8050
perf_get_page_size(unsigned long addr)8051 static u64 perf_get_page_size(unsigned long addr)
8052 {
8053 struct mm_struct *mm;
8054 unsigned long flags;
8055 u64 size;
8056
8057 if (!addr)
8058 return 0;
8059
8060 /*
8061 * Software page-table walkers must disable IRQs,
8062 * which prevents any tear down of the page tables.
8063 */
8064 local_irq_save(flags);
8065
8066 mm = current->mm;
8067 if (!mm) {
8068 /*
8069 * For kernel threads and the like, use init_mm so that
8070 * we can find kernel memory.
8071 */
8072 mm = &init_mm;
8073 }
8074
8075 size = perf_get_pgtable_size(mm, addr);
8076
8077 local_irq_restore(flags);
8078
8079 return size;
8080 }
8081
8082 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
8083
8084 struct perf_callchain_entry *
perf_callchain(struct perf_event * event,struct pt_regs * regs)8085 perf_callchain(struct perf_event *event, struct pt_regs *regs)
8086 {
8087 bool kernel = !event->attr.exclude_callchain_kernel;
8088 bool user = !event->attr.exclude_callchain_user;
8089 /* Disallow cross-task user callchains. */
8090 bool crosstask = event->ctx->task && event->ctx->task != current;
8091 const u32 max_stack = event->attr.sample_max_stack;
8092 struct perf_callchain_entry *callchain;
8093
8094 if (!kernel && !user)
8095 return &__empty_callchain;
8096
8097 callchain = get_perf_callchain(regs, 0, kernel, user,
8098 max_stack, crosstask, true);
8099 return callchain ?: &__empty_callchain;
8100 }
8101
__cond_set(u64 flags,u64 s,u64 d)8102 static __always_inline u64 __cond_set(u64 flags, u64 s, u64 d)
8103 {
8104 return d * !!(flags & s);
8105 }
8106
perf_prepare_sample(struct perf_sample_data * data,struct perf_event * event,struct pt_regs * regs)8107 void perf_prepare_sample(struct perf_sample_data *data,
8108 struct perf_event *event,
8109 struct pt_regs *regs)
8110 {
8111 u64 sample_type = event->attr.sample_type;
8112 u64 filtered_sample_type;
8113
8114 /*
8115 * Add the sample flags that are dependent to others. And clear the
8116 * sample flags that have already been done by the PMU driver.
8117 */
8118 filtered_sample_type = sample_type;
8119 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_CODE_PAGE_SIZE,
8120 PERF_SAMPLE_IP);
8121 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_DATA_PAGE_SIZE |
8122 PERF_SAMPLE_PHYS_ADDR, PERF_SAMPLE_ADDR);
8123 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_STACK_USER,
8124 PERF_SAMPLE_REGS_USER);
8125 filtered_sample_type &= ~data->sample_flags;
8126
8127 if (filtered_sample_type == 0) {
8128 /* Make sure it has the correct data->type for output */
8129 data->type = event->attr.sample_type;
8130 return;
8131 }
8132
8133 __perf_event_header__init_id(data, event, filtered_sample_type);
8134
8135 if (filtered_sample_type & PERF_SAMPLE_IP) {
8136 data->ip = perf_instruction_pointer(event, regs);
8137 data->sample_flags |= PERF_SAMPLE_IP;
8138 }
8139
8140 if (filtered_sample_type & PERF_SAMPLE_CALLCHAIN)
8141 perf_sample_save_callchain(data, event, regs);
8142
8143 if (filtered_sample_type & PERF_SAMPLE_RAW) {
8144 data->raw = NULL;
8145 data->dyn_size += sizeof(u64);
8146 data->sample_flags |= PERF_SAMPLE_RAW;
8147 }
8148
8149 if (filtered_sample_type & PERF_SAMPLE_BRANCH_STACK) {
8150 data->br_stack = NULL;
8151 data->dyn_size += sizeof(u64);
8152 data->sample_flags |= PERF_SAMPLE_BRANCH_STACK;
8153 }
8154
8155 if (filtered_sample_type & PERF_SAMPLE_REGS_USER)
8156 perf_sample_regs_user(&data->regs_user, regs);
8157
8158 /*
8159 * It cannot use the filtered_sample_type here as REGS_USER can be set
8160 * by STACK_USER (using __cond_set() above) and we don't want to update
8161 * the dyn_size if it's not requested by users.
8162 */
8163 if ((sample_type & ~data->sample_flags) & PERF_SAMPLE_REGS_USER) {
8164 /* regs dump ABI info */
8165 int size = sizeof(u64);
8166
8167 if (data->regs_user.regs) {
8168 u64 mask = event->attr.sample_regs_user;
8169 size += hweight64(mask) * sizeof(u64);
8170 }
8171
8172 data->dyn_size += size;
8173 data->sample_flags |= PERF_SAMPLE_REGS_USER;
8174 }
8175
8176 if (filtered_sample_type & PERF_SAMPLE_STACK_USER) {
8177 /*
8178 * Either we need PERF_SAMPLE_STACK_USER bit to be always
8179 * processed as the last one or have additional check added
8180 * in case new sample type is added, because we could eat
8181 * up the rest of the sample size.
8182 */
8183 u16 stack_size = event->attr.sample_stack_user;
8184 u16 header_size = perf_sample_data_size(data, event);
8185 u16 size = sizeof(u64);
8186
8187 stack_size = perf_sample_ustack_size(stack_size, header_size,
8188 data->regs_user.regs);
8189
8190 /*
8191 * If there is something to dump, add space for the dump
8192 * itself and for the field that tells the dynamic size,
8193 * which is how many have been actually dumped.
8194 */
8195 if (stack_size)
8196 size += sizeof(u64) + stack_size;
8197
8198 data->stack_user_size = stack_size;
8199 data->dyn_size += size;
8200 data->sample_flags |= PERF_SAMPLE_STACK_USER;
8201 }
8202
8203 if (filtered_sample_type & PERF_SAMPLE_WEIGHT_TYPE) {
8204 data->weight.full = 0;
8205 data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE;
8206 }
8207
8208 if (filtered_sample_type & PERF_SAMPLE_DATA_SRC) {
8209 data->data_src.val = PERF_MEM_NA;
8210 data->sample_flags |= PERF_SAMPLE_DATA_SRC;
8211 }
8212
8213 if (filtered_sample_type & PERF_SAMPLE_TRANSACTION) {
8214 data->txn = 0;
8215 data->sample_flags |= PERF_SAMPLE_TRANSACTION;
8216 }
8217
8218 if (filtered_sample_type & PERF_SAMPLE_ADDR) {
8219 data->addr = 0;
8220 data->sample_flags |= PERF_SAMPLE_ADDR;
8221 }
8222
8223 if (filtered_sample_type & PERF_SAMPLE_REGS_INTR) {
8224 /* regs dump ABI info */
8225 int size = sizeof(u64);
8226
8227 perf_sample_regs_intr(&data->regs_intr, regs);
8228
8229 if (data->regs_intr.regs) {
8230 u64 mask = event->attr.sample_regs_intr;
8231
8232 size += hweight64(mask) * sizeof(u64);
8233 }
8234
8235 data->dyn_size += size;
8236 data->sample_flags |= PERF_SAMPLE_REGS_INTR;
8237 }
8238
8239 if (filtered_sample_type & PERF_SAMPLE_PHYS_ADDR) {
8240 data->phys_addr = perf_virt_to_phys(data->addr);
8241 data->sample_flags |= PERF_SAMPLE_PHYS_ADDR;
8242 }
8243
8244 #ifdef CONFIG_CGROUP_PERF
8245 if (filtered_sample_type & PERF_SAMPLE_CGROUP) {
8246 struct cgroup *cgrp;
8247
8248 /* protected by RCU */
8249 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
8250 data->cgroup = cgroup_id(cgrp);
8251 data->sample_flags |= PERF_SAMPLE_CGROUP;
8252 }
8253 #endif
8254
8255 /*
8256 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't
8257 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr,
8258 * but the value will not dump to the userspace.
8259 */
8260 if (filtered_sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) {
8261 data->data_page_size = perf_get_page_size(data->addr);
8262 data->sample_flags |= PERF_SAMPLE_DATA_PAGE_SIZE;
8263 }
8264
8265 if (filtered_sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) {
8266 data->code_page_size = perf_get_page_size(data->ip);
8267 data->sample_flags |= PERF_SAMPLE_CODE_PAGE_SIZE;
8268 }
8269
8270 if (filtered_sample_type & PERF_SAMPLE_AUX) {
8271 u64 size;
8272 u16 header_size = perf_sample_data_size(data, event);
8273
8274 header_size += sizeof(u64); /* size */
8275
8276 /*
8277 * Given the 16bit nature of header::size, an AUX sample can
8278 * easily overflow it, what with all the preceding sample bits.
8279 * Make sure this doesn't happen by using up to U16_MAX bytes
8280 * per sample in total (rounded down to 8 byte boundary).
8281 */
8282 size = min_t(size_t, U16_MAX - header_size,
8283 event->attr.aux_sample_size);
8284 size = rounddown(size, 8);
8285 size = perf_prepare_sample_aux(event, data, size);
8286
8287 WARN_ON_ONCE(size + header_size > U16_MAX);
8288 data->dyn_size += size + sizeof(u64); /* size above */
8289 data->sample_flags |= PERF_SAMPLE_AUX;
8290 }
8291 }
8292
perf_prepare_header(struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event,struct pt_regs * regs)8293 void perf_prepare_header(struct perf_event_header *header,
8294 struct perf_sample_data *data,
8295 struct perf_event *event,
8296 struct pt_regs *regs)
8297 {
8298 header->type = PERF_RECORD_SAMPLE;
8299 header->size = perf_sample_data_size(data, event);
8300 header->misc = perf_misc_flags(event, regs);
8301
8302 /*
8303 * If you're adding more sample types here, you likely need to do
8304 * something about the overflowing header::size, like repurpose the
8305 * lowest 3 bits of size, which should be always zero at the moment.
8306 * This raises a more important question, do we really need 512k sized
8307 * samples and why, so good argumentation is in order for whatever you
8308 * do here next.
8309 */
8310 WARN_ON_ONCE(header->size & 7);
8311 }
8312
__perf_event_aux_pause(struct perf_event * event,bool pause)8313 static void __perf_event_aux_pause(struct perf_event *event, bool pause)
8314 {
8315 if (pause) {
8316 if (!event->hw.aux_paused) {
8317 event->hw.aux_paused = 1;
8318 event->pmu->stop(event, PERF_EF_PAUSE);
8319 }
8320 } else {
8321 if (event->hw.aux_paused) {
8322 event->hw.aux_paused = 0;
8323 event->pmu->start(event, PERF_EF_RESUME);
8324 }
8325 }
8326 }
8327
perf_event_aux_pause(struct perf_event * event,bool pause)8328 static void perf_event_aux_pause(struct perf_event *event, bool pause)
8329 {
8330 struct perf_buffer *rb;
8331
8332 if (WARN_ON_ONCE(!event))
8333 return;
8334
8335 rb = ring_buffer_get(event);
8336 if (!rb)
8337 return;
8338
8339 scoped_guard (irqsave) {
8340 /*
8341 * Guard against self-recursion here. Another event could trip
8342 * this same from NMI context.
8343 */
8344 if (READ_ONCE(rb->aux_in_pause_resume))
8345 break;
8346
8347 WRITE_ONCE(rb->aux_in_pause_resume, 1);
8348 barrier();
8349 __perf_event_aux_pause(event, pause);
8350 barrier();
8351 WRITE_ONCE(rb->aux_in_pause_resume, 0);
8352 }
8353 ring_buffer_put(rb);
8354 }
8355
8356 static __always_inline int
__perf_event_output(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs,int (* output_begin)(struct perf_output_handle *,struct perf_sample_data *,struct perf_event *,unsigned int))8357 __perf_event_output(struct perf_event *event,
8358 struct perf_sample_data *data,
8359 struct pt_regs *regs,
8360 int (*output_begin)(struct perf_output_handle *,
8361 struct perf_sample_data *,
8362 struct perf_event *,
8363 unsigned int))
8364 {
8365 struct perf_output_handle handle;
8366 struct perf_event_header header;
8367 int err;
8368
8369 /* protect the callchain buffers */
8370 rcu_read_lock();
8371
8372 perf_prepare_sample(data, event, regs);
8373 perf_prepare_header(&header, data, event, regs);
8374
8375 err = output_begin(&handle, data, event, header.size);
8376 if (err)
8377 goto exit;
8378
8379 perf_output_sample(&handle, &header, data, event);
8380
8381 perf_output_end(&handle);
8382
8383 exit:
8384 rcu_read_unlock();
8385 return err;
8386 }
8387
8388 void
perf_event_output_forward(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)8389 perf_event_output_forward(struct perf_event *event,
8390 struct perf_sample_data *data,
8391 struct pt_regs *regs)
8392 {
8393 __perf_event_output(event, data, regs, perf_output_begin_forward);
8394 }
8395
8396 void
perf_event_output_backward(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)8397 perf_event_output_backward(struct perf_event *event,
8398 struct perf_sample_data *data,
8399 struct pt_regs *regs)
8400 {
8401 __perf_event_output(event, data, regs, perf_output_begin_backward);
8402 }
8403
8404 int
perf_event_output(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)8405 perf_event_output(struct perf_event *event,
8406 struct perf_sample_data *data,
8407 struct pt_regs *regs)
8408 {
8409 return __perf_event_output(event, data, regs, perf_output_begin);
8410 }
8411
8412 /*
8413 * read event_id
8414 */
8415
8416 struct perf_read_event {
8417 struct perf_event_header header;
8418
8419 u32 pid;
8420 u32 tid;
8421 };
8422
8423 static void
perf_event_read_event(struct perf_event * event,struct task_struct * task)8424 perf_event_read_event(struct perf_event *event,
8425 struct task_struct *task)
8426 {
8427 struct perf_output_handle handle;
8428 struct perf_sample_data sample;
8429 struct perf_read_event read_event = {
8430 .header = {
8431 .type = PERF_RECORD_READ,
8432 .misc = 0,
8433 .size = sizeof(read_event) + event->read_size,
8434 },
8435 .pid = perf_event_pid(event, task),
8436 .tid = perf_event_tid(event, task),
8437 };
8438 int ret;
8439
8440 perf_event_header__init_id(&read_event.header, &sample, event);
8441 ret = perf_output_begin(&handle, &sample, event, read_event.header.size);
8442 if (ret)
8443 return;
8444
8445 perf_output_put(&handle, read_event);
8446 perf_output_read(&handle, event);
8447 perf_event__output_id_sample(event, &handle, &sample);
8448
8449 perf_output_end(&handle);
8450 }
8451
8452 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
8453
8454 static void
perf_iterate_ctx(struct perf_event_context * ctx,perf_iterate_f output,void * data,bool all)8455 perf_iterate_ctx(struct perf_event_context *ctx,
8456 perf_iterate_f output,
8457 void *data, bool all)
8458 {
8459 struct perf_event *event;
8460
8461 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
8462 if (!all) {
8463 if (event->state < PERF_EVENT_STATE_INACTIVE)
8464 continue;
8465 if (!event_filter_match(event))
8466 continue;
8467 }
8468
8469 output(event, data);
8470 }
8471 }
8472
perf_iterate_sb_cpu(perf_iterate_f output,void * data)8473 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
8474 {
8475 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
8476 struct perf_event *event;
8477
8478 list_for_each_entry_rcu(event, &pel->list, sb_list) {
8479 /*
8480 * Skip events that are not fully formed yet; ensure that
8481 * if we observe event->ctx, both event and ctx will be
8482 * complete enough. See perf_install_in_context().
8483 */
8484 if (!smp_load_acquire(&event->ctx))
8485 continue;
8486
8487 if (event->state < PERF_EVENT_STATE_INACTIVE)
8488 continue;
8489 if (!event_filter_match(event))
8490 continue;
8491 output(event, data);
8492 }
8493 }
8494
8495 /*
8496 * Iterate all events that need to receive side-band events.
8497 *
8498 * For new callers; ensure that account_pmu_sb_event() includes
8499 * your event, otherwise it might not get delivered.
8500 */
8501 static void
perf_iterate_sb(perf_iterate_f output,void * data,struct perf_event_context * task_ctx)8502 perf_iterate_sb(perf_iterate_f output, void *data,
8503 struct perf_event_context *task_ctx)
8504 {
8505 struct perf_event_context *ctx;
8506
8507 rcu_read_lock();
8508 preempt_disable();
8509
8510 /*
8511 * If we have task_ctx != NULL we only notify the task context itself.
8512 * The task_ctx is set only for EXIT events before releasing task
8513 * context.
8514 */
8515 if (task_ctx) {
8516 perf_iterate_ctx(task_ctx, output, data, false);
8517 goto done;
8518 }
8519
8520 perf_iterate_sb_cpu(output, data);
8521
8522 ctx = rcu_dereference(current->perf_event_ctxp);
8523 if (ctx)
8524 perf_iterate_ctx(ctx, output, data, false);
8525 done:
8526 preempt_enable();
8527 rcu_read_unlock();
8528 }
8529
8530 /*
8531 * Clear all file-based filters at exec, they'll have to be
8532 * re-instated when/if these objects are mmapped again.
8533 */
perf_event_addr_filters_exec(struct perf_event * event,void * data)8534 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
8535 {
8536 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8537 struct perf_addr_filter *filter;
8538 unsigned int restart = 0, count = 0;
8539 unsigned long flags;
8540
8541 if (!has_addr_filter(event))
8542 return;
8543
8544 raw_spin_lock_irqsave(&ifh->lock, flags);
8545 list_for_each_entry(filter, &ifh->list, entry) {
8546 if (filter->path.dentry) {
8547 event->addr_filter_ranges[count].start = 0;
8548 event->addr_filter_ranges[count].size = 0;
8549 restart++;
8550 }
8551
8552 count++;
8553 }
8554
8555 if (restart)
8556 event->addr_filters_gen++;
8557 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8558
8559 if (restart)
8560 perf_event_stop(event, 1);
8561 }
8562
perf_event_exec(void)8563 void perf_event_exec(void)
8564 {
8565 struct perf_event_context *ctx;
8566
8567 ctx = perf_pin_task_context(current);
8568 if (!ctx)
8569 return;
8570
8571 perf_event_enable_on_exec(ctx);
8572 perf_event_remove_on_exec(ctx);
8573 scoped_guard(rcu)
8574 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL, true);
8575
8576 perf_unpin_context(ctx);
8577 put_ctx(ctx);
8578 }
8579
8580 struct remote_output {
8581 struct perf_buffer *rb;
8582 int err;
8583 };
8584
__perf_event_output_stop(struct perf_event * event,void * data)8585 static void __perf_event_output_stop(struct perf_event *event, void *data)
8586 {
8587 struct perf_event *parent = event->parent;
8588 struct remote_output *ro = data;
8589 struct perf_buffer *rb = ro->rb;
8590 struct stop_event_data sd = {
8591 .event = event,
8592 };
8593
8594 if (!has_aux(event))
8595 return;
8596
8597 if (!parent)
8598 parent = event;
8599
8600 /*
8601 * In case of inheritance, it will be the parent that links to the
8602 * ring-buffer, but it will be the child that's actually using it.
8603 *
8604 * We are using event::rb to determine if the event should be stopped,
8605 * however this may race with ring_buffer_attach() (through set_output),
8606 * which will make us skip the event that actually needs to be stopped.
8607 * So ring_buffer_attach() has to stop an aux event before re-assigning
8608 * its rb pointer.
8609 */
8610 if (rcu_dereference(parent->rb) == rb)
8611 ro->err = __perf_event_stop(&sd);
8612 }
8613
__perf_pmu_output_stop(void * info)8614 static int __perf_pmu_output_stop(void *info)
8615 {
8616 struct perf_event *event = info;
8617 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
8618 struct remote_output ro = {
8619 .rb = event->rb,
8620 };
8621
8622 rcu_read_lock();
8623 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
8624 if (cpuctx->task_ctx)
8625 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
8626 &ro, false);
8627 rcu_read_unlock();
8628
8629 return ro.err;
8630 }
8631
perf_pmu_output_stop(struct perf_event * event)8632 static void perf_pmu_output_stop(struct perf_event *event)
8633 {
8634 struct perf_event *iter;
8635 int err, cpu;
8636
8637 restart:
8638 rcu_read_lock();
8639 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
8640 /*
8641 * For per-CPU events, we need to make sure that neither they
8642 * nor their children are running; for cpu==-1 events it's
8643 * sufficient to stop the event itself if it's active, since
8644 * it can't have children.
8645 */
8646 cpu = iter->cpu;
8647 if (cpu == -1)
8648 cpu = READ_ONCE(iter->oncpu);
8649
8650 if (cpu == -1)
8651 continue;
8652
8653 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
8654 if (err == -EAGAIN) {
8655 rcu_read_unlock();
8656 goto restart;
8657 }
8658 }
8659 rcu_read_unlock();
8660 }
8661
8662 /*
8663 * task tracking -- fork/exit
8664 *
8665 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
8666 */
8667
8668 struct perf_task_event {
8669 struct task_struct *task;
8670 struct perf_event_context *task_ctx;
8671
8672 struct {
8673 struct perf_event_header header;
8674
8675 u32 pid;
8676 u32 ppid;
8677 u32 tid;
8678 u32 ptid;
8679 u64 time;
8680 } event_id;
8681 };
8682
perf_event_task_match(struct perf_event * event)8683 static int perf_event_task_match(struct perf_event *event)
8684 {
8685 return event->attr.comm || event->attr.mmap ||
8686 event->attr.mmap2 || event->attr.mmap_data ||
8687 event->attr.task;
8688 }
8689
perf_event_task_output(struct perf_event * event,void * data)8690 static void perf_event_task_output(struct perf_event *event,
8691 void *data)
8692 {
8693 struct perf_task_event *task_event = data;
8694 struct perf_output_handle handle;
8695 struct perf_sample_data sample;
8696 struct task_struct *task = task_event->task;
8697 int ret, size = task_event->event_id.header.size;
8698
8699 if (!perf_event_task_match(event))
8700 return;
8701
8702 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
8703
8704 ret = perf_output_begin(&handle, &sample, event,
8705 task_event->event_id.header.size);
8706 if (ret)
8707 goto out;
8708
8709 task_event->event_id.pid = perf_event_pid(event, task);
8710 task_event->event_id.tid = perf_event_tid(event, task);
8711
8712 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
8713 task_event->event_id.ppid = perf_event_pid(event,
8714 task->real_parent);
8715 task_event->event_id.ptid = perf_event_pid(event,
8716 task->real_parent);
8717 } else { /* PERF_RECORD_FORK */
8718 task_event->event_id.ppid = perf_event_pid(event, current);
8719 task_event->event_id.ptid = perf_event_tid(event, current);
8720 }
8721
8722 task_event->event_id.time = perf_event_clock(event);
8723
8724 perf_output_put(&handle, task_event->event_id);
8725
8726 perf_event__output_id_sample(event, &handle, &sample);
8727
8728 perf_output_end(&handle);
8729 out:
8730 task_event->event_id.header.size = size;
8731 }
8732
perf_event_task(struct task_struct * task,struct perf_event_context * task_ctx,int new)8733 static void perf_event_task(struct task_struct *task,
8734 struct perf_event_context *task_ctx,
8735 int new)
8736 {
8737 struct perf_task_event task_event;
8738
8739 if (!atomic_read(&nr_comm_events) &&
8740 !atomic_read(&nr_mmap_events) &&
8741 !atomic_read(&nr_task_events))
8742 return;
8743
8744 task_event = (struct perf_task_event){
8745 .task = task,
8746 .task_ctx = task_ctx,
8747 .event_id = {
8748 .header = {
8749 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
8750 .misc = 0,
8751 .size = sizeof(task_event.event_id),
8752 },
8753 /* .pid */
8754 /* .ppid */
8755 /* .tid */
8756 /* .ptid */
8757 /* .time */
8758 },
8759 };
8760
8761 perf_iterate_sb(perf_event_task_output,
8762 &task_event,
8763 task_ctx);
8764 }
8765
8766 /*
8767 * Allocate data for a new task when profiling system-wide
8768 * events which require PMU specific data
8769 */
8770 static void
perf_event_alloc_task_data(struct task_struct * child,struct task_struct * parent)8771 perf_event_alloc_task_data(struct task_struct *child,
8772 struct task_struct *parent)
8773 {
8774 struct kmem_cache *ctx_cache = NULL;
8775 struct perf_ctx_data *cd;
8776
8777 if (!refcount_read(&global_ctx_data_ref))
8778 return;
8779
8780 scoped_guard (rcu) {
8781 cd = rcu_dereference(parent->perf_ctx_data);
8782 if (cd)
8783 ctx_cache = cd->ctx_cache;
8784 }
8785
8786 if (!ctx_cache)
8787 return;
8788
8789 guard(percpu_read)(&global_ctx_data_rwsem);
8790 scoped_guard (rcu) {
8791 cd = rcu_dereference(child->perf_ctx_data);
8792 if (!cd) {
8793 /*
8794 * A system-wide event may be unaccount,
8795 * when attaching the perf_ctx_data.
8796 */
8797 if (!refcount_read(&global_ctx_data_ref))
8798 return;
8799 goto attach;
8800 }
8801
8802 if (!cd->global) {
8803 cd->global = 1;
8804 refcount_inc(&cd->refcount);
8805 }
8806 }
8807
8808 return;
8809 attach:
8810 attach_task_ctx_data(child, ctx_cache, true);
8811 }
8812
perf_event_fork(struct task_struct * task)8813 void perf_event_fork(struct task_struct *task)
8814 {
8815 perf_event_task(task, NULL, 1);
8816 perf_event_namespaces(task);
8817 perf_event_alloc_task_data(task, current);
8818 }
8819
8820 /*
8821 * comm tracking
8822 */
8823
8824 struct perf_comm_event {
8825 struct task_struct *task;
8826 char *comm;
8827 int comm_size;
8828
8829 struct {
8830 struct perf_event_header header;
8831
8832 u32 pid;
8833 u32 tid;
8834 } event_id;
8835 };
8836
perf_event_comm_match(struct perf_event * event)8837 static int perf_event_comm_match(struct perf_event *event)
8838 {
8839 return event->attr.comm;
8840 }
8841
perf_event_comm_output(struct perf_event * event,void * data)8842 static void perf_event_comm_output(struct perf_event *event,
8843 void *data)
8844 {
8845 struct perf_comm_event *comm_event = data;
8846 struct perf_output_handle handle;
8847 struct perf_sample_data sample;
8848 int size = comm_event->event_id.header.size;
8849 int ret;
8850
8851 if (!perf_event_comm_match(event))
8852 return;
8853
8854 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
8855 ret = perf_output_begin(&handle, &sample, event,
8856 comm_event->event_id.header.size);
8857
8858 if (ret)
8859 goto out;
8860
8861 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
8862 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
8863
8864 perf_output_put(&handle, comm_event->event_id);
8865 __output_copy(&handle, comm_event->comm,
8866 comm_event->comm_size);
8867
8868 perf_event__output_id_sample(event, &handle, &sample);
8869
8870 perf_output_end(&handle);
8871 out:
8872 comm_event->event_id.header.size = size;
8873 }
8874
perf_event_comm_event(struct perf_comm_event * comm_event)8875 static void perf_event_comm_event(struct perf_comm_event *comm_event)
8876 {
8877 char comm[TASK_COMM_LEN];
8878 unsigned int size;
8879
8880 memset(comm, 0, sizeof(comm));
8881 strscpy(comm, comm_event->task->comm);
8882 size = ALIGN(strlen(comm)+1, sizeof(u64));
8883
8884 comm_event->comm = comm;
8885 comm_event->comm_size = size;
8886
8887 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
8888
8889 perf_iterate_sb(perf_event_comm_output,
8890 comm_event,
8891 NULL);
8892 }
8893
perf_event_comm(struct task_struct * task,bool exec)8894 void perf_event_comm(struct task_struct *task, bool exec)
8895 {
8896 struct perf_comm_event comm_event;
8897
8898 if (!atomic_read(&nr_comm_events))
8899 return;
8900
8901 comm_event = (struct perf_comm_event){
8902 .task = task,
8903 /* .comm */
8904 /* .comm_size */
8905 .event_id = {
8906 .header = {
8907 .type = PERF_RECORD_COMM,
8908 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
8909 /* .size */
8910 },
8911 /* .pid */
8912 /* .tid */
8913 },
8914 };
8915
8916 perf_event_comm_event(&comm_event);
8917 }
8918
8919 /*
8920 * namespaces tracking
8921 */
8922
8923 struct perf_namespaces_event {
8924 struct task_struct *task;
8925
8926 struct {
8927 struct perf_event_header header;
8928
8929 u32 pid;
8930 u32 tid;
8931 u64 nr_namespaces;
8932 struct perf_ns_link_info link_info[NR_NAMESPACES];
8933 } event_id;
8934 };
8935
perf_event_namespaces_match(struct perf_event * event)8936 static int perf_event_namespaces_match(struct perf_event *event)
8937 {
8938 return event->attr.namespaces;
8939 }
8940
perf_event_namespaces_output(struct perf_event * event,void * data)8941 static void perf_event_namespaces_output(struct perf_event *event,
8942 void *data)
8943 {
8944 struct perf_namespaces_event *namespaces_event = data;
8945 struct perf_output_handle handle;
8946 struct perf_sample_data sample;
8947 u16 header_size = namespaces_event->event_id.header.size;
8948 int ret;
8949
8950 if (!perf_event_namespaces_match(event))
8951 return;
8952
8953 perf_event_header__init_id(&namespaces_event->event_id.header,
8954 &sample, event);
8955 ret = perf_output_begin(&handle, &sample, event,
8956 namespaces_event->event_id.header.size);
8957 if (ret)
8958 goto out;
8959
8960 namespaces_event->event_id.pid = perf_event_pid(event,
8961 namespaces_event->task);
8962 namespaces_event->event_id.tid = perf_event_tid(event,
8963 namespaces_event->task);
8964
8965 perf_output_put(&handle, namespaces_event->event_id);
8966
8967 perf_event__output_id_sample(event, &handle, &sample);
8968
8969 perf_output_end(&handle);
8970 out:
8971 namespaces_event->event_id.header.size = header_size;
8972 }
8973
perf_fill_ns_link_info(struct perf_ns_link_info * ns_link_info,struct task_struct * task,const struct proc_ns_operations * ns_ops)8974 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
8975 struct task_struct *task,
8976 const struct proc_ns_operations *ns_ops)
8977 {
8978 struct path ns_path;
8979 struct inode *ns_inode;
8980 int error;
8981
8982 error = ns_get_path(&ns_path, task, ns_ops);
8983 if (!error) {
8984 ns_inode = ns_path.dentry->d_inode;
8985 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
8986 ns_link_info->ino = ns_inode->i_ino;
8987 path_put(&ns_path);
8988 }
8989 }
8990
perf_event_namespaces(struct task_struct * task)8991 void perf_event_namespaces(struct task_struct *task)
8992 {
8993 struct perf_namespaces_event namespaces_event;
8994 struct perf_ns_link_info *ns_link_info;
8995
8996 if (!atomic_read(&nr_namespaces_events))
8997 return;
8998
8999 namespaces_event = (struct perf_namespaces_event){
9000 .task = task,
9001 .event_id = {
9002 .header = {
9003 .type = PERF_RECORD_NAMESPACES,
9004 .misc = 0,
9005 .size = sizeof(namespaces_event.event_id),
9006 },
9007 /* .pid */
9008 /* .tid */
9009 .nr_namespaces = NR_NAMESPACES,
9010 /* .link_info[NR_NAMESPACES] */
9011 },
9012 };
9013
9014 ns_link_info = namespaces_event.event_id.link_info;
9015
9016 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
9017 task, &mntns_operations);
9018
9019 #ifdef CONFIG_USER_NS
9020 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
9021 task, &userns_operations);
9022 #endif
9023 #ifdef CONFIG_NET_NS
9024 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
9025 task, &netns_operations);
9026 #endif
9027 #ifdef CONFIG_UTS_NS
9028 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
9029 task, &utsns_operations);
9030 #endif
9031 #ifdef CONFIG_IPC_NS
9032 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
9033 task, &ipcns_operations);
9034 #endif
9035 #ifdef CONFIG_PID_NS
9036 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
9037 task, &pidns_operations);
9038 #endif
9039 #ifdef CONFIG_CGROUPS
9040 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
9041 task, &cgroupns_operations);
9042 #endif
9043
9044 perf_iterate_sb(perf_event_namespaces_output,
9045 &namespaces_event,
9046 NULL);
9047 }
9048
9049 /*
9050 * cgroup tracking
9051 */
9052 #ifdef CONFIG_CGROUP_PERF
9053
9054 struct perf_cgroup_event {
9055 char *path;
9056 int path_size;
9057 struct {
9058 struct perf_event_header header;
9059 u64 id;
9060 char path[];
9061 } event_id;
9062 };
9063
perf_event_cgroup_match(struct perf_event * event)9064 static int perf_event_cgroup_match(struct perf_event *event)
9065 {
9066 return event->attr.cgroup;
9067 }
9068
perf_event_cgroup_output(struct perf_event * event,void * data)9069 static void perf_event_cgroup_output(struct perf_event *event, void *data)
9070 {
9071 struct perf_cgroup_event *cgroup_event = data;
9072 struct perf_output_handle handle;
9073 struct perf_sample_data sample;
9074 u16 header_size = cgroup_event->event_id.header.size;
9075 int ret;
9076
9077 if (!perf_event_cgroup_match(event))
9078 return;
9079
9080 perf_event_header__init_id(&cgroup_event->event_id.header,
9081 &sample, event);
9082 ret = perf_output_begin(&handle, &sample, event,
9083 cgroup_event->event_id.header.size);
9084 if (ret)
9085 goto out;
9086
9087 perf_output_put(&handle, cgroup_event->event_id);
9088 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
9089
9090 perf_event__output_id_sample(event, &handle, &sample);
9091
9092 perf_output_end(&handle);
9093 out:
9094 cgroup_event->event_id.header.size = header_size;
9095 }
9096
perf_event_cgroup(struct cgroup * cgrp)9097 static void perf_event_cgroup(struct cgroup *cgrp)
9098 {
9099 struct perf_cgroup_event cgroup_event;
9100 char path_enomem[16] = "//enomem";
9101 char *pathname;
9102 size_t size;
9103
9104 if (!atomic_read(&nr_cgroup_events))
9105 return;
9106
9107 cgroup_event = (struct perf_cgroup_event){
9108 .event_id = {
9109 .header = {
9110 .type = PERF_RECORD_CGROUP,
9111 .misc = 0,
9112 .size = sizeof(cgroup_event.event_id),
9113 },
9114 .id = cgroup_id(cgrp),
9115 },
9116 };
9117
9118 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
9119 if (pathname == NULL) {
9120 cgroup_event.path = path_enomem;
9121 } else {
9122 /* just to be sure to have enough space for alignment */
9123 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
9124 cgroup_event.path = pathname;
9125 }
9126
9127 /*
9128 * Since our buffer works in 8 byte units we need to align our string
9129 * size to a multiple of 8. However, we must guarantee the tail end is
9130 * zero'd out to avoid leaking random bits to userspace.
9131 */
9132 size = strlen(cgroup_event.path) + 1;
9133 while (!IS_ALIGNED(size, sizeof(u64)))
9134 cgroup_event.path[size++] = '\0';
9135
9136 cgroup_event.event_id.header.size += size;
9137 cgroup_event.path_size = size;
9138
9139 perf_iterate_sb(perf_event_cgroup_output,
9140 &cgroup_event,
9141 NULL);
9142
9143 kfree(pathname);
9144 }
9145
9146 #endif
9147
9148 /*
9149 * mmap tracking
9150 */
9151
9152 struct perf_mmap_event {
9153 struct vm_area_struct *vma;
9154
9155 const char *file_name;
9156 int file_size;
9157 int maj, min;
9158 u64 ino;
9159 u64 ino_generation;
9160 u32 prot, flags;
9161 u8 build_id[BUILD_ID_SIZE_MAX];
9162 u32 build_id_size;
9163
9164 struct {
9165 struct perf_event_header header;
9166
9167 u32 pid;
9168 u32 tid;
9169 u64 start;
9170 u64 len;
9171 u64 pgoff;
9172 } event_id;
9173 };
9174
perf_event_mmap_match(struct perf_event * event,void * data)9175 static int perf_event_mmap_match(struct perf_event *event,
9176 void *data)
9177 {
9178 struct perf_mmap_event *mmap_event = data;
9179 struct vm_area_struct *vma = mmap_event->vma;
9180 int executable = vma->vm_flags & VM_EXEC;
9181
9182 return (!executable && event->attr.mmap_data) ||
9183 (executable && (event->attr.mmap || event->attr.mmap2));
9184 }
9185
perf_event_mmap_output(struct perf_event * event,void * data)9186 static void perf_event_mmap_output(struct perf_event *event,
9187 void *data)
9188 {
9189 struct perf_mmap_event *mmap_event = data;
9190 struct perf_output_handle handle;
9191 struct perf_sample_data sample;
9192 int size = mmap_event->event_id.header.size;
9193 u32 type = mmap_event->event_id.header.type;
9194 bool use_build_id;
9195 int ret;
9196
9197 if (!perf_event_mmap_match(event, data))
9198 return;
9199
9200 if (event->attr.mmap2) {
9201 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
9202 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
9203 mmap_event->event_id.header.size += sizeof(mmap_event->min);
9204 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
9205 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
9206 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
9207 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
9208 }
9209
9210 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
9211 ret = perf_output_begin(&handle, &sample, event,
9212 mmap_event->event_id.header.size);
9213 if (ret)
9214 goto out;
9215
9216 mmap_event->event_id.pid = perf_event_pid(event, current);
9217 mmap_event->event_id.tid = perf_event_tid(event, current);
9218
9219 use_build_id = event->attr.build_id && mmap_event->build_id_size;
9220
9221 if (event->attr.mmap2 && use_build_id)
9222 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID;
9223
9224 perf_output_put(&handle, mmap_event->event_id);
9225
9226 if (event->attr.mmap2) {
9227 if (use_build_id) {
9228 u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 };
9229
9230 __output_copy(&handle, size, 4);
9231 __output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX);
9232 } else {
9233 perf_output_put(&handle, mmap_event->maj);
9234 perf_output_put(&handle, mmap_event->min);
9235 perf_output_put(&handle, mmap_event->ino);
9236 perf_output_put(&handle, mmap_event->ino_generation);
9237 }
9238 perf_output_put(&handle, mmap_event->prot);
9239 perf_output_put(&handle, mmap_event->flags);
9240 }
9241
9242 __output_copy(&handle, mmap_event->file_name,
9243 mmap_event->file_size);
9244
9245 perf_event__output_id_sample(event, &handle, &sample);
9246
9247 perf_output_end(&handle);
9248 out:
9249 mmap_event->event_id.header.size = size;
9250 mmap_event->event_id.header.type = type;
9251 }
9252
perf_event_mmap_event(struct perf_mmap_event * mmap_event)9253 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
9254 {
9255 struct vm_area_struct *vma = mmap_event->vma;
9256 struct file *file = vma->vm_file;
9257 int maj = 0, min = 0;
9258 u64 ino = 0, gen = 0;
9259 u32 prot = 0, flags = 0;
9260 unsigned int size;
9261 char tmp[16];
9262 char *buf = NULL;
9263 char *name = NULL;
9264
9265 if (vma->vm_flags & VM_READ)
9266 prot |= PROT_READ;
9267 if (vma->vm_flags & VM_WRITE)
9268 prot |= PROT_WRITE;
9269 if (vma->vm_flags & VM_EXEC)
9270 prot |= PROT_EXEC;
9271
9272 if (vma->vm_flags & VM_MAYSHARE)
9273 flags = MAP_SHARED;
9274 else
9275 flags = MAP_PRIVATE;
9276
9277 if (vma->vm_flags & VM_LOCKED)
9278 flags |= MAP_LOCKED;
9279 if (is_vm_hugetlb_page(vma))
9280 flags |= MAP_HUGETLB;
9281
9282 if (file) {
9283 struct inode *inode;
9284 dev_t dev;
9285
9286 buf = kmalloc(PATH_MAX, GFP_KERNEL);
9287 if (!buf) {
9288 name = "//enomem";
9289 goto cpy_name;
9290 }
9291 /*
9292 * d_path() works from the end of the rb backwards, so we
9293 * need to add enough zero bytes after the string to handle
9294 * the 64bit alignment we do later.
9295 */
9296 name = file_path(file, buf, PATH_MAX - sizeof(u64));
9297 if (IS_ERR(name)) {
9298 name = "//toolong";
9299 goto cpy_name;
9300 }
9301 inode = file_inode(vma->vm_file);
9302 dev = inode->i_sb->s_dev;
9303 ino = inode->i_ino;
9304 gen = inode->i_generation;
9305 maj = MAJOR(dev);
9306 min = MINOR(dev);
9307
9308 goto got_name;
9309 } else {
9310 if (vma->vm_ops && vma->vm_ops->name)
9311 name = (char *) vma->vm_ops->name(vma);
9312 if (!name)
9313 name = (char *)arch_vma_name(vma);
9314 if (!name) {
9315 if (vma_is_initial_heap(vma))
9316 name = "[heap]";
9317 else if (vma_is_initial_stack(vma))
9318 name = "[stack]";
9319 else
9320 name = "//anon";
9321 }
9322 }
9323
9324 cpy_name:
9325 strscpy(tmp, name);
9326 name = tmp;
9327 got_name:
9328 /*
9329 * Since our buffer works in 8 byte units we need to align our string
9330 * size to a multiple of 8. However, we must guarantee the tail end is
9331 * zero'd out to avoid leaking random bits to userspace.
9332 */
9333 size = strlen(name)+1;
9334 while (!IS_ALIGNED(size, sizeof(u64)))
9335 name[size++] = '\0';
9336
9337 mmap_event->file_name = name;
9338 mmap_event->file_size = size;
9339 mmap_event->maj = maj;
9340 mmap_event->min = min;
9341 mmap_event->ino = ino;
9342 mmap_event->ino_generation = gen;
9343 mmap_event->prot = prot;
9344 mmap_event->flags = flags;
9345
9346 if (!(vma->vm_flags & VM_EXEC))
9347 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
9348
9349 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
9350
9351 if (atomic_read(&nr_build_id_events))
9352 build_id_parse_nofault(vma, mmap_event->build_id, &mmap_event->build_id_size);
9353
9354 perf_iterate_sb(perf_event_mmap_output,
9355 mmap_event,
9356 NULL);
9357
9358 kfree(buf);
9359 }
9360
9361 /*
9362 * Check whether inode and address range match filter criteria.
9363 */
perf_addr_filter_match(struct perf_addr_filter * filter,struct file * file,unsigned long offset,unsigned long size)9364 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
9365 struct file *file, unsigned long offset,
9366 unsigned long size)
9367 {
9368 /* d_inode(NULL) won't be equal to any mapped user-space file */
9369 if (!filter->path.dentry)
9370 return false;
9371
9372 if (d_inode(filter->path.dentry) != file_inode(file))
9373 return false;
9374
9375 if (filter->offset > offset + size)
9376 return false;
9377
9378 if (filter->offset + filter->size < offset)
9379 return false;
9380
9381 return true;
9382 }
9383
perf_addr_filter_vma_adjust(struct perf_addr_filter * filter,struct vm_area_struct * vma,struct perf_addr_filter_range * fr)9384 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
9385 struct vm_area_struct *vma,
9386 struct perf_addr_filter_range *fr)
9387 {
9388 unsigned long vma_size = vma->vm_end - vma->vm_start;
9389 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
9390 struct file *file = vma->vm_file;
9391
9392 if (!perf_addr_filter_match(filter, file, off, vma_size))
9393 return false;
9394
9395 if (filter->offset < off) {
9396 fr->start = vma->vm_start;
9397 fr->size = min(vma_size, filter->size - (off - filter->offset));
9398 } else {
9399 fr->start = vma->vm_start + filter->offset - off;
9400 fr->size = min(vma->vm_end - fr->start, filter->size);
9401 }
9402
9403 return true;
9404 }
9405
__perf_addr_filters_adjust(struct perf_event * event,void * data)9406 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
9407 {
9408 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
9409 struct vm_area_struct *vma = data;
9410 struct perf_addr_filter *filter;
9411 unsigned int restart = 0, count = 0;
9412 unsigned long flags;
9413
9414 if (!has_addr_filter(event))
9415 return;
9416
9417 if (!vma->vm_file)
9418 return;
9419
9420 raw_spin_lock_irqsave(&ifh->lock, flags);
9421 list_for_each_entry(filter, &ifh->list, entry) {
9422 if (perf_addr_filter_vma_adjust(filter, vma,
9423 &event->addr_filter_ranges[count]))
9424 restart++;
9425
9426 count++;
9427 }
9428
9429 if (restart)
9430 event->addr_filters_gen++;
9431 raw_spin_unlock_irqrestore(&ifh->lock, flags);
9432
9433 if (restart)
9434 perf_event_stop(event, 1);
9435 }
9436
9437 /*
9438 * Adjust all task's events' filters to the new vma
9439 */
perf_addr_filters_adjust(struct vm_area_struct * vma)9440 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
9441 {
9442 struct perf_event_context *ctx;
9443
9444 /*
9445 * Data tracing isn't supported yet and as such there is no need
9446 * to keep track of anything that isn't related to executable code:
9447 */
9448 if (!(vma->vm_flags & VM_EXEC))
9449 return;
9450
9451 rcu_read_lock();
9452 ctx = rcu_dereference(current->perf_event_ctxp);
9453 if (ctx)
9454 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
9455 rcu_read_unlock();
9456 }
9457
perf_event_mmap(struct vm_area_struct * vma)9458 void perf_event_mmap(struct vm_area_struct *vma)
9459 {
9460 struct perf_mmap_event mmap_event;
9461
9462 if (!atomic_read(&nr_mmap_events))
9463 return;
9464
9465 mmap_event = (struct perf_mmap_event){
9466 .vma = vma,
9467 /* .file_name */
9468 /* .file_size */
9469 .event_id = {
9470 .header = {
9471 .type = PERF_RECORD_MMAP,
9472 .misc = PERF_RECORD_MISC_USER,
9473 /* .size */
9474 },
9475 /* .pid */
9476 /* .tid */
9477 .start = vma->vm_start,
9478 .len = vma->vm_end - vma->vm_start,
9479 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
9480 },
9481 /* .maj (attr_mmap2 only) */
9482 /* .min (attr_mmap2 only) */
9483 /* .ino (attr_mmap2 only) */
9484 /* .ino_generation (attr_mmap2 only) */
9485 /* .prot (attr_mmap2 only) */
9486 /* .flags (attr_mmap2 only) */
9487 };
9488
9489 perf_addr_filters_adjust(vma);
9490 perf_event_mmap_event(&mmap_event);
9491 }
9492
perf_event_aux_event(struct perf_event * event,unsigned long head,unsigned long size,u64 flags)9493 void perf_event_aux_event(struct perf_event *event, unsigned long head,
9494 unsigned long size, u64 flags)
9495 {
9496 struct perf_output_handle handle;
9497 struct perf_sample_data sample;
9498 struct perf_aux_event {
9499 struct perf_event_header header;
9500 u64 offset;
9501 u64 size;
9502 u64 flags;
9503 } rec = {
9504 .header = {
9505 .type = PERF_RECORD_AUX,
9506 .misc = 0,
9507 .size = sizeof(rec),
9508 },
9509 .offset = head,
9510 .size = size,
9511 .flags = flags,
9512 };
9513 int ret;
9514
9515 perf_event_header__init_id(&rec.header, &sample, event);
9516 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
9517
9518 if (ret)
9519 return;
9520
9521 perf_output_put(&handle, rec);
9522 perf_event__output_id_sample(event, &handle, &sample);
9523
9524 perf_output_end(&handle);
9525 }
9526
9527 /*
9528 * Lost/dropped samples logging
9529 */
perf_log_lost_samples(struct perf_event * event,u64 lost)9530 void perf_log_lost_samples(struct perf_event *event, u64 lost)
9531 {
9532 struct perf_output_handle handle;
9533 struct perf_sample_data sample;
9534 int ret;
9535
9536 struct {
9537 struct perf_event_header header;
9538 u64 lost;
9539 } lost_samples_event = {
9540 .header = {
9541 .type = PERF_RECORD_LOST_SAMPLES,
9542 .misc = 0,
9543 .size = sizeof(lost_samples_event),
9544 },
9545 .lost = lost,
9546 };
9547
9548 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
9549
9550 ret = perf_output_begin(&handle, &sample, event,
9551 lost_samples_event.header.size);
9552 if (ret)
9553 return;
9554
9555 perf_output_put(&handle, lost_samples_event);
9556 perf_event__output_id_sample(event, &handle, &sample);
9557 perf_output_end(&handle);
9558 }
9559
9560 /*
9561 * context_switch tracking
9562 */
9563
9564 struct perf_switch_event {
9565 struct task_struct *task;
9566 struct task_struct *next_prev;
9567
9568 struct {
9569 struct perf_event_header header;
9570 u32 next_prev_pid;
9571 u32 next_prev_tid;
9572 } event_id;
9573 };
9574
perf_event_switch_match(struct perf_event * event)9575 static int perf_event_switch_match(struct perf_event *event)
9576 {
9577 return event->attr.context_switch;
9578 }
9579
perf_event_switch_output(struct perf_event * event,void * data)9580 static void perf_event_switch_output(struct perf_event *event, void *data)
9581 {
9582 struct perf_switch_event *se = data;
9583 struct perf_output_handle handle;
9584 struct perf_sample_data sample;
9585 int ret;
9586
9587 if (!perf_event_switch_match(event))
9588 return;
9589
9590 /* Only CPU-wide events are allowed to see next/prev pid/tid */
9591 if (event->ctx->task) {
9592 se->event_id.header.type = PERF_RECORD_SWITCH;
9593 se->event_id.header.size = sizeof(se->event_id.header);
9594 } else {
9595 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
9596 se->event_id.header.size = sizeof(se->event_id);
9597 se->event_id.next_prev_pid =
9598 perf_event_pid(event, se->next_prev);
9599 se->event_id.next_prev_tid =
9600 perf_event_tid(event, se->next_prev);
9601 }
9602
9603 perf_event_header__init_id(&se->event_id.header, &sample, event);
9604
9605 ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size);
9606 if (ret)
9607 return;
9608
9609 if (event->ctx->task)
9610 perf_output_put(&handle, se->event_id.header);
9611 else
9612 perf_output_put(&handle, se->event_id);
9613
9614 perf_event__output_id_sample(event, &handle, &sample);
9615
9616 perf_output_end(&handle);
9617 }
9618
perf_event_switch(struct task_struct * task,struct task_struct * next_prev,bool sched_in)9619 static void perf_event_switch(struct task_struct *task,
9620 struct task_struct *next_prev, bool sched_in)
9621 {
9622 struct perf_switch_event switch_event;
9623
9624 /* N.B. caller checks nr_switch_events != 0 */
9625
9626 switch_event = (struct perf_switch_event){
9627 .task = task,
9628 .next_prev = next_prev,
9629 .event_id = {
9630 .header = {
9631 /* .type */
9632 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
9633 /* .size */
9634 },
9635 /* .next_prev_pid */
9636 /* .next_prev_tid */
9637 },
9638 };
9639
9640 if (!sched_in && task_is_runnable(task)) {
9641 switch_event.event_id.header.misc |=
9642 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
9643 }
9644
9645 perf_iterate_sb(perf_event_switch_output, &switch_event, NULL);
9646 }
9647
9648 /*
9649 * IRQ throttle logging
9650 */
9651
perf_log_throttle(struct perf_event * event,int enable)9652 static void perf_log_throttle(struct perf_event *event, int enable)
9653 {
9654 struct perf_output_handle handle;
9655 struct perf_sample_data sample;
9656 int ret;
9657
9658 struct {
9659 struct perf_event_header header;
9660 u64 time;
9661 u64 id;
9662 u64 stream_id;
9663 } throttle_event = {
9664 .header = {
9665 .type = PERF_RECORD_THROTTLE,
9666 .misc = 0,
9667 .size = sizeof(throttle_event),
9668 },
9669 .time = perf_event_clock(event),
9670 .id = primary_event_id(event),
9671 .stream_id = event->id,
9672 };
9673
9674 if (enable)
9675 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
9676
9677 perf_event_header__init_id(&throttle_event.header, &sample, event);
9678
9679 ret = perf_output_begin(&handle, &sample, event,
9680 throttle_event.header.size);
9681 if (ret)
9682 return;
9683
9684 perf_output_put(&handle, throttle_event);
9685 perf_event__output_id_sample(event, &handle, &sample);
9686 perf_output_end(&handle);
9687 }
9688
9689 /*
9690 * ksymbol register/unregister tracking
9691 */
9692
9693 struct perf_ksymbol_event {
9694 const char *name;
9695 int name_len;
9696 struct {
9697 struct perf_event_header header;
9698 u64 addr;
9699 u32 len;
9700 u16 ksym_type;
9701 u16 flags;
9702 } event_id;
9703 };
9704
perf_event_ksymbol_match(struct perf_event * event)9705 static int perf_event_ksymbol_match(struct perf_event *event)
9706 {
9707 return event->attr.ksymbol;
9708 }
9709
perf_event_ksymbol_output(struct perf_event * event,void * data)9710 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
9711 {
9712 struct perf_ksymbol_event *ksymbol_event = data;
9713 struct perf_output_handle handle;
9714 struct perf_sample_data sample;
9715 int ret;
9716
9717 if (!perf_event_ksymbol_match(event))
9718 return;
9719
9720 perf_event_header__init_id(&ksymbol_event->event_id.header,
9721 &sample, event);
9722 ret = perf_output_begin(&handle, &sample, event,
9723 ksymbol_event->event_id.header.size);
9724 if (ret)
9725 return;
9726
9727 perf_output_put(&handle, ksymbol_event->event_id);
9728 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
9729 perf_event__output_id_sample(event, &handle, &sample);
9730
9731 perf_output_end(&handle);
9732 }
9733
perf_event_ksymbol(u16 ksym_type,u64 addr,u32 len,bool unregister,const char * sym)9734 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
9735 const char *sym)
9736 {
9737 struct perf_ksymbol_event ksymbol_event;
9738 char name[KSYM_NAME_LEN];
9739 u16 flags = 0;
9740 int name_len;
9741
9742 if (!atomic_read(&nr_ksymbol_events))
9743 return;
9744
9745 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
9746 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
9747 goto err;
9748
9749 strscpy(name, sym);
9750 name_len = strlen(name) + 1;
9751 while (!IS_ALIGNED(name_len, sizeof(u64)))
9752 name[name_len++] = '\0';
9753 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
9754
9755 if (unregister)
9756 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
9757
9758 ksymbol_event = (struct perf_ksymbol_event){
9759 .name = name,
9760 .name_len = name_len,
9761 .event_id = {
9762 .header = {
9763 .type = PERF_RECORD_KSYMBOL,
9764 .size = sizeof(ksymbol_event.event_id) +
9765 name_len,
9766 },
9767 .addr = addr,
9768 .len = len,
9769 .ksym_type = ksym_type,
9770 .flags = flags,
9771 },
9772 };
9773
9774 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
9775 return;
9776 err:
9777 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
9778 }
9779
9780 /*
9781 * bpf program load/unload tracking
9782 */
9783
9784 struct perf_bpf_event {
9785 struct bpf_prog *prog;
9786 struct {
9787 struct perf_event_header header;
9788 u16 type;
9789 u16 flags;
9790 u32 id;
9791 u8 tag[BPF_TAG_SIZE];
9792 } event_id;
9793 };
9794
perf_event_bpf_match(struct perf_event * event)9795 static int perf_event_bpf_match(struct perf_event *event)
9796 {
9797 return event->attr.bpf_event;
9798 }
9799
perf_event_bpf_output(struct perf_event * event,void * data)9800 static void perf_event_bpf_output(struct perf_event *event, void *data)
9801 {
9802 struct perf_bpf_event *bpf_event = data;
9803 struct perf_output_handle handle;
9804 struct perf_sample_data sample;
9805 int ret;
9806
9807 if (!perf_event_bpf_match(event))
9808 return;
9809
9810 perf_event_header__init_id(&bpf_event->event_id.header,
9811 &sample, event);
9812 ret = perf_output_begin(&handle, &sample, event,
9813 bpf_event->event_id.header.size);
9814 if (ret)
9815 return;
9816
9817 perf_output_put(&handle, bpf_event->event_id);
9818 perf_event__output_id_sample(event, &handle, &sample);
9819
9820 perf_output_end(&handle);
9821 }
9822
perf_event_bpf_emit_ksymbols(struct bpf_prog * prog,enum perf_bpf_event_type type)9823 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
9824 enum perf_bpf_event_type type)
9825 {
9826 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
9827 int i;
9828
9829 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
9830 (u64)(unsigned long)prog->bpf_func,
9831 prog->jited_len, unregister,
9832 prog->aux->ksym.name);
9833
9834 for (i = 1; i < prog->aux->func_cnt; i++) {
9835 struct bpf_prog *subprog = prog->aux->func[i];
9836
9837 perf_event_ksymbol(
9838 PERF_RECORD_KSYMBOL_TYPE_BPF,
9839 (u64)(unsigned long)subprog->bpf_func,
9840 subprog->jited_len, unregister,
9841 subprog->aux->ksym.name);
9842 }
9843 }
9844
perf_event_bpf_event(struct bpf_prog * prog,enum perf_bpf_event_type type,u16 flags)9845 void perf_event_bpf_event(struct bpf_prog *prog,
9846 enum perf_bpf_event_type type,
9847 u16 flags)
9848 {
9849 struct perf_bpf_event bpf_event;
9850
9851 switch (type) {
9852 case PERF_BPF_EVENT_PROG_LOAD:
9853 case PERF_BPF_EVENT_PROG_UNLOAD:
9854 if (atomic_read(&nr_ksymbol_events))
9855 perf_event_bpf_emit_ksymbols(prog, type);
9856 break;
9857 default:
9858 return;
9859 }
9860
9861 if (!atomic_read(&nr_bpf_events))
9862 return;
9863
9864 bpf_event = (struct perf_bpf_event){
9865 .prog = prog,
9866 .event_id = {
9867 .header = {
9868 .type = PERF_RECORD_BPF_EVENT,
9869 .size = sizeof(bpf_event.event_id),
9870 },
9871 .type = type,
9872 .flags = flags,
9873 .id = prog->aux->id,
9874 },
9875 };
9876
9877 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
9878
9879 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
9880 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
9881 }
9882
9883 struct perf_text_poke_event {
9884 const void *old_bytes;
9885 const void *new_bytes;
9886 size_t pad;
9887 u16 old_len;
9888 u16 new_len;
9889
9890 struct {
9891 struct perf_event_header header;
9892
9893 u64 addr;
9894 } event_id;
9895 };
9896
perf_event_text_poke_match(struct perf_event * event)9897 static int perf_event_text_poke_match(struct perf_event *event)
9898 {
9899 return event->attr.text_poke;
9900 }
9901
perf_event_text_poke_output(struct perf_event * event,void * data)9902 static void perf_event_text_poke_output(struct perf_event *event, void *data)
9903 {
9904 struct perf_text_poke_event *text_poke_event = data;
9905 struct perf_output_handle handle;
9906 struct perf_sample_data sample;
9907 u64 padding = 0;
9908 int ret;
9909
9910 if (!perf_event_text_poke_match(event))
9911 return;
9912
9913 perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
9914
9915 ret = perf_output_begin(&handle, &sample, event,
9916 text_poke_event->event_id.header.size);
9917 if (ret)
9918 return;
9919
9920 perf_output_put(&handle, text_poke_event->event_id);
9921 perf_output_put(&handle, text_poke_event->old_len);
9922 perf_output_put(&handle, text_poke_event->new_len);
9923
9924 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
9925 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
9926
9927 if (text_poke_event->pad)
9928 __output_copy(&handle, &padding, text_poke_event->pad);
9929
9930 perf_event__output_id_sample(event, &handle, &sample);
9931
9932 perf_output_end(&handle);
9933 }
9934
perf_event_text_poke(const void * addr,const void * old_bytes,size_t old_len,const void * new_bytes,size_t new_len)9935 void perf_event_text_poke(const void *addr, const void *old_bytes,
9936 size_t old_len, const void *new_bytes, size_t new_len)
9937 {
9938 struct perf_text_poke_event text_poke_event;
9939 size_t tot, pad;
9940
9941 if (!atomic_read(&nr_text_poke_events))
9942 return;
9943
9944 tot = sizeof(text_poke_event.old_len) + old_len;
9945 tot += sizeof(text_poke_event.new_len) + new_len;
9946 pad = ALIGN(tot, sizeof(u64)) - tot;
9947
9948 text_poke_event = (struct perf_text_poke_event){
9949 .old_bytes = old_bytes,
9950 .new_bytes = new_bytes,
9951 .pad = pad,
9952 .old_len = old_len,
9953 .new_len = new_len,
9954 .event_id = {
9955 .header = {
9956 .type = PERF_RECORD_TEXT_POKE,
9957 .misc = PERF_RECORD_MISC_KERNEL,
9958 .size = sizeof(text_poke_event.event_id) + tot + pad,
9959 },
9960 .addr = (unsigned long)addr,
9961 },
9962 };
9963
9964 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
9965 }
9966
perf_event_itrace_started(struct perf_event * event)9967 void perf_event_itrace_started(struct perf_event *event)
9968 {
9969 event->attach_state |= PERF_ATTACH_ITRACE;
9970 }
9971
perf_log_itrace_start(struct perf_event * event)9972 static void perf_log_itrace_start(struct perf_event *event)
9973 {
9974 struct perf_output_handle handle;
9975 struct perf_sample_data sample;
9976 struct perf_aux_event {
9977 struct perf_event_header header;
9978 u32 pid;
9979 u32 tid;
9980 } rec;
9981 int ret;
9982
9983 if (event->parent)
9984 event = event->parent;
9985
9986 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
9987 event->attach_state & PERF_ATTACH_ITRACE)
9988 return;
9989
9990 rec.header.type = PERF_RECORD_ITRACE_START;
9991 rec.header.misc = 0;
9992 rec.header.size = sizeof(rec);
9993 rec.pid = perf_event_pid(event, current);
9994 rec.tid = perf_event_tid(event, current);
9995
9996 perf_event_header__init_id(&rec.header, &sample, event);
9997 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
9998
9999 if (ret)
10000 return;
10001
10002 perf_output_put(&handle, rec);
10003 perf_event__output_id_sample(event, &handle, &sample);
10004
10005 perf_output_end(&handle);
10006 }
10007
perf_report_aux_output_id(struct perf_event * event,u64 hw_id)10008 void perf_report_aux_output_id(struct perf_event *event, u64 hw_id)
10009 {
10010 struct perf_output_handle handle;
10011 struct perf_sample_data sample;
10012 struct perf_aux_event {
10013 struct perf_event_header header;
10014 u64 hw_id;
10015 } rec;
10016 int ret;
10017
10018 if (event->parent)
10019 event = event->parent;
10020
10021 rec.header.type = PERF_RECORD_AUX_OUTPUT_HW_ID;
10022 rec.header.misc = 0;
10023 rec.header.size = sizeof(rec);
10024 rec.hw_id = hw_id;
10025
10026 perf_event_header__init_id(&rec.header, &sample, event);
10027 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
10028
10029 if (ret)
10030 return;
10031
10032 perf_output_put(&handle, rec);
10033 perf_event__output_id_sample(event, &handle, &sample);
10034
10035 perf_output_end(&handle);
10036 }
10037 EXPORT_SYMBOL_GPL(perf_report_aux_output_id);
10038
10039 static int
__perf_event_account_interrupt(struct perf_event * event,int throttle)10040 __perf_event_account_interrupt(struct perf_event *event, int throttle)
10041 {
10042 struct hw_perf_event *hwc = &event->hw;
10043 int ret = 0;
10044 u64 seq;
10045
10046 seq = __this_cpu_read(perf_throttled_seq);
10047 if (seq != hwc->interrupts_seq) {
10048 hwc->interrupts_seq = seq;
10049 hwc->interrupts = 1;
10050 } else {
10051 hwc->interrupts++;
10052 if (unlikely(throttle &&
10053 hwc->interrupts > max_samples_per_tick)) {
10054 __this_cpu_inc(perf_throttled_count);
10055 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
10056 hwc->interrupts = MAX_INTERRUPTS;
10057 perf_log_throttle(event, 0);
10058 ret = 1;
10059 }
10060 }
10061
10062 if (event->attr.freq) {
10063 u64 now = perf_clock();
10064 s64 delta = now - hwc->freq_time_stamp;
10065
10066 hwc->freq_time_stamp = now;
10067
10068 if (delta > 0 && delta < 2*TICK_NSEC)
10069 perf_adjust_period(event, delta, hwc->last_period, true);
10070 }
10071
10072 return ret;
10073 }
10074
perf_event_account_interrupt(struct perf_event * event)10075 int perf_event_account_interrupt(struct perf_event *event)
10076 {
10077 return __perf_event_account_interrupt(event, 1);
10078 }
10079
sample_is_allowed(struct perf_event * event,struct pt_regs * regs)10080 static inline bool sample_is_allowed(struct perf_event *event, struct pt_regs *regs)
10081 {
10082 /*
10083 * Due to interrupt latency (AKA "skid"), we may enter the
10084 * kernel before taking an overflow, even if the PMU is only
10085 * counting user events.
10086 */
10087 if (event->attr.exclude_kernel && !user_mode(regs))
10088 return false;
10089
10090 return true;
10091 }
10092
10093 #ifdef CONFIG_BPF_SYSCALL
bpf_overflow_handler(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)10094 static int bpf_overflow_handler(struct perf_event *event,
10095 struct perf_sample_data *data,
10096 struct pt_regs *regs)
10097 {
10098 struct bpf_perf_event_data_kern ctx = {
10099 .data = data,
10100 .event = event,
10101 };
10102 struct bpf_prog *prog;
10103 int ret = 0;
10104
10105 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
10106 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
10107 goto out;
10108 rcu_read_lock();
10109 prog = READ_ONCE(event->prog);
10110 if (prog) {
10111 perf_prepare_sample(data, event, regs);
10112 ret = bpf_prog_run(prog, &ctx);
10113 }
10114 rcu_read_unlock();
10115 out:
10116 __this_cpu_dec(bpf_prog_active);
10117
10118 return ret;
10119 }
10120
perf_event_set_bpf_handler(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)10121 static inline int perf_event_set_bpf_handler(struct perf_event *event,
10122 struct bpf_prog *prog,
10123 u64 bpf_cookie)
10124 {
10125 if (event->overflow_handler_context)
10126 /* hw breakpoint or kernel counter */
10127 return -EINVAL;
10128
10129 if (event->prog)
10130 return -EEXIST;
10131
10132 if (prog->type != BPF_PROG_TYPE_PERF_EVENT)
10133 return -EINVAL;
10134
10135 if (event->attr.precise_ip &&
10136 prog->call_get_stack &&
10137 (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) ||
10138 event->attr.exclude_callchain_kernel ||
10139 event->attr.exclude_callchain_user)) {
10140 /*
10141 * On perf_event with precise_ip, calling bpf_get_stack()
10142 * may trigger unwinder warnings and occasional crashes.
10143 * bpf_get_[stack|stackid] works around this issue by using
10144 * callchain attached to perf_sample_data. If the
10145 * perf_event does not full (kernel and user) callchain
10146 * attached to perf_sample_data, do not allow attaching BPF
10147 * program that calls bpf_get_[stack|stackid].
10148 */
10149 return -EPROTO;
10150 }
10151
10152 event->prog = prog;
10153 event->bpf_cookie = bpf_cookie;
10154 return 0;
10155 }
10156
perf_event_free_bpf_handler(struct perf_event * event)10157 static inline void perf_event_free_bpf_handler(struct perf_event *event)
10158 {
10159 struct bpf_prog *prog = event->prog;
10160
10161 if (!prog)
10162 return;
10163
10164 event->prog = NULL;
10165 bpf_prog_put(prog);
10166 }
10167 #else
bpf_overflow_handler(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)10168 static inline int bpf_overflow_handler(struct perf_event *event,
10169 struct perf_sample_data *data,
10170 struct pt_regs *regs)
10171 {
10172 return 1;
10173 }
10174
perf_event_set_bpf_handler(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)10175 static inline int perf_event_set_bpf_handler(struct perf_event *event,
10176 struct bpf_prog *prog,
10177 u64 bpf_cookie)
10178 {
10179 return -EOPNOTSUPP;
10180 }
10181
perf_event_free_bpf_handler(struct perf_event * event)10182 static inline void perf_event_free_bpf_handler(struct perf_event *event)
10183 {
10184 }
10185 #endif
10186
10187 /*
10188 * Generic event overflow handling, sampling.
10189 */
10190
__perf_event_overflow(struct perf_event * event,int throttle,struct perf_sample_data * data,struct pt_regs * regs)10191 static int __perf_event_overflow(struct perf_event *event,
10192 int throttle, struct perf_sample_data *data,
10193 struct pt_regs *regs)
10194 {
10195 int events = atomic_read(&event->event_limit);
10196 int ret = 0;
10197
10198 /*
10199 * Non-sampling counters might still use the PMI to fold short
10200 * hardware counters, ignore those.
10201 */
10202 if (unlikely(!is_sampling_event(event)))
10203 return 0;
10204
10205 ret = __perf_event_account_interrupt(event, throttle);
10206
10207 if (event->attr.aux_pause)
10208 perf_event_aux_pause(event->aux_event, true);
10209
10210 if (event->prog && event->prog->type == BPF_PROG_TYPE_PERF_EVENT &&
10211 !bpf_overflow_handler(event, data, regs))
10212 goto out;
10213
10214 /*
10215 * XXX event_limit might not quite work as expected on inherited
10216 * events
10217 */
10218
10219 event->pending_kill = POLL_IN;
10220 if (events && atomic_dec_and_test(&event->event_limit)) {
10221 ret = 1;
10222 event->pending_kill = POLL_HUP;
10223 perf_event_disable_inatomic(event);
10224 }
10225
10226 if (event->attr.sigtrap) {
10227 /*
10228 * The desired behaviour of sigtrap vs invalid samples is a bit
10229 * tricky; on the one hand, one should not loose the SIGTRAP if
10230 * it is the first event, on the other hand, we should also not
10231 * trigger the WARN or override the data address.
10232 */
10233 bool valid_sample = sample_is_allowed(event, regs);
10234 unsigned int pending_id = 1;
10235 enum task_work_notify_mode notify_mode;
10236
10237 if (regs)
10238 pending_id = hash32_ptr((void *)instruction_pointer(regs)) ?: 1;
10239
10240 notify_mode = in_nmi() ? TWA_NMI_CURRENT : TWA_RESUME;
10241
10242 if (!event->pending_work &&
10243 !task_work_add(current, &event->pending_task, notify_mode)) {
10244 event->pending_work = pending_id;
10245 local_inc(&event->ctx->nr_no_switch_fast);
10246
10247 event->pending_addr = 0;
10248 if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR))
10249 event->pending_addr = data->addr;
10250
10251 } else if (event->attr.exclude_kernel && valid_sample) {
10252 /*
10253 * Should not be able to return to user space without
10254 * consuming pending_work; with exceptions:
10255 *
10256 * 1. Where !exclude_kernel, events can overflow again
10257 * in the kernel without returning to user space.
10258 *
10259 * 2. Events that can overflow again before the IRQ-
10260 * work without user space progress (e.g. hrtimer).
10261 * To approximate progress (with false negatives),
10262 * check 32-bit hash of the current IP.
10263 */
10264 WARN_ON_ONCE(event->pending_work != pending_id);
10265 }
10266 }
10267
10268 READ_ONCE(event->overflow_handler)(event, data, regs);
10269
10270 if (*perf_event_fasync(event) && event->pending_kill) {
10271 event->pending_wakeup = 1;
10272 irq_work_queue(&event->pending_irq);
10273 }
10274 out:
10275 if (event->attr.aux_resume)
10276 perf_event_aux_pause(event->aux_event, false);
10277
10278 return ret;
10279 }
10280
perf_event_overflow(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)10281 int perf_event_overflow(struct perf_event *event,
10282 struct perf_sample_data *data,
10283 struct pt_regs *regs)
10284 {
10285 return __perf_event_overflow(event, 1, data, regs);
10286 }
10287
10288 /*
10289 * Generic software event infrastructure
10290 */
10291
10292 struct swevent_htable {
10293 struct swevent_hlist *swevent_hlist;
10294 struct mutex hlist_mutex;
10295 int hlist_refcount;
10296 };
10297 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
10298
10299 /*
10300 * We directly increment event->count and keep a second value in
10301 * event->hw.period_left to count intervals. This period event
10302 * is kept in the range [-sample_period, 0] so that we can use the
10303 * sign as trigger.
10304 */
10305
perf_swevent_set_period(struct perf_event * event)10306 u64 perf_swevent_set_period(struct perf_event *event)
10307 {
10308 struct hw_perf_event *hwc = &event->hw;
10309 u64 period = hwc->last_period;
10310 u64 nr, offset;
10311 s64 old, val;
10312
10313 hwc->last_period = hwc->sample_period;
10314
10315 old = local64_read(&hwc->period_left);
10316 do {
10317 val = old;
10318 if (val < 0)
10319 return 0;
10320
10321 nr = div64_u64(period + val, period);
10322 offset = nr * period;
10323 val -= offset;
10324 } while (!local64_try_cmpxchg(&hwc->period_left, &old, val));
10325
10326 return nr;
10327 }
10328
perf_swevent_overflow(struct perf_event * event,u64 overflow,struct perf_sample_data * data,struct pt_regs * regs)10329 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
10330 struct perf_sample_data *data,
10331 struct pt_regs *regs)
10332 {
10333 struct hw_perf_event *hwc = &event->hw;
10334 int throttle = 0;
10335
10336 if (!overflow)
10337 overflow = perf_swevent_set_period(event);
10338
10339 if (hwc->interrupts == MAX_INTERRUPTS)
10340 return;
10341
10342 for (; overflow; overflow--) {
10343 if (__perf_event_overflow(event, throttle,
10344 data, regs)) {
10345 /*
10346 * We inhibit the overflow from happening when
10347 * hwc->interrupts == MAX_INTERRUPTS.
10348 */
10349 break;
10350 }
10351 throttle = 1;
10352 }
10353 }
10354
perf_swevent_event(struct perf_event * event,u64 nr,struct perf_sample_data * data,struct pt_regs * regs)10355 static void perf_swevent_event(struct perf_event *event, u64 nr,
10356 struct perf_sample_data *data,
10357 struct pt_regs *regs)
10358 {
10359 struct hw_perf_event *hwc = &event->hw;
10360
10361 local64_add(nr, &event->count);
10362
10363 if (!regs)
10364 return;
10365
10366 if (!is_sampling_event(event))
10367 return;
10368
10369 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
10370 data->period = nr;
10371 return perf_swevent_overflow(event, 1, data, regs);
10372 } else
10373 data->period = event->hw.last_period;
10374
10375 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
10376 return perf_swevent_overflow(event, 1, data, regs);
10377
10378 if (local64_add_negative(nr, &hwc->period_left))
10379 return;
10380
10381 perf_swevent_overflow(event, 0, data, regs);
10382 }
10383
perf_exclude_event(struct perf_event * event,struct pt_regs * regs)10384 int perf_exclude_event(struct perf_event *event, struct pt_regs *regs)
10385 {
10386 if (event->hw.state & PERF_HES_STOPPED)
10387 return 1;
10388
10389 if (regs) {
10390 if (event->attr.exclude_user && user_mode(regs))
10391 return 1;
10392
10393 if (event->attr.exclude_kernel && !user_mode(regs))
10394 return 1;
10395 }
10396
10397 return 0;
10398 }
10399
perf_swevent_match(struct perf_event * event,enum perf_type_id type,u32 event_id,struct perf_sample_data * data,struct pt_regs * regs)10400 static int perf_swevent_match(struct perf_event *event,
10401 enum perf_type_id type,
10402 u32 event_id,
10403 struct perf_sample_data *data,
10404 struct pt_regs *regs)
10405 {
10406 if (event->attr.type != type)
10407 return 0;
10408
10409 if (event->attr.config != event_id)
10410 return 0;
10411
10412 if (perf_exclude_event(event, regs))
10413 return 0;
10414
10415 return 1;
10416 }
10417
swevent_hash(u64 type,u32 event_id)10418 static inline u64 swevent_hash(u64 type, u32 event_id)
10419 {
10420 u64 val = event_id | (type << 32);
10421
10422 return hash_64(val, SWEVENT_HLIST_BITS);
10423 }
10424
10425 static inline struct hlist_head *
__find_swevent_head(struct swevent_hlist * hlist,u64 type,u32 event_id)10426 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
10427 {
10428 u64 hash = swevent_hash(type, event_id);
10429
10430 return &hlist->heads[hash];
10431 }
10432
10433 /* For the read side: events when they trigger */
10434 static inline struct hlist_head *
find_swevent_head_rcu(struct swevent_htable * swhash,u64 type,u32 event_id)10435 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
10436 {
10437 struct swevent_hlist *hlist;
10438
10439 hlist = rcu_dereference(swhash->swevent_hlist);
10440 if (!hlist)
10441 return NULL;
10442
10443 return __find_swevent_head(hlist, type, event_id);
10444 }
10445
10446 /* For the event head insertion and removal in the hlist */
10447 static inline struct hlist_head *
find_swevent_head(struct swevent_htable * swhash,struct perf_event * event)10448 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
10449 {
10450 struct swevent_hlist *hlist;
10451 u32 event_id = event->attr.config;
10452 u64 type = event->attr.type;
10453
10454 /*
10455 * Event scheduling is always serialized against hlist allocation
10456 * and release. Which makes the protected version suitable here.
10457 * The context lock guarantees that.
10458 */
10459 hlist = rcu_dereference_protected(swhash->swevent_hlist,
10460 lockdep_is_held(&event->ctx->lock));
10461 if (!hlist)
10462 return NULL;
10463
10464 return __find_swevent_head(hlist, type, event_id);
10465 }
10466
do_perf_sw_event(enum perf_type_id type,u32 event_id,u64 nr,struct perf_sample_data * data,struct pt_regs * regs)10467 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
10468 u64 nr,
10469 struct perf_sample_data *data,
10470 struct pt_regs *regs)
10471 {
10472 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
10473 struct perf_event *event;
10474 struct hlist_head *head;
10475
10476 rcu_read_lock();
10477 head = find_swevent_head_rcu(swhash, type, event_id);
10478 if (!head)
10479 goto end;
10480
10481 hlist_for_each_entry_rcu(event, head, hlist_entry) {
10482 if (perf_swevent_match(event, type, event_id, data, regs))
10483 perf_swevent_event(event, nr, data, regs);
10484 }
10485 end:
10486 rcu_read_unlock();
10487 }
10488
10489 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
10490
perf_swevent_get_recursion_context(void)10491 int perf_swevent_get_recursion_context(void)
10492 {
10493 return get_recursion_context(current->perf_recursion);
10494 }
10495 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
10496
perf_swevent_put_recursion_context(int rctx)10497 void perf_swevent_put_recursion_context(int rctx)
10498 {
10499 put_recursion_context(current->perf_recursion, rctx);
10500 }
10501
___perf_sw_event(u32 event_id,u64 nr,struct pt_regs * regs,u64 addr)10502 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
10503 {
10504 struct perf_sample_data data;
10505
10506 if (WARN_ON_ONCE(!regs))
10507 return;
10508
10509 perf_sample_data_init(&data, addr, 0);
10510 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
10511 }
10512
__perf_sw_event(u32 event_id,u64 nr,struct pt_regs * regs,u64 addr)10513 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
10514 {
10515 int rctx;
10516
10517 preempt_disable_notrace();
10518 rctx = perf_swevent_get_recursion_context();
10519 if (unlikely(rctx < 0))
10520 goto fail;
10521
10522 ___perf_sw_event(event_id, nr, regs, addr);
10523
10524 perf_swevent_put_recursion_context(rctx);
10525 fail:
10526 preempt_enable_notrace();
10527 }
10528
perf_swevent_read(struct perf_event * event)10529 static void perf_swevent_read(struct perf_event *event)
10530 {
10531 }
10532
perf_swevent_add(struct perf_event * event,int flags)10533 static int perf_swevent_add(struct perf_event *event, int flags)
10534 {
10535 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
10536 struct hw_perf_event *hwc = &event->hw;
10537 struct hlist_head *head;
10538
10539 if (is_sampling_event(event)) {
10540 hwc->last_period = hwc->sample_period;
10541 perf_swevent_set_period(event);
10542 }
10543
10544 hwc->state = !(flags & PERF_EF_START);
10545
10546 head = find_swevent_head(swhash, event);
10547 if (WARN_ON_ONCE(!head))
10548 return -EINVAL;
10549
10550 hlist_add_head_rcu(&event->hlist_entry, head);
10551 perf_event_update_userpage(event);
10552
10553 return 0;
10554 }
10555
perf_swevent_del(struct perf_event * event,int flags)10556 static void perf_swevent_del(struct perf_event *event, int flags)
10557 {
10558 hlist_del_rcu(&event->hlist_entry);
10559 }
10560
perf_swevent_start(struct perf_event * event,int flags)10561 static void perf_swevent_start(struct perf_event *event, int flags)
10562 {
10563 event->hw.state = 0;
10564 }
10565
perf_swevent_stop(struct perf_event * event,int flags)10566 static void perf_swevent_stop(struct perf_event *event, int flags)
10567 {
10568 event->hw.state = PERF_HES_STOPPED;
10569 }
10570
10571 /* Deref the hlist from the update side */
10572 static inline struct swevent_hlist *
swevent_hlist_deref(struct swevent_htable * swhash)10573 swevent_hlist_deref(struct swevent_htable *swhash)
10574 {
10575 return rcu_dereference_protected(swhash->swevent_hlist,
10576 lockdep_is_held(&swhash->hlist_mutex));
10577 }
10578
swevent_hlist_release(struct swevent_htable * swhash)10579 static void swevent_hlist_release(struct swevent_htable *swhash)
10580 {
10581 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
10582
10583 if (!hlist)
10584 return;
10585
10586 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
10587 kfree_rcu(hlist, rcu_head);
10588 }
10589
swevent_hlist_put_cpu(int cpu)10590 static void swevent_hlist_put_cpu(int cpu)
10591 {
10592 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
10593
10594 mutex_lock(&swhash->hlist_mutex);
10595
10596 if (!--swhash->hlist_refcount)
10597 swevent_hlist_release(swhash);
10598
10599 mutex_unlock(&swhash->hlist_mutex);
10600 }
10601
swevent_hlist_put(void)10602 static void swevent_hlist_put(void)
10603 {
10604 int cpu;
10605
10606 for_each_possible_cpu(cpu)
10607 swevent_hlist_put_cpu(cpu);
10608 }
10609
swevent_hlist_get_cpu(int cpu)10610 static int swevent_hlist_get_cpu(int cpu)
10611 {
10612 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
10613 int err = 0;
10614
10615 mutex_lock(&swhash->hlist_mutex);
10616 if (!swevent_hlist_deref(swhash) &&
10617 cpumask_test_cpu(cpu, perf_online_mask)) {
10618 struct swevent_hlist *hlist;
10619
10620 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
10621 if (!hlist) {
10622 err = -ENOMEM;
10623 goto exit;
10624 }
10625 rcu_assign_pointer(swhash->swevent_hlist, hlist);
10626 }
10627 swhash->hlist_refcount++;
10628 exit:
10629 mutex_unlock(&swhash->hlist_mutex);
10630
10631 return err;
10632 }
10633
swevent_hlist_get(void)10634 static int swevent_hlist_get(void)
10635 {
10636 int err, cpu, failed_cpu;
10637
10638 mutex_lock(&pmus_lock);
10639 for_each_possible_cpu(cpu) {
10640 err = swevent_hlist_get_cpu(cpu);
10641 if (err) {
10642 failed_cpu = cpu;
10643 goto fail;
10644 }
10645 }
10646 mutex_unlock(&pmus_lock);
10647 return 0;
10648 fail:
10649 for_each_possible_cpu(cpu) {
10650 if (cpu == failed_cpu)
10651 break;
10652 swevent_hlist_put_cpu(cpu);
10653 }
10654 mutex_unlock(&pmus_lock);
10655 return err;
10656 }
10657
10658 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
10659
sw_perf_event_destroy(struct perf_event * event)10660 static void sw_perf_event_destroy(struct perf_event *event)
10661 {
10662 u64 event_id = event->attr.config;
10663
10664 WARN_ON(event->parent);
10665
10666 static_key_slow_dec(&perf_swevent_enabled[event_id]);
10667 swevent_hlist_put();
10668 }
10669
10670 static struct pmu perf_cpu_clock; /* fwd declaration */
10671 static struct pmu perf_task_clock;
10672
perf_swevent_init(struct perf_event * event)10673 static int perf_swevent_init(struct perf_event *event)
10674 {
10675 u64 event_id = event->attr.config;
10676
10677 if (event->attr.type != PERF_TYPE_SOFTWARE)
10678 return -ENOENT;
10679
10680 /*
10681 * no branch sampling for software events
10682 */
10683 if (has_branch_stack(event))
10684 return -EOPNOTSUPP;
10685
10686 switch (event_id) {
10687 case PERF_COUNT_SW_CPU_CLOCK:
10688 event->attr.type = perf_cpu_clock.type;
10689 return -ENOENT;
10690 case PERF_COUNT_SW_TASK_CLOCK:
10691 event->attr.type = perf_task_clock.type;
10692 return -ENOENT;
10693
10694 default:
10695 break;
10696 }
10697
10698 if (event_id >= PERF_COUNT_SW_MAX)
10699 return -ENOENT;
10700
10701 if (!event->parent) {
10702 int err;
10703
10704 err = swevent_hlist_get();
10705 if (err)
10706 return err;
10707
10708 static_key_slow_inc(&perf_swevent_enabled[event_id]);
10709 event->destroy = sw_perf_event_destroy;
10710 }
10711
10712 return 0;
10713 }
10714
10715 static struct pmu perf_swevent = {
10716 .task_ctx_nr = perf_sw_context,
10717
10718 .capabilities = PERF_PMU_CAP_NO_NMI,
10719
10720 .event_init = perf_swevent_init,
10721 .add = perf_swevent_add,
10722 .del = perf_swevent_del,
10723 .start = perf_swevent_start,
10724 .stop = perf_swevent_stop,
10725 .read = perf_swevent_read,
10726 };
10727
10728 #ifdef CONFIG_EVENT_TRACING
10729
tp_perf_event_destroy(struct perf_event * event)10730 static void tp_perf_event_destroy(struct perf_event *event)
10731 {
10732 perf_trace_destroy(event);
10733 }
10734
perf_tp_event_init(struct perf_event * event)10735 static int perf_tp_event_init(struct perf_event *event)
10736 {
10737 int err;
10738
10739 if (event->attr.type != PERF_TYPE_TRACEPOINT)
10740 return -ENOENT;
10741
10742 /*
10743 * no branch sampling for tracepoint events
10744 */
10745 if (has_branch_stack(event))
10746 return -EOPNOTSUPP;
10747
10748 err = perf_trace_init(event);
10749 if (err)
10750 return err;
10751
10752 event->destroy = tp_perf_event_destroy;
10753
10754 return 0;
10755 }
10756
10757 static struct pmu perf_tracepoint = {
10758 .task_ctx_nr = perf_sw_context,
10759
10760 .event_init = perf_tp_event_init,
10761 .add = perf_trace_add,
10762 .del = perf_trace_del,
10763 .start = perf_swevent_start,
10764 .stop = perf_swevent_stop,
10765 .read = perf_swevent_read,
10766 };
10767
perf_tp_filter_match(struct perf_event * event,struct perf_raw_record * raw)10768 static int perf_tp_filter_match(struct perf_event *event,
10769 struct perf_raw_record *raw)
10770 {
10771 void *record = raw->frag.data;
10772
10773 /* only top level events have filters set */
10774 if (event->parent)
10775 event = event->parent;
10776
10777 if (likely(!event->filter) || filter_match_preds(event->filter, record))
10778 return 1;
10779 return 0;
10780 }
10781
perf_tp_event_match(struct perf_event * event,struct perf_raw_record * raw,struct pt_regs * regs)10782 static int perf_tp_event_match(struct perf_event *event,
10783 struct perf_raw_record *raw,
10784 struct pt_regs *regs)
10785 {
10786 if (event->hw.state & PERF_HES_STOPPED)
10787 return 0;
10788 /*
10789 * If exclude_kernel, only trace user-space tracepoints (uprobes)
10790 */
10791 if (event->attr.exclude_kernel && !user_mode(regs))
10792 return 0;
10793
10794 if (!perf_tp_filter_match(event, raw))
10795 return 0;
10796
10797 return 1;
10798 }
10799
perf_trace_run_bpf_submit(void * raw_data,int size,int rctx,struct trace_event_call * call,u64 count,struct pt_regs * regs,struct hlist_head * head,struct task_struct * task)10800 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
10801 struct trace_event_call *call, u64 count,
10802 struct pt_regs *regs, struct hlist_head *head,
10803 struct task_struct *task)
10804 {
10805 if (bpf_prog_array_valid(call)) {
10806 *(struct pt_regs **)raw_data = regs;
10807 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
10808 perf_swevent_put_recursion_context(rctx);
10809 return;
10810 }
10811 }
10812 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
10813 rctx, task);
10814 }
10815 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
10816
__perf_tp_event_target_task(u64 count,void * record,struct pt_regs * regs,struct perf_sample_data * data,struct perf_raw_record * raw,struct perf_event * event)10817 static void __perf_tp_event_target_task(u64 count, void *record,
10818 struct pt_regs *regs,
10819 struct perf_sample_data *data,
10820 struct perf_raw_record *raw,
10821 struct perf_event *event)
10822 {
10823 struct trace_entry *entry = record;
10824
10825 if (event->attr.config != entry->type)
10826 return;
10827 /* Cannot deliver synchronous signal to other task. */
10828 if (event->attr.sigtrap)
10829 return;
10830 if (perf_tp_event_match(event, raw, regs)) {
10831 perf_sample_data_init(data, 0, 0);
10832 perf_sample_save_raw_data(data, event, raw);
10833 perf_swevent_event(event, count, data, regs);
10834 }
10835 }
10836
perf_tp_event_target_task(u64 count,void * record,struct pt_regs * regs,struct perf_sample_data * data,struct perf_raw_record * raw,struct perf_event_context * ctx)10837 static void perf_tp_event_target_task(u64 count, void *record,
10838 struct pt_regs *regs,
10839 struct perf_sample_data *data,
10840 struct perf_raw_record *raw,
10841 struct perf_event_context *ctx)
10842 {
10843 unsigned int cpu = smp_processor_id();
10844 struct pmu *pmu = &perf_tracepoint;
10845 struct perf_event *event, *sibling;
10846
10847 perf_event_groups_for_cpu_pmu(event, &ctx->pinned_groups, cpu, pmu) {
10848 __perf_tp_event_target_task(count, record, regs, data, raw, event);
10849 for_each_sibling_event(sibling, event)
10850 __perf_tp_event_target_task(count, record, regs, data, raw, sibling);
10851 }
10852
10853 perf_event_groups_for_cpu_pmu(event, &ctx->flexible_groups, cpu, pmu) {
10854 __perf_tp_event_target_task(count, record, regs, data, raw, event);
10855 for_each_sibling_event(sibling, event)
10856 __perf_tp_event_target_task(count, record, regs, data, raw, sibling);
10857 }
10858 }
10859
perf_tp_event(u16 event_type,u64 count,void * record,int entry_size,struct pt_regs * regs,struct hlist_head * head,int rctx,struct task_struct * task)10860 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
10861 struct pt_regs *regs, struct hlist_head *head, int rctx,
10862 struct task_struct *task)
10863 {
10864 struct perf_sample_data data;
10865 struct perf_event *event;
10866
10867 struct perf_raw_record raw = {
10868 .frag = {
10869 .size = entry_size,
10870 .data = record,
10871 },
10872 };
10873
10874 perf_trace_buf_update(record, event_type);
10875
10876 hlist_for_each_entry_rcu(event, head, hlist_entry) {
10877 if (perf_tp_event_match(event, &raw, regs)) {
10878 /*
10879 * Here use the same on-stack perf_sample_data,
10880 * some members in data are event-specific and
10881 * need to be re-computed for different sweveents.
10882 * Re-initialize data->sample_flags safely to avoid
10883 * the problem that next event skips preparing data
10884 * because data->sample_flags is set.
10885 */
10886 perf_sample_data_init(&data, 0, 0);
10887 perf_sample_save_raw_data(&data, event, &raw);
10888 perf_swevent_event(event, count, &data, regs);
10889 }
10890 }
10891
10892 /*
10893 * If we got specified a target task, also iterate its context and
10894 * deliver this event there too.
10895 */
10896 if (task && task != current) {
10897 struct perf_event_context *ctx;
10898
10899 rcu_read_lock();
10900 ctx = rcu_dereference(task->perf_event_ctxp);
10901 if (!ctx)
10902 goto unlock;
10903
10904 raw_spin_lock(&ctx->lock);
10905 perf_tp_event_target_task(count, record, regs, &data, &raw, ctx);
10906 raw_spin_unlock(&ctx->lock);
10907 unlock:
10908 rcu_read_unlock();
10909 }
10910
10911 perf_swevent_put_recursion_context(rctx);
10912 }
10913 EXPORT_SYMBOL_GPL(perf_tp_event);
10914
10915 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
10916 /*
10917 * Flags in config, used by dynamic PMU kprobe and uprobe
10918 * The flags should match following PMU_FORMAT_ATTR().
10919 *
10920 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
10921 * if not set, create kprobe/uprobe
10922 *
10923 * The following values specify a reference counter (or semaphore in the
10924 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
10925 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
10926 *
10927 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
10928 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
10929 */
10930 enum perf_probe_config {
10931 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
10932 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
10933 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
10934 };
10935
10936 PMU_FORMAT_ATTR(retprobe, "config:0");
10937 #endif
10938
10939 #ifdef CONFIG_KPROBE_EVENTS
10940 static struct attribute *kprobe_attrs[] = {
10941 &format_attr_retprobe.attr,
10942 NULL,
10943 };
10944
10945 static struct attribute_group kprobe_format_group = {
10946 .name = "format",
10947 .attrs = kprobe_attrs,
10948 };
10949
10950 static const struct attribute_group *kprobe_attr_groups[] = {
10951 &kprobe_format_group,
10952 NULL,
10953 };
10954
10955 static int perf_kprobe_event_init(struct perf_event *event);
10956 static struct pmu perf_kprobe = {
10957 .task_ctx_nr = perf_sw_context,
10958 .event_init = perf_kprobe_event_init,
10959 .add = perf_trace_add,
10960 .del = perf_trace_del,
10961 .start = perf_swevent_start,
10962 .stop = perf_swevent_stop,
10963 .read = perf_swevent_read,
10964 .attr_groups = kprobe_attr_groups,
10965 };
10966
perf_kprobe_event_init(struct perf_event * event)10967 static int perf_kprobe_event_init(struct perf_event *event)
10968 {
10969 int err;
10970 bool is_retprobe;
10971
10972 if (event->attr.type != perf_kprobe.type)
10973 return -ENOENT;
10974
10975 if (!perfmon_capable())
10976 return -EACCES;
10977
10978 /*
10979 * no branch sampling for probe events
10980 */
10981 if (has_branch_stack(event))
10982 return -EOPNOTSUPP;
10983
10984 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
10985 err = perf_kprobe_init(event, is_retprobe);
10986 if (err)
10987 return err;
10988
10989 event->destroy = perf_kprobe_destroy;
10990
10991 return 0;
10992 }
10993 #endif /* CONFIG_KPROBE_EVENTS */
10994
10995 #ifdef CONFIG_UPROBE_EVENTS
10996 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
10997
10998 static struct attribute *uprobe_attrs[] = {
10999 &format_attr_retprobe.attr,
11000 &format_attr_ref_ctr_offset.attr,
11001 NULL,
11002 };
11003
11004 static struct attribute_group uprobe_format_group = {
11005 .name = "format",
11006 .attrs = uprobe_attrs,
11007 };
11008
11009 static const struct attribute_group *uprobe_attr_groups[] = {
11010 &uprobe_format_group,
11011 NULL,
11012 };
11013
11014 static int perf_uprobe_event_init(struct perf_event *event);
11015 static struct pmu perf_uprobe = {
11016 .task_ctx_nr = perf_sw_context,
11017 .event_init = perf_uprobe_event_init,
11018 .add = perf_trace_add,
11019 .del = perf_trace_del,
11020 .start = perf_swevent_start,
11021 .stop = perf_swevent_stop,
11022 .read = perf_swevent_read,
11023 .attr_groups = uprobe_attr_groups,
11024 };
11025
perf_uprobe_event_init(struct perf_event * event)11026 static int perf_uprobe_event_init(struct perf_event *event)
11027 {
11028 int err;
11029 unsigned long ref_ctr_offset;
11030 bool is_retprobe;
11031
11032 if (event->attr.type != perf_uprobe.type)
11033 return -ENOENT;
11034
11035 if (!perfmon_capable())
11036 return -EACCES;
11037
11038 /*
11039 * no branch sampling for probe events
11040 */
11041 if (has_branch_stack(event))
11042 return -EOPNOTSUPP;
11043
11044 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
11045 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
11046 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
11047 if (err)
11048 return err;
11049
11050 event->destroy = perf_uprobe_destroy;
11051
11052 return 0;
11053 }
11054 #endif /* CONFIG_UPROBE_EVENTS */
11055
perf_tp_register(void)11056 static inline void perf_tp_register(void)
11057 {
11058 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
11059 #ifdef CONFIG_KPROBE_EVENTS
11060 perf_pmu_register(&perf_kprobe, "kprobe", -1);
11061 #endif
11062 #ifdef CONFIG_UPROBE_EVENTS
11063 perf_pmu_register(&perf_uprobe, "uprobe", -1);
11064 #endif
11065 }
11066
perf_event_free_filter(struct perf_event * event)11067 static void perf_event_free_filter(struct perf_event *event)
11068 {
11069 ftrace_profile_free_filter(event);
11070 }
11071
11072 /*
11073 * returns true if the event is a tracepoint, or a kprobe/upprobe created
11074 * with perf_event_open()
11075 */
perf_event_is_tracing(struct perf_event * event)11076 static inline bool perf_event_is_tracing(struct perf_event *event)
11077 {
11078 if (event->pmu == &perf_tracepoint)
11079 return true;
11080 #ifdef CONFIG_KPROBE_EVENTS
11081 if (event->pmu == &perf_kprobe)
11082 return true;
11083 #endif
11084 #ifdef CONFIG_UPROBE_EVENTS
11085 if (event->pmu == &perf_uprobe)
11086 return true;
11087 #endif
11088 return false;
11089 }
11090
perf_event_set_bpf_prog(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)11091 int perf_event_set_bpf_prog(struct perf_event *event, struct bpf_prog *prog,
11092 u64 bpf_cookie)
11093 {
11094 bool is_kprobe, is_uprobe, is_tracepoint, is_syscall_tp;
11095
11096 if (!perf_event_is_tracing(event))
11097 return perf_event_set_bpf_handler(event, prog, bpf_cookie);
11098
11099 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_KPROBE;
11100 is_uprobe = event->tp_event->flags & TRACE_EVENT_FL_UPROBE;
11101 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
11102 is_syscall_tp = is_syscall_trace_event(event->tp_event);
11103 if (!is_kprobe && !is_uprobe && !is_tracepoint && !is_syscall_tp)
11104 /* bpf programs can only be attached to u/kprobe or tracepoint */
11105 return -EINVAL;
11106
11107 if (((is_kprobe || is_uprobe) && prog->type != BPF_PROG_TYPE_KPROBE) ||
11108 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
11109 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT))
11110 return -EINVAL;
11111
11112 if (prog->type == BPF_PROG_TYPE_KPROBE && prog->sleepable && !is_uprobe)
11113 /* only uprobe programs are allowed to be sleepable */
11114 return -EINVAL;
11115
11116 /* Kprobe override only works for kprobes, not uprobes. */
11117 if (prog->kprobe_override && !is_kprobe)
11118 return -EINVAL;
11119
11120 if (is_tracepoint || is_syscall_tp) {
11121 int off = trace_event_get_offsets(event->tp_event);
11122
11123 if (prog->aux->max_ctx_offset > off)
11124 return -EACCES;
11125 }
11126
11127 return perf_event_attach_bpf_prog(event, prog, bpf_cookie);
11128 }
11129
perf_event_free_bpf_prog(struct perf_event * event)11130 void perf_event_free_bpf_prog(struct perf_event *event)
11131 {
11132 if (!event->prog)
11133 return;
11134
11135 if (!perf_event_is_tracing(event)) {
11136 perf_event_free_bpf_handler(event);
11137 return;
11138 }
11139 perf_event_detach_bpf_prog(event);
11140 }
11141
11142 #else
11143
perf_tp_register(void)11144 static inline void perf_tp_register(void)
11145 {
11146 }
11147
perf_event_free_filter(struct perf_event * event)11148 static void perf_event_free_filter(struct perf_event *event)
11149 {
11150 }
11151
perf_event_set_bpf_prog(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)11152 int perf_event_set_bpf_prog(struct perf_event *event, struct bpf_prog *prog,
11153 u64 bpf_cookie)
11154 {
11155 return -ENOENT;
11156 }
11157
perf_event_free_bpf_prog(struct perf_event * event)11158 void perf_event_free_bpf_prog(struct perf_event *event)
11159 {
11160 }
11161 #endif /* CONFIG_EVENT_TRACING */
11162
11163 #ifdef CONFIG_HAVE_HW_BREAKPOINT
perf_bp_event(struct perf_event * bp,void * data)11164 void perf_bp_event(struct perf_event *bp, void *data)
11165 {
11166 struct perf_sample_data sample;
11167 struct pt_regs *regs = data;
11168
11169 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
11170
11171 if (!bp->hw.state && !perf_exclude_event(bp, regs))
11172 perf_swevent_event(bp, 1, &sample, regs);
11173 }
11174 #endif
11175
11176 /*
11177 * Allocate a new address filter
11178 */
11179 static struct perf_addr_filter *
perf_addr_filter_new(struct perf_event * event,struct list_head * filters)11180 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
11181 {
11182 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
11183 struct perf_addr_filter *filter;
11184
11185 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
11186 if (!filter)
11187 return NULL;
11188
11189 INIT_LIST_HEAD(&filter->entry);
11190 list_add_tail(&filter->entry, filters);
11191
11192 return filter;
11193 }
11194
free_filters_list(struct list_head * filters)11195 static void free_filters_list(struct list_head *filters)
11196 {
11197 struct perf_addr_filter *filter, *iter;
11198
11199 list_for_each_entry_safe(filter, iter, filters, entry) {
11200 path_put(&filter->path);
11201 list_del(&filter->entry);
11202 kfree(filter);
11203 }
11204 }
11205
11206 /*
11207 * Free existing address filters and optionally install new ones
11208 */
perf_addr_filters_splice(struct perf_event * event,struct list_head * head)11209 static void perf_addr_filters_splice(struct perf_event *event,
11210 struct list_head *head)
11211 {
11212 unsigned long flags;
11213 LIST_HEAD(list);
11214
11215 if (!has_addr_filter(event))
11216 return;
11217
11218 /* don't bother with children, they don't have their own filters */
11219 if (event->parent)
11220 return;
11221
11222 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
11223
11224 list_splice_init(&event->addr_filters.list, &list);
11225 if (head)
11226 list_splice(head, &event->addr_filters.list);
11227
11228 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
11229
11230 free_filters_list(&list);
11231 }
11232
perf_free_addr_filters(struct perf_event * event)11233 static void perf_free_addr_filters(struct perf_event *event)
11234 {
11235 /*
11236 * Used during free paths, there is no concurrency.
11237 */
11238 if (list_empty(&event->addr_filters.list))
11239 return;
11240
11241 perf_addr_filters_splice(event, NULL);
11242 }
11243
11244 /*
11245 * Scan through mm's vmas and see if one of them matches the
11246 * @filter; if so, adjust filter's address range.
11247 * Called with mm::mmap_lock down for reading.
11248 */
perf_addr_filter_apply(struct perf_addr_filter * filter,struct mm_struct * mm,struct perf_addr_filter_range * fr)11249 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
11250 struct mm_struct *mm,
11251 struct perf_addr_filter_range *fr)
11252 {
11253 struct vm_area_struct *vma;
11254 VMA_ITERATOR(vmi, mm, 0);
11255
11256 for_each_vma(vmi, vma) {
11257 if (!vma->vm_file)
11258 continue;
11259
11260 if (perf_addr_filter_vma_adjust(filter, vma, fr))
11261 return;
11262 }
11263 }
11264
11265 /*
11266 * Update event's address range filters based on the
11267 * task's existing mappings, if any.
11268 */
perf_event_addr_filters_apply(struct perf_event * event)11269 static void perf_event_addr_filters_apply(struct perf_event *event)
11270 {
11271 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11272 struct task_struct *task = READ_ONCE(event->ctx->task);
11273 struct perf_addr_filter *filter;
11274 struct mm_struct *mm = NULL;
11275 unsigned int count = 0;
11276 unsigned long flags;
11277
11278 /*
11279 * We may observe TASK_TOMBSTONE, which means that the event tear-down
11280 * will stop on the parent's child_mutex that our caller is also holding
11281 */
11282 if (task == TASK_TOMBSTONE)
11283 return;
11284
11285 if (ifh->nr_file_filters) {
11286 mm = get_task_mm(task);
11287 if (!mm)
11288 goto restart;
11289
11290 mmap_read_lock(mm);
11291 }
11292
11293 raw_spin_lock_irqsave(&ifh->lock, flags);
11294 list_for_each_entry(filter, &ifh->list, entry) {
11295 if (filter->path.dentry) {
11296 /*
11297 * Adjust base offset if the filter is associated to a
11298 * binary that needs to be mapped:
11299 */
11300 event->addr_filter_ranges[count].start = 0;
11301 event->addr_filter_ranges[count].size = 0;
11302
11303 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
11304 } else {
11305 event->addr_filter_ranges[count].start = filter->offset;
11306 event->addr_filter_ranges[count].size = filter->size;
11307 }
11308
11309 count++;
11310 }
11311
11312 event->addr_filters_gen++;
11313 raw_spin_unlock_irqrestore(&ifh->lock, flags);
11314
11315 if (ifh->nr_file_filters) {
11316 mmap_read_unlock(mm);
11317
11318 mmput(mm);
11319 }
11320
11321 restart:
11322 perf_event_stop(event, 1);
11323 }
11324
11325 /*
11326 * Address range filtering: limiting the data to certain
11327 * instruction address ranges. Filters are ioctl()ed to us from
11328 * userspace as ascii strings.
11329 *
11330 * Filter string format:
11331 *
11332 * ACTION RANGE_SPEC
11333 * where ACTION is one of the
11334 * * "filter": limit the trace to this region
11335 * * "start": start tracing from this address
11336 * * "stop": stop tracing at this address/region;
11337 * RANGE_SPEC is
11338 * * for kernel addresses: <start address>[/<size>]
11339 * * for object files: <start address>[/<size>]@</path/to/object/file>
11340 *
11341 * if <size> is not specified or is zero, the range is treated as a single
11342 * address; not valid for ACTION=="filter".
11343 */
11344 enum {
11345 IF_ACT_NONE = -1,
11346 IF_ACT_FILTER,
11347 IF_ACT_START,
11348 IF_ACT_STOP,
11349 IF_SRC_FILE,
11350 IF_SRC_KERNEL,
11351 IF_SRC_FILEADDR,
11352 IF_SRC_KERNELADDR,
11353 };
11354
11355 enum {
11356 IF_STATE_ACTION = 0,
11357 IF_STATE_SOURCE,
11358 IF_STATE_END,
11359 };
11360
11361 static const match_table_t if_tokens = {
11362 { IF_ACT_FILTER, "filter" },
11363 { IF_ACT_START, "start" },
11364 { IF_ACT_STOP, "stop" },
11365 { IF_SRC_FILE, "%u/%u@%s" },
11366 { IF_SRC_KERNEL, "%u/%u" },
11367 { IF_SRC_FILEADDR, "%u@%s" },
11368 { IF_SRC_KERNELADDR, "%u" },
11369 { IF_ACT_NONE, NULL },
11370 };
11371
11372 /*
11373 * Address filter string parser
11374 */
11375 static int
perf_event_parse_addr_filter(struct perf_event * event,char * fstr,struct list_head * filters)11376 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
11377 struct list_head *filters)
11378 {
11379 struct perf_addr_filter *filter = NULL;
11380 char *start, *orig, *filename = NULL;
11381 substring_t args[MAX_OPT_ARGS];
11382 int state = IF_STATE_ACTION, token;
11383 unsigned int kernel = 0;
11384 int ret = -EINVAL;
11385
11386 orig = fstr = kstrdup(fstr, GFP_KERNEL);
11387 if (!fstr)
11388 return -ENOMEM;
11389
11390 while ((start = strsep(&fstr, " ,\n")) != NULL) {
11391 static const enum perf_addr_filter_action_t actions[] = {
11392 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
11393 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
11394 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
11395 };
11396 ret = -EINVAL;
11397
11398 if (!*start)
11399 continue;
11400
11401 /* filter definition begins */
11402 if (state == IF_STATE_ACTION) {
11403 filter = perf_addr_filter_new(event, filters);
11404 if (!filter)
11405 goto fail;
11406 }
11407
11408 token = match_token(start, if_tokens, args);
11409 switch (token) {
11410 case IF_ACT_FILTER:
11411 case IF_ACT_START:
11412 case IF_ACT_STOP:
11413 if (state != IF_STATE_ACTION)
11414 goto fail;
11415
11416 filter->action = actions[token];
11417 state = IF_STATE_SOURCE;
11418 break;
11419
11420 case IF_SRC_KERNELADDR:
11421 case IF_SRC_KERNEL:
11422 kernel = 1;
11423 fallthrough;
11424
11425 case IF_SRC_FILEADDR:
11426 case IF_SRC_FILE:
11427 if (state != IF_STATE_SOURCE)
11428 goto fail;
11429
11430 *args[0].to = 0;
11431 ret = kstrtoul(args[0].from, 0, &filter->offset);
11432 if (ret)
11433 goto fail;
11434
11435 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
11436 *args[1].to = 0;
11437 ret = kstrtoul(args[1].from, 0, &filter->size);
11438 if (ret)
11439 goto fail;
11440 }
11441
11442 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
11443 int fpos = token == IF_SRC_FILE ? 2 : 1;
11444
11445 kfree(filename);
11446 filename = match_strdup(&args[fpos]);
11447 if (!filename) {
11448 ret = -ENOMEM;
11449 goto fail;
11450 }
11451 }
11452
11453 state = IF_STATE_END;
11454 break;
11455
11456 default:
11457 goto fail;
11458 }
11459
11460 /*
11461 * Filter definition is fully parsed, validate and install it.
11462 * Make sure that it doesn't contradict itself or the event's
11463 * attribute.
11464 */
11465 if (state == IF_STATE_END) {
11466 ret = -EINVAL;
11467
11468 /*
11469 * ACTION "filter" must have a non-zero length region
11470 * specified.
11471 */
11472 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
11473 !filter->size)
11474 goto fail;
11475
11476 if (!kernel) {
11477 if (!filename)
11478 goto fail;
11479
11480 /*
11481 * For now, we only support file-based filters
11482 * in per-task events; doing so for CPU-wide
11483 * events requires additional context switching
11484 * trickery, since same object code will be
11485 * mapped at different virtual addresses in
11486 * different processes.
11487 */
11488 ret = -EOPNOTSUPP;
11489 if (!event->ctx->task)
11490 goto fail;
11491
11492 /* look up the path and grab its inode */
11493 ret = kern_path(filename, LOOKUP_FOLLOW,
11494 &filter->path);
11495 if (ret)
11496 goto fail;
11497
11498 ret = -EINVAL;
11499 if (!filter->path.dentry ||
11500 !S_ISREG(d_inode(filter->path.dentry)
11501 ->i_mode))
11502 goto fail;
11503
11504 event->addr_filters.nr_file_filters++;
11505 }
11506
11507 /* ready to consume more filters */
11508 kfree(filename);
11509 filename = NULL;
11510 state = IF_STATE_ACTION;
11511 filter = NULL;
11512 kernel = 0;
11513 }
11514 }
11515
11516 if (state != IF_STATE_ACTION)
11517 goto fail;
11518
11519 kfree(filename);
11520 kfree(orig);
11521
11522 return 0;
11523
11524 fail:
11525 kfree(filename);
11526 free_filters_list(filters);
11527 kfree(orig);
11528
11529 return ret;
11530 }
11531
11532 static int
perf_event_set_addr_filter(struct perf_event * event,char * filter_str)11533 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
11534 {
11535 LIST_HEAD(filters);
11536 int ret;
11537
11538 /*
11539 * Since this is called in perf_ioctl() path, we're already holding
11540 * ctx::mutex.
11541 */
11542 lockdep_assert_held(&event->ctx->mutex);
11543
11544 if (WARN_ON_ONCE(event->parent))
11545 return -EINVAL;
11546
11547 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
11548 if (ret)
11549 goto fail_clear_files;
11550
11551 ret = event->pmu->addr_filters_validate(&filters);
11552 if (ret)
11553 goto fail_free_filters;
11554
11555 /* remove existing filters, if any */
11556 perf_addr_filters_splice(event, &filters);
11557
11558 /* install new filters */
11559 perf_event_for_each_child(event, perf_event_addr_filters_apply);
11560
11561 return ret;
11562
11563 fail_free_filters:
11564 free_filters_list(&filters);
11565
11566 fail_clear_files:
11567 event->addr_filters.nr_file_filters = 0;
11568
11569 return ret;
11570 }
11571
perf_event_set_filter(struct perf_event * event,void __user * arg)11572 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
11573 {
11574 int ret = -EINVAL;
11575 char *filter_str;
11576
11577 filter_str = strndup_user(arg, PAGE_SIZE);
11578 if (IS_ERR(filter_str))
11579 return PTR_ERR(filter_str);
11580
11581 #ifdef CONFIG_EVENT_TRACING
11582 if (perf_event_is_tracing(event)) {
11583 struct perf_event_context *ctx = event->ctx;
11584
11585 /*
11586 * Beware, here be dragons!!
11587 *
11588 * the tracepoint muck will deadlock against ctx->mutex, but
11589 * the tracepoint stuff does not actually need it. So
11590 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
11591 * already have a reference on ctx.
11592 *
11593 * This can result in event getting moved to a different ctx,
11594 * but that does not affect the tracepoint state.
11595 */
11596 mutex_unlock(&ctx->mutex);
11597 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
11598 mutex_lock(&ctx->mutex);
11599 } else
11600 #endif
11601 if (has_addr_filter(event))
11602 ret = perf_event_set_addr_filter(event, filter_str);
11603
11604 kfree(filter_str);
11605 return ret;
11606 }
11607
11608 /*
11609 * hrtimer based swevent callback
11610 */
11611
perf_swevent_hrtimer(struct hrtimer * hrtimer)11612 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
11613 {
11614 enum hrtimer_restart ret = HRTIMER_RESTART;
11615 struct perf_sample_data data;
11616 struct pt_regs *regs;
11617 struct perf_event *event;
11618 u64 period;
11619
11620 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
11621
11622 if (event->state != PERF_EVENT_STATE_ACTIVE)
11623 return HRTIMER_NORESTART;
11624
11625 event->pmu->read(event);
11626
11627 perf_sample_data_init(&data, 0, event->hw.last_period);
11628 regs = get_irq_regs();
11629
11630 if (regs && !perf_exclude_event(event, regs)) {
11631 if (!(event->attr.exclude_idle && is_idle_task(current)))
11632 if (__perf_event_overflow(event, 1, &data, regs))
11633 ret = HRTIMER_NORESTART;
11634 }
11635
11636 period = max_t(u64, 10000, event->hw.sample_period);
11637 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
11638
11639 return ret;
11640 }
11641
perf_swevent_start_hrtimer(struct perf_event * event)11642 static void perf_swevent_start_hrtimer(struct perf_event *event)
11643 {
11644 struct hw_perf_event *hwc = &event->hw;
11645 s64 period;
11646
11647 if (!is_sampling_event(event))
11648 return;
11649
11650 period = local64_read(&hwc->period_left);
11651 if (period) {
11652 if (period < 0)
11653 period = 10000;
11654
11655 local64_set(&hwc->period_left, 0);
11656 } else {
11657 period = max_t(u64, 10000, hwc->sample_period);
11658 }
11659 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
11660 HRTIMER_MODE_REL_PINNED_HARD);
11661 }
11662
perf_swevent_cancel_hrtimer(struct perf_event * event)11663 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
11664 {
11665 struct hw_perf_event *hwc = &event->hw;
11666
11667 if (is_sampling_event(event)) {
11668 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
11669 local64_set(&hwc->period_left, ktime_to_ns(remaining));
11670
11671 hrtimer_cancel(&hwc->hrtimer);
11672 }
11673 }
11674
perf_swevent_init_hrtimer(struct perf_event * event)11675 static void perf_swevent_init_hrtimer(struct perf_event *event)
11676 {
11677 struct hw_perf_event *hwc = &event->hw;
11678
11679 if (!is_sampling_event(event))
11680 return;
11681
11682 hrtimer_setup(&hwc->hrtimer, perf_swevent_hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
11683
11684 /*
11685 * Since hrtimers have a fixed rate, we can do a static freq->period
11686 * mapping and avoid the whole period adjust feedback stuff.
11687 */
11688 if (event->attr.freq) {
11689 long freq = event->attr.sample_freq;
11690
11691 event->attr.sample_period = NSEC_PER_SEC / freq;
11692 hwc->sample_period = event->attr.sample_period;
11693 local64_set(&hwc->period_left, hwc->sample_period);
11694 hwc->last_period = hwc->sample_period;
11695 event->attr.freq = 0;
11696 }
11697 }
11698
11699 /*
11700 * Software event: cpu wall time clock
11701 */
11702
cpu_clock_event_update(struct perf_event * event)11703 static void cpu_clock_event_update(struct perf_event *event)
11704 {
11705 s64 prev;
11706 u64 now;
11707
11708 now = local_clock();
11709 prev = local64_xchg(&event->hw.prev_count, now);
11710 local64_add(now - prev, &event->count);
11711 }
11712
cpu_clock_event_start(struct perf_event * event,int flags)11713 static void cpu_clock_event_start(struct perf_event *event, int flags)
11714 {
11715 local64_set(&event->hw.prev_count, local_clock());
11716 perf_swevent_start_hrtimer(event);
11717 }
11718
cpu_clock_event_stop(struct perf_event * event,int flags)11719 static void cpu_clock_event_stop(struct perf_event *event, int flags)
11720 {
11721 perf_swevent_cancel_hrtimer(event);
11722 cpu_clock_event_update(event);
11723 }
11724
cpu_clock_event_add(struct perf_event * event,int flags)11725 static int cpu_clock_event_add(struct perf_event *event, int flags)
11726 {
11727 if (flags & PERF_EF_START)
11728 cpu_clock_event_start(event, flags);
11729 perf_event_update_userpage(event);
11730
11731 return 0;
11732 }
11733
cpu_clock_event_del(struct perf_event * event,int flags)11734 static void cpu_clock_event_del(struct perf_event *event, int flags)
11735 {
11736 cpu_clock_event_stop(event, flags);
11737 }
11738
cpu_clock_event_read(struct perf_event * event)11739 static void cpu_clock_event_read(struct perf_event *event)
11740 {
11741 cpu_clock_event_update(event);
11742 }
11743
cpu_clock_event_init(struct perf_event * event)11744 static int cpu_clock_event_init(struct perf_event *event)
11745 {
11746 if (event->attr.type != perf_cpu_clock.type)
11747 return -ENOENT;
11748
11749 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
11750 return -ENOENT;
11751
11752 /*
11753 * no branch sampling for software events
11754 */
11755 if (has_branch_stack(event))
11756 return -EOPNOTSUPP;
11757
11758 perf_swevent_init_hrtimer(event);
11759
11760 return 0;
11761 }
11762
11763 static struct pmu perf_cpu_clock = {
11764 .task_ctx_nr = perf_sw_context,
11765
11766 .capabilities = PERF_PMU_CAP_NO_NMI,
11767 .dev = PMU_NULL_DEV,
11768
11769 .event_init = cpu_clock_event_init,
11770 .add = cpu_clock_event_add,
11771 .del = cpu_clock_event_del,
11772 .start = cpu_clock_event_start,
11773 .stop = cpu_clock_event_stop,
11774 .read = cpu_clock_event_read,
11775 };
11776
11777 /*
11778 * Software event: task time clock
11779 */
11780
task_clock_event_update(struct perf_event * event,u64 now)11781 static void task_clock_event_update(struct perf_event *event, u64 now)
11782 {
11783 u64 prev;
11784 s64 delta;
11785
11786 prev = local64_xchg(&event->hw.prev_count, now);
11787 delta = now - prev;
11788 local64_add(delta, &event->count);
11789 }
11790
task_clock_event_start(struct perf_event * event,int flags)11791 static void task_clock_event_start(struct perf_event *event, int flags)
11792 {
11793 local64_set(&event->hw.prev_count, event->ctx->time);
11794 perf_swevent_start_hrtimer(event);
11795 }
11796
task_clock_event_stop(struct perf_event * event,int flags)11797 static void task_clock_event_stop(struct perf_event *event, int flags)
11798 {
11799 perf_swevent_cancel_hrtimer(event);
11800 task_clock_event_update(event, event->ctx->time);
11801 }
11802
task_clock_event_add(struct perf_event * event,int flags)11803 static int task_clock_event_add(struct perf_event *event, int flags)
11804 {
11805 if (flags & PERF_EF_START)
11806 task_clock_event_start(event, flags);
11807 perf_event_update_userpage(event);
11808
11809 return 0;
11810 }
11811
task_clock_event_del(struct perf_event * event,int flags)11812 static void task_clock_event_del(struct perf_event *event, int flags)
11813 {
11814 task_clock_event_stop(event, PERF_EF_UPDATE);
11815 }
11816
task_clock_event_read(struct perf_event * event)11817 static void task_clock_event_read(struct perf_event *event)
11818 {
11819 u64 now = perf_clock();
11820 u64 delta = now - event->ctx->timestamp;
11821 u64 time = event->ctx->time + delta;
11822
11823 task_clock_event_update(event, time);
11824 }
11825
task_clock_event_init(struct perf_event * event)11826 static int task_clock_event_init(struct perf_event *event)
11827 {
11828 if (event->attr.type != perf_task_clock.type)
11829 return -ENOENT;
11830
11831 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
11832 return -ENOENT;
11833
11834 /*
11835 * no branch sampling for software events
11836 */
11837 if (has_branch_stack(event))
11838 return -EOPNOTSUPP;
11839
11840 perf_swevent_init_hrtimer(event);
11841
11842 return 0;
11843 }
11844
11845 static struct pmu perf_task_clock = {
11846 .task_ctx_nr = perf_sw_context,
11847
11848 .capabilities = PERF_PMU_CAP_NO_NMI,
11849 .dev = PMU_NULL_DEV,
11850
11851 .event_init = task_clock_event_init,
11852 .add = task_clock_event_add,
11853 .del = task_clock_event_del,
11854 .start = task_clock_event_start,
11855 .stop = task_clock_event_stop,
11856 .read = task_clock_event_read,
11857 };
11858
perf_pmu_nop_void(struct pmu * pmu)11859 static void perf_pmu_nop_void(struct pmu *pmu)
11860 {
11861 }
11862
perf_pmu_nop_txn(struct pmu * pmu,unsigned int flags)11863 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
11864 {
11865 }
11866
perf_pmu_nop_int(struct pmu * pmu)11867 static int perf_pmu_nop_int(struct pmu *pmu)
11868 {
11869 return 0;
11870 }
11871
perf_event_nop_int(struct perf_event * event,u64 value)11872 static int perf_event_nop_int(struct perf_event *event, u64 value)
11873 {
11874 return 0;
11875 }
11876
11877 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
11878
perf_pmu_start_txn(struct pmu * pmu,unsigned int flags)11879 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
11880 {
11881 __this_cpu_write(nop_txn_flags, flags);
11882
11883 if (flags & ~PERF_PMU_TXN_ADD)
11884 return;
11885
11886 perf_pmu_disable(pmu);
11887 }
11888
perf_pmu_commit_txn(struct pmu * pmu)11889 static int perf_pmu_commit_txn(struct pmu *pmu)
11890 {
11891 unsigned int flags = __this_cpu_read(nop_txn_flags);
11892
11893 __this_cpu_write(nop_txn_flags, 0);
11894
11895 if (flags & ~PERF_PMU_TXN_ADD)
11896 return 0;
11897
11898 perf_pmu_enable(pmu);
11899 return 0;
11900 }
11901
perf_pmu_cancel_txn(struct pmu * pmu)11902 static void perf_pmu_cancel_txn(struct pmu *pmu)
11903 {
11904 unsigned int flags = __this_cpu_read(nop_txn_flags);
11905
11906 __this_cpu_write(nop_txn_flags, 0);
11907
11908 if (flags & ~PERF_PMU_TXN_ADD)
11909 return;
11910
11911 perf_pmu_enable(pmu);
11912 }
11913
perf_event_idx_default(struct perf_event * event)11914 static int perf_event_idx_default(struct perf_event *event)
11915 {
11916 return 0;
11917 }
11918
11919 /*
11920 * Let userspace know that this PMU supports address range filtering:
11921 */
nr_addr_filters_show(struct device * dev,struct device_attribute * attr,char * page)11922 static ssize_t nr_addr_filters_show(struct device *dev,
11923 struct device_attribute *attr,
11924 char *page)
11925 {
11926 struct pmu *pmu = dev_get_drvdata(dev);
11927
11928 return sysfs_emit(page, "%d\n", pmu->nr_addr_filters);
11929 }
11930 DEVICE_ATTR_RO(nr_addr_filters);
11931
11932 static struct idr pmu_idr;
11933
11934 static ssize_t
type_show(struct device * dev,struct device_attribute * attr,char * page)11935 type_show(struct device *dev, struct device_attribute *attr, char *page)
11936 {
11937 struct pmu *pmu = dev_get_drvdata(dev);
11938
11939 return sysfs_emit(page, "%d\n", pmu->type);
11940 }
11941 static DEVICE_ATTR_RO(type);
11942
11943 static ssize_t
perf_event_mux_interval_ms_show(struct device * dev,struct device_attribute * attr,char * page)11944 perf_event_mux_interval_ms_show(struct device *dev,
11945 struct device_attribute *attr,
11946 char *page)
11947 {
11948 struct pmu *pmu = dev_get_drvdata(dev);
11949
11950 return sysfs_emit(page, "%d\n", pmu->hrtimer_interval_ms);
11951 }
11952
11953 static DEFINE_MUTEX(mux_interval_mutex);
11954
11955 static ssize_t
perf_event_mux_interval_ms_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)11956 perf_event_mux_interval_ms_store(struct device *dev,
11957 struct device_attribute *attr,
11958 const char *buf, size_t count)
11959 {
11960 struct pmu *pmu = dev_get_drvdata(dev);
11961 int timer, cpu, ret;
11962
11963 ret = kstrtoint(buf, 0, &timer);
11964 if (ret)
11965 return ret;
11966
11967 if (timer < 1)
11968 return -EINVAL;
11969
11970 /* same value, noting to do */
11971 if (timer == pmu->hrtimer_interval_ms)
11972 return count;
11973
11974 mutex_lock(&mux_interval_mutex);
11975 pmu->hrtimer_interval_ms = timer;
11976
11977 /* update all cpuctx for this PMU */
11978 cpus_read_lock();
11979 for_each_online_cpu(cpu) {
11980 struct perf_cpu_pmu_context *cpc;
11981 cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu);
11982 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
11983
11984 cpu_function_call(cpu, perf_mux_hrtimer_restart_ipi, cpc);
11985 }
11986 cpus_read_unlock();
11987 mutex_unlock(&mux_interval_mutex);
11988
11989 return count;
11990 }
11991 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
11992
perf_scope_cpu_topology_cpumask(unsigned int scope,int cpu)11993 static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu)
11994 {
11995 switch (scope) {
11996 case PERF_PMU_SCOPE_CORE:
11997 return topology_sibling_cpumask(cpu);
11998 case PERF_PMU_SCOPE_DIE:
11999 return topology_die_cpumask(cpu);
12000 case PERF_PMU_SCOPE_CLUSTER:
12001 return topology_cluster_cpumask(cpu);
12002 case PERF_PMU_SCOPE_PKG:
12003 return topology_core_cpumask(cpu);
12004 case PERF_PMU_SCOPE_SYS_WIDE:
12005 return cpu_online_mask;
12006 }
12007
12008 return NULL;
12009 }
12010
perf_scope_cpumask(unsigned int scope)12011 static inline struct cpumask *perf_scope_cpumask(unsigned int scope)
12012 {
12013 switch (scope) {
12014 case PERF_PMU_SCOPE_CORE:
12015 return perf_online_core_mask;
12016 case PERF_PMU_SCOPE_DIE:
12017 return perf_online_die_mask;
12018 case PERF_PMU_SCOPE_CLUSTER:
12019 return perf_online_cluster_mask;
12020 case PERF_PMU_SCOPE_PKG:
12021 return perf_online_pkg_mask;
12022 case PERF_PMU_SCOPE_SYS_WIDE:
12023 return perf_online_sys_mask;
12024 }
12025
12026 return NULL;
12027 }
12028
cpumask_show(struct device * dev,struct device_attribute * attr,char * buf)12029 static ssize_t cpumask_show(struct device *dev, struct device_attribute *attr,
12030 char *buf)
12031 {
12032 struct pmu *pmu = dev_get_drvdata(dev);
12033 struct cpumask *mask = perf_scope_cpumask(pmu->scope);
12034
12035 if (mask)
12036 return cpumap_print_to_pagebuf(true, buf, mask);
12037 return 0;
12038 }
12039
12040 static DEVICE_ATTR_RO(cpumask);
12041
12042 static struct attribute *pmu_dev_attrs[] = {
12043 &dev_attr_type.attr,
12044 &dev_attr_perf_event_mux_interval_ms.attr,
12045 &dev_attr_nr_addr_filters.attr,
12046 &dev_attr_cpumask.attr,
12047 NULL,
12048 };
12049
pmu_dev_is_visible(struct kobject * kobj,struct attribute * a,int n)12050 static umode_t pmu_dev_is_visible(struct kobject *kobj, struct attribute *a, int n)
12051 {
12052 struct device *dev = kobj_to_dev(kobj);
12053 struct pmu *pmu = dev_get_drvdata(dev);
12054
12055 if (n == 2 && !pmu->nr_addr_filters)
12056 return 0;
12057
12058 /* cpumask */
12059 if (n == 3 && pmu->scope == PERF_PMU_SCOPE_NONE)
12060 return 0;
12061
12062 return a->mode;
12063 }
12064
12065 static struct attribute_group pmu_dev_attr_group = {
12066 .is_visible = pmu_dev_is_visible,
12067 .attrs = pmu_dev_attrs,
12068 };
12069
12070 static const struct attribute_group *pmu_dev_groups[] = {
12071 &pmu_dev_attr_group,
12072 NULL,
12073 };
12074
12075 static int pmu_bus_running;
12076 static struct bus_type pmu_bus = {
12077 .name = "event_source",
12078 .dev_groups = pmu_dev_groups,
12079 };
12080
pmu_dev_release(struct device * dev)12081 static void pmu_dev_release(struct device *dev)
12082 {
12083 kfree(dev);
12084 }
12085
pmu_dev_alloc(struct pmu * pmu)12086 static int pmu_dev_alloc(struct pmu *pmu)
12087 {
12088 int ret = -ENOMEM;
12089
12090 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
12091 if (!pmu->dev)
12092 goto out;
12093
12094 pmu->dev->groups = pmu->attr_groups;
12095 device_initialize(pmu->dev);
12096
12097 dev_set_drvdata(pmu->dev, pmu);
12098 pmu->dev->bus = &pmu_bus;
12099 pmu->dev->parent = pmu->parent;
12100 pmu->dev->release = pmu_dev_release;
12101
12102 ret = dev_set_name(pmu->dev, "%s", pmu->name);
12103 if (ret)
12104 goto free_dev;
12105
12106 ret = device_add(pmu->dev);
12107 if (ret)
12108 goto free_dev;
12109
12110 if (pmu->attr_update) {
12111 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
12112 if (ret)
12113 goto del_dev;
12114 }
12115
12116 out:
12117 return ret;
12118
12119 del_dev:
12120 device_del(pmu->dev);
12121
12122 free_dev:
12123 put_device(pmu->dev);
12124 pmu->dev = NULL;
12125 goto out;
12126 }
12127
12128 static struct lock_class_key cpuctx_mutex;
12129 static struct lock_class_key cpuctx_lock;
12130
idr_cmpxchg(struct idr * idr,unsigned long id,void * old,void * new)12131 static bool idr_cmpxchg(struct idr *idr, unsigned long id, void *old, void *new)
12132 {
12133 void *tmp, *val = idr_find(idr, id);
12134
12135 if (val != old)
12136 return false;
12137
12138 tmp = idr_replace(idr, new, id);
12139 if (IS_ERR(tmp))
12140 return false;
12141
12142 WARN_ON_ONCE(tmp != val);
12143 return true;
12144 }
12145
perf_pmu_free(struct pmu * pmu)12146 static void perf_pmu_free(struct pmu *pmu)
12147 {
12148 if (pmu_bus_running && pmu->dev && pmu->dev != PMU_NULL_DEV) {
12149 if (pmu->nr_addr_filters)
12150 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
12151 device_del(pmu->dev);
12152 put_device(pmu->dev);
12153 }
12154
12155 if (pmu->cpu_pmu_context) {
12156 int cpu;
12157
12158 for_each_possible_cpu(cpu) {
12159 struct perf_cpu_pmu_context *cpc;
12160
12161 cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu);
12162 if (!cpc)
12163 continue;
12164 if (cpc->epc.embedded) {
12165 /* refcount managed */
12166 put_pmu_ctx(&cpc->epc);
12167 continue;
12168 }
12169 kfree(cpc);
12170 }
12171 free_percpu(pmu->cpu_pmu_context);
12172 }
12173 }
12174
DEFINE_FREE(pmu_unregister,struct pmu *,if (_T)perf_pmu_free (_T))12175 DEFINE_FREE(pmu_unregister, struct pmu *, if (_T) perf_pmu_free(_T))
12176
12177 int perf_pmu_register(struct pmu *_pmu, const char *name, int type)
12178 {
12179 int cpu, max = PERF_TYPE_MAX;
12180
12181 struct pmu *pmu __free(pmu_unregister) = _pmu;
12182 guard(mutex)(&pmus_lock);
12183
12184 if (WARN_ONCE(!name, "Can not register anonymous pmu.\n"))
12185 return -EINVAL;
12186
12187 if (WARN_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE,
12188 "Can not register a pmu with an invalid scope.\n"))
12189 return -EINVAL;
12190
12191 pmu->name = name;
12192
12193 if (type >= 0)
12194 max = type;
12195
12196 CLASS(idr_alloc, pmu_type)(&pmu_idr, NULL, max, 0, GFP_KERNEL);
12197 if (pmu_type.id < 0)
12198 return pmu_type.id;
12199
12200 WARN_ON(type >= 0 && pmu_type.id != type);
12201
12202 pmu->type = pmu_type.id;
12203 atomic_set(&pmu->exclusive_cnt, 0);
12204
12205 if (pmu_bus_running && !pmu->dev) {
12206 int ret = pmu_dev_alloc(pmu);
12207 if (ret)
12208 return ret;
12209 }
12210
12211 pmu->cpu_pmu_context = alloc_percpu(struct perf_cpu_pmu_context *);
12212 if (!pmu->cpu_pmu_context)
12213 return -ENOMEM;
12214
12215 for_each_possible_cpu(cpu) {
12216 struct perf_cpu_pmu_context *cpc =
12217 kmalloc_node(sizeof(struct perf_cpu_pmu_context),
12218 GFP_KERNEL | __GFP_ZERO,
12219 cpu_to_node(cpu));
12220
12221 if (!cpc)
12222 return -ENOMEM;
12223
12224 *per_cpu_ptr(pmu->cpu_pmu_context, cpu) = cpc;
12225 __perf_init_event_pmu_context(&cpc->epc, pmu);
12226 __perf_mux_hrtimer_init(cpc, cpu);
12227 }
12228
12229 if (!pmu->start_txn) {
12230 if (pmu->pmu_enable) {
12231 /*
12232 * If we have pmu_enable/pmu_disable calls, install
12233 * transaction stubs that use that to try and batch
12234 * hardware accesses.
12235 */
12236 pmu->start_txn = perf_pmu_start_txn;
12237 pmu->commit_txn = perf_pmu_commit_txn;
12238 pmu->cancel_txn = perf_pmu_cancel_txn;
12239 } else {
12240 pmu->start_txn = perf_pmu_nop_txn;
12241 pmu->commit_txn = perf_pmu_nop_int;
12242 pmu->cancel_txn = perf_pmu_nop_void;
12243 }
12244 }
12245
12246 if (!pmu->pmu_enable) {
12247 pmu->pmu_enable = perf_pmu_nop_void;
12248 pmu->pmu_disable = perf_pmu_nop_void;
12249 }
12250
12251 if (!pmu->check_period)
12252 pmu->check_period = perf_event_nop_int;
12253
12254 if (!pmu->event_idx)
12255 pmu->event_idx = perf_event_idx_default;
12256
12257 /*
12258 * Now that the PMU is complete, make it visible to perf_try_init_event().
12259 */
12260 if (!idr_cmpxchg(&pmu_idr, pmu->type, NULL, pmu))
12261 return -EINVAL;
12262 list_add_rcu(&pmu->entry, &pmus);
12263
12264 take_idr_id(pmu_type);
12265 _pmu = no_free_ptr(pmu); // let it rip
12266 return 0;
12267 }
12268 EXPORT_SYMBOL_GPL(perf_pmu_register);
12269
perf_pmu_unregister(struct pmu * pmu)12270 void perf_pmu_unregister(struct pmu *pmu)
12271 {
12272 scoped_guard (mutex, &pmus_lock) {
12273 list_del_rcu(&pmu->entry);
12274 idr_remove(&pmu_idr, pmu->type);
12275 }
12276
12277 /*
12278 * We dereference the pmu list under both SRCU and regular RCU, so
12279 * synchronize against both of those.
12280 */
12281 synchronize_srcu(&pmus_srcu);
12282 synchronize_rcu();
12283
12284 perf_pmu_free(pmu);
12285 }
12286 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
12287
has_extended_regs(struct perf_event * event)12288 static inline bool has_extended_regs(struct perf_event *event)
12289 {
12290 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
12291 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
12292 }
12293
perf_try_init_event(struct pmu * pmu,struct perf_event * event)12294 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
12295 {
12296 struct perf_event_context *ctx = NULL;
12297 int ret;
12298
12299 if (!try_module_get(pmu->module))
12300 return -ENODEV;
12301
12302 /*
12303 * A number of pmu->event_init() methods iterate the sibling_list to,
12304 * for example, validate if the group fits on the PMU. Therefore,
12305 * if this is a sibling event, acquire the ctx->mutex to protect
12306 * the sibling_list.
12307 */
12308 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
12309 /*
12310 * This ctx->mutex can nest when we're called through
12311 * inheritance. See the perf_event_ctx_lock_nested() comment.
12312 */
12313 ctx = perf_event_ctx_lock_nested(event->group_leader,
12314 SINGLE_DEPTH_NESTING);
12315 BUG_ON(!ctx);
12316 }
12317
12318 event->pmu = pmu;
12319 ret = pmu->event_init(event);
12320
12321 if (ctx)
12322 perf_event_ctx_unlock(event->group_leader, ctx);
12323
12324 if (ret)
12325 goto err_pmu;
12326
12327 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
12328 has_extended_regs(event)) {
12329 ret = -EOPNOTSUPP;
12330 goto err_destroy;
12331 }
12332
12333 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
12334 event_has_any_exclude_flag(event)) {
12335 ret = -EINVAL;
12336 goto err_destroy;
12337 }
12338
12339 if (pmu->scope != PERF_PMU_SCOPE_NONE && event->cpu >= 0) {
12340 const struct cpumask *cpumask;
12341 struct cpumask *pmu_cpumask;
12342 int cpu;
12343
12344 cpumask = perf_scope_cpu_topology_cpumask(pmu->scope, event->cpu);
12345 pmu_cpumask = perf_scope_cpumask(pmu->scope);
12346
12347 ret = -ENODEV;
12348 if (!pmu_cpumask || !cpumask)
12349 goto err_destroy;
12350
12351 cpu = cpumask_any_and(pmu_cpumask, cpumask);
12352 if (cpu >= nr_cpu_ids)
12353 goto err_destroy;
12354
12355 event->event_caps |= PERF_EV_CAP_READ_SCOPE;
12356 }
12357
12358 return 0;
12359
12360 err_destroy:
12361 if (event->destroy) {
12362 event->destroy(event);
12363 event->destroy = NULL;
12364 }
12365
12366 err_pmu:
12367 event->pmu = NULL;
12368 module_put(pmu->module);
12369 return ret;
12370 }
12371
perf_init_event(struct perf_event * event)12372 static struct pmu *perf_init_event(struct perf_event *event)
12373 {
12374 bool extended_type = false;
12375 struct pmu *pmu;
12376 int type, ret;
12377
12378 guard(srcu)(&pmus_srcu);
12379
12380 /*
12381 * Save original type before calling pmu->event_init() since certain
12382 * pmus overwrites event->attr.type to forward event to another pmu.
12383 */
12384 event->orig_type = event->attr.type;
12385
12386 /* Try parent's PMU first: */
12387 if (event->parent && event->parent->pmu) {
12388 pmu = event->parent->pmu;
12389 ret = perf_try_init_event(pmu, event);
12390 if (!ret)
12391 return pmu;
12392 }
12393
12394 /*
12395 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
12396 * are often aliases for PERF_TYPE_RAW.
12397 */
12398 type = event->attr.type;
12399 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE) {
12400 type = event->attr.config >> PERF_PMU_TYPE_SHIFT;
12401 if (!type) {
12402 type = PERF_TYPE_RAW;
12403 } else {
12404 extended_type = true;
12405 event->attr.config &= PERF_HW_EVENT_MASK;
12406 }
12407 }
12408
12409 again:
12410 scoped_guard (rcu)
12411 pmu = idr_find(&pmu_idr, type);
12412 if (pmu) {
12413 if (event->attr.type != type && type != PERF_TYPE_RAW &&
12414 !(pmu->capabilities & PERF_PMU_CAP_EXTENDED_HW_TYPE))
12415 return ERR_PTR(-ENOENT);
12416
12417 ret = perf_try_init_event(pmu, event);
12418 if (ret == -ENOENT && event->attr.type != type && !extended_type) {
12419 type = event->attr.type;
12420 goto again;
12421 }
12422
12423 if (ret)
12424 return ERR_PTR(ret);
12425
12426 return pmu;
12427 }
12428
12429 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
12430 ret = perf_try_init_event(pmu, event);
12431 if (!ret)
12432 return pmu;
12433
12434 if (ret != -ENOENT)
12435 return ERR_PTR(ret);
12436 }
12437
12438 return ERR_PTR(-ENOENT);
12439 }
12440
attach_sb_event(struct perf_event * event)12441 static void attach_sb_event(struct perf_event *event)
12442 {
12443 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
12444
12445 raw_spin_lock(&pel->lock);
12446 list_add_rcu(&event->sb_list, &pel->list);
12447 raw_spin_unlock(&pel->lock);
12448 }
12449
12450 /*
12451 * We keep a list of all !task (and therefore per-cpu) events
12452 * that need to receive side-band records.
12453 *
12454 * This avoids having to scan all the various PMU per-cpu contexts
12455 * looking for them.
12456 */
account_pmu_sb_event(struct perf_event * event)12457 static void account_pmu_sb_event(struct perf_event *event)
12458 {
12459 if (is_sb_event(event))
12460 attach_sb_event(event);
12461 }
12462
12463 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
account_freq_event_nohz(void)12464 static void account_freq_event_nohz(void)
12465 {
12466 #ifdef CONFIG_NO_HZ_FULL
12467 /* Lock so we don't race with concurrent unaccount */
12468 spin_lock(&nr_freq_lock);
12469 if (atomic_inc_return(&nr_freq_events) == 1)
12470 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
12471 spin_unlock(&nr_freq_lock);
12472 #endif
12473 }
12474
account_freq_event(void)12475 static void account_freq_event(void)
12476 {
12477 if (tick_nohz_full_enabled())
12478 account_freq_event_nohz();
12479 else
12480 atomic_inc(&nr_freq_events);
12481 }
12482
12483
account_event(struct perf_event * event)12484 static void account_event(struct perf_event *event)
12485 {
12486 bool inc = false;
12487
12488 if (event->parent)
12489 return;
12490
12491 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
12492 inc = true;
12493 if (event->attr.mmap || event->attr.mmap_data)
12494 atomic_inc(&nr_mmap_events);
12495 if (event->attr.build_id)
12496 atomic_inc(&nr_build_id_events);
12497 if (event->attr.comm)
12498 atomic_inc(&nr_comm_events);
12499 if (event->attr.namespaces)
12500 atomic_inc(&nr_namespaces_events);
12501 if (event->attr.cgroup)
12502 atomic_inc(&nr_cgroup_events);
12503 if (event->attr.task)
12504 atomic_inc(&nr_task_events);
12505 if (event->attr.freq)
12506 account_freq_event();
12507 if (event->attr.context_switch) {
12508 atomic_inc(&nr_switch_events);
12509 inc = true;
12510 }
12511 if (has_branch_stack(event))
12512 inc = true;
12513 if (is_cgroup_event(event))
12514 inc = true;
12515 if (event->attr.ksymbol)
12516 atomic_inc(&nr_ksymbol_events);
12517 if (event->attr.bpf_event)
12518 atomic_inc(&nr_bpf_events);
12519 if (event->attr.text_poke)
12520 atomic_inc(&nr_text_poke_events);
12521
12522 if (inc) {
12523 /*
12524 * We need the mutex here because static_branch_enable()
12525 * must complete *before* the perf_sched_count increment
12526 * becomes visible.
12527 */
12528 if (atomic_inc_not_zero(&perf_sched_count))
12529 goto enabled;
12530
12531 mutex_lock(&perf_sched_mutex);
12532 if (!atomic_read(&perf_sched_count)) {
12533 static_branch_enable(&perf_sched_events);
12534 /*
12535 * Guarantee that all CPUs observe they key change and
12536 * call the perf scheduling hooks before proceeding to
12537 * install events that need them.
12538 */
12539 synchronize_rcu();
12540 }
12541 /*
12542 * Now that we have waited for the sync_sched(), allow further
12543 * increments to by-pass the mutex.
12544 */
12545 atomic_inc(&perf_sched_count);
12546 mutex_unlock(&perf_sched_mutex);
12547 }
12548 enabled:
12549
12550 account_pmu_sb_event(event);
12551 }
12552
12553 /*
12554 * Allocate and initialize an event structure
12555 */
12556 static struct perf_event *
perf_event_alloc(struct perf_event_attr * attr,int cpu,struct task_struct * task,struct perf_event * group_leader,struct perf_event * parent_event,perf_overflow_handler_t overflow_handler,void * context,int cgroup_fd)12557 perf_event_alloc(struct perf_event_attr *attr, int cpu,
12558 struct task_struct *task,
12559 struct perf_event *group_leader,
12560 struct perf_event *parent_event,
12561 perf_overflow_handler_t overflow_handler,
12562 void *context, int cgroup_fd)
12563 {
12564 struct pmu *pmu;
12565 struct hw_perf_event *hwc;
12566 long err = -EINVAL;
12567 int node;
12568
12569 if ((unsigned)cpu >= nr_cpu_ids) {
12570 if (!task || cpu != -1)
12571 return ERR_PTR(-EINVAL);
12572 }
12573 if (attr->sigtrap && !task) {
12574 /* Requires a task: avoid signalling random tasks. */
12575 return ERR_PTR(-EINVAL);
12576 }
12577
12578 node = (cpu >= 0) ? cpu_to_node(cpu) : -1;
12579 struct perf_event *event __free(__free_event) =
12580 kmem_cache_alloc_node(perf_event_cache, GFP_KERNEL | __GFP_ZERO, node);
12581 if (!event)
12582 return ERR_PTR(-ENOMEM);
12583
12584 /*
12585 * Single events are their own group leaders, with an
12586 * empty sibling list:
12587 */
12588 if (!group_leader)
12589 group_leader = event;
12590
12591 mutex_init(&event->child_mutex);
12592 INIT_LIST_HEAD(&event->child_list);
12593
12594 INIT_LIST_HEAD(&event->event_entry);
12595 INIT_LIST_HEAD(&event->sibling_list);
12596 INIT_LIST_HEAD(&event->active_list);
12597 init_event_group(event);
12598 INIT_LIST_HEAD(&event->rb_entry);
12599 INIT_LIST_HEAD(&event->active_entry);
12600 INIT_LIST_HEAD(&event->addr_filters.list);
12601 INIT_HLIST_NODE(&event->hlist_entry);
12602
12603
12604 init_waitqueue_head(&event->waitq);
12605 init_irq_work(&event->pending_irq, perf_pending_irq);
12606 event->pending_disable_irq = IRQ_WORK_INIT_HARD(perf_pending_disable);
12607 init_task_work(&event->pending_task, perf_pending_task);
12608 rcuwait_init(&event->pending_work_wait);
12609
12610 mutex_init(&event->mmap_mutex);
12611 raw_spin_lock_init(&event->addr_filters.lock);
12612
12613 atomic_long_set(&event->refcount, 1);
12614 event->cpu = cpu;
12615 event->attr = *attr;
12616 event->group_leader = group_leader;
12617 event->pmu = NULL;
12618 event->oncpu = -1;
12619
12620 event->parent = parent_event;
12621
12622 event->ns = get_pid_ns(task_active_pid_ns(current));
12623 event->id = atomic64_inc_return(&perf_event_id);
12624
12625 event->state = PERF_EVENT_STATE_INACTIVE;
12626
12627 if (parent_event)
12628 event->event_caps = parent_event->event_caps;
12629
12630 if (task) {
12631 event->attach_state = PERF_ATTACH_TASK;
12632 /*
12633 * XXX pmu::event_init needs to know what task to account to
12634 * and we cannot use the ctx information because we need the
12635 * pmu before we get a ctx.
12636 */
12637 event->hw.target = get_task_struct(task);
12638 }
12639
12640 event->clock = &local_clock;
12641 if (parent_event)
12642 event->clock = parent_event->clock;
12643
12644 if (!overflow_handler && parent_event) {
12645 overflow_handler = parent_event->overflow_handler;
12646 context = parent_event->overflow_handler_context;
12647 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
12648 if (parent_event->prog) {
12649 struct bpf_prog *prog = parent_event->prog;
12650
12651 bpf_prog_inc(prog);
12652 event->prog = prog;
12653 }
12654 #endif
12655 }
12656
12657 if (overflow_handler) {
12658 event->overflow_handler = overflow_handler;
12659 event->overflow_handler_context = context;
12660 } else if (is_write_backward(event)){
12661 event->overflow_handler = perf_event_output_backward;
12662 event->overflow_handler_context = NULL;
12663 } else {
12664 event->overflow_handler = perf_event_output_forward;
12665 event->overflow_handler_context = NULL;
12666 }
12667
12668 perf_event__state_init(event);
12669
12670 pmu = NULL;
12671
12672 hwc = &event->hw;
12673 hwc->sample_period = attr->sample_period;
12674 if (attr->freq && attr->sample_freq)
12675 hwc->sample_period = 1;
12676 hwc->last_period = hwc->sample_period;
12677
12678 local64_set(&hwc->period_left, hwc->sample_period);
12679
12680 /*
12681 * We do not support PERF_SAMPLE_READ on inherited events unless
12682 * PERF_SAMPLE_TID is also selected, which allows inherited events to
12683 * collect per-thread samples.
12684 * See perf_output_read().
12685 */
12686 if (has_inherit_and_sample_read(attr) && !(attr->sample_type & PERF_SAMPLE_TID))
12687 return ERR_PTR(-EINVAL);
12688
12689 if (!has_branch_stack(event))
12690 event->attr.branch_sample_type = 0;
12691
12692 pmu = perf_init_event(event);
12693 if (IS_ERR(pmu))
12694 return (void*)pmu;
12695
12696 /*
12697 * The PERF_ATTACH_TASK_DATA is set in the event_init()->hw_config().
12698 * The attach should be right after the perf_init_event().
12699 * Otherwise, the __free_event() would mistakenly detach the non-exist
12700 * perf_ctx_data because of the other errors between them.
12701 */
12702 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
12703 err = attach_perf_ctx_data(event);
12704 if (err)
12705 return ERR_PTR(err);
12706 }
12707
12708 /*
12709 * Disallow uncore-task events. Similarly, disallow uncore-cgroup
12710 * events (they don't make sense as the cgroup will be different
12711 * on other CPUs in the uncore mask).
12712 */
12713 if (pmu->task_ctx_nr == perf_invalid_context && (task || cgroup_fd != -1))
12714 return ERR_PTR(-EINVAL);
12715
12716 if (event->attr.aux_output &&
12717 (!(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT) ||
12718 event->attr.aux_pause || event->attr.aux_resume))
12719 return ERR_PTR(-EOPNOTSUPP);
12720
12721 if (event->attr.aux_pause && event->attr.aux_resume)
12722 return ERR_PTR(-EINVAL);
12723
12724 if (event->attr.aux_start_paused) {
12725 if (!(pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE))
12726 return ERR_PTR(-EOPNOTSUPP);
12727 event->hw.aux_paused = 1;
12728 }
12729
12730 if (cgroup_fd != -1) {
12731 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
12732 if (err)
12733 return ERR_PTR(err);
12734 }
12735
12736 err = exclusive_event_init(event);
12737 if (err)
12738 return ERR_PTR(err);
12739
12740 if (has_addr_filter(event)) {
12741 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
12742 sizeof(struct perf_addr_filter_range),
12743 GFP_KERNEL);
12744 if (!event->addr_filter_ranges)
12745 return ERR_PTR(-ENOMEM);
12746
12747 /*
12748 * Clone the parent's vma offsets: they are valid until exec()
12749 * even if the mm is not shared with the parent.
12750 */
12751 if (event->parent) {
12752 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
12753
12754 raw_spin_lock_irq(&ifh->lock);
12755 memcpy(event->addr_filter_ranges,
12756 event->parent->addr_filter_ranges,
12757 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
12758 raw_spin_unlock_irq(&ifh->lock);
12759 }
12760
12761 /* force hw sync on the address filters */
12762 event->addr_filters_gen = 1;
12763 }
12764
12765 if (!event->parent) {
12766 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
12767 err = get_callchain_buffers(attr->sample_max_stack);
12768 if (err)
12769 return ERR_PTR(err);
12770 event->attach_state |= PERF_ATTACH_CALLCHAIN;
12771 }
12772 }
12773
12774 err = security_perf_event_alloc(event);
12775 if (err)
12776 return ERR_PTR(err);
12777
12778 /* symmetric to unaccount_event() in _free_event() */
12779 account_event(event);
12780
12781 return_ptr(event);
12782 }
12783
perf_copy_attr(struct perf_event_attr __user * uattr,struct perf_event_attr * attr)12784 static int perf_copy_attr(struct perf_event_attr __user *uattr,
12785 struct perf_event_attr *attr)
12786 {
12787 u32 size;
12788 int ret;
12789
12790 /* Zero the full structure, so that a short copy will be nice. */
12791 memset(attr, 0, sizeof(*attr));
12792
12793 ret = get_user(size, &uattr->size);
12794 if (ret)
12795 return ret;
12796
12797 /* ABI compatibility quirk: */
12798 if (!size)
12799 size = PERF_ATTR_SIZE_VER0;
12800 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
12801 goto err_size;
12802
12803 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
12804 if (ret) {
12805 if (ret == -E2BIG)
12806 goto err_size;
12807 return ret;
12808 }
12809
12810 attr->size = size;
12811
12812 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
12813 return -EINVAL;
12814
12815 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
12816 return -EINVAL;
12817
12818 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
12819 return -EINVAL;
12820
12821 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
12822 u64 mask = attr->branch_sample_type;
12823
12824 /* only using defined bits */
12825 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
12826 return -EINVAL;
12827
12828 /* at least one branch bit must be set */
12829 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
12830 return -EINVAL;
12831
12832 /* propagate priv level, when not set for branch */
12833 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
12834
12835 /* exclude_kernel checked on syscall entry */
12836 if (!attr->exclude_kernel)
12837 mask |= PERF_SAMPLE_BRANCH_KERNEL;
12838
12839 if (!attr->exclude_user)
12840 mask |= PERF_SAMPLE_BRANCH_USER;
12841
12842 if (!attr->exclude_hv)
12843 mask |= PERF_SAMPLE_BRANCH_HV;
12844 /*
12845 * adjust user setting (for HW filter setup)
12846 */
12847 attr->branch_sample_type = mask;
12848 }
12849 /* privileged levels capture (kernel, hv): check permissions */
12850 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
12851 ret = perf_allow_kernel();
12852 if (ret)
12853 return ret;
12854 }
12855 }
12856
12857 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
12858 ret = perf_reg_validate(attr->sample_regs_user);
12859 if (ret)
12860 return ret;
12861 }
12862
12863 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
12864 if (!arch_perf_have_user_stack_dump())
12865 return -ENOSYS;
12866
12867 /*
12868 * We have __u32 type for the size, but so far
12869 * we can only use __u16 as maximum due to the
12870 * __u16 sample size limit.
12871 */
12872 if (attr->sample_stack_user >= USHRT_MAX)
12873 return -EINVAL;
12874 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
12875 return -EINVAL;
12876 }
12877
12878 if (!attr->sample_max_stack)
12879 attr->sample_max_stack = sysctl_perf_event_max_stack;
12880
12881 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
12882 ret = perf_reg_validate(attr->sample_regs_intr);
12883
12884 #ifndef CONFIG_CGROUP_PERF
12885 if (attr->sample_type & PERF_SAMPLE_CGROUP)
12886 return -EINVAL;
12887 #endif
12888 if ((attr->sample_type & PERF_SAMPLE_WEIGHT) &&
12889 (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT))
12890 return -EINVAL;
12891
12892 if (!attr->inherit && attr->inherit_thread)
12893 return -EINVAL;
12894
12895 if (attr->remove_on_exec && attr->enable_on_exec)
12896 return -EINVAL;
12897
12898 if (attr->sigtrap && !attr->remove_on_exec)
12899 return -EINVAL;
12900
12901 out:
12902 return ret;
12903
12904 err_size:
12905 put_user(sizeof(*attr), &uattr->size);
12906 ret = -E2BIG;
12907 goto out;
12908 }
12909
mutex_lock_double(struct mutex * a,struct mutex * b)12910 static void mutex_lock_double(struct mutex *a, struct mutex *b)
12911 {
12912 if (b < a)
12913 swap(a, b);
12914
12915 mutex_lock(a);
12916 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
12917 }
12918
12919 static int
perf_event_set_output(struct perf_event * event,struct perf_event * output_event)12920 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
12921 {
12922 struct perf_buffer *rb = NULL;
12923 int ret = -EINVAL;
12924
12925 if (!output_event) {
12926 mutex_lock(&event->mmap_mutex);
12927 goto set;
12928 }
12929
12930 /* don't allow circular references */
12931 if (event == output_event)
12932 goto out;
12933
12934 /*
12935 * Don't allow cross-cpu buffers
12936 */
12937 if (output_event->cpu != event->cpu)
12938 goto out;
12939
12940 /*
12941 * If its not a per-cpu rb, it must be the same task.
12942 */
12943 if (output_event->cpu == -1 && output_event->hw.target != event->hw.target)
12944 goto out;
12945
12946 /*
12947 * Mixing clocks in the same buffer is trouble you don't need.
12948 */
12949 if (output_event->clock != event->clock)
12950 goto out;
12951
12952 /*
12953 * Either writing ring buffer from beginning or from end.
12954 * Mixing is not allowed.
12955 */
12956 if (is_write_backward(output_event) != is_write_backward(event))
12957 goto out;
12958
12959 /*
12960 * If both events generate aux data, they must be on the same PMU
12961 */
12962 if (has_aux(event) && has_aux(output_event) &&
12963 event->pmu != output_event->pmu)
12964 goto out;
12965
12966 /*
12967 * Hold both mmap_mutex to serialize against perf_mmap_close(). Since
12968 * output_event is already on rb->event_list, and the list iteration
12969 * restarts after every removal, it is guaranteed this new event is
12970 * observed *OR* if output_event is already removed, it's guaranteed we
12971 * observe !rb->mmap_count.
12972 */
12973 mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex);
12974 set:
12975 /* Can't redirect output if we've got an active mmap() */
12976 if (atomic_read(&event->mmap_count))
12977 goto unlock;
12978
12979 if (output_event) {
12980 /* get the rb we want to redirect to */
12981 rb = ring_buffer_get(output_event);
12982 if (!rb)
12983 goto unlock;
12984
12985 /* did we race against perf_mmap_close() */
12986 if (!atomic_read(&rb->mmap_count)) {
12987 ring_buffer_put(rb);
12988 goto unlock;
12989 }
12990 }
12991
12992 ring_buffer_attach(event, rb);
12993
12994 ret = 0;
12995 unlock:
12996 mutex_unlock(&event->mmap_mutex);
12997 if (output_event)
12998 mutex_unlock(&output_event->mmap_mutex);
12999
13000 out:
13001 return ret;
13002 }
13003
perf_event_set_clock(struct perf_event * event,clockid_t clk_id)13004 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
13005 {
13006 bool nmi_safe = false;
13007
13008 switch (clk_id) {
13009 case CLOCK_MONOTONIC:
13010 event->clock = &ktime_get_mono_fast_ns;
13011 nmi_safe = true;
13012 break;
13013
13014 case CLOCK_MONOTONIC_RAW:
13015 event->clock = &ktime_get_raw_fast_ns;
13016 nmi_safe = true;
13017 break;
13018
13019 case CLOCK_REALTIME:
13020 event->clock = &ktime_get_real_ns;
13021 break;
13022
13023 case CLOCK_BOOTTIME:
13024 event->clock = &ktime_get_boottime_ns;
13025 break;
13026
13027 case CLOCK_TAI:
13028 event->clock = &ktime_get_clocktai_ns;
13029 break;
13030
13031 default:
13032 return -EINVAL;
13033 }
13034
13035 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
13036 return -EINVAL;
13037
13038 return 0;
13039 }
13040
13041 static bool
perf_check_permission(struct perf_event_attr * attr,struct task_struct * task)13042 perf_check_permission(struct perf_event_attr *attr, struct task_struct *task)
13043 {
13044 unsigned int ptrace_mode = PTRACE_MODE_READ_REALCREDS;
13045 bool is_capable = perfmon_capable();
13046
13047 if (attr->sigtrap) {
13048 /*
13049 * perf_event_attr::sigtrap sends signals to the other task.
13050 * Require the current task to also have CAP_KILL.
13051 */
13052 rcu_read_lock();
13053 is_capable &= ns_capable(__task_cred(task)->user_ns, CAP_KILL);
13054 rcu_read_unlock();
13055
13056 /*
13057 * If the required capabilities aren't available, checks for
13058 * ptrace permissions: upgrade to ATTACH, since sending signals
13059 * can effectively change the target task.
13060 */
13061 ptrace_mode = PTRACE_MODE_ATTACH_REALCREDS;
13062 }
13063
13064 /*
13065 * Preserve ptrace permission check for backwards compatibility. The
13066 * ptrace check also includes checks that the current task and other
13067 * task have matching uids, and is therefore not done here explicitly.
13068 */
13069 return is_capable || ptrace_may_access(task, ptrace_mode);
13070 }
13071
13072 /**
13073 * sys_perf_event_open - open a performance event, associate it to a task/cpu
13074 *
13075 * @attr_uptr: event_id type attributes for monitoring/sampling
13076 * @pid: target pid
13077 * @cpu: target cpu
13078 * @group_fd: group leader event fd
13079 * @flags: perf event open flags
13080 */
SYSCALL_DEFINE5(perf_event_open,struct perf_event_attr __user *,attr_uptr,pid_t,pid,int,cpu,int,group_fd,unsigned long,flags)13081 SYSCALL_DEFINE5(perf_event_open,
13082 struct perf_event_attr __user *, attr_uptr,
13083 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
13084 {
13085 struct perf_event *group_leader = NULL, *output_event = NULL;
13086 struct perf_event_pmu_context *pmu_ctx;
13087 struct perf_event *event, *sibling;
13088 struct perf_event_attr attr;
13089 struct perf_event_context *ctx;
13090 struct file *event_file = NULL;
13091 struct task_struct *task = NULL;
13092 struct pmu *pmu;
13093 int event_fd;
13094 int move_group = 0;
13095 int err;
13096 int f_flags = O_RDWR;
13097 int cgroup_fd = -1;
13098
13099 /* for future expandability... */
13100 if (flags & ~PERF_FLAG_ALL)
13101 return -EINVAL;
13102
13103 err = perf_copy_attr(attr_uptr, &attr);
13104 if (err)
13105 return err;
13106
13107 /* Do we allow access to perf_event_open(2) ? */
13108 err = security_perf_event_open(PERF_SECURITY_OPEN);
13109 if (err)
13110 return err;
13111
13112 if (!attr.exclude_kernel) {
13113 err = perf_allow_kernel();
13114 if (err)
13115 return err;
13116 }
13117
13118 if (attr.namespaces) {
13119 if (!perfmon_capable())
13120 return -EACCES;
13121 }
13122
13123 if (attr.freq) {
13124 if (attr.sample_freq > sysctl_perf_event_sample_rate)
13125 return -EINVAL;
13126 } else {
13127 if (attr.sample_period & (1ULL << 63))
13128 return -EINVAL;
13129 }
13130
13131 /* Only privileged users can get physical addresses */
13132 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
13133 err = perf_allow_kernel();
13134 if (err)
13135 return err;
13136 }
13137
13138 /* REGS_INTR can leak data, lockdown must prevent this */
13139 if (attr.sample_type & PERF_SAMPLE_REGS_INTR) {
13140 err = security_locked_down(LOCKDOWN_PERF);
13141 if (err)
13142 return err;
13143 }
13144
13145 /*
13146 * In cgroup mode, the pid argument is used to pass the fd
13147 * opened to the cgroup directory in cgroupfs. The cpu argument
13148 * designates the cpu on which to monitor threads from that
13149 * cgroup.
13150 */
13151 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
13152 return -EINVAL;
13153
13154 if (flags & PERF_FLAG_FD_CLOEXEC)
13155 f_flags |= O_CLOEXEC;
13156
13157 event_fd = get_unused_fd_flags(f_flags);
13158 if (event_fd < 0)
13159 return event_fd;
13160
13161 CLASS(fd, group)(group_fd); // group_fd == -1 => empty
13162 if (group_fd != -1) {
13163 if (!is_perf_file(group)) {
13164 err = -EBADF;
13165 goto err_fd;
13166 }
13167 group_leader = fd_file(group)->private_data;
13168 if (flags & PERF_FLAG_FD_OUTPUT)
13169 output_event = group_leader;
13170 if (flags & PERF_FLAG_FD_NO_GROUP)
13171 group_leader = NULL;
13172 }
13173
13174 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
13175 task = find_lively_task_by_vpid(pid);
13176 if (IS_ERR(task)) {
13177 err = PTR_ERR(task);
13178 goto err_fd;
13179 }
13180 }
13181
13182 if (task && group_leader &&
13183 group_leader->attr.inherit != attr.inherit) {
13184 err = -EINVAL;
13185 goto err_task;
13186 }
13187
13188 if (flags & PERF_FLAG_PID_CGROUP)
13189 cgroup_fd = pid;
13190
13191 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
13192 NULL, NULL, cgroup_fd);
13193 if (IS_ERR(event)) {
13194 err = PTR_ERR(event);
13195 goto err_task;
13196 }
13197
13198 if (is_sampling_event(event)) {
13199 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
13200 err = -EOPNOTSUPP;
13201 goto err_alloc;
13202 }
13203 }
13204
13205 /*
13206 * Special case software events and allow them to be part of
13207 * any hardware group.
13208 */
13209 pmu = event->pmu;
13210
13211 if (attr.use_clockid) {
13212 err = perf_event_set_clock(event, attr.clockid);
13213 if (err)
13214 goto err_alloc;
13215 }
13216
13217 if (pmu->task_ctx_nr == perf_sw_context)
13218 event->event_caps |= PERF_EV_CAP_SOFTWARE;
13219
13220 if (task) {
13221 err = down_read_interruptible(&task->signal->exec_update_lock);
13222 if (err)
13223 goto err_alloc;
13224
13225 /*
13226 * We must hold exec_update_lock across this and any potential
13227 * perf_install_in_context() call for this new event to
13228 * serialize against exec() altering our credentials (and the
13229 * perf_event_exit_task() that could imply).
13230 */
13231 err = -EACCES;
13232 if (!perf_check_permission(&attr, task))
13233 goto err_cred;
13234 }
13235
13236 /*
13237 * Get the target context (task or percpu):
13238 */
13239 ctx = find_get_context(task, event);
13240 if (IS_ERR(ctx)) {
13241 err = PTR_ERR(ctx);
13242 goto err_cred;
13243 }
13244
13245 mutex_lock(&ctx->mutex);
13246
13247 if (ctx->task == TASK_TOMBSTONE) {
13248 err = -ESRCH;
13249 goto err_locked;
13250 }
13251
13252 if (!task) {
13253 /*
13254 * Check if the @cpu we're creating an event for is online.
13255 *
13256 * We use the perf_cpu_context::ctx::mutex to serialize against
13257 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
13258 */
13259 struct perf_cpu_context *cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
13260
13261 if (!cpuctx->online) {
13262 err = -ENODEV;
13263 goto err_locked;
13264 }
13265 }
13266
13267 if (group_leader) {
13268 err = -EINVAL;
13269
13270 /*
13271 * Do not allow a recursive hierarchy (this new sibling
13272 * becoming part of another group-sibling):
13273 */
13274 if (group_leader->group_leader != group_leader)
13275 goto err_locked;
13276
13277 /* All events in a group should have the same clock */
13278 if (group_leader->clock != event->clock)
13279 goto err_locked;
13280
13281 /*
13282 * Make sure we're both events for the same CPU;
13283 * grouping events for different CPUs is broken; since
13284 * you can never concurrently schedule them anyhow.
13285 */
13286 if (group_leader->cpu != event->cpu)
13287 goto err_locked;
13288
13289 /*
13290 * Make sure we're both on the same context; either task or cpu.
13291 */
13292 if (group_leader->ctx != ctx)
13293 goto err_locked;
13294
13295 /*
13296 * Only a group leader can be exclusive or pinned
13297 */
13298 if (attr.exclusive || attr.pinned)
13299 goto err_locked;
13300
13301 if (is_software_event(event) &&
13302 !in_software_context(group_leader)) {
13303 /*
13304 * If the event is a sw event, but the group_leader
13305 * is on hw context.
13306 *
13307 * Allow the addition of software events to hw
13308 * groups, this is safe because software events
13309 * never fail to schedule.
13310 *
13311 * Note the comment that goes with struct
13312 * perf_event_pmu_context.
13313 */
13314 pmu = group_leader->pmu_ctx->pmu;
13315 } else if (!is_software_event(event)) {
13316 if (is_software_event(group_leader) &&
13317 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
13318 /*
13319 * In case the group is a pure software group, and we
13320 * try to add a hardware event, move the whole group to
13321 * the hardware context.
13322 */
13323 move_group = 1;
13324 }
13325
13326 /* Don't allow group of multiple hw events from different pmus */
13327 if (!in_software_context(group_leader) &&
13328 group_leader->pmu_ctx->pmu != pmu)
13329 goto err_locked;
13330 }
13331 }
13332
13333 /*
13334 * Now that we're certain of the pmu; find the pmu_ctx.
13335 */
13336 pmu_ctx = find_get_pmu_context(pmu, ctx, event);
13337 if (IS_ERR(pmu_ctx)) {
13338 err = PTR_ERR(pmu_ctx);
13339 goto err_locked;
13340 }
13341 event->pmu_ctx = pmu_ctx;
13342
13343 if (output_event) {
13344 err = perf_event_set_output(event, output_event);
13345 if (err)
13346 goto err_context;
13347 }
13348
13349 if (!perf_event_validate_size(event)) {
13350 err = -E2BIG;
13351 goto err_context;
13352 }
13353
13354 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
13355 err = -EINVAL;
13356 goto err_context;
13357 }
13358
13359 /*
13360 * Must be under the same ctx::mutex as perf_install_in_context(),
13361 * because we need to serialize with concurrent event creation.
13362 */
13363 if (!exclusive_event_installable(event, ctx)) {
13364 err = -EBUSY;
13365 goto err_context;
13366 }
13367
13368 WARN_ON_ONCE(ctx->parent_ctx);
13369
13370 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags);
13371 if (IS_ERR(event_file)) {
13372 err = PTR_ERR(event_file);
13373 event_file = NULL;
13374 goto err_context;
13375 }
13376
13377 /*
13378 * This is the point on no return; we cannot fail hereafter. This is
13379 * where we start modifying current state.
13380 */
13381
13382 if (move_group) {
13383 perf_remove_from_context(group_leader, 0);
13384 put_pmu_ctx(group_leader->pmu_ctx);
13385
13386 for_each_sibling_event(sibling, group_leader) {
13387 perf_remove_from_context(sibling, 0);
13388 put_pmu_ctx(sibling->pmu_ctx);
13389 }
13390
13391 /*
13392 * Install the group siblings before the group leader.
13393 *
13394 * Because a group leader will try and install the entire group
13395 * (through the sibling list, which is still in-tact), we can
13396 * end up with siblings installed in the wrong context.
13397 *
13398 * By installing siblings first we NO-OP because they're not
13399 * reachable through the group lists.
13400 */
13401 for_each_sibling_event(sibling, group_leader) {
13402 sibling->pmu_ctx = pmu_ctx;
13403 get_pmu_ctx(pmu_ctx);
13404 perf_event__state_init(sibling);
13405 perf_install_in_context(ctx, sibling, sibling->cpu);
13406 }
13407
13408 /*
13409 * Removing from the context ends up with disabled
13410 * event. What we want here is event in the initial
13411 * startup state, ready to be add into new context.
13412 */
13413 group_leader->pmu_ctx = pmu_ctx;
13414 get_pmu_ctx(pmu_ctx);
13415 perf_event__state_init(group_leader);
13416 perf_install_in_context(ctx, group_leader, group_leader->cpu);
13417 }
13418
13419 /*
13420 * Precalculate sample_data sizes; do while holding ctx::mutex such
13421 * that we're serialized against further additions and before
13422 * perf_install_in_context() which is the point the event is active and
13423 * can use these values.
13424 */
13425 perf_event__header_size(event);
13426 perf_event__id_header_size(event);
13427
13428 event->owner = current;
13429
13430 perf_install_in_context(ctx, event, event->cpu);
13431 perf_unpin_context(ctx);
13432
13433 mutex_unlock(&ctx->mutex);
13434
13435 if (task) {
13436 up_read(&task->signal->exec_update_lock);
13437 put_task_struct(task);
13438 }
13439
13440 mutex_lock(¤t->perf_event_mutex);
13441 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
13442 mutex_unlock(¤t->perf_event_mutex);
13443
13444 /*
13445 * File reference in group guarantees that group_leader has been
13446 * kept alive until we place the new event on the sibling_list.
13447 * This ensures destruction of the group leader will find
13448 * the pointer to itself in perf_group_detach().
13449 */
13450 fd_install(event_fd, event_file);
13451 return event_fd;
13452
13453 err_context:
13454 put_pmu_ctx(event->pmu_ctx);
13455 event->pmu_ctx = NULL; /* _free_event() */
13456 err_locked:
13457 mutex_unlock(&ctx->mutex);
13458 perf_unpin_context(ctx);
13459 put_ctx(ctx);
13460 err_cred:
13461 if (task)
13462 up_read(&task->signal->exec_update_lock);
13463 err_alloc:
13464 free_event(event);
13465 err_task:
13466 if (task)
13467 put_task_struct(task);
13468 err_fd:
13469 put_unused_fd(event_fd);
13470 return err;
13471 }
13472
13473 /**
13474 * perf_event_create_kernel_counter
13475 *
13476 * @attr: attributes of the counter to create
13477 * @cpu: cpu in which the counter is bound
13478 * @task: task to profile (NULL for percpu)
13479 * @overflow_handler: callback to trigger when we hit the event
13480 * @context: context data could be used in overflow_handler callback
13481 */
13482 struct perf_event *
perf_event_create_kernel_counter(struct perf_event_attr * attr,int cpu,struct task_struct * task,perf_overflow_handler_t overflow_handler,void * context)13483 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
13484 struct task_struct *task,
13485 perf_overflow_handler_t overflow_handler,
13486 void *context)
13487 {
13488 struct perf_event_pmu_context *pmu_ctx;
13489 struct perf_event_context *ctx;
13490 struct perf_event *event;
13491 struct pmu *pmu;
13492 int err;
13493
13494 /*
13495 * Grouping is not supported for kernel events, neither is 'AUX',
13496 * make sure the caller's intentions are adjusted.
13497 */
13498 if (attr->aux_output || attr->aux_action)
13499 return ERR_PTR(-EINVAL);
13500
13501 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
13502 overflow_handler, context, -1);
13503 if (IS_ERR(event)) {
13504 err = PTR_ERR(event);
13505 goto err;
13506 }
13507
13508 /* Mark owner so we could distinguish it from user events. */
13509 event->owner = TASK_TOMBSTONE;
13510 pmu = event->pmu;
13511
13512 if (pmu->task_ctx_nr == perf_sw_context)
13513 event->event_caps |= PERF_EV_CAP_SOFTWARE;
13514
13515 /*
13516 * Get the target context (task or percpu):
13517 */
13518 ctx = find_get_context(task, event);
13519 if (IS_ERR(ctx)) {
13520 err = PTR_ERR(ctx);
13521 goto err_alloc;
13522 }
13523
13524 WARN_ON_ONCE(ctx->parent_ctx);
13525 mutex_lock(&ctx->mutex);
13526 if (ctx->task == TASK_TOMBSTONE) {
13527 err = -ESRCH;
13528 goto err_unlock;
13529 }
13530
13531 pmu_ctx = find_get_pmu_context(pmu, ctx, event);
13532 if (IS_ERR(pmu_ctx)) {
13533 err = PTR_ERR(pmu_ctx);
13534 goto err_unlock;
13535 }
13536 event->pmu_ctx = pmu_ctx;
13537
13538 if (!task) {
13539 /*
13540 * Check if the @cpu we're creating an event for is online.
13541 *
13542 * We use the perf_cpu_context::ctx::mutex to serialize against
13543 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
13544 */
13545 struct perf_cpu_context *cpuctx =
13546 container_of(ctx, struct perf_cpu_context, ctx);
13547 if (!cpuctx->online) {
13548 err = -ENODEV;
13549 goto err_pmu_ctx;
13550 }
13551 }
13552
13553 if (!exclusive_event_installable(event, ctx)) {
13554 err = -EBUSY;
13555 goto err_pmu_ctx;
13556 }
13557
13558 perf_install_in_context(ctx, event, event->cpu);
13559 perf_unpin_context(ctx);
13560 mutex_unlock(&ctx->mutex);
13561
13562 return event;
13563
13564 err_pmu_ctx:
13565 put_pmu_ctx(pmu_ctx);
13566 event->pmu_ctx = NULL; /* _free_event() */
13567 err_unlock:
13568 mutex_unlock(&ctx->mutex);
13569 perf_unpin_context(ctx);
13570 put_ctx(ctx);
13571 err_alloc:
13572 free_event(event);
13573 err:
13574 return ERR_PTR(err);
13575 }
13576 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
13577
__perf_pmu_remove(struct perf_event_context * ctx,int cpu,struct pmu * pmu,struct perf_event_groups * groups,struct list_head * events)13578 static void __perf_pmu_remove(struct perf_event_context *ctx,
13579 int cpu, struct pmu *pmu,
13580 struct perf_event_groups *groups,
13581 struct list_head *events)
13582 {
13583 struct perf_event *event, *sibling;
13584
13585 perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) {
13586 perf_remove_from_context(event, 0);
13587 put_pmu_ctx(event->pmu_ctx);
13588 list_add(&event->migrate_entry, events);
13589
13590 for_each_sibling_event(sibling, event) {
13591 perf_remove_from_context(sibling, 0);
13592 put_pmu_ctx(sibling->pmu_ctx);
13593 list_add(&sibling->migrate_entry, events);
13594 }
13595 }
13596 }
13597
__perf_pmu_install_event(struct pmu * pmu,struct perf_event_context * ctx,int cpu,struct perf_event * event)13598 static void __perf_pmu_install_event(struct pmu *pmu,
13599 struct perf_event_context *ctx,
13600 int cpu, struct perf_event *event)
13601 {
13602 struct perf_event_pmu_context *epc;
13603 struct perf_event_context *old_ctx = event->ctx;
13604
13605 get_ctx(ctx); /* normally find_get_context() */
13606
13607 event->cpu = cpu;
13608 epc = find_get_pmu_context(pmu, ctx, event);
13609 event->pmu_ctx = epc;
13610
13611 if (event->state >= PERF_EVENT_STATE_OFF)
13612 event->state = PERF_EVENT_STATE_INACTIVE;
13613 perf_install_in_context(ctx, event, cpu);
13614
13615 /*
13616 * Now that event->ctx is updated and visible, put the old ctx.
13617 */
13618 put_ctx(old_ctx);
13619 }
13620
__perf_pmu_install(struct perf_event_context * ctx,int cpu,struct pmu * pmu,struct list_head * events)13621 static void __perf_pmu_install(struct perf_event_context *ctx,
13622 int cpu, struct pmu *pmu, struct list_head *events)
13623 {
13624 struct perf_event *event, *tmp;
13625
13626 /*
13627 * Re-instate events in 2 passes.
13628 *
13629 * Skip over group leaders and only install siblings on this first
13630 * pass, siblings will not get enabled without a leader, however a
13631 * leader will enable its siblings, even if those are still on the old
13632 * context.
13633 */
13634 list_for_each_entry_safe(event, tmp, events, migrate_entry) {
13635 if (event->group_leader == event)
13636 continue;
13637
13638 list_del(&event->migrate_entry);
13639 __perf_pmu_install_event(pmu, ctx, cpu, event);
13640 }
13641
13642 /*
13643 * Once all the siblings are setup properly, install the group leaders
13644 * to make it go.
13645 */
13646 list_for_each_entry_safe(event, tmp, events, migrate_entry) {
13647 list_del(&event->migrate_entry);
13648 __perf_pmu_install_event(pmu, ctx, cpu, event);
13649 }
13650 }
13651
perf_pmu_migrate_context(struct pmu * pmu,int src_cpu,int dst_cpu)13652 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
13653 {
13654 struct perf_event_context *src_ctx, *dst_ctx;
13655 LIST_HEAD(events);
13656
13657 /*
13658 * Since per-cpu context is persistent, no need to grab an extra
13659 * reference.
13660 */
13661 src_ctx = &per_cpu_ptr(&perf_cpu_context, src_cpu)->ctx;
13662 dst_ctx = &per_cpu_ptr(&perf_cpu_context, dst_cpu)->ctx;
13663
13664 /*
13665 * See perf_event_ctx_lock() for comments on the details
13666 * of swizzling perf_event::ctx.
13667 */
13668 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
13669
13670 __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->pinned_groups, &events);
13671 __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->flexible_groups, &events);
13672
13673 if (!list_empty(&events)) {
13674 /*
13675 * Wait for the events to quiesce before re-instating them.
13676 */
13677 synchronize_rcu();
13678
13679 __perf_pmu_install(dst_ctx, dst_cpu, pmu, &events);
13680 }
13681
13682 mutex_unlock(&dst_ctx->mutex);
13683 mutex_unlock(&src_ctx->mutex);
13684 }
13685 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
13686
sync_child_event(struct perf_event * child_event)13687 static void sync_child_event(struct perf_event *child_event)
13688 {
13689 struct perf_event *parent_event = child_event->parent;
13690 u64 child_val;
13691
13692 if (child_event->attr.inherit_stat) {
13693 struct task_struct *task = child_event->ctx->task;
13694
13695 if (task && task != TASK_TOMBSTONE)
13696 perf_event_read_event(child_event, task);
13697 }
13698
13699 child_val = perf_event_count(child_event, false);
13700
13701 /*
13702 * Add back the child's count to the parent's count:
13703 */
13704 atomic64_add(child_val, &parent_event->child_count);
13705 atomic64_add(child_event->total_time_enabled,
13706 &parent_event->child_total_time_enabled);
13707 atomic64_add(child_event->total_time_running,
13708 &parent_event->child_total_time_running);
13709 }
13710
13711 static void
perf_event_exit_event(struct perf_event * event,struct perf_event_context * ctx)13712 perf_event_exit_event(struct perf_event *event, struct perf_event_context *ctx)
13713 {
13714 struct perf_event *parent_event = event->parent;
13715 unsigned long detach_flags = 0;
13716
13717 if (parent_event) {
13718 /*
13719 * Do not destroy the 'original' grouping; because of the
13720 * context switch optimization the original events could've
13721 * ended up in a random child task.
13722 *
13723 * If we were to destroy the original group, all group related
13724 * operations would cease to function properly after this
13725 * random child dies.
13726 *
13727 * Do destroy all inherited groups, we don't care about those
13728 * and being thorough is better.
13729 */
13730 detach_flags = DETACH_GROUP | DETACH_CHILD;
13731 mutex_lock(&parent_event->child_mutex);
13732 }
13733
13734 perf_remove_from_context(event, detach_flags);
13735
13736 raw_spin_lock_irq(&ctx->lock);
13737 if (event->state > PERF_EVENT_STATE_EXIT)
13738 perf_event_set_state(event, PERF_EVENT_STATE_EXIT);
13739 raw_spin_unlock_irq(&ctx->lock);
13740
13741 /*
13742 * Child events can be freed.
13743 */
13744 if (parent_event) {
13745 mutex_unlock(&parent_event->child_mutex);
13746 /*
13747 * Kick perf_poll() for is_event_hup();
13748 */
13749 perf_event_wakeup(parent_event);
13750 free_event(event);
13751 put_event(parent_event);
13752 return;
13753 }
13754
13755 /*
13756 * Parent events are governed by their filedesc, retain them.
13757 */
13758 perf_event_wakeup(event);
13759 }
13760
perf_event_exit_task_context(struct task_struct * child)13761 static void perf_event_exit_task_context(struct task_struct *child)
13762 {
13763 struct perf_event_context *child_ctx, *clone_ctx = NULL;
13764 struct perf_event *child_event, *next;
13765
13766 WARN_ON_ONCE(child != current);
13767
13768 child_ctx = perf_pin_task_context(child);
13769 if (!child_ctx)
13770 return;
13771
13772 /*
13773 * In order to reduce the amount of tricky in ctx tear-down, we hold
13774 * ctx::mutex over the entire thing. This serializes against almost
13775 * everything that wants to access the ctx.
13776 *
13777 * The exception is sys_perf_event_open() /
13778 * perf_event_create_kernel_count() which does find_get_context()
13779 * without ctx::mutex (it cannot because of the move_group double mutex
13780 * lock thing). See the comments in perf_install_in_context().
13781 */
13782 mutex_lock(&child_ctx->mutex);
13783
13784 /*
13785 * In a single ctx::lock section, de-schedule the events and detach the
13786 * context from the task such that we cannot ever get it scheduled back
13787 * in.
13788 */
13789 raw_spin_lock_irq(&child_ctx->lock);
13790 task_ctx_sched_out(child_ctx, NULL, EVENT_ALL);
13791
13792 /*
13793 * Now that the context is inactive, destroy the task <-> ctx relation
13794 * and mark the context dead.
13795 */
13796 RCU_INIT_POINTER(child->perf_event_ctxp, NULL);
13797 put_ctx(child_ctx); /* cannot be last */
13798 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
13799 put_task_struct(current); /* cannot be last */
13800
13801 clone_ctx = unclone_ctx(child_ctx);
13802 raw_spin_unlock_irq(&child_ctx->lock);
13803
13804 if (clone_ctx)
13805 put_ctx(clone_ctx);
13806
13807 /*
13808 * Report the task dead after unscheduling the events so that we
13809 * won't get any samples after PERF_RECORD_EXIT. We can however still
13810 * get a few PERF_RECORD_READ events.
13811 */
13812 perf_event_task(child, child_ctx, 0);
13813
13814 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
13815 perf_event_exit_event(child_event, child_ctx);
13816
13817 mutex_unlock(&child_ctx->mutex);
13818
13819 put_ctx(child_ctx);
13820 }
13821
13822 /*
13823 * When a child task exits, feed back event values to parent events.
13824 *
13825 * Can be called with exec_update_lock held when called from
13826 * setup_new_exec().
13827 */
perf_event_exit_task(struct task_struct * child)13828 void perf_event_exit_task(struct task_struct *child)
13829 {
13830 struct perf_event *event, *tmp;
13831
13832 mutex_lock(&child->perf_event_mutex);
13833 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
13834 owner_entry) {
13835 list_del_init(&event->owner_entry);
13836
13837 /*
13838 * Ensure the list deletion is visible before we clear
13839 * the owner, closes a race against perf_release() where
13840 * we need to serialize on the owner->perf_event_mutex.
13841 */
13842 smp_store_release(&event->owner, NULL);
13843 }
13844 mutex_unlock(&child->perf_event_mutex);
13845
13846 perf_event_exit_task_context(child);
13847
13848 /*
13849 * The perf_event_exit_task_context calls perf_event_task
13850 * with child's task_ctx, which generates EXIT events for
13851 * child contexts and sets child->perf_event_ctxp[] to NULL.
13852 * At this point we need to send EXIT events to cpu contexts.
13853 */
13854 perf_event_task(child, NULL, 0);
13855
13856 /*
13857 * Detach the perf_ctx_data for the system-wide event.
13858 */
13859 guard(percpu_read)(&global_ctx_data_rwsem);
13860 detach_task_ctx_data(child);
13861 }
13862
perf_free_event(struct perf_event * event,struct perf_event_context * ctx)13863 static void perf_free_event(struct perf_event *event,
13864 struct perf_event_context *ctx)
13865 {
13866 struct perf_event *parent = event->parent;
13867
13868 if (WARN_ON_ONCE(!parent))
13869 return;
13870
13871 mutex_lock(&parent->child_mutex);
13872 list_del_init(&event->child_list);
13873 mutex_unlock(&parent->child_mutex);
13874
13875 put_event(parent);
13876
13877 raw_spin_lock_irq(&ctx->lock);
13878 perf_group_detach(event);
13879 list_del_event(event, ctx);
13880 raw_spin_unlock_irq(&ctx->lock);
13881 free_event(event);
13882 }
13883
13884 /*
13885 * Free a context as created by inheritance by perf_event_init_task() below,
13886 * used by fork() in case of fail.
13887 *
13888 * Even though the task has never lived, the context and events have been
13889 * exposed through the child_list, so we must take care tearing it all down.
13890 */
perf_event_free_task(struct task_struct * task)13891 void perf_event_free_task(struct task_struct *task)
13892 {
13893 struct perf_event_context *ctx;
13894 struct perf_event *event, *tmp;
13895
13896 ctx = rcu_access_pointer(task->perf_event_ctxp);
13897 if (!ctx)
13898 return;
13899
13900 mutex_lock(&ctx->mutex);
13901 raw_spin_lock_irq(&ctx->lock);
13902 /*
13903 * Destroy the task <-> ctx relation and mark the context dead.
13904 *
13905 * This is important because even though the task hasn't been
13906 * exposed yet the context has been (through child_list).
13907 */
13908 RCU_INIT_POINTER(task->perf_event_ctxp, NULL);
13909 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
13910 put_task_struct(task); /* cannot be last */
13911 raw_spin_unlock_irq(&ctx->lock);
13912
13913
13914 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
13915 perf_free_event(event, ctx);
13916
13917 mutex_unlock(&ctx->mutex);
13918
13919 /*
13920 * perf_event_release_kernel() could've stolen some of our
13921 * child events and still have them on its free_list. In that
13922 * case we must wait for these events to have been freed (in
13923 * particular all their references to this task must've been
13924 * dropped).
13925 *
13926 * Without this copy_process() will unconditionally free this
13927 * task (irrespective of its reference count) and
13928 * _free_event()'s put_task_struct(event->hw.target) will be a
13929 * use-after-free.
13930 *
13931 * Wait for all events to drop their context reference.
13932 */
13933 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
13934 put_ctx(ctx); /* must be last */
13935 }
13936
perf_event_delayed_put(struct task_struct * task)13937 void perf_event_delayed_put(struct task_struct *task)
13938 {
13939 WARN_ON_ONCE(task->perf_event_ctxp);
13940 }
13941
perf_event_get(unsigned int fd)13942 struct file *perf_event_get(unsigned int fd)
13943 {
13944 struct file *file = fget(fd);
13945 if (!file)
13946 return ERR_PTR(-EBADF);
13947
13948 if (file->f_op != &perf_fops) {
13949 fput(file);
13950 return ERR_PTR(-EBADF);
13951 }
13952
13953 return file;
13954 }
13955
perf_get_event(struct file * file)13956 const struct perf_event *perf_get_event(struct file *file)
13957 {
13958 if (file->f_op != &perf_fops)
13959 return ERR_PTR(-EINVAL);
13960
13961 return file->private_data;
13962 }
13963
perf_event_attrs(struct perf_event * event)13964 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
13965 {
13966 if (!event)
13967 return ERR_PTR(-EINVAL);
13968
13969 return &event->attr;
13970 }
13971
perf_allow_kernel(void)13972 int perf_allow_kernel(void)
13973 {
13974 if (sysctl_perf_event_paranoid > 1 && !perfmon_capable())
13975 return -EACCES;
13976
13977 return security_perf_event_open(PERF_SECURITY_KERNEL);
13978 }
13979 EXPORT_SYMBOL_GPL(perf_allow_kernel);
13980
13981 /*
13982 * Inherit an event from parent task to child task.
13983 *
13984 * Returns:
13985 * - valid pointer on success
13986 * - NULL for orphaned events
13987 * - IS_ERR() on error
13988 */
13989 static struct perf_event *
inherit_event(struct perf_event * parent_event,struct task_struct * parent,struct perf_event_context * parent_ctx,struct task_struct * child,struct perf_event * group_leader,struct perf_event_context * child_ctx)13990 inherit_event(struct perf_event *parent_event,
13991 struct task_struct *parent,
13992 struct perf_event_context *parent_ctx,
13993 struct task_struct *child,
13994 struct perf_event *group_leader,
13995 struct perf_event_context *child_ctx)
13996 {
13997 enum perf_event_state parent_state = parent_event->state;
13998 struct perf_event_pmu_context *pmu_ctx;
13999 struct perf_event *child_event;
14000 unsigned long flags;
14001
14002 /*
14003 * Instead of creating recursive hierarchies of events,
14004 * we link inherited events back to the original parent,
14005 * which has a filp for sure, which we use as the reference
14006 * count:
14007 */
14008 if (parent_event->parent)
14009 parent_event = parent_event->parent;
14010
14011 child_event = perf_event_alloc(&parent_event->attr,
14012 parent_event->cpu,
14013 child,
14014 group_leader, parent_event,
14015 NULL, NULL, -1);
14016 if (IS_ERR(child_event))
14017 return child_event;
14018
14019 pmu_ctx = find_get_pmu_context(child_event->pmu, child_ctx, child_event);
14020 if (IS_ERR(pmu_ctx)) {
14021 free_event(child_event);
14022 return ERR_CAST(pmu_ctx);
14023 }
14024 child_event->pmu_ctx = pmu_ctx;
14025
14026 /*
14027 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
14028 * must be under the same lock in order to serialize against
14029 * perf_event_release_kernel(), such that either we must observe
14030 * is_orphaned_event() or they will observe us on the child_list.
14031 */
14032 mutex_lock(&parent_event->child_mutex);
14033 if (is_orphaned_event(parent_event) ||
14034 !atomic_long_inc_not_zero(&parent_event->refcount)) {
14035 mutex_unlock(&parent_event->child_mutex);
14036 free_event(child_event);
14037 return NULL;
14038 }
14039
14040 get_ctx(child_ctx);
14041
14042 /*
14043 * Make the child state follow the state of the parent event,
14044 * not its attr.disabled bit. We hold the parent's mutex,
14045 * so we won't race with perf_event_{en, dis}able_family.
14046 */
14047 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
14048 child_event->state = PERF_EVENT_STATE_INACTIVE;
14049 else
14050 child_event->state = PERF_EVENT_STATE_OFF;
14051
14052 if (parent_event->attr.freq) {
14053 u64 sample_period = parent_event->hw.sample_period;
14054 struct hw_perf_event *hwc = &child_event->hw;
14055
14056 hwc->sample_period = sample_period;
14057 hwc->last_period = sample_period;
14058
14059 local64_set(&hwc->period_left, sample_period);
14060 }
14061
14062 child_event->ctx = child_ctx;
14063 child_event->overflow_handler = parent_event->overflow_handler;
14064 child_event->overflow_handler_context
14065 = parent_event->overflow_handler_context;
14066
14067 /*
14068 * Precalculate sample_data sizes
14069 */
14070 perf_event__header_size(child_event);
14071 perf_event__id_header_size(child_event);
14072
14073 /*
14074 * Link it up in the child's context:
14075 */
14076 raw_spin_lock_irqsave(&child_ctx->lock, flags);
14077 add_event_to_ctx(child_event, child_ctx);
14078 child_event->attach_state |= PERF_ATTACH_CHILD;
14079 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
14080
14081 /*
14082 * Link this into the parent event's child list
14083 */
14084 list_add_tail(&child_event->child_list, &parent_event->child_list);
14085 mutex_unlock(&parent_event->child_mutex);
14086
14087 return child_event;
14088 }
14089
14090 /*
14091 * Inherits an event group.
14092 *
14093 * This will quietly suppress orphaned events; !inherit_event() is not an error.
14094 * This matches with perf_event_release_kernel() removing all child events.
14095 *
14096 * Returns:
14097 * - 0 on success
14098 * - <0 on error
14099 */
inherit_group(struct perf_event * parent_event,struct task_struct * parent,struct perf_event_context * parent_ctx,struct task_struct * child,struct perf_event_context * child_ctx)14100 static int inherit_group(struct perf_event *parent_event,
14101 struct task_struct *parent,
14102 struct perf_event_context *parent_ctx,
14103 struct task_struct *child,
14104 struct perf_event_context *child_ctx)
14105 {
14106 struct perf_event *leader;
14107 struct perf_event *sub;
14108 struct perf_event *child_ctr;
14109
14110 leader = inherit_event(parent_event, parent, parent_ctx,
14111 child, NULL, child_ctx);
14112 if (IS_ERR(leader))
14113 return PTR_ERR(leader);
14114 /*
14115 * @leader can be NULL here because of is_orphaned_event(). In this
14116 * case inherit_event() will create individual events, similar to what
14117 * perf_group_detach() would do anyway.
14118 */
14119 for_each_sibling_event(sub, parent_event) {
14120 child_ctr = inherit_event(sub, parent, parent_ctx,
14121 child, leader, child_ctx);
14122 if (IS_ERR(child_ctr))
14123 return PTR_ERR(child_ctr);
14124
14125 if (sub->aux_event == parent_event && child_ctr &&
14126 !perf_get_aux_event(child_ctr, leader))
14127 return -EINVAL;
14128 }
14129 if (leader)
14130 leader->group_generation = parent_event->group_generation;
14131 return 0;
14132 }
14133
14134 /*
14135 * Creates the child task context and tries to inherit the event-group.
14136 *
14137 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
14138 * inherited_all set when we 'fail' to inherit an orphaned event; this is
14139 * consistent with perf_event_release_kernel() removing all child events.
14140 *
14141 * Returns:
14142 * - 0 on success
14143 * - <0 on error
14144 */
14145 static int
inherit_task_group(struct perf_event * event,struct task_struct * parent,struct perf_event_context * parent_ctx,struct task_struct * child,u64 clone_flags,int * inherited_all)14146 inherit_task_group(struct perf_event *event, struct task_struct *parent,
14147 struct perf_event_context *parent_ctx,
14148 struct task_struct *child,
14149 u64 clone_flags, int *inherited_all)
14150 {
14151 struct perf_event_context *child_ctx;
14152 int ret;
14153
14154 if (!event->attr.inherit ||
14155 (event->attr.inherit_thread && !(clone_flags & CLONE_THREAD)) ||
14156 /* Do not inherit if sigtrap and signal handlers were cleared. */
14157 (event->attr.sigtrap && (clone_flags & CLONE_CLEAR_SIGHAND))) {
14158 *inherited_all = 0;
14159 return 0;
14160 }
14161
14162 child_ctx = child->perf_event_ctxp;
14163 if (!child_ctx) {
14164 /*
14165 * This is executed from the parent task context, so
14166 * inherit events that have been marked for cloning.
14167 * First allocate and initialize a context for the
14168 * child.
14169 */
14170 child_ctx = alloc_perf_context(child);
14171 if (!child_ctx)
14172 return -ENOMEM;
14173
14174 child->perf_event_ctxp = child_ctx;
14175 }
14176
14177 ret = inherit_group(event, parent, parent_ctx, child, child_ctx);
14178 if (ret)
14179 *inherited_all = 0;
14180
14181 return ret;
14182 }
14183
14184 /*
14185 * Initialize the perf_event context in task_struct
14186 */
perf_event_init_context(struct task_struct * child,u64 clone_flags)14187 static int perf_event_init_context(struct task_struct *child, u64 clone_flags)
14188 {
14189 struct perf_event_context *child_ctx, *parent_ctx;
14190 struct perf_event_context *cloned_ctx;
14191 struct perf_event *event;
14192 struct task_struct *parent = current;
14193 int inherited_all = 1;
14194 unsigned long flags;
14195 int ret = 0;
14196
14197 if (likely(!parent->perf_event_ctxp))
14198 return 0;
14199
14200 /*
14201 * If the parent's context is a clone, pin it so it won't get
14202 * swapped under us.
14203 */
14204 parent_ctx = perf_pin_task_context(parent);
14205 if (!parent_ctx)
14206 return 0;
14207
14208 /*
14209 * No need to check if parent_ctx != NULL here; since we saw
14210 * it non-NULL earlier, the only reason for it to become NULL
14211 * is if we exit, and since we're currently in the middle of
14212 * a fork we can't be exiting at the same time.
14213 */
14214
14215 /*
14216 * Lock the parent list. No need to lock the child - not PID
14217 * hashed yet and not running, so nobody can access it.
14218 */
14219 mutex_lock(&parent_ctx->mutex);
14220
14221 /*
14222 * We dont have to disable NMIs - we are only looking at
14223 * the list, not manipulating it:
14224 */
14225 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
14226 ret = inherit_task_group(event, parent, parent_ctx,
14227 child, clone_flags, &inherited_all);
14228 if (ret)
14229 goto out_unlock;
14230 }
14231
14232 /*
14233 * We can't hold ctx->lock when iterating the ->flexible_group list due
14234 * to allocations, but we need to prevent rotation because
14235 * rotate_ctx() will change the list from interrupt context.
14236 */
14237 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
14238 parent_ctx->rotate_disable = 1;
14239 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
14240
14241 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
14242 ret = inherit_task_group(event, parent, parent_ctx,
14243 child, clone_flags, &inherited_all);
14244 if (ret)
14245 goto out_unlock;
14246 }
14247
14248 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
14249 parent_ctx->rotate_disable = 0;
14250
14251 child_ctx = child->perf_event_ctxp;
14252
14253 if (child_ctx && inherited_all) {
14254 /*
14255 * Mark the child context as a clone of the parent
14256 * context, or of whatever the parent is a clone of.
14257 *
14258 * Note that if the parent is a clone, the holding of
14259 * parent_ctx->lock avoids it from being uncloned.
14260 */
14261 cloned_ctx = parent_ctx->parent_ctx;
14262 if (cloned_ctx) {
14263 child_ctx->parent_ctx = cloned_ctx;
14264 child_ctx->parent_gen = parent_ctx->parent_gen;
14265 } else {
14266 child_ctx->parent_ctx = parent_ctx;
14267 child_ctx->parent_gen = parent_ctx->generation;
14268 }
14269 get_ctx(child_ctx->parent_ctx);
14270 }
14271
14272 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
14273 out_unlock:
14274 mutex_unlock(&parent_ctx->mutex);
14275
14276 perf_unpin_context(parent_ctx);
14277 put_ctx(parent_ctx);
14278
14279 return ret;
14280 }
14281
14282 /*
14283 * Initialize the perf_event context in task_struct
14284 */
perf_event_init_task(struct task_struct * child,u64 clone_flags)14285 int perf_event_init_task(struct task_struct *child, u64 clone_flags)
14286 {
14287 int ret;
14288
14289 memset(child->perf_recursion, 0, sizeof(child->perf_recursion));
14290 child->perf_event_ctxp = NULL;
14291 mutex_init(&child->perf_event_mutex);
14292 INIT_LIST_HEAD(&child->perf_event_list);
14293 child->perf_ctx_data = NULL;
14294
14295 ret = perf_event_init_context(child, clone_flags);
14296 if (ret) {
14297 perf_event_free_task(child);
14298 return ret;
14299 }
14300
14301 return 0;
14302 }
14303
perf_event_init_all_cpus(void)14304 static void __init perf_event_init_all_cpus(void)
14305 {
14306 struct swevent_htable *swhash;
14307 struct perf_cpu_context *cpuctx;
14308 int cpu;
14309
14310 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
14311 zalloc_cpumask_var(&perf_online_core_mask, GFP_KERNEL);
14312 zalloc_cpumask_var(&perf_online_die_mask, GFP_KERNEL);
14313 zalloc_cpumask_var(&perf_online_cluster_mask, GFP_KERNEL);
14314 zalloc_cpumask_var(&perf_online_pkg_mask, GFP_KERNEL);
14315 zalloc_cpumask_var(&perf_online_sys_mask, GFP_KERNEL);
14316
14317
14318 for_each_possible_cpu(cpu) {
14319 swhash = &per_cpu(swevent_htable, cpu);
14320 mutex_init(&swhash->hlist_mutex);
14321
14322 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
14323 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
14324
14325 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
14326
14327 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
14328 __perf_event_init_context(&cpuctx->ctx);
14329 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
14330 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
14331 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
14332 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
14333 cpuctx->heap = cpuctx->heap_default;
14334 }
14335 }
14336
perf_swevent_init_cpu(unsigned int cpu)14337 static void perf_swevent_init_cpu(unsigned int cpu)
14338 {
14339 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
14340
14341 mutex_lock(&swhash->hlist_mutex);
14342 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
14343 struct swevent_hlist *hlist;
14344
14345 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
14346 WARN_ON(!hlist);
14347 rcu_assign_pointer(swhash->swevent_hlist, hlist);
14348 }
14349 mutex_unlock(&swhash->hlist_mutex);
14350 }
14351
14352 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
__perf_event_exit_context(void * __info)14353 static void __perf_event_exit_context(void *__info)
14354 {
14355 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
14356 struct perf_event_context *ctx = __info;
14357 struct perf_event *event;
14358
14359 raw_spin_lock(&ctx->lock);
14360 ctx_sched_out(ctx, NULL, EVENT_TIME);
14361 list_for_each_entry(event, &ctx->event_list, event_entry)
14362 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
14363 raw_spin_unlock(&ctx->lock);
14364 }
14365
perf_event_clear_cpumask(unsigned int cpu)14366 static void perf_event_clear_cpumask(unsigned int cpu)
14367 {
14368 int target[PERF_PMU_MAX_SCOPE];
14369 unsigned int scope;
14370 struct pmu *pmu;
14371
14372 cpumask_clear_cpu(cpu, perf_online_mask);
14373
14374 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) {
14375 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu);
14376 struct cpumask *pmu_cpumask = perf_scope_cpumask(scope);
14377
14378 target[scope] = -1;
14379 if (WARN_ON_ONCE(!pmu_cpumask || !cpumask))
14380 continue;
14381
14382 if (!cpumask_test_and_clear_cpu(cpu, pmu_cpumask))
14383 continue;
14384 target[scope] = cpumask_any_but(cpumask, cpu);
14385 if (target[scope] < nr_cpu_ids)
14386 cpumask_set_cpu(target[scope], pmu_cpumask);
14387 }
14388
14389 /* migrate */
14390 list_for_each_entry(pmu, &pmus, entry) {
14391 if (pmu->scope == PERF_PMU_SCOPE_NONE ||
14392 WARN_ON_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE))
14393 continue;
14394
14395 if (target[pmu->scope] >= 0 && target[pmu->scope] < nr_cpu_ids)
14396 perf_pmu_migrate_context(pmu, cpu, target[pmu->scope]);
14397 }
14398 }
14399
perf_event_exit_cpu_context(int cpu)14400 static void perf_event_exit_cpu_context(int cpu)
14401 {
14402 struct perf_cpu_context *cpuctx;
14403 struct perf_event_context *ctx;
14404
14405 // XXX simplify cpuctx->online
14406 mutex_lock(&pmus_lock);
14407 /*
14408 * Clear the cpumasks, and migrate to other CPUs if possible.
14409 * Must be invoked before the __perf_event_exit_context.
14410 */
14411 perf_event_clear_cpumask(cpu);
14412 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
14413 ctx = &cpuctx->ctx;
14414
14415 mutex_lock(&ctx->mutex);
14416 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
14417 cpuctx->online = 0;
14418 mutex_unlock(&ctx->mutex);
14419 mutex_unlock(&pmus_lock);
14420 }
14421 #else
14422
perf_event_exit_cpu_context(int cpu)14423 static void perf_event_exit_cpu_context(int cpu) { }
14424
14425 #endif
14426
perf_event_setup_cpumask(unsigned int cpu)14427 static void perf_event_setup_cpumask(unsigned int cpu)
14428 {
14429 struct cpumask *pmu_cpumask;
14430 unsigned int scope;
14431
14432 /*
14433 * Early boot stage, the cpumask hasn't been set yet.
14434 * The perf_online_<domain>_masks includes the first CPU of each domain.
14435 * Always unconditionally set the boot CPU for the perf_online_<domain>_masks.
14436 */
14437 if (cpumask_empty(perf_online_mask)) {
14438 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) {
14439 pmu_cpumask = perf_scope_cpumask(scope);
14440 if (WARN_ON_ONCE(!pmu_cpumask))
14441 continue;
14442 cpumask_set_cpu(cpu, pmu_cpumask);
14443 }
14444 goto end;
14445 }
14446
14447 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) {
14448 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu);
14449
14450 pmu_cpumask = perf_scope_cpumask(scope);
14451
14452 if (WARN_ON_ONCE(!pmu_cpumask || !cpumask))
14453 continue;
14454
14455 if (!cpumask_empty(cpumask) &&
14456 cpumask_any_and(pmu_cpumask, cpumask) >= nr_cpu_ids)
14457 cpumask_set_cpu(cpu, pmu_cpumask);
14458 }
14459 end:
14460 cpumask_set_cpu(cpu, perf_online_mask);
14461 }
14462
perf_event_init_cpu(unsigned int cpu)14463 int perf_event_init_cpu(unsigned int cpu)
14464 {
14465 struct perf_cpu_context *cpuctx;
14466 struct perf_event_context *ctx;
14467
14468 perf_swevent_init_cpu(cpu);
14469
14470 mutex_lock(&pmus_lock);
14471 perf_event_setup_cpumask(cpu);
14472 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
14473 ctx = &cpuctx->ctx;
14474
14475 mutex_lock(&ctx->mutex);
14476 cpuctx->online = 1;
14477 mutex_unlock(&ctx->mutex);
14478 mutex_unlock(&pmus_lock);
14479
14480 return 0;
14481 }
14482
perf_event_exit_cpu(unsigned int cpu)14483 int perf_event_exit_cpu(unsigned int cpu)
14484 {
14485 perf_event_exit_cpu_context(cpu);
14486 return 0;
14487 }
14488
14489 static int
perf_reboot(struct notifier_block * notifier,unsigned long val,void * v)14490 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
14491 {
14492 int cpu;
14493
14494 for_each_online_cpu(cpu)
14495 perf_event_exit_cpu(cpu);
14496
14497 return NOTIFY_OK;
14498 }
14499
14500 /*
14501 * Run the perf reboot notifier at the very last possible moment so that
14502 * the generic watchdog code runs as long as possible.
14503 */
14504 static struct notifier_block perf_reboot_notifier = {
14505 .notifier_call = perf_reboot,
14506 .priority = INT_MIN,
14507 };
14508
perf_event_init(void)14509 void __init perf_event_init(void)
14510 {
14511 int ret;
14512
14513 idr_init(&pmu_idr);
14514
14515 perf_event_init_all_cpus();
14516 init_srcu_struct(&pmus_srcu);
14517 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
14518 perf_pmu_register(&perf_cpu_clock, "cpu_clock", -1);
14519 perf_pmu_register(&perf_task_clock, "task_clock", -1);
14520 perf_tp_register();
14521 perf_event_init_cpu(smp_processor_id());
14522 register_reboot_notifier(&perf_reboot_notifier);
14523
14524 ret = init_hw_breakpoint();
14525 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
14526
14527 perf_event_cache = KMEM_CACHE(perf_event, SLAB_PANIC);
14528
14529 /*
14530 * Build time assertion that we keep the data_head at the intended
14531 * location. IOW, validation we got the __reserved[] size right.
14532 */
14533 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
14534 != 1024);
14535 }
14536
perf_event_sysfs_show(struct device * dev,struct device_attribute * attr,char * page)14537 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
14538 char *page)
14539 {
14540 struct perf_pmu_events_attr *pmu_attr =
14541 container_of(attr, struct perf_pmu_events_attr, attr);
14542
14543 if (pmu_attr->event_str)
14544 return sprintf(page, "%s\n", pmu_attr->event_str);
14545
14546 return 0;
14547 }
14548 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
14549
perf_event_sysfs_init(void)14550 static int __init perf_event_sysfs_init(void)
14551 {
14552 struct pmu *pmu;
14553 int ret;
14554
14555 mutex_lock(&pmus_lock);
14556
14557 ret = bus_register(&pmu_bus);
14558 if (ret)
14559 goto unlock;
14560
14561 list_for_each_entry(pmu, &pmus, entry) {
14562 if (pmu->dev)
14563 continue;
14564
14565 ret = pmu_dev_alloc(pmu);
14566 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
14567 }
14568 pmu_bus_running = 1;
14569 ret = 0;
14570
14571 unlock:
14572 mutex_unlock(&pmus_lock);
14573
14574 return ret;
14575 }
14576 device_initcall(perf_event_sysfs_init);
14577
14578 #ifdef CONFIG_CGROUP_PERF
14579 static struct cgroup_subsys_state *
perf_cgroup_css_alloc(struct cgroup_subsys_state * parent_css)14580 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
14581 {
14582 struct perf_cgroup *jc;
14583
14584 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
14585 if (!jc)
14586 return ERR_PTR(-ENOMEM);
14587
14588 jc->info = alloc_percpu(struct perf_cgroup_info);
14589 if (!jc->info) {
14590 kfree(jc);
14591 return ERR_PTR(-ENOMEM);
14592 }
14593
14594 return &jc->css;
14595 }
14596
perf_cgroup_css_free(struct cgroup_subsys_state * css)14597 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
14598 {
14599 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
14600
14601 free_percpu(jc->info);
14602 kfree(jc);
14603 }
14604
perf_cgroup_css_online(struct cgroup_subsys_state * css)14605 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
14606 {
14607 perf_event_cgroup(css->cgroup);
14608 return 0;
14609 }
14610
__perf_cgroup_move(void * info)14611 static int __perf_cgroup_move(void *info)
14612 {
14613 struct task_struct *task = info;
14614
14615 preempt_disable();
14616 perf_cgroup_switch(task);
14617 preempt_enable();
14618
14619 return 0;
14620 }
14621
perf_cgroup_attach(struct cgroup_taskset * tset)14622 static void perf_cgroup_attach(struct cgroup_taskset *tset)
14623 {
14624 struct task_struct *task;
14625 struct cgroup_subsys_state *css;
14626
14627 cgroup_taskset_for_each(task, css, tset)
14628 task_function_call(task, __perf_cgroup_move, task);
14629 }
14630
14631 struct cgroup_subsys perf_event_cgrp_subsys = {
14632 .css_alloc = perf_cgroup_css_alloc,
14633 .css_free = perf_cgroup_css_free,
14634 .css_online = perf_cgroup_css_online,
14635 .attach = perf_cgroup_attach,
14636 /*
14637 * Implicitly enable on dfl hierarchy so that perf events can
14638 * always be filtered by cgroup2 path as long as perf_event
14639 * controller is not mounted on a legacy hierarchy.
14640 */
14641 .implicit_on_dfl = true,
14642 .threaded = true,
14643 };
14644 #endif /* CONFIG_CGROUP_PERF */
14645
14646 DEFINE_STATIC_CALL_RET0(perf_snapshot_branch_stack, perf_snapshot_branch_stack_t);
14647