1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Performance events core code:
4 *
5 * Copyright (C) 2008 Linutronix GmbH, Thomas Gleixner <tglx@kernel.org>
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 #include <linux/unwind_deferred.h>
60 #include <linux/kvm_types.h>
61 #include <linux/seq_file.h>
62
63 #include "internal.h"
64
65 #include <asm/irq_regs.h>
66
67 typedef int (*remote_function_f)(void *);
68
69 struct remote_function_call {
70 struct task_struct *p;
71 remote_function_f func;
72 void *info;
73 int ret;
74 };
75
remote_function(void * data)76 static void remote_function(void *data)
77 {
78 struct remote_function_call *tfc = data;
79 struct task_struct *p = tfc->p;
80
81 if (p) {
82 /* -EAGAIN */
83 if (task_cpu(p) != smp_processor_id())
84 return;
85
86 /*
87 * Now that we're on right CPU with IRQs disabled, we can test
88 * if we hit the right task without races.
89 */
90
91 tfc->ret = -ESRCH; /* No such (running) process */
92 if (p != current)
93 return;
94 }
95
96 tfc->ret = tfc->func(tfc->info);
97 }
98
99 /**
100 * task_function_call - call a function on the cpu on which a task runs
101 * @p: the task to evaluate
102 * @func: the function to be called
103 * @info: the function call argument
104 *
105 * Calls the function @func when the task is currently running. This might
106 * be on the current CPU, which just calls the function directly. This will
107 * retry due to any failures in smp_call_function_single(), such as if the
108 * task_cpu() goes offline concurrently.
109 *
110 * returns @func return value or -ESRCH or -ENXIO when the process isn't running
111 */
112 static int
task_function_call(struct task_struct * p,remote_function_f func,void * info)113 task_function_call(struct task_struct *p, remote_function_f func, void *info)
114 {
115 struct remote_function_call data = {
116 .p = p,
117 .func = func,
118 .info = info,
119 .ret = -EAGAIN,
120 };
121 int ret;
122
123 for (;;) {
124 ret = smp_call_function_single(task_cpu(p), remote_function,
125 &data, 1);
126 if (!ret)
127 ret = data.ret;
128
129 if (ret != -EAGAIN)
130 break;
131
132 cond_resched();
133 }
134
135 return ret;
136 }
137
138 /**
139 * cpu_function_call - call a function on the cpu
140 * @cpu: target cpu to queue this function
141 * @func: the function to be called
142 * @info: the function call argument
143 *
144 * Calls the function @func on the remote cpu.
145 *
146 * returns: @func return value or -ENXIO when the cpu is offline
147 */
cpu_function_call(int cpu,remote_function_f func,void * info)148 static int cpu_function_call(int cpu, remote_function_f func, void *info)
149 {
150 struct remote_function_call data = {
151 .p = NULL,
152 .func = func,
153 .info = info,
154 .ret = -ENXIO, /* No such CPU */
155 };
156
157 smp_call_function_single(cpu, remote_function, &data, 1);
158
159 return data.ret;
160 }
161
162 enum event_type_t {
163 EVENT_FLEXIBLE = 0x01,
164 EVENT_PINNED = 0x02,
165 EVENT_TIME = 0x04,
166 EVENT_FROZEN = 0x08,
167 /* see ctx_resched() for details */
168 EVENT_CPU = 0x10,
169 EVENT_CGROUP = 0x20,
170
171 /*
172 * EVENT_GUEST is set when scheduling in/out events between the host
173 * and a guest with a mediated vPMU. Among other things, EVENT_GUEST
174 * is used:
175 *
176 * - In for_each_epc() to skip PMUs that don't support events in a
177 * MEDIATED_VPMU guest, i.e. don't need to be context switched.
178 * - To indicate the start/end point of the events in a guest. Guest
179 * running time is deducted for host-only (exclude_guest) events.
180 */
181 EVENT_GUEST = 0x40,
182 EVENT_FLAGS = EVENT_CGROUP | EVENT_GUEST,
183 /* compound helpers */
184 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
185 EVENT_TIME_FROZEN = EVENT_TIME | EVENT_FROZEN,
186 };
187
__perf_ctx_lock(struct perf_event_context * ctx)188 static inline void __perf_ctx_lock(struct perf_event_context *ctx)
189 {
190 raw_spin_lock(&ctx->lock);
191 WARN_ON_ONCE(ctx->is_active & EVENT_FROZEN);
192 }
193
perf_ctx_lock(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)194 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
195 struct perf_event_context *ctx)
196 {
197 __perf_ctx_lock(&cpuctx->ctx);
198 if (ctx)
199 __perf_ctx_lock(ctx);
200 }
201
__perf_ctx_unlock(struct perf_event_context * ctx)202 static inline void __perf_ctx_unlock(struct perf_event_context *ctx)
203 {
204 /*
205 * If ctx_sched_in() didn't again set any ALL flags, clean up
206 * after ctx_sched_out() by clearing is_active.
207 */
208 if (ctx->is_active & EVENT_FROZEN) {
209 if (!(ctx->is_active & EVENT_ALL))
210 ctx->is_active = 0;
211 else
212 ctx->is_active &= ~EVENT_FROZEN;
213 }
214 raw_spin_unlock(&ctx->lock);
215 }
216
perf_ctx_unlock(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)217 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
218 struct perf_event_context *ctx)
219 {
220 if (ctx)
221 __perf_ctx_unlock(ctx);
222 __perf_ctx_unlock(&cpuctx->ctx);
223 }
224
225 typedef struct {
226 struct perf_cpu_context *cpuctx;
227 struct perf_event_context *ctx;
228 } class_perf_ctx_lock_t;
229
class_perf_ctx_lock_destructor(class_perf_ctx_lock_t * _T)230 static inline void class_perf_ctx_lock_destructor(class_perf_ctx_lock_t *_T)
231 { perf_ctx_unlock(_T->cpuctx, _T->ctx); }
232
233 static inline class_perf_ctx_lock_t
class_perf_ctx_lock_constructor(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)234 class_perf_ctx_lock_constructor(struct perf_cpu_context *cpuctx,
235 struct perf_event_context *ctx)
236 { perf_ctx_lock(cpuctx, ctx); return (class_perf_ctx_lock_t){ cpuctx, ctx }; }
237
238 #define TASK_TOMBSTONE ((void *)-1L)
239
is_kernel_event(struct perf_event * event)240 static bool is_kernel_event(struct perf_event *event)
241 {
242 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
243 }
244
245 static DEFINE_PER_CPU(struct perf_cpu_context, perf_cpu_context);
246
perf_cpu_task_ctx(void)247 struct perf_event_context *perf_cpu_task_ctx(void)
248 {
249 lockdep_assert_irqs_disabled();
250 return this_cpu_ptr(&perf_cpu_context)->task_ctx;
251 }
252
253 /*
254 * On task ctx scheduling...
255 *
256 * When !ctx->nr_events a task context will not be scheduled. This means
257 * we can disable the scheduler hooks (for performance) without leaving
258 * pending task ctx state.
259 *
260 * This however results in two special cases:
261 *
262 * - removing the last event from a task ctx; this is relatively straight
263 * forward and is done in __perf_remove_from_context.
264 *
265 * - adding the first event to a task ctx; this is tricky because we cannot
266 * rely on ctx->is_active and therefore cannot use event_function_call().
267 * See perf_install_in_context().
268 *
269 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
270 */
271
272 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
273 struct perf_event_context *, void *);
274
275 struct event_function_struct {
276 struct perf_event *event;
277 event_f func;
278 void *data;
279 };
280
event_function(void * info)281 static int event_function(void *info)
282 {
283 struct event_function_struct *efs = info;
284 struct perf_event *event = efs->event;
285 struct perf_event_context *ctx = event->ctx;
286 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
287 struct perf_event_context *task_ctx = cpuctx->task_ctx;
288 int ret = 0;
289
290 lockdep_assert_irqs_disabled();
291
292 perf_ctx_lock(cpuctx, task_ctx);
293 /*
294 * Since we do the IPI call without holding ctx->lock things can have
295 * changed, double check we hit the task we set out to hit.
296 */
297 if (ctx->task) {
298 if (ctx->task != current) {
299 ret = -ESRCH;
300 goto unlock;
301 }
302
303 /*
304 * We only use event_function_call() on established contexts,
305 * and event_function() is only ever called when active (or
306 * rather, we'll have bailed in task_function_call() or the
307 * above ctx->task != current test), therefore we must have
308 * ctx->is_active here.
309 */
310 WARN_ON_ONCE(!ctx->is_active);
311 /*
312 * And since we have ctx->is_active, cpuctx->task_ctx must
313 * match.
314 */
315 WARN_ON_ONCE(task_ctx != ctx);
316 } else {
317 WARN_ON_ONCE(&cpuctx->ctx != ctx);
318 }
319
320 efs->func(event, cpuctx, ctx, efs->data);
321 unlock:
322 perf_ctx_unlock(cpuctx, task_ctx);
323
324 return ret;
325 }
326
event_function_call(struct perf_event * event,event_f func,void * data)327 static void event_function_call(struct perf_event *event, event_f func, void *data)
328 {
329 struct perf_event_context *ctx = event->ctx;
330 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
331 struct perf_cpu_context *cpuctx;
332 struct event_function_struct efs = {
333 .event = event,
334 .func = func,
335 .data = data,
336 };
337
338 if (!event->parent) {
339 /*
340 * If this is a !child event, we must hold ctx::mutex to
341 * stabilize the event->ctx relation. See
342 * perf_event_ctx_lock().
343 */
344 lockdep_assert_held(&ctx->mutex);
345 }
346
347 if (!task) {
348 cpu_function_call(event->cpu, event_function, &efs);
349 return;
350 }
351
352 if (task == TASK_TOMBSTONE)
353 return;
354
355 again:
356 if (!task_function_call(task, event_function, &efs))
357 return;
358
359 local_irq_disable();
360 cpuctx = this_cpu_ptr(&perf_cpu_context);
361 perf_ctx_lock(cpuctx, ctx);
362 /*
363 * Reload the task pointer, it might have been changed by
364 * a concurrent perf_event_context_sched_out().
365 */
366 task = ctx->task;
367 if (task == TASK_TOMBSTONE)
368 goto unlock;
369 if (ctx->is_active) {
370 perf_ctx_unlock(cpuctx, ctx);
371 local_irq_enable();
372 goto again;
373 }
374 func(event, NULL, ctx, data);
375 unlock:
376 perf_ctx_unlock(cpuctx, ctx);
377 local_irq_enable();
378 }
379
380 /*
381 * Similar to event_function_call() + event_function(), but hard assumes IRQs
382 * are already disabled and we're on the right CPU.
383 */
event_function_local(struct perf_event * event,event_f func,void * data)384 static void event_function_local(struct perf_event *event, event_f func, void *data)
385 {
386 struct perf_event_context *ctx = event->ctx;
387 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
388 struct task_struct *task = READ_ONCE(ctx->task);
389 struct perf_event_context *task_ctx = NULL;
390
391 lockdep_assert_irqs_disabled();
392
393 if (task) {
394 if (task == TASK_TOMBSTONE)
395 return;
396
397 task_ctx = ctx;
398 }
399
400 perf_ctx_lock(cpuctx, task_ctx);
401
402 task = ctx->task;
403 if (task == TASK_TOMBSTONE)
404 goto unlock;
405
406 if (task) {
407 /*
408 * We must be either inactive or active and the right task,
409 * otherwise we're screwed, since we cannot IPI to somewhere
410 * else.
411 */
412 if (ctx->is_active) {
413 if (WARN_ON_ONCE(task != current))
414 goto unlock;
415
416 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
417 goto unlock;
418 }
419 } else {
420 WARN_ON_ONCE(&cpuctx->ctx != ctx);
421 }
422
423 func(event, cpuctx, ctx, data);
424 unlock:
425 perf_ctx_unlock(cpuctx, task_ctx);
426 }
427
428 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
429 PERF_FLAG_FD_OUTPUT |\
430 PERF_FLAG_PID_CGROUP |\
431 PERF_FLAG_FD_CLOEXEC)
432
433 /*
434 * branch priv levels that need permission checks
435 */
436 #define PERF_SAMPLE_BRANCH_PERM_PLM \
437 (PERF_SAMPLE_BRANCH_KERNEL |\
438 PERF_SAMPLE_BRANCH_HV)
439
440 /*
441 * perf_sched_events : >0 events exist
442 */
443
444 static void perf_sched_delayed(struct work_struct *work);
445 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
446 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
447 static DEFINE_MUTEX(perf_sched_mutex);
448 static atomic_t perf_sched_count;
449
450 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
451
452 static atomic_t nr_mmap_events __read_mostly;
453 static atomic_t nr_comm_events __read_mostly;
454 static atomic_t nr_namespaces_events __read_mostly;
455 static atomic_t nr_task_events __read_mostly;
456 static atomic_t nr_freq_events __read_mostly;
457 static atomic_t nr_switch_events __read_mostly;
458 static atomic_t nr_ksymbol_events __read_mostly;
459 static atomic_t nr_bpf_events __read_mostly;
460 static atomic_t nr_cgroup_events __read_mostly;
461 static atomic_t nr_text_poke_events __read_mostly;
462 static atomic_t nr_build_id_events __read_mostly;
463
464 static LIST_HEAD(pmus);
465 static DEFINE_MUTEX(pmus_lock);
466 static struct srcu_struct pmus_srcu;
467 static cpumask_var_t perf_online_mask;
468 static cpumask_var_t perf_online_core_mask;
469 static cpumask_var_t perf_online_die_mask;
470 static cpumask_var_t perf_online_cluster_mask;
471 static cpumask_var_t perf_online_pkg_mask;
472 static cpumask_var_t perf_online_sys_mask;
473 static struct kmem_cache *perf_event_cache;
474
475 #ifdef CONFIG_PERF_GUEST_MEDIATED_PMU
476 static DEFINE_PER_CPU(bool, guest_ctx_loaded);
477
is_guest_mediated_pmu_loaded(void)478 static __always_inline bool is_guest_mediated_pmu_loaded(void)
479 {
480 return __this_cpu_read(guest_ctx_loaded);
481 }
482 #else
is_guest_mediated_pmu_loaded(void)483 static __always_inline bool is_guest_mediated_pmu_loaded(void)
484 {
485 return false;
486 }
487 #endif
488
489 /*
490 * perf event paranoia level:
491 * -1 - not paranoid at all
492 * 0 - disallow raw tracepoint access for unpriv
493 * 1 - disallow cpu events for unpriv
494 * 2 - disallow kernel profiling for unpriv
495 */
496 int sysctl_perf_event_paranoid __read_mostly = 2;
497
498 /* Minimum for 512 kiB + 1 user control page. 'free' kiB per user. */
499 static int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024);
500
501 /*
502 * max perf event sample rate
503 */
504 #define DEFAULT_MAX_SAMPLE_RATE 100000
505 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
506 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
507
508 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
509 static int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
510
511 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
512 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
513
514 static int perf_sample_allowed_ns __read_mostly =
515 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
516
update_perf_cpu_limits(void)517 static void update_perf_cpu_limits(void)
518 {
519 u64 tmp = perf_sample_period_ns;
520
521 tmp *= sysctl_perf_cpu_time_max_percent;
522 tmp = div_u64(tmp, 100);
523 if (!tmp)
524 tmp = 1;
525
526 WRITE_ONCE(perf_sample_allowed_ns, tmp);
527 }
528
529 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc);
530
perf_event_max_sample_rate_handler(const struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)531 static int perf_event_max_sample_rate_handler(const struct ctl_table *table, int write,
532 void *buffer, size_t *lenp, loff_t *ppos)
533 {
534 int ret;
535 int perf_cpu = sysctl_perf_cpu_time_max_percent;
536 /*
537 * If throttling is disabled don't allow the write:
538 */
539 if (write && (perf_cpu == 100 || perf_cpu == 0))
540 return -EINVAL;
541
542 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
543 if (ret || !write)
544 return ret;
545
546 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
547 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
548 update_perf_cpu_limits();
549
550 return 0;
551 }
552
perf_cpu_time_max_percent_handler(const struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)553 static int perf_cpu_time_max_percent_handler(const struct ctl_table *table, int write,
554 void *buffer, size_t *lenp, loff_t *ppos)
555 {
556 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
557
558 if (ret || !write)
559 return ret;
560
561 if (sysctl_perf_cpu_time_max_percent == 100 ||
562 sysctl_perf_cpu_time_max_percent == 0) {
563 printk(KERN_WARNING
564 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
565 WRITE_ONCE(perf_sample_allowed_ns, 0);
566 } else {
567 update_perf_cpu_limits();
568 }
569
570 return 0;
571 }
572
573 static const struct ctl_table events_core_sysctl_table[] = {
574 /*
575 * User-space relies on this file as a feature check for
576 * perf_events being enabled. It's an ABI, do not remove!
577 */
578 {
579 .procname = "perf_event_paranoid",
580 .data = &sysctl_perf_event_paranoid,
581 .maxlen = sizeof(sysctl_perf_event_paranoid),
582 .mode = 0644,
583 .proc_handler = proc_dointvec,
584 },
585 {
586 .procname = "perf_event_mlock_kb",
587 .data = &sysctl_perf_event_mlock,
588 .maxlen = sizeof(sysctl_perf_event_mlock),
589 .mode = 0644,
590 .proc_handler = proc_dointvec,
591 },
592 {
593 .procname = "perf_event_max_sample_rate",
594 .data = &sysctl_perf_event_sample_rate,
595 .maxlen = sizeof(sysctl_perf_event_sample_rate),
596 .mode = 0644,
597 .proc_handler = perf_event_max_sample_rate_handler,
598 .extra1 = SYSCTL_ONE,
599 },
600 {
601 .procname = "perf_cpu_time_max_percent",
602 .data = &sysctl_perf_cpu_time_max_percent,
603 .maxlen = sizeof(sysctl_perf_cpu_time_max_percent),
604 .mode = 0644,
605 .proc_handler = perf_cpu_time_max_percent_handler,
606 .extra1 = SYSCTL_ZERO,
607 .extra2 = SYSCTL_ONE_HUNDRED,
608 },
609 };
610
init_events_core_sysctls(void)611 static int __init init_events_core_sysctls(void)
612 {
613 register_sysctl_init("kernel", events_core_sysctl_table);
614 return 0;
615 }
616 core_initcall(init_events_core_sysctls);
617
618
619 /*
620 * perf samples are done in some very critical code paths (NMIs).
621 * If they take too much CPU time, the system can lock up and not
622 * get any real work done. This will drop the sample rate when
623 * we detect that events are taking too long.
624 */
625 #define NR_ACCUMULATED_SAMPLES 128
626 static DEFINE_PER_CPU(u64, running_sample_length);
627
628 static u64 __report_avg;
629 static u64 __report_allowed;
630
perf_duration_warn(struct irq_work * w)631 static void perf_duration_warn(struct irq_work *w)
632 {
633 printk_ratelimited(KERN_INFO
634 "perf: interrupt took too long (%lld > %lld), lowering "
635 "kernel.perf_event_max_sample_rate to %d\n",
636 __report_avg, __report_allowed,
637 sysctl_perf_event_sample_rate);
638 }
639
640 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
641
perf_sample_event_took(u64 sample_len_ns)642 void perf_sample_event_took(u64 sample_len_ns)
643 {
644 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
645 u64 running_len;
646 u64 avg_len;
647 u32 max;
648
649 if (max_len == 0)
650 return;
651
652 /* Decay the counter by 1 average sample. */
653 running_len = __this_cpu_read(running_sample_length);
654 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
655 running_len += sample_len_ns;
656 __this_cpu_write(running_sample_length, running_len);
657
658 /*
659 * Note: this will be biased artificially low until we have
660 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
661 * from having to maintain a count.
662 */
663 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
664 if (avg_len <= max_len)
665 return;
666
667 __report_avg = avg_len;
668 __report_allowed = max_len;
669
670 /*
671 * Compute a throttle threshold 25% below the current duration.
672 */
673 avg_len += avg_len / 4;
674 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
675 if (avg_len < max)
676 max /= (u32)avg_len;
677 else
678 max = 1;
679
680 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
681 WRITE_ONCE(max_samples_per_tick, max);
682
683 sysctl_perf_event_sample_rate = max * HZ;
684 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
685
686 if (!irq_work_queue(&perf_duration_work)) {
687 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
688 "kernel.perf_event_max_sample_rate to %d\n",
689 __report_avg, __report_allowed,
690 sysctl_perf_event_sample_rate);
691 }
692 }
693
694 static atomic64_t perf_event_id;
695
696 static void update_context_time(struct perf_event_context *ctx);
697 static u64 perf_event_time(struct perf_event *event);
698
perf_event_print_debug(void)699 void __weak perf_event_print_debug(void) { }
700
perf_clock(void)701 static inline u64 perf_clock(void)
702 {
703 return local_clock();
704 }
705
perf_event_clock(struct perf_event * event)706 static inline u64 perf_event_clock(struct perf_event *event)
707 {
708 return event->clock();
709 }
710
711 /*
712 * State based event timekeeping...
713 *
714 * The basic idea is to use event->state to determine which (if any) time
715 * fields to increment with the current delta. This means we only need to
716 * update timestamps when we change state or when they are explicitly requested
717 * (read).
718 *
719 * Event groups make things a little more complicated, but not terribly so. The
720 * rules for a group are that if the group leader is OFF the entire group is
721 * OFF, irrespective of what the group member states are. This results in
722 * __perf_effective_state().
723 *
724 * A further ramification is that when a group leader flips between OFF and
725 * !OFF, we need to update all group member times.
726 *
727 *
728 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
729 * need to make sure the relevant context time is updated before we try and
730 * update our timestamps.
731 */
732
733 static __always_inline enum perf_event_state
__perf_effective_state(struct perf_event * event)734 __perf_effective_state(struct perf_event *event)
735 {
736 struct perf_event *leader = event->group_leader;
737
738 if (leader->state <= PERF_EVENT_STATE_OFF)
739 return leader->state;
740
741 return event->state;
742 }
743
744 static __always_inline void
__perf_update_times(struct perf_event * event,u64 now,u64 * enabled,u64 * running)745 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
746 {
747 enum perf_event_state state = __perf_effective_state(event);
748 u64 delta = now - event->tstamp;
749
750 *enabled = event->total_time_enabled;
751 if (state >= PERF_EVENT_STATE_INACTIVE)
752 *enabled += delta;
753
754 *running = event->total_time_running;
755 if (state >= PERF_EVENT_STATE_ACTIVE)
756 *running += delta;
757 }
758
perf_event_update_time(struct perf_event * event)759 static void perf_event_update_time(struct perf_event *event)
760 {
761 u64 now = perf_event_time(event);
762
763 __perf_update_times(event, now, &event->total_time_enabled,
764 &event->total_time_running);
765 event->tstamp = now;
766 }
767
perf_event_update_sibling_time(struct perf_event * leader)768 static void perf_event_update_sibling_time(struct perf_event *leader)
769 {
770 struct perf_event *sibling;
771
772 for_each_sibling_event(sibling, leader)
773 perf_event_update_time(sibling);
774 }
775
776 static void
perf_event_set_state(struct perf_event * event,enum perf_event_state state)777 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
778 {
779 if (event->state == state)
780 return;
781
782 perf_event_update_time(event);
783 /*
784 * If a group leader gets enabled/disabled all its siblings
785 * are affected too.
786 */
787 if ((event->state < 0) ^ (state < 0))
788 perf_event_update_sibling_time(event);
789
790 WRITE_ONCE(event->state, state);
791 }
792
793 /*
794 * UP store-release, load-acquire
795 */
796
797 #define __store_release(ptr, val) \
798 do { \
799 barrier(); \
800 WRITE_ONCE(*(ptr), (val)); \
801 } while (0)
802
803 #define __load_acquire(ptr) \
804 ({ \
805 __unqual_scalar_typeof(*(ptr)) ___p = READ_ONCE(*(ptr)); \
806 barrier(); \
807 ___p; \
808 })
809
perf_skip_pmu_ctx(struct perf_event_pmu_context * pmu_ctx,enum event_type_t event_type)810 static bool perf_skip_pmu_ctx(struct perf_event_pmu_context *pmu_ctx,
811 enum event_type_t event_type)
812 {
813 if ((event_type & EVENT_CGROUP) && !pmu_ctx->nr_cgroups)
814 return true;
815 if ((event_type & EVENT_GUEST) &&
816 !(pmu_ctx->pmu->capabilities & PERF_PMU_CAP_MEDIATED_VPMU))
817 return true;
818 return false;
819 }
820
821 #define for_each_epc(_epc, _ctx, _pmu, _event_type) \
822 list_for_each_entry(_epc, &((_ctx)->pmu_ctx_list), pmu_ctx_entry) \
823 if (perf_skip_pmu_ctx(_epc, _event_type)) \
824 continue; \
825 else if (_pmu && _epc->pmu != _pmu) \
826 continue; \
827 else
828
perf_ctx_disable(struct perf_event_context * ctx,enum event_type_t event_type)829 static void perf_ctx_disable(struct perf_event_context *ctx,
830 enum event_type_t event_type)
831 {
832 struct perf_event_pmu_context *pmu_ctx;
833
834 for_each_epc(pmu_ctx, ctx, NULL, event_type)
835 perf_pmu_disable(pmu_ctx->pmu);
836 }
837
perf_ctx_enable(struct perf_event_context * ctx,enum event_type_t event_type)838 static void perf_ctx_enable(struct perf_event_context *ctx,
839 enum event_type_t event_type)
840 {
841 struct perf_event_pmu_context *pmu_ctx;
842
843 for_each_epc(pmu_ctx, ctx, NULL, event_type)
844 perf_pmu_enable(pmu_ctx->pmu);
845 }
846
847 static void ctx_sched_out(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type);
848 static void ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type);
849
update_perf_time_ctx(struct perf_time_ctx * time,u64 now,bool adv)850 static inline void update_perf_time_ctx(struct perf_time_ctx *time, u64 now, bool adv)
851 {
852 if (adv)
853 time->time += now - time->stamp;
854 time->stamp = now;
855
856 /*
857 * The above: time' = time + (now - timestamp), can be re-arranged
858 * into: time` = now + (time - timestamp), which gives a single value
859 * offset to compute future time without locks on.
860 *
861 * See perf_event_time_now(), which can be used from NMI context where
862 * it's (obviously) not possible to acquire ctx->lock in order to read
863 * both the above values in a consistent manner.
864 */
865 WRITE_ONCE(time->offset, time->time - time->stamp);
866 }
867
868 static_assert(offsetof(struct perf_event_context, timeguest) -
869 offsetof(struct perf_event_context, time) ==
870 sizeof(struct perf_time_ctx));
871
872 #define T_TOTAL 0
873 #define T_GUEST 1
874
__perf_event_time_ctx(struct perf_event * event,struct perf_time_ctx * times)875 static inline u64 __perf_event_time_ctx(struct perf_event *event,
876 struct perf_time_ctx *times)
877 {
878 u64 time = times[T_TOTAL].time;
879
880 if (event->attr.exclude_guest)
881 time -= times[T_GUEST].time;
882
883 return time;
884 }
885
__perf_event_time_ctx_now(struct perf_event * event,struct perf_time_ctx * times,u64 now)886 static inline u64 __perf_event_time_ctx_now(struct perf_event *event,
887 struct perf_time_ctx *times,
888 u64 now)
889 {
890 if (is_guest_mediated_pmu_loaded() && event->attr.exclude_guest) {
891 /*
892 * (now + times[total].offset) - (now + times[guest].offset) :=
893 * times[total].offset - times[guest].offset
894 */
895 return READ_ONCE(times[T_TOTAL].offset) - READ_ONCE(times[T_GUEST].offset);
896 }
897
898 return now + READ_ONCE(times[T_TOTAL].offset);
899 }
900
901 #ifdef CONFIG_CGROUP_PERF
902
903 static inline bool
perf_cgroup_match(struct perf_event * event)904 perf_cgroup_match(struct perf_event *event)
905 {
906 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
907
908 /* @event doesn't care about cgroup */
909 if (!event->cgrp)
910 return true;
911
912 /* wants specific cgroup scope but @cpuctx isn't associated with any */
913 if (!cpuctx->cgrp)
914 return false;
915
916 /*
917 * Cgroup scoping is recursive. An event enabled for a cgroup is
918 * also enabled for all its descendant cgroups. If @cpuctx's
919 * cgroup is a descendant of @event's (the test covers identity
920 * case), it's a match.
921 */
922 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
923 event->cgrp->css.cgroup);
924 }
925
perf_detach_cgroup(struct perf_event * event)926 static inline void perf_detach_cgroup(struct perf_event *event)
927 {
928 css_put(&event->cgrp->css);
929 event->cgrp = NULL;
930 }
931
is_cgroup_event(struct perf_event * event)932 static inline int is_cgroup_event(struct perf_event *event)
933 {
934 return event->cgrp != NULL;
935 }
936
937 static_assert(offsetof(struct perf_cgroup_info, timeguest) -
938 offsetof(struct perf_cgroup_info, time) ==
939 sizeof(struct perf_time_ctx));
940
perf_cgroup_event_time(struct perf_event * event)941 static inline u64 perf_cgroup_event_time(struct perf_event *event)
942 {
943 struct perf_cgroup_info *t;
944
945 t = per_cpu_ptr(event->cgrp->info, event->cpu);
946 return __perf_event_time_ctx(event, &t->time);
947 }
948
perf_cgroup_event_time_now(struct perf_event * event,u64 now)949 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
950 {
951 struct perf_cgroup_info *t;
952
953 t = per_cpu_ptr(event->cgrp->info, event->cpu);
954 if (!__load_acquire(&t->active))
955 return __perf_event_time_ctx(event, &t->time);
956
957 return __perf_event_time_ctx_now(event, &t->time, now);
958 }
959
__update_cgrp_guest_time(struct perf_cgroup_info * info,u64 now,bool adv)960 static inline void __update_cgrp_guest_time(struct perf_cgroup_info *info, u64 now, bool adv)
961 {
962 update_perf_time_ctx(&info->timeguest, now, adv);
963 }
964
update_cgrp_time(struct perf_cgroup_info * info,u64 now)965 static inline void update_cgrp_time(struct perf_cgroup_info *info, u64 now)
966 {
967 update_perf_time_ctx(&info->time, now, true);
968 if (is_guest_mediated_pmu_loaded())
969 __update_cgrp_guest_time(info, now, true);
970 }
971
update_cgrp_time_from_cpuctx(struct perf_cpu_context * cpuctx,bool final)972 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx, bool final)
973 {
974 struct perf_cgroup *cgrp = cpuctx->cgrp;
975 struct cgroup_subsys_state *css;
976 struct perf_cgroup_info *info;
977
978 if (cgrp) {
979 u64 now = perf_clock();
980
981 for (css = &cgrp->css; css; css = css->parent) {
982 cgrp = container_of(css, struct perf_cgroup, css);
983 info = this_cpu_ptr(cgrp->info);
984
985 update_cgrp_time(info, now);
986 if (final)
987 __store_release(&info->active, 0);
988 }
989 }
990 }
991
update_cgrp_time_from_event(struct perf_event * event)992 static inline void update_cgrp_time_from_event(struct perf_event *event)
993 {
994 struct perf_cgroup_info *info;
995
996 /*
997 * ensure we access cgroup data only when needed and
998 * when we know the cgroup is pinned (css_get)
999 */
1000 if (!is_cgroup_event(event))
1001 return;
1002
1003 info = this_cpu_ptr(event->cgrp->info);
1004 /*
1005 * Do not update time when cgroup is not active
1006 */
1007 if (info->active)
1008 update_cgrp_time(info, perf_clock());
1009 }
1010
1011 static inline void
perf_cgroup_set_timestamp(struct perf_cpu_context * cpuctx,bool guest)1012 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx, bool guest)
1013 {
1014 struct perf_event_context *ctx = &cpuctx->ctx;
1015 struct perf_cgroup *cgrp = cpuctx->cgrp;
1016 struct perf_cgroup_info *info;
1017 struct cgroup_subsys_state *css;
1018
1019 /*
1020 * ctx->lock held by caller
1021 * ensure we do not access cgroup data
1022 * unless we have the cgroup pinned (css_get)
1023 */
1024 if (!cgrp)
1025 return;
1026
1027 WARN_ON_ONCE(!ctx->nr_cgroups);
1028
1029 for (css = &cgrp->css; css; css = css->parent) {
1030 cgrp = container_of(css, struct perf_cgroup, css);
1031 info = this_cpu_ptr(cgrp->info);
1032 if (guest) {
1033 __update_cgrp_guest_time(info, ctx->time.stamp, false);
1034 } else {
1035 update_perf_time_ctx(&info->time, ctx->time.stamp, false);
1036 __store_release(&info->active, 1);
1037 }
1038 }
1039 }
1040
1041 /*
1042 * reschedule events based on the cgroup constraint of task.
1043 */
perf_cgroup_switch(struct task_struct * task)1044 static void perf_cgroup_switch(struct task_struct *task)
1045 {
1046 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
1047 struct perf_cgroup *cgrp;
1048
1049 /*
1050 * cpuctx->cgrp is set when the first cgroup event enabled,
1051 * and is cleared when the last cgroup event disabled.
1052 */
1053 if (READ_ONCE(cpuctx->cgrp) == NULL)
1054 return;
1055
1056 cgrp = perf_cgroup_from_task(task, NULL);
1057 if (READ_ONCE(cpuctx->cgrp) == cgrp)
1058 return;
1059
1060 guard(perf_ctx_lock)(cpuctx, cpuctx->task_ctx);
1061 /*
1062 * Re-check, could've raced vs perf_remove_from_context().
1063 */
1064 if (READ_ONCE(cpuctx->cgrp) == NULL)
1065 return;
1066
1067 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
1068 perf_ctx_disable(&cpuctx->ctx, EVENT_CGROUP);
1069
1070 ctx_sched_out(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP);
1071 /*
1072 * must not be done before ctxswout due
1073 * to update_cgrp_time_from_cpuctx() in
1074 * ctx_sched_out()
1075 */
1076 cpuctx->cgrp = cgrp;
1077 /*
1078 * set cgrp before ctxsw in to allow
1079 * perf_cgroup_set_timestamp() in ctx_sched_in()
1080 * to not have to pass task around
1081 */
1082 ctx_sched_in(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP);
1083
1084 perf_ctx_enable(&cpuctx->ctx, EVENT_CGROUP);
1085 }
1086
perf_cgroup_ensure_storage(struct perf_event * event,struct cgroup_subsys_state * css)1087 static int perf_cgroup_ensure_storage(struct perf_event *event,
1088 struct cgroup_subsys_state *css)
1089 {
1090 struct perf_cpu_context *cpuctx;
1091 struct perf_event **storage;
1092 int cpu, heap_size, ret = 0;
1093
1094 /*
1095 * Allow storage to have sufficient space for an iterator for each
1096 * possibly nested cgroup plus an iterator for events with no cgroup.
1097 */
1098 for (heap_size = 1; css; css = css->parent)
1099 heap_size++;
1100
1101 for_each_possible_cpu(cpu) {
1102 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
1103 if (heap_size <= cpuctx->heap_size)
1104 continue;
1105
1106 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
1107 GFP_KERNEL, cpu_to_node(cpu));
1108 if (!storage) {
1109 ret = -ENOMEM;
1110 break;
1111 }
1112
1113 raw_spin_lock_irq(&cpuctx->ctx.lock);
1114 if (cpuctx->heap_size < heap_size) {
1115 swap(cpuctx->heap, storage);
1116 if (storage == cpuctx->heap_default)
1117 storage = NULL;
1118 cpuctx->heap_size = heap_size;
1119 }
1120 raw_spin_unlock_irq(&cpuctx->ctx.lock);
1121
1122 kfree(storage);
1123 }
1124
1125 return ret;
1126 }
1127
perf_cgroup_connect(int fd,struct perf_event * event,struct perf_event_attr * attr,struct perf_event * group_leader)1128 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
1129 struct perf_event_attr *attr,
1130 struct perf_event *group_leader)
1131 {
1132 struct perf_cgroup *cgrp;
1133 struct cgroup_subsys_state *css;
1134 CLASS(fd, f)(fd);
1135 int ret = 0;
1136
1137 if (fd_empty(f))
1138 return -EBADF;
1139
1140 css = css_tryget_online_from_dir(fd_file(f)->f_path.dentry,
1141 &perf_event_cgrp_subsys);
1142 if (IS_ERR(css))
1143 return PTR_ERR(css);
1144
1145 ret = perf_cgroup_ensure_storage(event, css);
1146 if (ret)
1147 return ret;
1148
1149 cgrp = container_of(css, struct perf_cgroup, css);
1150 event->cgrp = cgrp;
1151
1152 /*
1153 * all events in a group must monitor
1154 * the same cgroup because a task belongs
1155 * to only one perf cgroup at a time
1156 */
1157 if (group_leader && group_leader->cgrp != cgrp) {
1158 perf_detach_cgroup(event);
1159 ret = -EINVAL;
1160 }
1161 return ret;
1162 }
1163
1164 static inline void
perf_cgroup_event_enable(struct perf_event * event,struct perf_event_context * ctx)1165 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1166 {
1167 struct perf_cpu_context *cpuctx;
1168
1169 if (!is_cgroup_event(event))
1170 return;
1171
1172 event->pmu_ctx->nr_cgroups++;
1173
1174 /*
1175 * Because cgroup events are always per-cpu events,
1176 * @ctx == &cpuctx->ctx.
1177 */
1178 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1179
1180 if (ctx->nr_cgroups++)
1181 return;
1182
1183 cpuctx->cgrp = perf_cgroup_from_task(current, ctx);
1184 }
1185
1186 static inline void
perf_cgroup_event_disable(struct perf_event * event,struct perf_event_context * ctx)1187 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1188 {
1189 struct perf_cpu_context *cpuctx;
1190
1191 if (!is_cgroup_event(event))
1192 return;
1193
1194 event->pmu_ctx->nr_cgroups--;
1195
1196 /*
1197 * Because cgroup events are always per-cpu events,
1198 * @ctx == &cpuctx->ctx.
1199 */
1200 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1201
1202 if (--ctx->nr_cgroups)
1203 return;
1204
1205 cpuctx->cgrp = NULL;
1206 }
1207
1208 #else /* !CONFIG_CGROUP_PERF */
1209
1210 static inline bool
perf_cgroup_match(struct perf_event * event)1211 perf_cgroup_match(struct perf_event *event)
1212 {
1213 return true;
1214 }
1215
perf_detach_cgroup(struct perf_event * event)1216 static inline void perf_detach_cgroup(struct perf_event *event)
1217 {}
1218
is_cgroup_event(struct perf_event * event)1219 static inline int is_cgroup_event(struct perf_event *event)
1220 {
1221 return 0;
1222 }
1223
update_cgrp_time_from_event(struct perf_event * event)1224 static inline void update_cgrp_time_from_event(struct perf_event *event)
1225 {
1226 }
1227
update_cgrp_time_from_cpuctx(struct perf_cpu_context * cpuctx,bool final)1228 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx,
1229 bool final)
1230 {
1231 }
1232
perf_cgroup_connect(pid_t pid,struct perf_event * event,struct perf_event_attr * attr,struct perf_event * group_leader)1233 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1234 struct perf_event_attr *attr,
1235 struct perf_event *group_leader)
1236 {
1237 return -EINVAL;
1238 }
1239
1240 static inline void
perf_cgroup_set_timestamp(struct perf_cpu_context * cpuctx,bool guest)1241 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx, bool guest)
1242 {
1243 }
1244
perf_cgroup_event_time(struct perf_event * event)1245 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1246 {
1247 return 0;
1248 }
1249
perf_cgroup_event_time_now(struct perf_event * event,u64 now)1250 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
1251 {
1252 return 0;
1253 }
1254
1255 static inline void
perf_cgroup_event_enable(struct perf_event * event,struct perf_event_context * ctx)1256 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1257 {
1258 }
1259
1260 static inline void
perf_cgroup_event_disable(struct perf_event * event,struct perf_event_context * ctx)1261 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1262 {
1263 }
1264
perf_cgroup_switch(struct task_struct * task)1265 static void perf_cgroup_switch(struct task_struct *task)
1266 {
1267 }
1268 #endif
1269
1270 /*
1271 * set default to be dependent on timer tick just
1272 * like original code
1273 */
1274 #define PERF_CPU_HRTIMER (1000 / HZ)
1275 /*
1276 * function must be called with interrupts disabled
1277 */
perf_mux_hrtimer_handler(struct hrtimer * hr)1278 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1279 {
1280 struct perf_cpu_pmu_context *cpc;
1281 bool rotations;
1282
1283 lockdep_assert_irqs_disabled();
1284
1285 cpc = container_of(hr, struct perf_cpu_pmu_context, hrtimer);
1286 rotations = perf_rotate_context(cpc);
1287
1288 raw_spin_lock(&cpc->hrtimer_lock);
1289 if (rotations)
1290 hrtimer_forward_now(hr, cpc->hrtimer_interval);
1291 else
1292 cpc->hrtimer_active = 0;
1293 raw_spin_unlock(&cpc->hrtimer_lock);
1294
1295 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1296 }
1297
__perf_mux_hrtimer_init(struct perf_cpu_pmu_context * cpc,int cpu)1298 static void __perf_mux_hrtimer_init(struct perf_cpu_pmu_context *cpc, int cpu)
1299 {
1300 struct hrtimer *timer = &cpc->hrtimer;
1301 struct pmu *pmu = cpc->epc.pmu;
1302 u64 interval;
1303
1304 /*
1305 * check default is sane, if not set then force to
1306 * default interval (1/tick)
1307 */
1308 interval = pmu->hrtimer_interval_ms;
1309 if (interval < 1)
1310 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1311
1312 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1313
1314 raw_spin_lock_init(&cpc->hrtimer_lock);
1315 hrtimer_setup(timer, perf_mux_hrtimer_handler, CLOCK_MONOTONIC,
1316 HRTIMER_MODE_ABS_PINNED_HARD);
1317 }
1318
perf_mux_hrtimer_restart(struct perf_cpu_pmu_context * cpc)1319 static int perf_mux_hrtimer_restart(struct perf_cpu_pmu_context *cpc)
1320 {
1321 struct hrtimer *timer = &cpc->hrtimer;
1322 unsigned long flags;
1323
1324 raw_spin_lock_irqsave(&cpc->hrtimer_lock, flags);
1325 if (!cpc->hrtimer_active) {
1326 cpc->hrtimer_active = 1;
1327 hrtimer_forward_now(timer, cpc->hrtimer_interval);
1328 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1329 }
1330 raw_spin_unlock_irqrestore(&cpc->hrtimer_lock, flags);
1331
1332 return 0;
1333 }
1334
perf_mux_hrtimer_restart_ipi(void * arg)1335 static int perf_mux_hrtimer_restart_ipi(void *arg)
1336 {
1337 return perf_mux_hrtimer_restart(arg);
1338 }
1339
this_cpc(struct pmu * pmu)1340 static __always_inline struct perf_cpu_pmu_context *this_cpc(struct pmu *pmu)
1341 {
1342 return *this_cpu_ptr(pmu->cpu_pmu_context);
1343 }
1344
perf_pmu_disable(struct pmu * pmu)1345 void perf_pmu_disable(struct pmu *pmu)
1346 {
1347 int *count = &this_cpc(pmu)->pmu_disable_count;
1348 if (!(*count)++)
1349 pmu->pmu_disable(pmu);
1350 }
1351
perf_pmu_enable(struct pmu * pmu)1352 void perf_pmu_enable(struct pmu *pmu)
1353 {
1354 int *count = &this_cpc(pmu)->pmu_disable_count;
1355 if (!--(*count))
1356 pmu->pmu_enable(pmu);
1357 }
1358
perf_assert_pmu_disabled(struct pmu * pmu)1359 static void perf_assert_pmu_disabled(struct pmu *pmu)
1360 {
1361 int *count = &this_cpc(pmu)->pmu_disable_count;
1362 WARN_ON_ONCE(*count == 0);
1363 }
1364
perf_pmu_read(struct perf_event * event)1365 static inline void perf_pmu_read(struct perf_event *event)
1366 {
1367 if (event->state == PERF_EVENT_STATE_ACTIVE)
1368 event->pmu->read(event);
1369 }
1370
get_ctx(struct perf_event_context * ctx)1371 static void get_ctx(struct perf_event_context *ctx)
1372 {
1373 refcount_inc(&ctx->refcount);
1374 }
1375
free_ctx(struct rcu_head * head)1376 static void free_ctx(struct rcu_head *head)
1377 {
1378 struct perf_event_context *ctx;
1379
1380 ctx = container_of(head, struct perf_event_context, rcu_head);
1381 kfree(ctx);
1382 }
1383
put_ctx(struct perf_event_context * ctx)1384 static void put_ctx(struct perf_event_context *ctx)
1385 {
1386 if (refcount_dec_and_test(&ctx->refcount)) {
1387 if (ctx->parent_ctx)
1388 put_ctx(ctx->parent_ctx);
1389 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1390 put_task_struct(ctx->task);
1391 call_rcu(&ctx->rcu_head, free_ctx);
1392 } else {
1393 smp_mb__after_atomic(); /* pairs with wait_var_event() */
1394 if (ctx->task == TASK_TOMBSTONE)
1395 wake_up_var(&ctx->refcount);
1396 }
1397 }
1398
1399 /*
1400 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1401 * perf_pmu_migrate_context() we need some magic.
1402 *
1403 * Those places that change perf_event::ctx will hold both
1404 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1405 *
1406 * Lock ordering is by mutex address. There are two other sites where
1407 * perf_event_context::mutex nests and those are:
1408 *
1409 * - perf_event_exit_task_context() [ child , 0 ]
1410 * perf_event_exit_event()
1411 * put_event() [ parent, 1 ]
1412 *
1413 * - perf_event_init_context() [ parent, 0 ]
1414 * inherit_task_group()
1415 * inherit_group()
1416 * inherit_event()
1417 * perf_event_alloc()
1418 * perf_init_event()
1419 * perf_try_init_event() [ child , 1 ]
1420 *
1421 * While it appears there is an obvious deadlock here -- the parent and child
1422 * nesting levels are inverted between the two. This is in fact safe because
1423 * life-time rules separate them. That is an exiting task cannot fork, and a
1424 * spawning task cannot (yet) exit.
1425 *
1426 * But remember that these are parent<->child context relations, and
1427 * migration does not affect children, therefore these two orderings should not
1428 * interact.
1429 *
1430 * The change in perf_event::ctx does not affect children (as claimed above)
1431 * because the sys_perf_event_open() case will install a new event and break
1432 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1433 * concerned with cpuctx and that doesn't have children.
1434 *
1435 * The places that change perf_event::ctx will issue:
1436 *
1437 * perf_remove_from_context();
1438 * synchronize_rcu();
1439 * perf_install_in_context();
1440 *
1441 * to affect the change. The remove_from_context() + synchronize_rcu() should
1442 * quiesce the event, after which we can install it in the new location. This
1443 * means that only external vectors (perf_fops, prctl) can perturb the event
1444 * while in transit. Therefore all such accessors should also acquire
1445 * perf_event_context::mutex to serialize against this.
1446 *
1447 * However; because event->ctx can change while we're waiting to acquire
1448 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1449 * function.
1450 *
1451 * Lock order:
1452 * exec_update_lock
1453 * task_struct::perf_event_mutex
1454 * perf_event_context::mutex
1455 * perf_event::child_mutex;
1456 * perf_event_context::lock
1457 * mmap_lock
1458 * perf_event::mmap_mutex
1459 * perf_buffer::aux_mutex
1460 * perf_addr_filters_head::lock
1461 *
1462 * cpu_hotplug_lock
1463 * pmus_lock
1464 * cpuctx->mutex / perf_event_context::mutex
1465 */
1466 static struct perf_event_context *
perf_event_ctx_lock_nested(struct perf_event * event,int nesting)1467 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1468 {
1469 struct perf_event_context *ctx;
1470
1471 again:
1472 rcu_read_lock();
1473 ctx = READ_ONCE(event->ctx);
1474 if (!refcount_inc_not_zero(&ctx->refcount)) {
1475 rcu_read_unlock();
1476 goto again;
1477 }
1478 rcu_read_unlock();
1479
1480 mutex_lock_nested(&ctx->mutex, nesting);
1481 if (event->ctx != ctx) {
1482 mutex_unlock(&ctx->mutex);
1483 put_ctx(ctx);
1484 goto again;
1485 }
1486
1487 return ctx;
1488 }
1489
1490 static inline struct perf_event_context *
perf_event_ctx_lock(struct perf_event * event)1491 perf_event_ctx_lock(struct perf_event *event)
1492 {
1493 return perf_event_ctx_lock_nested(event, 0);
1494 }
1495
perf_event_ctx_unlock(struct perf_event * event,struct perf_event_context * ctx)1496 static void perf_event_ctx_unlock(struct perf_event *event,
1497 struct perf_event_context *ctx)
1498 {
1499 mutex_unlock(&ctx->mutex);
1500 put_ctx(ctx);
1501 }
1502
1503 /*
1504 * This must be done under the ctx->lock, such as to serialize against
1505 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1506 * calling scheduler related locks and ctx->lock nests inside those.
1507 */
1508 static __must_check struct perf_event_context *
unclone_ctx(struct perf_event_context * ctx)1509 unclone_ctx(struct perf_event_context *ctx)
1510 {
1511 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1512
1513 lockdep_assert_held(&ctx->lock);
1514
1515 if (parent_ctx)
1516 ctx->parent_ctx = NULL;
1517 ctx->generation++;
1518
1519 return parent_ctx;
1520 }
1521
perf_event_pid_type(struct perf_event * event,struct task_struct * p,enum pid_type type)1522 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1523 enum pid_type type)
1524 {
1525 u32 nr;
1526 /*
1527 * only top level events have the pid namespace they were created in
1528 */
1529 if (event->parent)
1530 event = event->parent;
1531
1532 nr = __task_pid_nr_ns(p, type, event->ns);
1533 /* avoid -1 if it is idle thread or runs in another ns */
1534 if (!nr && !pid_alive(p))
1535 nr = -1;
1536 return nr;
1537 }
1538
perf_event_pid(struct perf_event * event,struct task_struct * p)1539 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1540 {
1541 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1542 }
1543
perf_event_tid(struct perf_event * event,struct task_struct * p)1544 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1545 {
1546 return perf_event_pid_type(event, p, PIDTYPE_PID);
1547 }
1548
1549 /*
1550 * If we inherit events we want to return the parent event id
1551 * to userspace.
1552 */
primary_event_id(struct perf_event * event)1553 static u64 primary_event_id(struct perf_event *event)
1554 {
1555 u64 id = event->id;
1556
1557 if (event->parent)
1558 id = event->parent->id;
1559
1560 return id;
1561 }
1562
1563 /*
1564 * Get the perf_event_context for a task and lock it.
1565 *
1566 * This has to cope with the fact that until it is locked,
1567 * the context could get moved to another task.
1568 */
1569 static struct perf_event_context *
perf_lock_task_context(struct task_struct * task,unsigned long * flags)1570 perf_lock_task_context(struct task_struct *task, unsigned long *flags)
1571 {
1572 struct perf_event_context *ctx;
1573
1574 retry:
1575 /*
1576 * One of the few rules of preemptible RCU is that one cannot do
1577 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1578 * part of the read side critical section was irqs-enabled -- see
1579 * rcu_read_unlock_special().
1580 *
1581 * Since ctx->lock nests under rq->lock we must ensure the entire read
1582 * side critical section has interrupts disabled.
1583 */
1584 local_irq_save(*flags);
1585 rcu_read_lock();
1586 ctx = rcu_dereference(task->perf_event_ctxp);
1587 if (ctx) {
1588 /*
1589 * If this context is a clone of another, it might
1590 * get swapped for another underneath us by
1591 * perf_event_task_sched_out, though the
1592 * rcu_read_lock() protects us from any context
1593 * getting freed. Lock the context and check if it
1594 * got swapped before we could get the lock, and retry
1595 * if so. If we locked the right context, then it
1596 * can't get swapped on us any more.
1597 */
1598 raw_spin_lock(&ctx->lock);
1599 if (ctx != rcu_dereference(task->perf_event_ctxp)) {
1600 raw_spin_unlock(&ctx->lock);
1601 rcu_read_unlock();
1602 local_irq_restore(*flags);
1603 goto retry;
1604 }
1605
1606 if (ctx->task == TASK_TOMBSTONE ||
1607 !refcount_inc_not_zero(&ctx->refcount)) {
1608 raw_spin_unlock(&ctx->lock);
1609 ctx = NULL;
1610 } else {
1611 WARN_ON_ONCE(ctx->task != task);
1612 }
1613 }
1614 rcu_read_unlock();
1615 if (!ctx)
1616 local_irq_restore(*flags);
1617 return ctx;
1618 }
1619
1620 /*
1621 * Get the context for a task and increment its pin_count so it
1622 * can't get swapped to another task. This also increments its
1623 * reference count so that the context can't get freed.
1624 */
1625 static struct perf_event_context *
perf_pin_task_context(struct task_struct * task)1626 perf_pin_task_context(struct task_struct *task)
1627 {
1628 struct perf_event_context *ctx;
1629 unsigned long flags;
1630
1631 ctx = perf_lock_task_context(task, &flags);
1632 if (ctx) {
1633 ++ctx->pin_count;
1634 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1635 }
1636 return ctx;
1637 }
1638
perf_unpin_context(struct perf_event_context * ctx)1639 static void perf_unpin_context(struct perf_event_context *ctx)
1640 {
1641 unsigned long flags;
1642
1643 raw_spin_lock_irqsave(&ctx->lock, flags);
1644 --ctx->pin_count;
1645 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1646 }
1647
1648 /*
1649 * Update the record of the current time in a context.
1650 */
__update_context_time(struct perf_event_context * ctx,bool adv)1651 static void __update_context_time(struct perf_event_context *ctx, bool adv)
1652 {
1653 lockdep_assert_held(&ctx->lock);
1654
1655 update_perf_time_ctx(&ctx->time, perf_clock(), adv);
1656 }
1657
__update_context_guest_time(struct perf_event_context * ctx,bool adv)1658 static void __update_context_guest_time(struct perf_event_context *ctx, bool adv)
1659 {
1660 lockdep_assert_held(&ctx->lock);
1661
1662 /* must be called after __update_context_time(); */
1663 update_perf_time_ctx(&ctx->timeguest, ctx->time.stamp, adv);
1664 }
1665
update_context_time(struct perf_event_context * ctx)1666 static void update_context_time(struct perf_event_context *ctx)
1667 {
1668 __update_context_time(ctx, true);
1669 if (is_guest_mediated_pmu_loaded())
1670 __update_context_guest_time(ctx, true);
1671 }
1672
perf_event_time(struct perf_event * event)1673 static u64 perf_event_time(struct perf_event *event)
1674 {
1675 struct perf_event_context *ctx = event->ctx;
1676
1677 if (unlikely(!ctx))
1678 return 0;
1679
1680 if (is_cgroup_event(event))
1681 return perf_cgroup_event_time(event);
1682
1683 return __perf_event_time_ctx(event, &ctx->time);
1684 }
1685
perf_event_time_now(struct perf_event * event,u64 now)1686 static u64 perf_event_time_now(struct perf_event *event, u64 now)
1687 {
1688 struct perf_event_context *ctx = event->ctx;
1689
1690 if (unlikely(!ctx))
1691 return 0;
1692
1693 if (is_cgroup_event(event))
1694 return perf_cgroup_event_time_now(event, now);
1695
1696 if (!(__load_acquire(&ctx->is_active) & EVENT_TIME))
1697 return __perf_event_time_ctx(event, &ctx->time);
1698
1699 return __perf_event_time_ctx_now(event, &ctx->time, now);
1700 }
1701
get_event_type(struct perf_event * event)1702 static enum event_type_t get_event_type(struct perf_event *event)
1703 {
1704 struct perf_event_context *ctx = event->ctx;
1705 enum event_type_t event_type;
1706
1707 lockdep_assert_held(&ctx->lock);
1708
1709 /*
1710 * It's 'group type', really, because if our group leader is
1711 * pinned, so are we.
1712 */
1713 if (event->group_leader != event)
1714 event = event->group_leader;
1715
1716 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1717 if (!ctx->task)
1718 event_type |= EVENT_CPU;
1719
1720 return event_type;
1721 }
1722
1723 /*
1724 * Helper function to initialize event group nodes.
1725 */
init_event_group(struct perf_event * event)1726 static void init_event_group(struct perf_event *event)
1727 {
1728 RB_CLEAR_NODE(&event->group_node);
1729 event->group_index = 0;
1730 }
1731
1732 /*
1733 * Extract pinned or flexible groups from the context
1734 * based on event attrs bits.
1735 */
1736 static struct perf_event_groups *
get_event_groups(struct perf_event * event,struct perf_event_context * ctx)1737 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1738 {
1739 if (event->attr.pinned)
1740 return &ctx->pinned_groups;
1741 else
1742 return &ctx->flexible_groups;
1743 }
1744
1745 /*
1746 * Helper function to initializes perf_event_group trees.
1747 */
perf_event_groups_init(struct perf_event_groups * groups)1748 static void perf_event_groups_init(struct perf_event_groups *groups)
1749 {
1750 groups->tree = RB_ROOT;
1751 groups->index = 0;
1752 }
1753
event_cgroup(const struct perf_event * event)1754 static inline struct cgroup *event_cgroup(const struct perf_event *event)
1755 {
1756 struct cgroup *cgroup = NULL;
1757
1758 #ifdef CONFIG_CGROUP_PERF
1759 if (event->cgrp)
1760 cgroup = event->cgrp->css.cgroup;
1761 #endif
1762
1763 return cgroup;
1764 }
1765
1766 /*
1767 * Compare function for event groups;
1768 *
1769 * Implements complex key that first sorts by CPU and then by virtual index
1770 * which provides ordering when rotating groups for the same CPU.
1771 */
1772 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)1773 perf_event_groups_cmp(const int left_cpu, const struct pmu *left_pmu,
1774 const struct cgroup *left_cgroup, const u64 left_group_index,
1775 const struct perf_event *right)
1776 {
1777 if (left_cpu < right->cpu)
1778 return -1;
1779 if (left_cpu > right->cpu)
1780 return 1;
1781
1782 if (left_pmu) {
1783 if (left_pmu < right->pmu_ctx->pmu)
1784 return -1;
1785 if (left_pmu > right->pmu_ctx->pmu)
1786 return 1;
1787 }
1788
1789 #ifdef CONFIG_CGROUP_PERF
1790 {
1791 const struct cgroup *right_cgroup = event_cgroup(right);
1792
1793 if (left_cgroup != right_cgroup) {
1794 if (!left_cgroup) {
1795 /*
1796 * Left has no cgroup but right does, no
1797 * cgroups come first.
1798 */
1799 return -1;
1800 }
1801 if (!right_cgroup) {
1802 /*
1803 * Right has no cgroup but left does, no
1804 * cgroups come first.
1805 */
1806 return 1;
1807 }
1808 /* Two dissimilar cgroups, order by id. */
1809 if (cgroup_id(left_cgroup) < cgroup_id(right_cgroup))
1810 return -1;
1811
1812 return 1;
1813 }
1814 }
1815 #endif
1816
1817 if (left_group_index < right->group_index)
1818 return -1;
1819 if (left_group_index > right->group_index)
1820 return 1;
1821
1822 return 0;
1823 }
1824
1825 #define __node_2_pe(node) \
1826 rb_entry((node), struct perf_event, group_node)
1827
__group_less(struct rb_node * a,const struct rb_node * b)1828 static inline bool __group_less(struct rb_node *a, const struct rb_node *b)
1829 {
1830 struct perf_event *e = __node_2_pe(a);
1831 return perf_event_groups_cmp(e->cpu, e->pmu_ctx->pmu, event_cgroup(e),
1832 e->group_index, __node_2_pe(b)) < 0;
1833 }
1834
1835 struct __group_key {
1836 int cpu;
1837 struct pmu *pmu;
1838 struct cgroup *cgroup;
1839 };
1840
__group_cmp(const void * key,const struct rb_node * node)1841 static inline int __group_cmp(const void *key, const struct rb_node *node)
1842 {
1843 const struct __group_key *a = key;
1844 const struct perf_event *b = __node_2_pe(node);
1845
1846 /* partial/subtree match: @cpu, @pmu, @cgroup; ignore: @group_index */
1847 return perf_event_groups_cmp(a->cpu, a->pmu, a->cgroup, b->group_index, b);
1848 }
1849
1850 static inline int
__group_cmp_ignore_cgroup(const void * key,const struct rb_node * node)1851 __group_cmp_ignore_cgroup(const void *key, const struct rb_node *node)
1852 {
1853 const struct __group_key *a = key;
1854 const struct perf_event *b = __node_2_pe(node);
1855
1856 /* partial/subtree match: @cpu, @pmu, ignore: @cgroup, @group_index */
1857 return perf_event_groups_cmp(a->cpu, a->pmu, event_cgroup(b),
1858 b->group_index, b);
1859 }
1860
1861 /*
1862 * Insert @event into @groups' tree; using
1863 * {@event->cpu, @event->pmu_ctx->pmu, event_cgroup(@event), ++@groups->index}
1864 * as key. This places it last inside the {cpu,pmu,cgroup} subtree.
1865 */
1866 static void
perf_event_groups_insert(struct perf_event_groups * groups,struct perf_event * event)1867 perf_event_groups_insert(struct perf_event_groups *groups,
1868 struct perf_event *event)
1869 {
1870 event->group_index = ++groups->index;
1871
1872 rb_add(&event->group_node, &groups->tree, __group_less);
1873 }
1874
1875 /*
1876 * Helper function to insert event into the pinned or flexible groups.
1877 */
1878 static void
add_event_to_groups(struct perf_event * event,struct perf_event_context * ctx)1879 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1880 {
1881 struct perf_event_groups *groups;
1882
1883 groups = get_event_groups(event, ctx);
1884 perf_event_groups_insert(groups, event);
1885 }
1886
1887 /*
1888 * Delete a group from a tree.
1889 */
1890 static void
perf_event_groups_delete(struct perf_event_groups * groups,struct perf_event * event)1891 perf_event_groups_delete(struct perf_event_groups *groups,
1892 struct perf_event *event)
1893 {
1894 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1895 RB_EMPTY_ROOT(&groups->tree));
1896
1897 rb_erase(&event->group_node, &groups->tree);
1898 init_event_group(event);
1899 }
1900
1901 /*
1902 * Helper function to delete event from its groups.
1903 */
1904 static void
del_event_from_groups(struct perf_event * event,struct perf_event_context * ctx)1905 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1906 {
1907 struct perf_event_groups *groups;
1908
1909 groups = get_event_groups(event, ctx);
1910 perf_event_groups_delete(groups, event);
1911 }
1912
1913 /*
1914 * Get the leftmost event in the {cpu,pmu,cgroup} subtree.
1915 */
1916 static struct perf_event *
perf_event_groups_first(struct perf_event_groups * groups,int cpu,struct pmu * pmu,struct cgroup * cgrp)1917 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1918 struct pmu *pmu, struct cgroup *cgrp)
1919 {
1920 struct __group_key key = {
1921 .cpu = cpu,
1922 .pmu = pmu,
1923 .cgroup = cgrp,
1924 };
1925 struct rb_node *node;
1926
1927 node = rb_find_first(&key, &groups->tree, __group_cmp);
1928 if (node)
1929 return __node_2_pe(node);
1930
1931 return NULL;
1932 }
1933
1934 static struct perf_event *
perf_event_groups_next(struct perf_event * event,struct pmu * pmu)1935 perf_event_groups_next(struct perf_event *event, struct pmu *pmu)
1936 {
1937 struct __group_key key = {
1938 .cpu = event->cpu,
1939 .pmu = pmu,
1940 .cgroup = event_cgroup(event),
1941 };
1942 struct rb_node *next;
1943
1944 next = rb_next_match(&key, &event->group_node, __group_cmp);
1945 if (next)
1946 return __node_2_pe(next);
1947
1948 return NULL;
1949 }
1950
1951 #define perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) \
1952 for (event = perf_event_groups_first(groups, cpu, pmu, NULL); \
1953 event; event = perf_event_groups_next(event, pmu))
1954
1955 /*
1956 * Iterate through the whole groups tree.
1957 */
1958 #define perf_event_groups_for_each(event, groups) \
1959 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1960 typeof(*event), group_node); event; \
1961 event = rb_entry_safe(rb_next(&event->group_node), \
1962 typeof(*event), group_node))
1963
1964 /*
1965 * Does the event attribute request inherit with PERF_SAMPLE_READ
1966 */
has_inherit_and_sample_read(struct perf_event_attr * attr)1967 static inline bool has_inherit_and_sample_read(struct perf_event_attr *attr)
1968 {
1969 return attr->inherit && (attr->sample_type & PERF_SAMPLE_READ);
1970 }
1971
1972 /*
1973 * Add an event from the lists for its context.
1974 * Must be called with ctx->mutex and ctx->lock held.
1975 */
1976 static void
list_add_event(struct perf_event * event,struct perf_event_context * ctx)1977 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1978 {
1979 lockdep_assert_held(&ctx->lock);
1980
1981 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1982 event->attach_state |= PERF_ATTACH_CONTEXT;
1983
1984 event->tstamp = perf_event_time(event);
1985
1986 /*
1987 * If we're a stand alone event or group leader, we go to the context
1988 * list, group events are kept attached to the group so that
1989 * perf_group_detach can, at all times, locate all siblings.
1990 */
1991 if (event->group_leader == event) {
1992 event->group_caps = event->event_caps;
1993 add_event_to_groups(event, ctx);
1994 }
1995
1996 list_add_rcu(&event->event_entry, &ctx->event_list);
1997 ctx->nr_events++;
1998 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
1999 ctx->nr_user++;
2000 if (event->attr.inherit_stat)
2001 ctx->nr_stat++;
2002 if (has_inherit_and_sample_read(&event->attr))
2003 local_inc(&ctx->nr_no_switch_fast);
2004
2005 if (event->state > PERF_EVENT_STATE_OFF)
2006 perf_cgroup_event_enable(event, ctx);
2007
2008 ctx->generation++;
2009 event->pmu_ctx->nr_events++;
2010 }
2011
2012 /*
2013 * Initialize event state based on the perf_event_attr::disabled.
2014 */
perf_event__state_init(struct perf_event * event)2015 static inline void perf_event__state_init(struct perf_event *event)
2016 {
2017 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
2018 PERF_EVENT_STATE_INACTIVE;
2019 }
2020
__perf_event_read_size(u64 read_format,int nr_siblings)2021 static int __perf_event_read_size(u64 read_format, int nr_siblings)
2022 {
2023 int entry = sizeof(u64); /* value */
2024 int size = 0;
2025 int nr = 1;
2026
2027 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
2028 size += sizeof(u64);
2029
2030 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
2031 size += sizeof(u64);
2032
2033 if (read_format & PERF_FORMAT_ID)
2034 entry += sizeof(u64);
2035
2036 if (read_format & PERF_FORMAT_LOST)
2037 entry += sizeof(u64);
2038
2039 if (read_format & PERF_FORMAT_GROUP) {
2040 nr += nr_siblings;
2041 size += sizeof(u64);
2042 }
2043
2044 /*
2045 * Since perf_event_validate_size() limits this to 16k and inhibits
2046 * adding more siblings, this will never overflow.
2047 */
2048 return size + nr * entry;
2049 }
2050
__perf_event_header_size(struct perf_event * event,u64 sample_type)2051 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
2052 {
2053 struct perf_sample_data *data;
2054 u16 size = 0;
2055
2056 if (sample_type & PERF_SAMPLE_IP)
2057 size += sizeof(data->ip);
2058
2059 if (sample_type & PERF_SAMPLE_ADDR)
2060 size += sizeof(data->addr);
2061
2062 if (sample_type & PERF_SAMPLE_PERIOD)
2063 size += sizeof(data->period);
2064
2065 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
2066 size += sizeof(data->weight.full);
2067
2068 if (sample_type & PERF_SAMPLE_READ)
2069 size += event->read_size;
2070
2071 if (sample_type & PERF_SAMPLE_DATA_SRC)
2072 size += sizeof(data->data_src.val);
2073
2074 if (sample_type & PERF_SAMPLE_TRANSACTION)
2075 size += sizeof(data->txn);
2076
2077 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
2078 size += sizeof(data->phys_addr);
2079
2080 if (sample_type & PERF_SAMPLE_CGROUP)
2081 size += sizeof(data->cgroup);
2082
2083 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
2084 size += sizeof(data->data_page_size);
2085
2086 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
2087 size += sizeof(data->code_page_size);
2088
2089 event->header_size = size;
2090 }
2091
2092 /*
2093 * Called at perf_event creation and when events are attached/detached from a
2094 * group.
2095 */
perf_event__header_size(struct perf_event * event)2096 static void perf_event__header_size(struct perf_event *event)
2097 {
2098 event->read_size =
2099 __perf_event_read_size(event->attr.read_format,
2100 event->group_leader->nr_siblings);
2101 __perf_event_header_size(event, event->attr.sample_type);
2102 }
2103
perf_event__id_header_size(struct perf_event * event)2104 static void perf_event__id_header_size(struct perf_event *event)
2105 {
2106 struct perf_sample_data *data;
2107 u64 sample_type = event->attr.sample_type;
2108 u16 size = 0;
2109
2110 if (sample_type & PERF_SAMPLE_TID)
2111 size += sizeof(data->tid_entry);
2112
2113 if (sample_type & PERF_SAMPLE_TIME)
2114 size += sizeof(data->time);
2115
2116 if (sample_type & PERF_SAMPLE_IDENTIFIER)
2117 size += sizeof(data->id);
2118
2119 if (sample_type & PERF_SAMPLE_ID)
2120 size += sizeof(data->id);
2121
2122 if (sample_type & PERF_SAMPLE_STREAM_ID)
2123 size += sizeof(data->stream_id);
2124
2125 if (sample_type & PERF_SAMPLE_CPU)
2126 size += sizeof(data->cpu_entry);
2127
2128 event->id_header_size = size;
2129 }
2130
2131 /*
2132 * Check that adding an event to the group does not result in anybody
2133 * overflowing the 64k event limit imposed by the output buffer.
2134 *
2135 * Specifically, check that the read_size for the event does not exceed 16k,
2136 * read_size being the one term that grows with groups size. Since read_size
2137 * depends on per-event read_format, also (re)check the existing events.
2138 *
2139 * This leaves 48k for the constant size fields and things like callchains,
2140 * branch stacks and register sets.
2141 */
perf_event_validate_size(struct perf_event * event)2142 static bool perf_event_validate_size(struct perf_event *event)
2143 {
2144 struct perf_event *sibling, *group_leader = event->group_leader;
2145
2146 if (__perf_event_read_size(event->attr.read_format,
2147 group_leader->nr_siblings + 1) > 16*1024)
2148 return false;
2149
2150 if (__perf_event_read_size(group_leader->attr.read_format,
2151 group_leader->nr_siblings + 1) > 16*1024)
2152 return false;
2153
2154 /*
2155 * When creating a new group leader, group_leader->ctx is initialized
2156 * after the size has been validated, but we cannot safely use
2157 * for_each_sibling_event() until group_leader->ctx is set. A new group
2158 * leader cannot have any siblings yet, so we can safely skip checking
2159 * the non-existent siblings.
2160 */
2161 if (event == group_leader)
2162 return true;
2163
2164 for_each_sibling_event(sibling, group_leader) {
2165 if (__perf_event_read_size(sibling->attr.read_format,
2166 group_leader->nr_siblings + 1) > 16*1024)
2167 return false;
2168 }
2169
2170 return true;
2171 }
2172
perf_group_attach(struct perf_event * event)2173 static void perf_group_attach(struct perf_event *event)
2174 {
2175 struct perf_event *group_leader = event->group_leader, *pos;
2176
2177 lockdep_assert_held(&event->ctx->lock);
2178
2179 /*
2180 * We can have double attach due to group movement (move_group) in
2181 * perf_event_open().
2182 */
2183 if (event->attach_state & PERF_ATTACH_GROUP)
2184 return;
2185
2186 event->attach_state |= PERF_ATTACH_GROUP;
2187
2188 if (group_leader == event)
2189 return;
2190
2191 WARN_ON_ONCE(group_leader->ctx != event->ctx);
2192
2193 group_leader->group_caps &= event->event_caps;
2194
2195 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
2196 group_leader->nr_siblings++;
2197 group_leader->group_generation++;
2198
2199 perf_event__header_size(group_leader);
2200
2201 for_each_sibling_event(pos, group_leader)
2202 perf_event__header_size(pos);
2203 }
2204
2205 /*
2206 * Remove an event from the lists for its context.
2207 * Must be called with ctx->mutex and ctx->lock held.
2208 */
2209 static void
list_del_event(struct perf_event * event,struct perf_event_context * ctx)2210 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
2211 {
2212 WARN_ON_ONCE(event->ctx != ctx);
2213 lockdep_assert_held(&ctx->lock);
2214
2215 /*
2216 * We can have double detach due to exit/hot-unplug + close.
2217 */
2218 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
2219 return;
2220
2221 event->attach_state &= ~PERF_ATTACH_CONTEXT;
2222
2223 ctx->nr_events--;
2224 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
2225 ctx->nr_user--;
2226 if (event->attr.inherit_stat)
2227 ctx->nr_stat--;
2228 if (has_inherit_and_sample_read(&event->attr))
2229 local_dec(&ctx->nr_no_switch_fast);
2230
2231 list_del_rcu(&event->event_entry);
2232
2233 if (event->group_leader == event)
2234 del_event_from_groups(event, ctx);
2235
2236 ctx->generation++;
2237 event->pmu_ctx->nr_events--;
2238 }
2239
2240 static int
perf_aux_output_match(struct perf_event * event,struct perf_event * aux_event)2241 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2242 {
2243 if (!has_aux(aux_event))
2244 return 0;
2245
2246 if (!event->pmu->aux_output_match)
2247 return 0;
2248
2249 return event->pmu->aux_output_match(aux_event);
2250 }
2251
2252 static void put_event(struct perf_event *event);
2253 static void __event_disable(struct perf_event *event,
2254 struct perf_event_context *ctx,
2255 enum perf_event_state state);
2256
perf_put_aux_event(struct perf_event * event)2257 static void perf_put_aux_event(struct perf_event *event)
2258 {
2259 struct perf_event_context *ctx = event->ctx;
2260 struct perf_event *iter;
2261
2262 /*
2263 * If event uses aux_event tear down the link
2264 */
2265 if (event->aux_event) {
2266 iter = event->aux_event;
2267 event->aux_event = NULL;
2268 put_event(iter);
2269 return;
2270 }
2271
2272 /*
2273 * If the event is an aux_event, tear down all links to
2274 * it from other events.
2275 */
2276 for_each_sibling_event(iter, event) {
2277 if (iter->aux_event != event)
2278 continue;
2279
2280 iter->aux_event = NULL;
2281 put_event(event);
2282
2283 /*
2284 * If it's ACTIVE, schedule it out and put it into ERROR
2285 * state so that we don't try to schedule it again. Note
2286 * that perf_event_enable() will clear the ERROR status.
2287 */
2288 __event_disable(iter, ctx, PERF_EVENT_STATE_ERROR);
2289 }
2290 }
2291
perf_need_aux_event(struct perf_event * event)2292 static bool perf_need_aux_event(struct perf_event *event)
2293 {
2294 return event->attr.aux_output || has_aux_action(event);
2295 }
2296
perf_get_aux_event(struct perf_event * event,struct perf_event * group_leader)2297 static int perf_get_aux_event(struct perf_event *event,
2298 struct perf_event *group_leader)
2299 {
2300 /*
2301 * Our group leader must be an aux event if we want to be
2302 * an aux_output. This way, the aux event will precede its
2303 * aux_output events in the group, and therefore will always
2304 * schedule first.
2305 */
2306 if (!group_leader)
2307 return 0;
2308
2309 /*
2310 * aux_output and aux_sample_size are mutually exclusive.
2311 */
2312 if (event->attr.aux_output && event->attr.aux_sample_size)
2313 return 0;
2314
2315 if (event->attr.aux_output &&
2316 !perf_aux_output_match(event, group_leader))
2317 return 0;
2318
2319 if ((event->attr.aux_pause || event->attr.aux_resume) &&
2320 !(group_leader->pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE))
2321 return 0;
2322
2323 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2324 return 0;
2325
2326 if (!atomic_long_inc_not_zero(&group_leader->refcount))
2327 return 0;
2328
2329 /*
2330 * Link aux_outputs to their aux event; this is undone in
2331 * perf_group_detach() by perf_put_aux_event(). When the
2332 * group in torn down, the aux_output events loose their
2333 * link to the aux_event and can't schedule any more.
2334 */
2335 event->aux_event = group_leader;
2336
2337 return 1;
2338 }
2339
get_event_list(struct perf_event * event)2340 static inline struct list_head *get_event_list(struct perf_event *event)
2341 {
2342 return event->attr.pinned ? &event->pmu_ctx->pinned_active :
2343 &event->pmu_ctx->flexible_active;
2344 }
2345
2346 /* @sibling must already be unlinked from its old leader's sibling_list. */
perf_promote_sibling_to_leader(struct perf_event * sibling,struct perf_event_context * ctx,int group_caps)2347 static void perf_promote_sibling_to_leader(struct perf_event *sibling,
2348 struct perf_event_context *ctx,
2349 int group_caps)
2350 {
2351 /*
2352 * Events that have PERF_EV_CAP_SIBLING require being part of
2353 * a group and cannot exist on their own, schedule them out
2354 * and move them into the ERROR state. Also see
2355 * _perf_event_enable(), it will not be able to recover this
2356 * ERROR state.
2357 */
2358 if (sibling->event_caps & PERF_EV_CAP_SIBLING)
2359 __event_disable(sibling, ctx, PERF_EVENT_STATE_ERROR);
2360
2361 sibling->group_leader = sibling;
2362 sibling->group_caps = group_caps;
2363
2364 if (sibling->attach_state & PERF_ATTACH_CONTEXT) {
2365 add_event_to_groups(sibling, ctx);
2366
2367 if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2368 list_add_tail(&sibling->active_list, get_event_list(sibling));
2369 }
2370
2371 perf_event__header_size(sibling);
2372 }
2373
perf_group_detach(struct perf_event * event)2374 static void perf_group_detach(struct perf_event *event)
2375 {
2376 struct perf_event *leader = event->group_leader;
2377 struct perf_event *sibling, *tmp;
2378 struct perf_event_context *ctx = event->ctx;
2379
2380 lockdep_assert_held(&ctx->lock);
2381
2382 /*
2383 * We can have double detach due to exit/hot-unplug + close.
2384 */
2385 if (!(event->attach_state & PERF_ATTACH_GROUP))
2386 return;
2387
2388 event->attach_state &= ~PERF_ATTACH_GROUP;
2389
2390 perf_put_aux_event(event);
2391
2392 /*
2393 * If this is a sibling, remove it from its group.
2394 */
2395 if (leader != event) {
2396 list_del_init(&event->sibling_list);
2397 leader->nr_siblings--;
2398 leader->group_generation++;
2399 perf_promote_sibling_to_leader(event, ctx, event->event_caps);
2400 goto out;
2401 }
2402
2403 /*
2404 * If this was a group event with sibling events then
2405 * upgrade the siblings to singleton events by adding them
2406 * to whatever list we are on.
2407 */
2408 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2409 list_del_init(&sibling->sibling_list);
2410
2411 /* Inherit group flags from the previous leader */
2412 perf_promote_sibling_to_leader(sibling, ctx, event->group_caps);
2413
2414 WARN_ON_ONCE(sibling->ctx != event->ctx);
2415 }
2416 event->nr_siblings = 0;
2417
2418 out:
2419 for_each_sibling_event(tmp, leader)
2420 perf_event__header_size(tmp);
2421
2422 perf_event__header_size(leader);
2423 }
2424
perf_child_detach(struct perf_event * event)2425 static void perf_child_detach(struct perf_event *event)
2426 {
2427 struct perf_event *parent_event = event->parent;
2428
2429 if (!(event->attach_state & PERF_ATTACH_CHILD))
2430 return;
2431
2432 event->attach_state &= ~PERF_ATTACH_CHILD;
2433
2434 if (WARN_ON_ONCE(!parent_event))
2435 return;
2436
2437 /*
2438 * Can't check this from an IPI, the holder is likey another CPU.
2439 *
2440 lockdep_assert_held(&parent_event->child_mutex);
2441 */
2442
2443 list_del_init(&event->child_list);
2444 }
2445
is_orphaned_event(struct perf_event * event)2446 static bool is_orphaned_event(struct perf_event *event)
2447 {
2448 return event->state == PERF_EVENT_STATE_DEAD;
2449 }
2450
2451 static inline int
event_filter_match(struct perf_event * event)2452 event_filter_match(struct perf_event *event)
2453 {
2454 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2455 perf_cgroup_match(event);
2456 }
2457
is_event_in_freq_mode(struct perf_event * event)2458 static inline bool is_event_in_freq_mode(struct perf_event *event)
2459 {
2460 return event->attr.freq && event->attr.sample_freq;
2461 }
2462
2463 static void
event_sched_out(struct perf_event * event,struct perf_event_context * ctx)2464 event_sched_out(struct perf_event *event, struct perf_event_context *ctx)
2465 {
2466 struct perf_event_pmu_context *epc = event->pmu_ctx;
2467 struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu);
2468 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2469
2470 // XXX cpc serialization, probably per-cpu IRQ disabled
2471
2472 WARN_ON_ONCE(event->ctx != ctx);
2473 lockdep_assert_held(&ctx->lock);
2474
2475 if (event->state != PERF_EVENT_STATE_ACTIVE)
2476 return;
2477
2478 /*
2479 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2480 * we can schedule events _OUT_ individually through things like
2481 * __perf_remove_from_context().
2482 */
2483 list_del_init(&event->active_list);
2484
2485 perf_pmu_disable(event->pmu);
2486
2487 event->pmu->del(event, 0);
2488 event->oncpu = -1;
2489
2490 if (event->pending_disable) {
2491 event->pending_disable = 0;
2492 perf_cgroup_event_disable(event, ctx);
2493 state = PERF_EVENT_STATE_OFF;
2494 }
2495
2496 perf_event_set_state(event, state);
2497
2498 if (!is_software_event(event))
2499 cpc->active_oncpu--;
2500 if (is_event_in_freq_mode(event)) {
2501 ctx->nr_freq--;
2502 epc->nr_freq--;
2503 }
2504 if (event->attr.exclusive || !cpc->active_oncpu)
2505 cpc->exclusive = 0;
2506
2507 perf_pmu_enable(event->pmu);
2508 }
2509
2510 static void
group_sched_out(struct perf_event * group_event,struct perf_event_context * ctx)2511 group_sched_out(struct perf_event *group_event, struct perf_event_context *ctx)
2512 {
2513 struct perf_event *event;
2514
2515 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2516 return;
2517
2518 perf_assert_pmu_disabled(group_event->pmu_ctx->pmu);
2519
2520 event_sched_out(group_event, ctx);
2521
2522 /*
2523 * Schedule out siblings (if any):
2524 */
2525 for_each_sibling_event(event, group_event)
2526 event_sched_out(event, ctx);
2527 }
2528
2529 static inline void
__ctx_time_update(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,bool final,enum event_type_t event_type)2530 __ctx_time_update(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx,
2531 bool final, enum event_type_t event_type)
2532 {
2533 if (ctx->is_active & EVENT_TIME) {
2534 if (ctx->is_active & EVENT_FROZEN)
2535 return;
2536
2537 update_context_time(ctx);
2538 /* vPMU should not stop time */
2539 update_cgrp_time_from_cpuctx(cpuctx, !(event_type & EVENT_GUEST) && final);
2540 }
2541 }
2542
2543 static inline void
ctx_time_update(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)2544 ctx_time_update(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx)
2545 {
2546 __ctx_time_update(cpuctx, ctx, false, 0);
2547 }
2548
2549 /*
2550 * To be used inside perf_ctx_lock() / perf_ctx_unlock(). Lasts until perf_ctx_unlock().
2551 */
2552 static inline void
ctx_time_freeze(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)2553 ctx_time_freeze(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx)
2554 {
2555 ctx_time_update(cpuctx, ctx);
2556 if (ctx->is_active & EVENT_TIME)
2557 ctx->is_active |= EVENT_FROZEN;
2558 }
2559
2560 static inline void
ctx_time_update_event(struct perf_event_context * ctx,struct perf_event * event)2561 ctx_time_update_event(struct perf_event_context *ctx, struct perf_event *event)
2562 {
2563 if (ctx->is_active & EVENT_TIME) {
2564 if (ctx->is_active & EVENT_FROZEN)
2565 return;
2566 update_context_time(ctx);
2567 update_cgrp_time_from_event(event);
2568 }
2569 }
2570
2571 #define DETACH_GROUP 0x01UL
2572 #define DETACH_CHILD 0x02UL
2573 #define DETACH_EXIT 0x04UL
2574 #define DETACH_REVOKE 0x08UL
2575 #define DETACH_DEAD 0x10UL
2576
2577 /*
2578 * Cross CPU call to remove a performance event
2579 *
2580 * We disable the event on the hardware level first. After that we
2581 * remove it from the context list.
2582 */
2583 static void
__perf_remove_from_context(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)2584 __perf_remove_from_context(struct perf_event *event,
2585 struct perf_cpu_context *cpuctx,
2586 struct perf_event_context *ctx,
2587 void *info)
2588 {
2589 struct perf_event_pmu_context *pmu_ctx = event->pmu_ctx;
2590 enum perf_event_state state = PERF_EVENT_STATE_OFF;
2591 unsigned long flags = (unsigned long)info;
2592
2593 ctx_time_update(cpuctx, ctx);
2594
2595 /*
2596 * Ensure event_sched_out() switches to OFF, at the very least
2597 * this avoids raising perf_pending_task() at this time.
2598 */
2599 if (flags & DETACH_EXIT)
2600 state = PERF_EVENT_STATE_EXIT;
2601 if (flags & DETACH_REVOKE)
2602 state = PERF_EVENT_STATE_REVOKED;
2603 if (flags & DETACH_DEAD)
2604 state = PERF_EVENT_STATE_DEAD;
2605
2606 __event_disable(event, ctx, state);
2607
2608 if (flags & DETACH_GROUP)
2609 perf_group_detach(event);
2610 if (flags & DETACH_CHILD)
2611 perf_child_detach(event);
2612 list_del_event(event, ctx);
2613
2614 if (!pmu_ctx->nr_events) {
2615 pmu_ctx->rotate_necessary = 0;
2616
2617 if (ctx->task && ctx->is_active) {
2618 struct perf_cpu_pmu_context *cpc = this_cpc(pmu_ctx->pmu);
2619
2620 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
2621 cpc->task_epc = NULL;
2622 }
2623 }
2624
2625 if (!ctx->nr_events && ctx->is_active) {
2626 if (ctx == &cpuctx->ctx)
2627 update_cgrp_time_from_cpuctx(cpuctx, true);
2628
2629 ctx->is_active = 0;
2630 if (ctx->task) {
2631 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2632 cpuctx->task_ctx = NULL;
2633 }
2634 }
2635 }
2636
2637 /*
2638 * Remove the event from a task's (or a CPU's) list of events.
2639 *
2640 * If event->ctx is a cloned context, callers must make sure that
2641 * every task struct that event->ctx->task could possibly point to
2642 * remains valid. This is OK when called from perf_release since
2643 * that only calls us on the top-level context, which can't be a clone.
2644 * When called from perf_event_exit_task, it's OK because the
2645 * context has been detached from its task.
2646 */
perf_remove_from_context(struct perf_event * event,unsigned long flags)2647 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2648 {
2649 struct perf_event_context *ctx = event->ctx;
2650
2651 lockdep_assert_held(&ctx->mutex);
2652
2653 /*
2654 * Because of perf_event_exit_task(), perf_remove_from_context() ought
2655 * to work in the face of TASK_TOMBSTONE, unlike every other
2656 * event_function_call() user.
2657 */
2658 raw_spin_lock_irq(&ctx->lock);
2659 if (!ctx->is_active) {
2660 __perf_remove_from_context(event, this_cpu_ptr(&perf_cpu_context),
2661 ctx, (void *)flags);
2662 raw_spin_unlock_irq(&ctx->lock);
2663 return;
2664 }
2665 raw_spin_unlock_irq(&ctx->lock);
2666
2667 event_function_call(event, __perf_remove_from_context, (void *)flags);
2668 }
2669
__event_disable(struct perf_event * event,struct perf_event_context * ctx,enum perf_event_state state)2670 static void __event_disable(struct perf_event *event,
2671 struct perf_event_context *ctx,
2672 enum perf_event_state state)
2673 {
2674 event_sched_out(event, ctx);
2675 if (event->state > PERF_EVENT_STATE_OFF)
2676 perf_cgroup_event_disable(event, ctx);
2677 perf_event_set_state(event, min(event->state, state));
2678 }
2679
2680 /*
2681 * Cross CPU call to disable a performance event
2682 */
__perf_event_disable(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)2683 static void __perf_event_disable(struct perf_event *event,
2684 struct perf_cpu_context *cpuctx,
2685 struct perf_event_context *ctx,
2686 void *info)
2687 {
2688 if (event->state < PERF_EVENT_STATE_INACTIVE)
2689 return;
2690
2691 perf_pmu_disable(event->pmu_ctx->pmu);
2692 ctx_time_update_event(ctx, event);
2693
2694 /*
2695 * When disabling a group leader, the whole group becomes ineligible
2696 * to run, so schedule out the full group.
2697 */
2698 if (event == event->group_leader)
2699 group_sched_out(event, ctx);
2700
2701 /*
2702 * But only mark the leader OFF; the siblings will remain
2703 * INACTIVE.
2704 */
2705 __event_disable(event, ctx, PERF_EVENT_STATE_OFF);
2706
2707 perf_pmu_enable(event->pmu_ctx->pmu);
2708 }
2709
2710 /*
2711 * Disable an event.
2712 *
2713 * If event->ctx is a cloned context, callers must make sure that
2714 * every task struct that event->ctx->task could possibly point to
2715 * remains valid. This condition is satisfied when called through
2716 * perf_event_for_each_child or perf_event_for_each because they
2717 * hold the top-level event's child_mutex, so any descendant that
2718 * goes to exit will block in perf_event_exit_event().
2719 *
2720 * When called from perf_pending_disable it's OK because event->ctx
2721 * is the current context on this CPU and preemption is disabled,
2722 * hence we can't get into perf_event_task_sched_out for this context.
2723 */
_perf_event_disable(struct perf_event * event)2724 static void _perf_event_disable(struct perf_event *event)
2725 {
2726 struct perf_event_context *ctx = event->ctx;
2727
2728 raw_spin_lock_irq(&ctx->lock);
2729 if (event->state <= PERF_EVENT_STATE_OFF) {
2730 raw_spin_unlock_irq(&ctx->lock);
2731 return;
2732 }
2733 raw_spin_unlock_irq(&ctx->lock);
2734
2735 event_function_call(event, __perf_event_disable, NULL);
2736 }
2737
perf_event_disable_local(struct perf_event * event)2738 void perf_event_disable_local(struct perf_event *event)
2739 {
2740 event_function_local(event, __perf_event_disable, NULL);
2741 }
2742
2743 /*
2744 * Strictly speaking kernel users cannot create groups and therefore this
2745 * interface does not need the perf_event_ctx_lock() magic.
2746 */
perf_event_disable(struct perf_event * event)2747 void perf_event_disable(struct perf_event *event)
2748 {
2749 struct perf_event_context *ctx;
2750
2751 ctx = perf_event_ctx_lock(event);
2752 _perf_event_disable(event);
2753 perf_event_ctx_unlock(event, ctx);
2754 }
2755 EXPORT_SYMBOL_GPL(perf_event_disable);
2756
perf_event_disable_inatomic(struct perf_event * event)2757 void perf_event_disable_inatomic(struct perf_event *event)
2758 {
2759 event->pending_disable = 1;
2760 irq_work_queue(&event->pending_disable_irq);
2761 }
2762
2763 #define MAX_INTERRUPTS (~0ULL)
2764
2765 static void perf_log_throttle(struct perf_event *event, int enable);
2766 static void perf_log_itrace_start(struct perf_event *event);
2767
perf_event_unthrottle(struct perf_event * event,bool start)2768 static void perf_event_unthrottle(struct perf_event *event, bool start)
2769 {
2770 if (event->state != PERF_EVENT_STATE_ACTIVE)
2771 return;
2772
2773 event->hw.interrupts = 0;
2774 if (start)
2775 event->pmu->start(event, 0);
2776 if (event == event->group_leader)
2777 perf_log_throttle(event, 1);
2778 }
2779
perf_event_throttle(struct perf_event * event)2780 static void perf_event_throttle(struct perf_event *event)
2781 {
2782 if (event->state != PERF_EVENT_STATE_ACTIVE)
2783 return;
2784
2785 event->hw.interrupts = MAX_INTERRUPTS;
2786 event->pmu->stop(event, 0);
2787 if (event == event->group_leader)
2788 perf_log_throttle(event, 0);
2789 }
2790
perf_event_unthrottle_group(struct perf_event * event,bool skip_start_event)2791 static void perf_event_unthrottle_group(struct perf_event *event, bool skip_start_event)
2792 {
2793 struct perf_event *sibling, *leader = event->group_leader;
2794
2795 perf_event_unthrottle(leader, skip_start_event ? leader != event : true);
2796 for_each_sibling_event(sibling, leader)
2797 perf_event_unthrottle(sibling, skip_start_event ? sibling != event : true);
2798 }
2799
perf_event_throttle_group(struct perf_event * event)2800 static void perf_event_throttle_group(struct perf_event *event)
2801 {
2802 struct perf_event *sibling, *leader = event->group_leader;
2803
2804 perf_event_throttle(leader);
2805 for_each_sibling_event(sibling, leader)
2806 perf_event_throttle(sibling);
2807 }
2808
2809 static int
event_sched_in(struct perf_event * event,struct perf_event_context * ctx)2810 event_sched_in(struct perf_event *event, struct perf_event_context *ctx)
2811 {
2812 struct perf_event_pmu_context *epc = event->pmu_ctx;
2813 struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu);
2814 int ret = 0;
2815
2816 WARN_ON_ONCE(event->ctx != ctx);
2817
2818 lockdep_assert_held(&ctx->lock);
2819
2820 if (event->state <= PERF_EVENT_STATE_OFF)
2821 return 0;
2822
2823 WRITE_ONCE(event->oncpu, smp_processor_id());
2824 /*
2825 * Order event::oncpu write to happen before the ACTIVE state is
2826 * visible. This allows perf_event_{stop,read}() to observe the correct
2827 * ->oncpu if it sees ACTIVE.
2828 */
2829 smp_wmb();
2830 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2831
2832 /*
2833 * Unthrottle events, since we scheduled we might have missed several
2834 * ticks already, also for a heavily scheduling task there is little
2835 * guarantee it'll get a tick in a timely manner.
2836 */
2837 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS))
2838 perf_event_unthrottle(event, false);
2839
2840 perf_pmu_disable(event->pmu);
2841
2842 perf_log_itrace_start(event);
2843
2844 if (event->pmu->add(event, PERF_EF_START)) {
2845 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2846 event->oncpu = -1;
2847 ret = -EAGAIN;
2848 goto out;
2849 }
2850
2851 if (!is_software_event(event))
2852 cpc->active_oncpu++;
2853 if (is_event_in_freq_mode(event)) {
2854 ctx->nr_freq++;
2855 epc->nr_freq++;
2856 }
2857 if (event->attr.exclusive)
2858 cpc->exclusive = 1;
2859
2860 out:
2861 perf_pmu_enable(event->pmu);
2862
2863 return ret;
2864 }
2865
2866 static int
group_sched_in(struct perf_event * group_event,struct perf_event_context * ctx)2867 group_sched_in(struct perf_event *group_event, struct perf_event_context *ctx)
2868 {
2869 struct perf_event *event, *partial_group = NULL;
2870 struct pmu *pmu = group_event->pmu_ctx->pmu;
2871
2872 if (group_event->state == PERF_EVENT_STATE_OFF)
2873 return 0;
2874
2875 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2876
2877 if (event_sched_in(group_event, ctx))
2878 goto error;
2879
2880 /*
2881 * Schedule in siblings as one group (if any):
2882 */
2883 for_each_sibling_event(event, group_event) {
2884 if (event_sched_in(event, ctx)) {
2885 partial_group = event;
2886 goto group_error;
2887 }
2888 }
2889
2890 if (!pmu->commit_txn(pmu))
2891 return 0;
2892
2893 group_error:
2894 /*
2895 * Groups can be scheduled in as one unit only, so undo any
2896 * partial group before returning:
2897 * The events up to the failed event are scheduled out normally.
2898 */
2899 for_each_sibling_event(event, group_event) {
2900 if (event == partial_group)
2901 break;
2902
2903 event_sched_out(event, ctx);
2904 }
2905 event_sched_out(group_event, ctx);
2906
2907 error:
2908 pmu->cancel_txn(pmu);
2909 return -EAGAIN;
2910 }
2911
2912 /*
2913 * Work out whether we can put this event group on the CPU now.
2914 */
group_can_go_on(struct perf_event * event,int can_add_hw)2915 static int group_can_go_on(struct perf_event *event, int can_add_hw)
2916 {
2917 struct perf_event_pmu_context *epc = event->pmu_ctx;
2918 struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu);
2919
2920 /*
2921 * Groups consisting entirely of software events can always go on.
2922 */
2923 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2924 return 1;
2925 /*
2926 * If an exclusive group is already on, no other hardware
2927 * events can go on.
2928 */
2929 if (cpc->exclusive)
2930 return 0;
2931 /*
2932 * If this group is exclusive and there are already
2933 * events on the CPU, it can't go on.
2934 */
2935 if (event->attr.exclusive && !list_empty(get_event_list(event)))
2936 return 0;
2937 /*
2938 * Otherwise, try to add it if all previous groups were able
2939 * to go on.
2940 */
2941 return can_add_hw;
2942 }
2943
add_event_to_ctx(struct perf_event * event,struct perf_event_context * ctx)2944 static void add_event_to_ctx(struct perf_event *event,
2945 struct perf_event_context *ctx)
2946 {
2947 list_add_event(event, ctx);
2948 perf_group_attach(event);
2949 }
2950
task_ctx_sched_out(struct perf_event_context * ctx,struct pmu * pmu,enum event_type_t event_type)2951 static void task_ctx_sched_out(struct perf_event_context *ctx,
2952 struct pmu *pmu,
2953 enum event_type_t event_type)
2954 {
2955 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2956
2957 if (!cpuctx->task_ctx)
2958 return;
2959
2960 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2961 return;
2962
2963 ctx_sched_out(ctx, pmu, event_type);
2964 }
2965
perf_event_sched_in(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,struct pmu * pmu,enum event_type_t event_type)2966 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2967 struct perf_event_context *ctx,
2968 struct pmu *pmu,
2969 enum event_type_t event_type)
2970 {
2971 ctx_sched_in(&cpuctx->ctx, pmu, EVENT_PINNED | event_type);
2972 if (ctx)
2973 ctx_sched_in(ctx, pmu, EVENT_PINNED | event_type);
2974 ctx_sched_in(&cpuctx->ctx, pmu, EVENT_FLEXIBLE | event_type);
2975 if (ctx)
2976 ctx_sched_in(ctx, pmu, EVENT_FLEXIBLE | event_type);
2977 }
2978
2979 /*
2980 * We want to maintain the following priority of scheduling:
2981 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2982 * - task pinned (EVENT_PINNED)
2983 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2984 * - task flexible (EVENT_FLEXIBLE).
2985 *
2986 * In order to avoid unscheduling and scheduling back in everything every
2987 * time an event is added, only do it for the groups of equal priority and
2988 * below.
2989 *
2990 * This can be called after a batch operation on task events, in which case
2991 * event_type is a bit mask of the types of events involved. For CPU events,
2992 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2993 */
ctx_resched(struct perf_cpu_context * cpuctx,struct perf_event_context * task_ctx,struct pmu * pmu,enum event_type_t event_type)2994 static void ctx_resched(struct perf_cpu_context *cpuctx,
2995 struct perf_event_context *task_ctx,
2996 struct pmu *pmu, enum event_type_t event_type)
2997 {
2998 bool cpu_event = !!(event_type & EVENT_CPU);
2999 struct perf_event_pmu_context *epc;
3000
3001 /*
3002 * If pinned groups are involved, flexible groups also need to be
3003 * scheduled out.
3004 */
3005 if (event_type & EVENT_PINNED)
3006 event_type |= EVENT_FLEXIBLE;
3007
3008 event_type &= EVENT_ALL;
3009
3010 for_each_epc(epc, &cpuctx->ctx, pmu, 0)
3011 perf_pmu_disable(epc->pmu);
3012
3013 if (task_ctx) {
3014 for_each_epc(epc, task_ctx, pmu, 0)
3015 perf_pmu_disable(epc->pmu);
3016
3017 task_ctx_sched_out(task_ctx, pmu, event_type);
3018 }
3019
3020 /*
3021 * Decide which cpu ctx groups to schedule out based on the types
3022 * of events that caused rescheduling:
3023 * - EVENT_CPU: schedule out corresponding groups;
3024 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
3025 * - otherwise, do nothing more.
3026 */
3027 if (cpu_event)
3028 ctx_sched_out(&cpuctx->ctx, pmu, event_type);
3029 else if (event_type & EVENT_PINNED)
3030 ctx_sched_out(&cpuctx->ctx, pmu, EVENT_FLEXIBLE);
3031
3032 perf_event_sched_in(cpuctx, task_ctx, pmu, 0);
3033
3034 for_each_epc(epc, &cpuctx->ctx, pmu, 0)
3035 perf_pmu_enable(epc->pmu);
3036
3037 if (task_ctx) {
3038 for_each_epc(epc, task_ctx, pmu, 0)
3039 perf_pmu_enable(epc->pmu);
3040 }
3041 }
3042
perf_pmu_resched(struct pmu * pmu)3043 void perf_pmu_resched(struct pmu *pmu)
3044 {
3045 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3046 struct perf_event_context *task_ctx = cpuctx->task_ctx;
3047
3048 perf_ctx_lock(cpuctx, task_ctx);
3049 ctx_resched(cpuctx, task_ctx, pmu, EVENT_ALL|EVENT_CPU);
3050 perf_ctx_unlock(cpuctx, task_ctx);
3051 }
3052
3053 /*
3054 * Cross CPU call to install and enable a performance event
3055 *
3056 * Very similar to remote_function() + event_function() but cannot assume that
3057 * things like ctx->is_active and cpuctx->task_ctx are set.
3058 */
__perf_install_in_context(void * info)3059 static int __perf_install_in_context(void *info)
3060 {
3061 struct perf_event *event = info;
3062 struct perf_event_context *ctx = event->ctx;
3063 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3064 struct perf_event_context *task_ctx = cpuctx->task_ctx;
3065 bool reprogram = true;
3066 int ret = 0;
3067
3068 raw_spin_lock(&cpuctx->ctx.lock);
3069 if (ctx->task) {
3070 raw_spin_lock(&ctx->lock);
3071 task_ctx = ctx;
3072
3073 reprogram = (ctx->task == current);
3074
3075 /*
3076 * If the task is running, it must be running on this CPU,
3077 * otherwise we cannot reprogram things.
3078 *
3079 * If its not running, we don't care, ctx->lock will
3080 * serialize against it becoming runnable.
3081 */
3082 if (task_curr(ctx->task) && !reprogram) {
3083 ret = -ESRCH;
3084 goto unlock;
3085 }
3086
3087 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
3088 } else if (task_ctx) {
3089 raw_spin_lock(&task_ctx->lock);
3090 }
3091
3092 #ifdef CONFIG_CGROUP_PERF
3093 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
3094 /*
3095 * If the current cgroup doesn't match the event's
3096 * cgroup, we should not try to schedule it.
3097 */
3098 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
3099 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
3100 event->cgrp->css.cgroup);
3101 }
3102 #endif
3103
3104 if (reprogram) {
3105 ctx_time_freeze(cpuctx, ctx);
3106 add_event_to_ctx(event, ctx);
3107 ctx_resched(cpuctx, task_ctx, event->pmu_ctx->pmu,
3108 get_event_type(event));
3109 } else {
3110 add_event_to_ctx(event, ctx);
3111 }
3112
3113 unlock:
3114 perf_ctx_unlock(cpuctx, task_ctx);
3115
3116 return ret;
3117 }
3118
3119 static bool exclusive_event_installable(struct perf_event *event,
3120 struct perf_event_context *ctx);
3121
3122 /*
3123 * Attach a performance event to a context.
3124 *
3125 * Very similar to event_function_call, see comment there.
3126 */
3127 static void
perf_install_in_context(struct perf_event_context * ctx,struct perf_event * event,int cpu)3128 perf_install_in_context(struct perf_event_context *ctx,
3129 struct perf_event *event,
3130 int cpu)
3131 {
3132 struct task_struct *task = READ_ONCE(ctx->task);
3133
3134 lockdep_assert_held(&ctx->mutex);
3135
3136 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
3137
3138 if (event->cpu != -1)
3139 WARN_ON_ONCE(event->cpu != cpu);
3140
3141 /*
3142 * Ensures that if we can observe event->ctx, both the event and ctx
3143 * will be 'complete'. See perf_iterate_sb_cpu().
3144 */
3145 smp_store_release(&event->ctx, ctx);
3146
3147 /*
3148 * perf_event_attr::disabled events will not run and can be initialized
3149 * without IPI. Except when this is the first event for the context, in
3150 * that case we need the magic of the IPI to set ctx->is_active.
3151 *
3152 * The IOC_ENABLE that is sure to follow the creation of a disabled
3153 * event will issue the IPI and reprogram the hardware.
3154 */
3155 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF &&
3156 ctx->nr_events && !is_cgroup_event(event)) {
3157 raw_spin_lock_irq(&ctx->lock);
3158 if (ctx->task == TASK_TOMBSTONE) {
3159 raw_spin_unlock_irq(&ctx->lock);
3160 return;
3161 }
3162 add_event_to_ctx(event, ctx);
3163 raw_spin_unlock_irq(&ctx->lock);
3164 return;
3165 }
3166
3167 if (!task) {
3168 cpu_function_call(cpu, __perf_install_in_context, event);
3169 return;
3170 }
3171
3172 /*
3173 * Should not happen, we validate the ctx is still alive before calling.
3174 */
3175 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
3176 return;
3177
3178 /*
3179 * Installing events is tricky because we cannot rely on ctx->is_active
3180 * to be set in case this is the nr_events 0 -> 1 transition.
3181 *
3182 * Instead we use task_curr(), which tells us if the task is running.
3183 * However, since we use task_curr() outside of rq::lock, we can race
3184 * against the actual state. This means the result can be wrong.
3185 *
3186 * If we get a false positive, we retry, this is harmless.
3187 *
3188 * If we get a false negative, things are complicated. If we are after
3189 * perf_event_context_sched_in() ctx::lock will serialize us, and the
3190 * value must be correct. If we're before, it doesn't matter since
3191 * perf_event_context_sched_in() will program the counter.
3192 *
3193 * However, this hinges on the remote context switch having observed
3194 * our task->perf_event_ctxp[] store, such that it will in fact take
3195 * ctx::lock in perf_event_context_sched_in().
3196 *
3197 * We do this by task_function_call(), if the IPI fails to hit the task
3198 * we know any future context switch of task must see the
3199 * perf_event_ctpx[] store.
3200 */
3201
3202 /*
3203 * This smp_mb() orders the task->perf_event_ctxp[] store with the
3204 * task_cpu() load, such that if the IPI then does not find the task
3205 * running, a future context switch of that task must observe the
3206 * store.
3207 */
3208 smp_mb();
3209 again:
3210 if (!task_function_call(task, __perf_install_in_context, event))
3211 return;
3212
3213 raw_spin_lock_irq(&ctx->lock);
3214 task = ctx->task;
3215 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
3216 /*
3217 * Cannot happen because we already checked above (which also
3218 * cannot happen), and we hold ctx->mutex, which serializes us
3219 * against perf_event_exit_task_context().
3220 */
3221 raw_spin_unlock_irq(&ctx->lock);
3222 return;
3223 }
3224 /*
3225 * If the task is not running, ctx->lock will avoid it becoming so,
3226 * thus we can safely install the event.
3227 */
3228 if (task_curr(task)) {
3229 raw_spin_unlock_irq(&ctx->lock);
3230 goto again;
3231 }
3232 add_event_to_ctx(event, ctx);
3233 raw_spin_unlock_irq(&ctx->lock);
3234 }
3235
3236 /*
3237 * Cross CPU call to enable a performance event
3238 */
__perf_event_enable(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)3239 static void __perf_event_enable(struct perf_event *event,
3240 struct perf_cpu_context *cpuctx,
3241 struct perf_event_context *ctx,
3242 void *info)
3243 {
3244 struct perf_event *leader = event->group_leader;
3245 struct perf_event_context *task_ctx;
3246
3247 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
3248 event->state <= PERF_EVENT_STATE_ERROR)
3249 return;
3250
3251 ctx_time_freeze(cpuctx, ctx);
3252
3253 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
3254 perf_cgroup_event_enable(event, ctx);
3255
3256 if (!ctx->is_active)
3257 return;
3258
3259 if (!event_filter_match(event))
3260 return;
3261
3262 /*
3263 * If the event is in a group and isn't the group leader,
3264 * then don't put it on unless the group is on.
3265 */
3266 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
3267 return;
3268
3269 task_ctx = cpuctx->task_ctx;
3270 if (ctx->task)
3271 WARN_ON_ONCE(task_ctx != ctx);
3272
3273 ctx_resched(cpuctx, task_ctx, event->pmu_ctx->pmu, get_event_type(event));
3274 }
3275
3276 /*
3277 * Enable an event.
3278 *
3279 * If event->ctx is a cloned context, callers must make sure that
3280 * every task struct that event->ctx->task could possibly point to
3281 * remains valid. This condition is satisfied when called through
3282 * perf_event_for_each_child or perf_event_for_each as described
3283 * for perf_event_disable.
3284 */
_perf_event_enable(struct perf_event * event)3285 static void _perf_event_enable(struct perf_event *event)
3286 {
3287 struct perf_event_context *ctx = event->ctx;
3288
3289 raw_spin_lock_irq(&ctx->lock);
3290 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
3291 event->state < PERF_EVENT_STATE_ERROR) {
3292 out:
3293 raw_spin_unlock_irq(&ctx->lock);
3294 return;
3295 }
3296
3297 /*
3298 * If the event is in error state, clear that first.
3299 *
3300 * That way, if we see the event in error state below, we know that it
3301 * has gone back into error state, as distinct from the task having
3302 * been scheduled away before the cross-call arrived.
3303 */
3304 if (event->state == PERF_EVENT_STATE_ERROR) {
3305 /*
3306 * Detached SIBLING events cannot leave ERROR state.
3307 */
3308 if (event->event_caps & PERF_EV_CAP_SIBLING &&
3309 event->group_leader == event)
3310 goto out;
3311
3312 event->state = PERF_EVENT_STATE_OFF;
3313 }
3314 raw_spin_unlock_irq(&ctx->lock);
3315
3316 event_function_call(event, __perf_event_enable, NULL);
3317 }
3318
3319 /*
3320 * See perf_event_disable();
3321 */
perf_event_enable(struct perf_event * event)3322 void perf_event_enable(struct perf_event *event)
3323 {
3324 struct perf_event_context *ctx;
3325
3326 ctx = perf_event_ctx_lock(event);
3327 _perf_event_enable(event);
3328 perf_event_ctx_unlock(event, ctx);
3329 }
3330 EXPORT_SYMBOL_GPL(perf_event_enable);
3331
3332 struct stop_event_data {
3333 struct perf_event *event;
3334 unsigned int restart;
3335 };
3336
__perf_event_stop(void * info)3337 static int __perf_event_stop(void *info)
3338 {
3339 struct stop_event_data *sd = info;
3340 struct perf_event *event = sd->event;
3341
3342 /* if it's already INACTIVE, do nothing */
3343 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3344 return 0;
3345
3346 /* matches smp_wmb() in event_sched_in() */
3347 smp_rmb();
3348
3349 /*
3350 * There is a window with interrupts enabled before we get here,
3351 * so we need to check again lest we try to stop another CPU's event.
3352 */
3353 if (READ_ONCE(event->oncpu) != smp_processor_id())
3354 return -EAGAIN;
3355
3356 event->pmu->stop(event, PERF_EF_UPDATE);
3357
3358 /*
3359 * May race with the actual stop (through perf_pmu_output_stop()),
3360 * but it is only used for events with AUX ring buffer, and such
3361 * events will refuse to restart because of rb::aux_mmap_count==0,
3362 * see comments in perf_aux_output_begin().
3363 *
3364 * Since this is happening on an event-local CPU, no trace is lost
3365 * while restarting.
3366 */
3367 if (sd->restart)
3368 event->pmu->start(event, 0);
3369
3370 return 0;
3371 }
3372
perf_event_stop(struct perf_event * event,int restart)3373 static int perf_event_stop(struct perf_event *event, int restart)
3374 {
3375 struct stop_event_data sd = {
3376 .event = event,
3377 .restart = restart,
3378 };
3379 int ret = 0;
3380
3381 do {
3382 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3383 return 0;
3384
3385 /* matches smp_wmb() in event_sched_in() */
3386 smp_rmb();
3387
3388 /*
3389 * We only want to restart ACTIVE events, so if the event goes
3390 * inactive here (event->oncpu==-1), there's nothing more to do;
3391 * fall through with ret==-ENXIO.
3392 */
3393 ret = cpu_function_call(READ_ONCE(event->oncpu),
3394 __perf_event_stop, &sd);
3395 } while (ret == -EAGAIN);
3396
3397 return ret;
3398 }
3399
3400 /*
3401 * In order to contain the amount of racy and tricky in the address filter
3402 * configuration management, it is a two part process:
3403 *
3404 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3405 * we update the addresses of corresponding vmas in
3406 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
3407 * (p2) when an event is scheduled in (pmu::add), it calls
3408 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3409 * if the generation has changed since the previous call.
3410 *
3411 * If (p1) happens while the event is active, we restart it to force (p2).
3412 *
3413 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3414 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3415 * ioctl;
3416 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3417 * registered mapping, called for every new mmap(), with mm::mmap_lock down
3418 * for reading;
3419 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3420 * of exec.
3421 */
perf_event_addr_filters_sync(struct perf_event * event)3422 void perf_event_addr_filters_sync(struct perf_event *event)
3423 {
3424 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3425
3426 if (!has_addr_filter(event))
3427 return;
3428
3429 raw_spin_lock(&ifh->lock);
3430 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3431 event->pmu->addr_filters_sync(event);
3432 event->hw.addr_filters_gen = event->addr_filters_gen;
3433 }
3434 raw_spin_unlock(&ifh->lock);
3435 }
3436 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3437
_perf_event_refresh(struct perf_event * event,int refresh)3438 static int _perf_event_refresh(struct perf_event *event, int refresh)
3439 {
3440 /*
3441 * not supported on inherited events
3442 */
3443 if (event->attr.inherit || !is_sampling_event(event))
3444 return -EINVAL;
3445
3446 atomic_add(refresh, &event->event_limit);
3447 _perf_event_enable(event);
3448
3449 return 0;
3450 }
3451
3452 /*
3453 * See perf_event_disable()
3454 */
perf_event_refresh(struct perf_event * event,int refresh)3455 int perf_event_refresh(struct perf_event *event, int refresh)
3456 {
3457 struct perf_event_context *ctx;
3458 int ret;
3459
3460 ctx = perf_event_ctx_lock(event);
3461 ret = _perf_event_refresh(event, refresh);
3462 perf_event_ctx_unlock(event, ctx);
3463
3464 return ret;
3465 }
3466 EXPORT_SYMBOL_GPL(perf_event_refresh);
3467
perf_event_modify_breakpoint(struct perf_event * bp,struct perf_event_attr * attr)3468 static int perf_event_modify_breakpoint(struct perf_event *bp,
3469 struct perf_event_attr *attr)
3470 {
3471 int err;
3472
3473 _perf_event_disable(bp);
3474
3475 err = modify_user_hw_breakpoint_check(bp, attr, true);
3476
3477 if (!bp->attr.disabled)
3478 _perf_event_enable(bp);
3479
3480 return err;
3481 }
3482
3483 /*
3484 * Copy event-type-independent attributes that may be modified.
3485 */
perf_event_modify_copy_attr(struct perf_event_attr * to,const struct perf_event_attr * from)3486 static void perf_event_modify_copy_attr(struct perf_event_attr *to,
3487 const struct perf_event_attr *from)
3488 {
3489 to->sig_data = from->sig_data;
3490 }
3491
perf_event_modify_attr(struct perf_event * event,struct perf_event_attr * attr)3492 static int perf_event_modify_attr(struct perf_event *event,
3493 struct perf_event_attr *attr)
3494 {
3495 int (*func)(struct perf_event *, struct perf_event_attr *);
3496 struct perf_event *child;
3497 int err;
3498
3499 if (event->attr.type != attr->type)
3500 return -EINVAL;
3501
3502 switch (event->attr.type) {
3503 case PERF_TYPE_BREAKPOINT:
3504 func = perf_event_modify_breakpoint;
3505 break;
3506 default:
3507 /* Place holder for future additions. */
3508 return -EOPNOTSUPP;
3509 }
3510
3511 WARN_ON_ONCE(event->ctx->parent_ctx);
3512
3513 mutex_lock(&event->child_mutex);
3514 /*
3515 * Event-type-independent attributes must be copied before event-type
3516 * modification, which will validate that final attributes match the
3517 * source attributes after all relevant attributes have been copied.
3518 */
3519 perf_event_modify_copy_attr(&event->attr, attr);
3520 err = func(event, attr);
3521 if (err)
3522 goto out;
3523 list_for_each_entry(child, &event->child_list, child_list) {
3524 perf_event_modify_copy_attr(&child->attr, attr);
3525 err = func(child, attr);
3526 if (err)
3527 goto out;
3528 }
3529 out:
3530 mutex_unlock(&event->child_mutex);
3531 return err;
3532 }
3533
__pmu_ctx_sched_out(struct perf_event_pmu_context * pmu_ctx,enum event_type_t event_type)3534 static void __pmu_ctx_sched_out(struct perf_event_pmu_context *pmu_ctx,
3535 enum event_type_t event_type)
3536 {
3537 struct perf_event_context *ctx = pmu_ctx->ctx;
3538 struct perf_event *event, *tmp;
3539 struct pmu *pmu = pmu_ctx->pmu;
3540
3541 if (ctx->task && !(ctx->is_active & EVENT_ALL)) {
3542 struct perf_cpu_pmu_context *cpc = this_cpc(pmu);
3543
3544 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
3545 cpc->task_epc = NULL;
3546 }
3547
3548 if (!(event_type & EVENT_ALL))
3549 return;
3550
3551 perf_pmu_disable(pmu);
3552 if (event_type & EVENT_PINNED) {
3553 list_for_each_entry_safe(event, tmp,
3554 &pmu_ctx->pinned_active,
3555 active_list)
3556 group_sched_out(event, ctx);
3557 }
3558
3559 if (event_type & EVENT_FLEXIBLE) {
3560 list_for_each_entry_safe(event, tmp,
3561 &pmu_ctx->flexible_active,
3562 active_list)
3563 group_sched_out(event, ctx);
3564 /*
3565 * Since we cleared EVENT_FLEXIBLE, also clear
3566 * rotate_necessary, is will be reset by
3567 * ctx_flexible_sched_in() when needed.
3568 */
3569 pmu_ctx->rotate_necessary = 0;
3570 }
3571 perf_pmu_enable(pmu);
3572 }
3573
3574 /*
3575 * Be very careful with the @pmu argument since this will change ctx state.
3576 * The @pmu argument works for ctx_resched(), because that is symmetric in
3577 * ctx_sched_out() / ctx_sched_in() usage and the ctx state ends up invariant.
3578 *
3579 * However, if you were to be asymmetrical, you could end up with messed up
3580 * state, eg. ctx->is_active cleared even though most EPCs would still actually
3581 * be active.
3582 */
3583 static void
ctx_sched_out(struct perf_event_context * ctx,struct pmu * pmu,enum event_type_t event_type)3584 ctx_sched_out(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type)
3585 {
3586 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3587 enum event_type_t active_type = event_type & ~EVENT_FLAGS;
3588 struct perf_event_pmu_context *pmu_ctx;
3589 int is_active = ctx->is_active;
3590
3591
3592 lockdep_assert_held(&ctx->lock);
3593
3594 if (likely(!ctx->nr_events)) {
3595 /*
3596 * See __perf_remove_from_context().
3597 */
3598 WARN_ON_ONCE(ctx->is_active);
3599 if (ctx->task)
3600 WARN_ON_ONCE(cpuctx->task_ctx);
3601 return;
3602 }
3603
3604 /*
3605 * Always update time if it was set; not only when it changes.
3606 * Otherwise we can 'forget' to update time for any but the last
3607 * context we sched out. For example:
3608 *
3609 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3610 * ctx_sched_out(.event_type = EVENT_PINNED)
3611 *
3612 * would only update time for the pinned events.
3613 */
3614 __ctx_time_update(cpuctx, ctx, ctx == &cpuctx->ctx, event_type);
3615
3616 /*
3617 * CPU-release for the below ->is_active store,
3618 * see __load_acquire() in perf_event_time_now()
3619 */
3620 barrier();
3621 ctx->is_active &= ~active_type;
3622
3623 if (!(ctx->is_active & EVENT_ALL)) {
3624 /*
3625 * For FROZEN, preserve TIME|FROZEN such that perf_event_time_now()
3626 * does not observe a hole. perf_ctx_unlock() will clean up.
3627 */
3628 if (ctx->is_active & EVENT_FROZEN)
3629 ctx->is_active &= EVENT_TIME_FROZEN;
3630 else
3631 ctx->is_active = 0;
3632 }
3633
3634 if (ctx->task) {
3635 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3636 if (!(ctx->is_active & EVENT_ALL))
3637 cpuctx->task_ctx = NULL;
3638 }
3639
3640 if (event_type & EVENT_GUEST) {
3641 /*
3642 * Schedule out all exclude_guest events of PMU
3643 * with PERF_PMU_CAP_MEDIATED_VPMU.
3644 */
3645 is_active = EVENT_ALL;
3646 __update_context_guest_time(ctx, false);
3647 perf_cgroup_set_timestamp(cpuctx, true);
3648 barrier();
3649 } else {
3650 is_active ^= ctx->is_active; /* changed bits */
3651 }
3652
3653 for_each_epc(pmu_ctx, ctx, pmu, event_type)
3654 __pmu_ctx_sched_out(pmu_ctx, is_active);
3655 }
3656
3657 /*
3658 * Test whether two contexts are equivalent, i.e. whether they have both been
3659 * cloned from the same version of the same context.
3660 *
3661 * Equivalence is measured using a generation number in the context that is
3662 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3663 * and list_del_event().
3664 */
context_equiv(struct perf_event_context * ctx1,struct perf_event_context * ctx2)3665 static int context_equiv(struct perf_event_context *ctx1,
3666 struct perf_event_context *ctx2)
3667 {
3668 lockdep_assert_held(&ctx1->lock);
3669 lockdep_assert_held(&ctx2->lock);
3670
3671 /* Pinning disables the swap optimization */
3672 if (ctx1->pin_count || ctx2->pin_count)
3673 return 0;
3674
3675 /* If ctx1 is the parent of ctx2 */
3676 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3677 return 1;
3678
3679 /* If ctx2 is the parent of ctx1 */
3680 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3681 return 1;
3682
3683 /*
3684 * If ctx1 and ctx2 have the same parent; we flatten the parent
3685 * hierarchy, see perf_event_init_context().
3686 */
3687 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3688 ctx1->parent_gen == ctx2->parent_gen)
3689 return 1;
3690
3691 /* Unmatched */
3692 return 0;
3693 }
3694
__perf_event_sync_stat(struct perf_event * event,struct perf_event * next_event)3695 static void __perf_event_sync_stat(struct perf_event *event,
3696 struct perf_event *next_event)
3697 {
3698 u64 value;
3699
3700 if (!event->attr.inherit_stat)
3701 return;
3702
3703 /*
3704 * Update the event value, we cannot use perf_event_read()
3705 * because we're in the middle of a context switch and have IRQs
3706 * disabled, which upsets smp_call_function_single(), however
3707 * we know the event must be on the current CPU, therefore we
3708 * don't need to use it.
3709 */
3710 perf_pmu_read(event);
3711
3712 perf_event_update_time(event);
3713
3714 /*
3715 * In order to keep per-task stats reliable we need to flip the event
3716 * values when we flip the contexts.
3717 */
3718 value = local64_read(&next_event->count);
3719 value = local64_xchg(&event->count, value);
3720 local64_set(&next_event->count, value);
3721
3722 swap(event->total_time_enabled, next_event->total_time_enabled);
3723 swap(event->total_time_running, next_event->total_time_running);
3724
3725 /*
3726 * Since we swizzled the values, update the user visible data too.
3727 */
3728 perf_event_update_userpage(event);
3729 perf_event_update_userpage(next_event);
3730 }
3731
perf_event_sync_stat(struct perf_event_context * ctx,struct perf_event_context * next_ctx)3732 static void perf_event_sync_stat(struct perf_event_context *ctx,
3733 struct perf_event_context *next_ctx)
3734 {
3735 struct perf_event *event, *next_event;
3736
3737 if (!ctx->nr_stat)
3738 return;
3739
3740 update_context_time(ctx);
3741
3742 event = list_first_entry(&ctx->event_list,
3743 struct perf_event, event_entry);
3744
3745 next_event = list_first_entry(&next_ctx->event_list,
3746 struct perf_event, event_entry);
3747
3748 while (&event->event_entry != &ctx->event_list &&
3749 &next_event->event_entry != &next_ctx->event_list) {
3750
3751 __perf_event_sync_stat(event, next_event);
3752
3753 event = list_next_entry(event, event_entry);
3754 next_event = list_next_entry(next_event, event_entry);
3755 }
3756 }
3757
perf_ctx_sched_task_cb(struct perf_event_context * ctx,struct task_struct * task,bool sched_in)3758 static void perf_ctx_sched_task_cb(struct perf_event_context *ctx,
3759 struct task_struct *task, bool sched_in)
3760 {
3761 struct perf_event_pmu_context *pmu_ctx;
3762 struct perf_cpu_pmu_context *cpc;
3763
3764 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
3765 cpc = this_cpc(pmu_ctx->pmu);
3766
3767 if (cpc->sched_cb_usage && pmu_ctx->pmu->sched_task)
3768 pmu_ctx->pmu->sched_task(pmu_ctx, task, sched_in);
3769 }
3770 }
3771
3772 static void
perf_event_context_sched_out(struct task_struct * task,struct task_struct * next)3773 perf_event_context_sched_out(struct task_struct *task, struct task_struct *next)
3774 {
3775 struct perf_event_context *ctx = task->perf_event_ctxp;
3776 struct perf_event_context *next_ctx;
3777 struct perf_event_context *parent, *next_parent;
3778 int do_switch = 1;
3779
3780 if (likely(!ctx))
3781 return;
3782
3783 rcu_read_lock();
3784 next_ctx = rcu_dereference(next->perf_event_ctxp);
3785 if (!next_ctx)
3786 goto unlock;
3787
3788 parent = rcu_dereference(ctx->parent_ctx);
3789 next_parent = rcu_dereference(next_ctx->parent_ctx);
3790
3791 /* If neither context have a parent context; they cannot be clones. */
3792 if (!parent && !next_parent)
3793 goto unlock;
3794
3795 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3796 /*
3797 * Looks like the two contexts are clones, so we might be
3798 * able to optimize the context switch. We lock both
3799 * contexts and check that they are clones under the
3800 * lock (including re-checking that neither has been
3801 * uncloned in the meantime). It doesn't matter which
3802 * order we take the locks because no other cpu could
3803 * be trying to lock both of these tasks.
3804 */
3805 raw_spin_lock(&ctx->lock);
3806 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3807 if (context_equiv(ctx, next_ctx)) {
3808
3809 perf_ctx_disable(ctx, 0);
3810
3811 /* PMIs are disabled; ctx->nr_no_switch_fast is stable. */
3812 if (local_read(&ctx->nr_no_switch_fast) ||
3813 local_read(&next_ctx->nr_no_switch_fast)) {
3814 /*
3815 * Must not swap out ctx when there's pending
3816 * events that rely on the ctx->task relation.
3817 *
3818 * Likewise, when a context contains inherit +
3819 * SAMPLE_READ events they should be switched
3820 * out using the slow path so that they are
3821 * treated as if they were distinct contexts.
3822 */
3823 raw_spin_unlock(&next_ctx->lock);
3824 rcu_read_unlock();
3825 goto inside_switch;
3826 }
3827
3828 WRITE_ONCE(ctx->task, next);
3829 WRITE_ONCE(next_ctx->task, task);
3830
3831 perf_ctx_sched_task_cb(ctx, task, false);
3832
3833 perf_ctx_enable(ctx, 0);
3834
3835 /*
3836 * RCU_INIT_POINTER here is safe because we've not
3837 * modified the ctx and the above modification of
3838 * ctx->task is immaterial since this value is
3839 * always verified under ctx->lock which we're now
3840 * holding.
3841 */
3842 RCU_INIT_POINTER(task->perf_event_ctxp, next_ctx);
3843 RCU_INIT_POINTER(next->perf_event_ctxp, ctx);
3844
3845 do_switch = 0;
3846
3847 perf_event_sync_stat(ctx, next_ctx);
3848 }
3849 raw_spin_unlock(&next_ctx->lock);
3850 raw_spin_unlock(&ctx->lock);
3851 }
3852 unlock:
3853 rcu_read_unlock();
3854
3855 if (do_switch) {
3856 raw_spin_lock(&ctx->lock);
3857 perf_ctx_disable(ctx, 0);
3858
3859 inside_switch:
3860 perf_ctx_sched_task_cb(ctx, task, false);
3861 task_ctx_sched_out(ctx, NULL, EVENT_ALL);
3862
3863 perf_ctx_enable(ctx, 0);
3864 raw_spin_unlock(&ctx->lock);
3865 }
3866 }
3867
3868 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3869 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
3870
perf_sched_cb_dec(struct pmu * pmu)3871 void perf_sched_cb_dec(struct pmu *pmu)
3872 {
3873 struct perf_cpu_pmu_context *cpc = this_cpc(pmu);
3874
3875 this_cpu_dec(perf_sched_cb_usages);
3876 barrier();
3877
3878 if (!--cpc->sched_cb_usage)
3879 list_del(&cpc->sched_cb_entry);
3880 }
3881
3882
perf_sched_cb_inc(struct pmu * pmu)3883 void perf_sched_cb_inc(struct pmu *pmu)
3884 {
3885 struct perf_cpu_pmu_context *cpc = this_cpc(pmu);
3886
3887 if (!cpc->sched_cb_usage++)
3888 list_add(&cpc->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3889
3890 barrier();
3891 this_cpu_inc(perf_sched_cb_usages);
3892 }
3893
3894 /*
3895 * This function provides the context switch callback to the lower code
3896 * layer. It is invoked ONLY when the context switch callback is enabled.
3897 *
3898 * This callback is relevant even to per-cpu events; for example multi event
3899 * PEBS requires this to provide PID/TID information. This requires we flush
3900 * all queued PEBS records before we context switch to a new task.
3901 */
__perf_pmu_sched_task(struct perf_cpu_pmu_context * cpc,struct task_struct * task,bool sched_in)3902 static void __perf_pmu_sched_task(struct perf_cpu_pmu_context *cpc,
3903 struct task_struct *task, bool sched_in)
3904 {
3905 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3906 struct pmu *pmu;
3907
3908 pmu = cpc->epc.pmu;
3909
3910 /* software PMUs will not have sched_task */
3911 if (WARN_ON_ONCE(!pmu->sched_task))
3912 return;
3913
3914 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3915 perf_pmu_disable(pmu);
3916
3917 pmu->sched_task(cpc->task_epc, task, sched_in);
3918
3919 perf_pmu_enable(pmu);
3920 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3921 }
3922
perf_pmu_sched_task(struct task_struct * prev,struct task_struct * next,bool sched_in)3923 static void perf_pmu_sched_task(struct task_struct *prev,
3924 struct task_struct *next,
3925 bool sched_in)
3926 {
3927 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3928 struct perf_cpu_pmu_context *cpc, *cpc2;
3929
3930 /* cpuctx->task_ctx will be handled in perf_event_context_sched_in/out */
3931 if (prev == next || cpuctx->task_ctx)
3932 return;
3933
3934 list_for_each_entry_safe(cpc, cpc2, this_cpu_ptr(&sched_cb_list), sched_cb_entry)
3935 __perf_pmu_sched_task(cpc, sched_in ? next : prev, sched_in);
3936 }
3937
3938 static void perf_event_switch(struct task_struct *task,
3939 struct task_struct *next_prev, bool sched_in);
3940
3941 /*
3942 * Called from scheduler to remove the events of the current task,
3943 * with interrupts disabled.
3944 *
3945 * We stop each event and update the event value in event->count.
3946 *
3947 * This does not protect us against NMI, but disable()
3948 * sets the disabled bit in the control field of event _before_
3949 * accessing the event control register. If a NMI hits, then it will
3950 * not restart the event.
3951 */
__perf_event_task_sched_out(struct task_struct * task,struct task_struct * next)3952 void __perf_event_task_sched_out(struct task_struct *task,
3953 struct task_struct *next)
3954 {
3955 if (__this_cpu_read(perf_sched_cb_usages))
3956 perf_pmu_sched_task(task, next, false);
3957
3958 if (atomic_read(&nr_switch_events))
3959 perf_event_switch(task, next, false);
3960
3961 perf_event_context_sched_out(task, next);
3962
3963 /*
3964 * if cgroup events exist on this CPU, then we need
3965 * to check if we have to switch out PMU state.
3966 * cgroup event are system-wide mode only
3967 */
3968 perf_cgroup_switch(next);
3969 }
3970
perf_less_group_idx(const void * l,const void * r,void __always_unused * args)3971 static bool perf_less_group_idx(const void *l, const void *r, void __always_unused *args)
3972 {
3973 const struct perf_event *le = *(const struct perf_event **)l;
3974 const struct perf_event *re = *(const struct perf_event **)r;
3975
3976 return le->group_index < re->group_index;
3977 }
3978
3979 DEFINE_MIN_HEAP(struct perf_event *, perf_event_min_heap);
3980
3981 static const struct min_heap_callbacks perf_min_heap = {
3982 .less = perf_less_group_idx,
3983 .swp = NULL,
3984 };
3985
__heap_add(struct perf_event_min_heap * heap,struct perf_event * event)3986 static void __heap_add(struct perf_event_min_heap *heap, struct perf_event *event)
3987 {
3988 struct perf_event **itrs = heap->data;
3989
3990 if (event) {
3991 itrs[heap->nr] = event;
3992 heap->nr++;
3993 }
3994 }
3995
__link_epc(struct perf_event_pmu_context * pmu_ctx)3996 static void __link_epc(struct perf_event_pmu_context *pmu_ctx)
3997 {
3998 struct perf_cpu_pmu_context *cpc;
3999
4000 if (!pmu_ctx->ctx->task)
4001 return;
4002
4003 cpc = this_cpc(pmu_ctx->pmu);
4004 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
4005 cpc->task_epc = pmu_ctx;
4006 }
4007
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)4008 static noinline int visit_groups_merge(struct perf_event_context *ctx,
4009 struct perf_event_groups *groups, int cpu,
4010 struct pmu *pmu,
4011 int (*func)(struct perf_event *, void *),
4012 void *data)
4013 {
4014 #ifdef CONFIG_CGROUP_PERF
4015 struct cgroup_subsys_state *css = NULL;
4016 #endif
4017 struct perf_cpu_context *cpuctx = NULL;
4018 /* Space for per CPU and/or any CPU event iterators. */
4019 struct perf_event *itrs[2];
4020 struct perf_event_min_heap event_heap;
4021 struct perf_event **evt;
4022 int ret;
4023
4024 if (pmu->filter && pmu->filter(pmu, cpu))
4025 return 0;
4026
4027 if (!ctx->task) {
4028 cpuctx = this_cpu_ptr(&perf_cpu_context);
4029 event_heap = (struct perf_event_min_heap){
4030 .data = cpuctx->heap,
4031 .nr = 0,
4032 .size = cpuctx->heap_size,
4033 };
4034
4035 lockdep_assert_held(&cpuctx->ctx.lock);
4036
4037 #ifdef CONFIG_CGROUP_PERF
4038 if (cpuctx->cgrp)
4039 css = &cpuctx->cgrp->css;
4040 #endif
4041 } else {
4042 event_heap = (struct perf_event_min_heap){
4043 .data = itrs,
4044 .nr = 0,
4045 .size = ARRAY_SIZE(itrs),
4046 };
4047 /* Events not within a CPU context may be on any CPU. */
4048 __heap_add(&event_heap, perf_event_groups_first(groups, -1, pmu, NULL));
4049 }
4050 evt = event_heap.data;
4051
4052 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, NULL));
4053
4054 #ifdef CONFIG_CGROUP_PERF
4055 for (; css; css = css->parent)
4056 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, css->cgroup));
4057 #endif
4058
4059 if (event_heap.nr) {
4060 __link_epc((*evt)->pmu_ctx);
4061 perf_assert_pmu_disabled((*evt)->pmu_ctx->pmu);
4062 }
4063
4064 min_heapify_all_inline(&event_heap, &perf_min_heap, NULL);
4065
4066 while (event_heap.nr) {
4067 ret = func(*evt, data);
4068 if (ret)
4069 return ret;
4070
4071 *evt = perf_event_groups_next(*evt, pmu);
4072 if (*evt)
4073 min_heap_sift_down_inline(&event_heap, 0, &perf_min_heap, NULL);
4074 else
4075 min_heap_pop_inline(&event_heap, &perf_min_heap, NULL);
4076 }
4077
4078 return 0;
4079 }
4080
4081 /*
4082 * Because the userpage is strictly per-event (there is no concept of context,
4083 * so there cannot be a context indirection), every userpage must be updated
4084 * when context time starts :-(
4085 *
4086 * IOW, we must not miss EVENT_TIME edges.
4087 */
event_update_userpage(struct perf_event * event)4088 static inline bool event_update_userpage(struct perf_event *event)
4089 {
4090 if (likely(!refcount_read(&event->mmap_count)))
4091 return false;
4092
4093 perf_event_update_time(event);
4094 perf_event_update_userpage(event);
4095
4096 return true;
4097 }
4098
group_update_userpage(struct perf_event * group_event)4099 static inline void group_update_userpage(struct perf_event *group_event)
4100 {
4101 struct perf_event *event;
4102
4103 if (!event_update_userpage(group_event))
4104 return;
4105
4106 for_each_sibling_event(event, group_event)
4107 event_update_userpage(event);
4108 }
4109
4110 struct merge_sched_data {
4111 int can_add_hw;
4112 enum event_type_t event_type;
4113 };
4114
merge_sched_in(struct perf_event * event,void * data)4115 static int merge_sched_in(struct perf_event *event, void *data)
4116 {
4117 struct perf_event_context *ctx = event->ctx;
4118 struct merge_sched_data *msd = data;
4119
4120 if (event->state <= PERF_EVENT_STATE_OFF)
4121 return 0;
4122
4123 if (!event_filter_match(event))
4124 return 0;
4125
4126 /*
4127 * Don't schedule in any host events from PMU with
4128 * PERF_PMU_CAP_MEDIATED_VPMU, while a guest is running.
4129 */
4130 if (is_guest_mediated_pmu_loaded() &&
4131 event->pmu_ctx->pmu->capabilities & PERF_PMU_CAP_MEDIATED_VPMU &&
4132 !(msd->event_type & EVENT_GUEST))
4133 return 0;
4134
4135 if (group_can_go_on(event, msd->can_add_hw)) {
4136 if (!group_sched_in(event, ctx))
4137 list_add_tail(&event->active_list, get_event_list(event));
4138 }
4139
4140 if (event->state == PERF_EVENT_STATE_INACTIVE) {
4141 msd->can_add_hw = 0;
4142 if (event->attr.pinned) {
4143 perf_cgroup_event_disable(event, ctx);
4144 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
4145
4146 if (*perf_event_fasync(event))
4147 event->pending_kill = POLL_ERR;
4148
4149 event->pending_wakeup = 1;
4150 irq_work_queue(&event->pending_irq);
4151 } else {
4152 struct perf_cpu_pmu_context *cpc = this_cpc(event->pmu_ctx->pmu);
4153
4154 event->pmu_ctx->rotate_necessary = 1;
4155 perf_mux_hrtimer_restart(cpc);
4156 group_update_userpage(event);
4157 }
4158 }
4159
4160 return 0;
4161 }
4162
pmu_groups_sched_in(struct perf_event_context * ctx,struct perf_event_groups * groups,struct pmu * pmu,enum event_type_t event_type)4163 static void pmu_groups_sched_in(struct perf_event_context *ctx,
4164 struct perf_event_groups *groups,
4165 struct pmu *pmu,
4166 enum event_type_t event_type)
4167 {
4168 struct merge_sched_data msd = {
4169 .can_add_hw = 1,
4170 .event_type = event_type,
4171 };
4172 visit_groups_merge(ctx, groups, smp_processor_id(), pmu,
4173 merge_sched_in, &msd);
4174 }
4175
__pmu_ctx_sched_in(struct perf_event_pmu_context * pmu_ctx,enum event_type_t event_type)4176 static void __pmu_ctx_sched_in(struct perf_event_pmu_context *pmu_ctx,
4177 enum event_type_t event_type)
4178 {
4179 struct perf_event_context *ctx = pmu_ctx->ctx;
4180
4181 if (event_type & EVENT_PINNED)
4182 pmu_groups_sched_in(ctx, &ctx->pinned_groups, pmu_ctx->pmu, event_type);
4183 if (event_type & EVENT_FLEXIBLE)
4184 pmu_groups_sched_in(ctx, &ctx->flexible_groups, pmu_ctx->pmu, event_type);
4185 }
4186
4187 static void
ctx_sched_in(struct perf_event_context * ctx,struct pmu * pmu,enum event_type_t event_type)4188 ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type)
4189 {
4190 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4191 enum event_type_t active_type = event_type & ~EVENT_FLAGS;
4192 struct perf_event_pmu_context *pmu_ctx;
4193 int is_active = ctx->is_active;
4194
4195 lockdep_assert_held(&ctx->lock);
4196
4197 if (likely(!ctx->nr_events))
4198 return;
4199
4200 if (!(is_active & EVENT_TIME)) {
4201 /* EVENT_TIME should be active while the guest runs */
4202 WARN_ON_ONCE(event_type & EVENT_GUEST);
4203 /* start ctx time */
4204 __update_context_time(ctx, false);
4205 perf_cgroup_set_timestamp(cpuctx, false);
4206 /*
4207 * CPU-release for the below ->is_active store,
4208 * see __load_acquire() in perf_event_time_now()
4209 */
4210 barrier();
4211 }
4212
4213 ctx->is_active |= active_type | EVENT_TIME;
4214 if (ctx->task) {
4215 if (!(is_active & EVENT_ALL))
4216 cpuctx->task_ctx = ctx;
4217 else
4218 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
4219 }
4220
4221 if (event_type & EVENT_GUEST) {
4222 /*
4223 * Schedule in the required exclude_guest events of PMU
4224 * with PERF_PMU_CAP_MEDIATED_VPMU.
4225 */
4226 is_active = event_type & EVENT_ALL;
4227
4228 /*
4229 * Update ctx time to set the new start time for
4230 * the exclude_guest events.
4231 */
4232 update_context_time(ctx);
4233 update_cgrp_time_from_cpuctx(cpuctx, false);
4234 barrier();
4235 } else {
4236 is_active ^= ctx->is_active; /* changed bits */
4237 }
4238
4239 /*
4240 * First go through the list and put on any pinned groups
4241 * in order to give them the best chance of going on.
4242 */
4243 if (is_active & EVENT_PINNED) {
4244 for_each_epc(pmu_ctx, ctx, pmu, event_type)
4245 __pmu_ctx_sched_in(pmu_ctx, EVENT_PINNED | (event_type & EVENT_GUEST));
4246 }
4247
4248 /* Then walk through the lower prio flexible groups */
4249 if (is_active & EVENT_FLEXIBLE) {
4250 for_each_epc(pmu_ctx, ctx, pmu, event_type)
4251 __pmu_ctx_sched_in(pmu_ctx, EVENT_FLEXIBLE | (event_type & EVENT_GUEST));
4252 }
4253 }
4254
perf_event_context_sched_in(struct task_struct * task)4255 static void perf_event_context_sched_in(struct task_struct *task)
4256 {
4257 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4258 struct perf_event_context *ctx;
4259
4260 rcu_read_lock();
4261 ctx = rcu_dereference(task->perf_event_ctxp);
4262 if (!ctx)
4263 goto rcu_unlock;
4264
4265 if (cpuctx->task_ctx == ctx) {
4266 perf_ctx_lock(cpuctx, ctx);
4267 perf_ctx_disable(ctx, 0);
4268
4269 perf_ctx_sched_task_cb(ctx, task, true);
4270
4271 perf_ctx_enable(ctx, 0);
4272 perf_ctx_unlock(cpuctx, ctx);
4273 goto rcu_unlock;
4274 }
4275
4276 perf_ctx_lock(cpuctx, ctx);
4277 /*
4278 * We must check ctx->nr_events while holding ctx->lock, such
4279 * that we serialize against perf_install_in_context().
4280 */
4281 if (!ctx->nr_events)
4282 goto unlock;
4283
4284 perf_ctx_disable(ctx, 0);
4285 /*
4286 * We want to keep the following priority order:
4287 * cpu pinned (that don't need to move), task pinned,
4288 * cpu flexible, task flexible.
4289 *
4290 * However, if task's ctx is not carrying any pinned
4291 * events, no need to flip the cpuctx's events around.
4292 */
4293 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree)) {
4294 perf_ctx_disable(&cpuctx->ctx, 0);
4295 ctx_sched_out(&cpuctx->ctx, NULL, EVENT_FLEXIBLE);
4296 }
4297
4298 perf_event_sched_in(cpuctx, ctx, NULL, 0);
4299
4300 perf_ctx_sched_task_cb(cpuctx->task_ctx, task, true);
4301
4302 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
4303 perf_ctx_enable(&cpuctx->ctx, 0);
4304
4305 perf_ctx_enable(ctx, 0);
4306
4307 unlock:
4308 perf_ctx_unlock(cpuctx, ctx);
4309 rcu_unlock:
4310 rcu_read_unlock();
4311 }
4312
4313 /*
4314 * Called from scheduler to add the events of the current task
4315 * with interrupts disabled.
4316 *
4317 * We restore the event value and then enable it.
4318 *
4319 * This does not protect us against NMI, but enable()
4320 * sets the enabled bit in the control field of event _before_
4321 * accessing the event control register. If a NMI hits, then it will
4322 * keep the event running.
4323 */
__perf_event_task_sched_in(struct task_struct * prev,struct task_struct * task)4324 void __perf_event_task_sched_in(struct task_struct *prev,
4325 struct task_struct *task)
4326 {
4327 perf_event_context_sched_in(task);
4328
4329 if (atomic_read(&nr_switch_events))
4330 perf_event_switch(task, prev, true);
4331
4332 if (__this_cpu_read(perf_sched_cb_usages))
4333 perf_pmu_sched_task(prev, task, true);
4334 }
4335
perf_calculate_period(struct perf_event * event,u64 nsec,u64 count)4336 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
4337 {
4338 u64 frequency = event->attr.sample_freq;
4339 u64 sec = NSEC_PER_SEC;
4340 u64 divisor, dividend;
4341
4342 int count_fls, nsec_fls, frequency_fls, sec_fls;
4343
4344 count_fls = fls64(count);
4345 nsec_fls = fls64(nsec);
4346 frequency_fls = fls64(frequency);
4347 sec_fls = 30;
4348
4349 /*
4350 * We got @count in @nsec, with a target of sample_freq HZ
4351 * the target period becomes:
4352 *
4353 * @count * 10^9
4354 * period = -------------------
4355 * @nsec * sample_freq
4356 *
4357 */
4358
4359 /*
4360 * Reduce accuracy by one bit such that @a and @b converge
4361 * to a similar magnitude.
4362 */
4363 #define REDUCE_FLS(a, b) \
4364 do { \
4365 if (a##_fls > b##_fls) { \
4366 a >>= 1; \
4367 a##_fls--; \
4368 } else { \
4369 b >>= 1; \
4370 b##_fls--; \
4371 } \
4372 } while (0)
4373
4374 /*
4375 * Reduce accuracy until either term fits in a u64, then proceed with
4376 * the other, so that finally we can do a u64/u64 division.
4377 */
4378 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
4379 REDUCE_FLS(nsec, frequency);
4380 REDUCE_FLS(sec, count);
4381 }
4382
4383 if (count_fls + sec_fls > 64) {
4384 divisor = nsec * frequency;
4385
4386 while (count_fls + sec_fls > 64) {
4387 REDUCE_FLS(count, sec);
4388 divisor >>= 1;
4389 }
4390
4391 dividend = count * sec;
4392 } else {
4393 dividend = count * sec;
4394
4395 while (nsec_fls + frequency_fls > 64) {
4396 REDUCE_FLS(nsec, frequency);
4397 dividend >>= 1;
4398 }
4399
4400 divisor = nsec * frequency;
4401 }
4402
4403 if (!divisor)
4404 return dividend;
4405
4406 return div64_u64(dividend, divisor);
4407 }
4408
4409 static DEFINE_PER_CPU(int, perf_throttled_count);
4410 static DEFINE_PER_CPU(u64, perf_throttled_seq);
4411
perf_adjust_period(struct perf_event * event,u64 nsec,u64 count,bool disable)4412 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
4413 {
4414 struct hw_perf_event *hwc = &event->hw;
4415 s64 period, sample_period;
4416 s64 delta;
4417
4418 period = perf_calculate_period(event, nsec, count);
4419
4420 delta = (s64)(period - hwc->sample_period);
4421 if (delta >= 0)
4422 delta += 7;
4423 else
4424 delta -= 7;
4425 delta /= 8; /* low pass filter */
4426
4427 sample_period = hwc->sample_period + delta;
4428
4429 if (!sample_period)
4430 sample_period = 1;
4431
4432 hwc->sample_period = sample_period;
4433
4434 if (local64_read(&hwc->period_left) > 8*sample_period) {
4435 if (disable)
4436 event->pmu->stop(event, PERF_EF_UPDATE);
4437
4438 local64_set(&hwc->period_left, 0);
4439
4440 if (disable)
4441 event->pmu->start(event, PERF_EF_RELOAD);
4442 }
4443 }
4444
perf_adjust_freq_unthr_events(struct list_head * event_list)4445 static void perf_adjust_freq_unthr_events(struct list_head *event_list)
4446 {
4447 struct perf_event *event;
4448 struct hw_perf_event *hwc;
4449 u64 now, period = TICK_NSEC;
4450 s64 delta;
4451
4452 list_for_each_entry(event, event_list, active_list) {
4453 if (event->state != PERF_EVENT_STATE_ACTIVE)
4454 continue;
4455
4456 // XXX use visit thingy to avoid the -1,cpu match
4457 if (!event_filter_match(event))
4458 continue;
4459
4460 hwc = &event->hw;
4461
4462 if (hwc->interrupts == MAX_INTERRUPTS)
4463 perf_event_unthrottle_group(event, is_event_in_freq_mode(event));
4464
4465 if (!is_event_in_freq_mode(event))
4466 continue;
4467
4468 /*
4469 * stop the event and update event->count
4470 */
4471 event->pmu->stop(event, PERF_EF_UPDATE);
4472
4473 now = local64_read(&event->count);
4474 delta = now - hwc->freq_count_stamp;
4475 hwc->freq_count_stamp = now;
4476
4477 /*
4478 * restart the event
4479 * reload only if value has changed
4480 * we have stopped the event so tell that
4481 * to perf_adjust_period() to avoid stopping it
4482 * twice.
4483 */
4484 if (delta > 0)
4485 perf_adjust_period(event, period, delta, false);
4486
4487 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
4488 }
4489 }
4490
4491 /*
4492 * combine freq adjustment with unthrottling to avoid two passes over the
4493 * events. At the same time, make sure, having freq events does not change
4494 * the rate of unthrottling as that would introduce bias.
4495 */
4496 static void
perf_adjust_freq_unthr_context(struct perf_event_context * ctx,bool unthrottle)4497 perf_adjust_freq_unthr_context(struct perf_event_context *ctx, bool unthrottle)
4498 {
4499 struct perf_event_pmu_context *pmu_ctx;
4500
4501 /*
4502 * only need to iterate over all events iff:
4503 * - context have events in frequency mode (needs freq adjust)
4504 * - there are events to unthrottle on this cpu
4505 */
4506 if (!(ctx->nr_freq || unthrottle))
4507 return;
4508
4509 raw_spin_lock(&ctx->lock);
4510
4511 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
4512 if (!(pmu_ctx->nr_freq || unthrottle))
4513 continue;
4514 if (!perf_pmu_ctx_is_active(pmu_ctx))
4515 continue;
4516 if (pmu_ctx->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT)
4517 continue;
4518
4519 perf_pmu_disable(pmu_ctx->pmu);
4520 perf_adjust_freq_unthr_events(&pmu_ctx->pinned_active);
4521 perf_adjust_freq_unthr_events(&pmu_ctx->flexible_active);
4522 perf_pmu_enable(pmu_ctx->pmu);
4523 }
4524
4525 raw_spin_unlock(&ctx->lock);
4526 }
4527
4528 /*
4529 * Move @event to the tail of the @ctx's elegible events.
4530 */
rotate_ctx(struct perf_event_context * ctx,struct perf_event * event)4531 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4532 {
4533 /*
4534 * Rotate the first entry last of non-pinned groups. Rotation might be
4535 * disabled by the inheritance code.
4536 */
4537 if (ctx->rotate_disable)
4538 return;
4539
4540 perf_event_groups_delete(&ctx->flexible_groups, event);
4541 perf_event_groups_insert(&ctx->flexible_groups, event);
4542 }
4543
4544 /* pick an event from the flexible_groups to rotate */
4545 static inline struct perf_event *
ctx_event_to_rotate(struct perf_event_pmu_context * pmu_ctx)4546 ctx_event_to_rotate(struct perf_event_pmu_context *pmu_ctx)
4547 {
4548 struct perf_event *event;
4549 struct rb_node *node;
4550 struct rb_root *tree;
4551 struct __group_key key = {
4552 .pmu = pmu_ctx->pmu,
4553 };
4554
4555 /* pick the first active flexible event */
4556 event = list_first_entry_or_null(&pmu_ctx->flexible_active,
4557 struct perf_event, active_list);
4558 if (event)
4559 goto out;
4560
4561 /* if no active flexible event, pick the first event */
4562 tree = &pmu_ctx->ctx->flexible_groups.tree;
4563
4564 if (!pmu_ctx->ctx->task) {
4565 key.cpu = smp_processor_id();
4566
4567 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4568 if (node)
4569 event = __node_2_pe(node);
4570 goto out;
4571 }
4572
4573 key.cpu = -1;
4574 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4575 if (node) {
4576 event = __node_2_pe(node);
4577 goto out;
4578 }
4579
4580 key.cpu = smp_processor_id();
4581 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4582 if (node)
4583 event = __node_2_pe(node);
4584
4585 out:
4586 /*
4587 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4588 * finds there are unschedulable events, it will set it again.
4589 */
4590 pmu_ctx->rotate_necessary = 0;
4591
4592 return event;
4593 }
4594
perf_rotate_context(struct perf_cpu_pmu_context * cpc)4595 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc)
4596 {
4597 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4598 struct perf_event_pmu_context *cpu_epc, *task_epc = NULL;
4599 struct perf_event *cpu_event = NULL, *task_event = NULL;
4600 int cpu_rotate, task_rotate;
4601 struct pmu *pmu;
4602
4603 /*
4604 * Since we run this from IRQ context, nobody can install new
4605 * events, thus the event count values are stable.
4606 */
4607
4608 cpu_epc = &cpc->epc;
4609 pmu = cpu_epc->pmu;
4610 task_epc = cpc->task_epc;
4611
4612 cpu_rotate = cpu_epc->rotate_necessary;
4613 task_rotate = task_epc ? task_epc->rotate_necessary : 0;
4614
4615 if (!(cpu_rotate || task_rotate))
4616 return false;
4617
4618 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4619 perf_pmu_disable(pmu);
4620
4621 if (task_rotate)
4622 task_event = ctx_event_to_rotate(task_epc);
4623 if (cpu_rotate)
4624 cpu_event = ctx_event_to_rotate(cpu_epc);
4625
4626 /*
4627 * As per the order given at ctx_resched() first 'pop' task flexible
4628 * and then, if needed CPU flexible.
4629 */
4630 if (task_event || (task_epc && cpu_event)) {
4631 update_context_time(task_epc->ctx);
4632 __pmu_ctx_sched_out(task_epc, EVENT_FLEXIBLE);
4633 }
4634
4635 if (cpu_event) {
4636 update_context_time(&cpuctx->ctx);
4637 __pmu_ctx_sched_out(cpu_epc, EVENT_FLEXIBLE);
4638 rotate_ctx(&cpuctx->ctx, cpu_event);
4639 __pmu_ctx_sched_in(cpu_epc, EVENT_FLEXIBLE);
4640 }
4641
4642 if (task_event)
4643 rotate_ctx(task_epc->ctx, task_event);
4644
4645 if (task_event || (task_epc && cpu_event))
4646 __pmu_ctx_sched_in(task_epc, EVENT_FLEXIBLE);
4647
4648 perf_pmu_enable(pmu);
4649 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4650
4651 return true;
4652 }
4653
perf_event_task_tick(void)4654 void perf_event_task_tick(void)
4655 {
4656 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4657 struct perf_event_context *ctx;
4658 int throttled;
4659
4660 lockdep_assert_irqs_disabled();
4661
4662 __this_cpu_inc(perf_throttled_seq);
4663 throttled = __this_cpu_xchg(perf_throttled_count, 0);
4664 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4665
4666 perf_adjust_freq_unthr_context(&cpuctx->ctx, !!throttled);
4667
4668 rcu_read_lock();
4669 ctx = rcu_dereference(current->perf_event_ctxp);
4670 if (ctx)
4671 perf_adjust_freq_unthr_context(ctx, !!throttled);
4672 rcu_read_unlock();
4673 }
4674
event_enable_on_exec(struct perf_event * event,struct perf_event_context * ctx)4675 static int event_enable_on_exec(struct perf_event *event,
4676 struct perf_event_context *ctx)
4677 {
4678 if (!event->attr.enable_on_exec)
4679 return 0;
4680
4681 event->attr.enable_on_exec = 0;
4682 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4683 return 0;
4684
4685 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4686
4687 return 1;
4688 }
4689
4690 /*
4691 * Enable all of a task's events that have been marked enable-on-exec.
4692 * This expects task == current.
4693 */
perf_event_enable_on_exec(struct perf_event_context * ctx)4694 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
4695 {
4696 struct perf_event_context *clone_ctx = NULL;
4697 enum event_type_t event_type = 0;
4698 struct perf_cpu_context *cpuctx;
4699 struct perf_event *event;
4700 unsigned long flags;
4701 int enabled = 0;
4702
4703 local_irq_save(flags);
4704 if (WARN_ON_ONCE(current->perf_event_ctxp != ctx))
4705 goto out;
4706
4707 if (!ctx->nr_events)
4708 goto out;
4709
4710 cpuctx = this_cpu_ptr(&perf_cpu_context);
4711 perf_ctx_lock(cpuctx, ctx);
4712 ctx_time_freeze(cpuctx, ctx);
4713
4714 list_for_each_entry(event, &ctx->event_list, event_entry) {
4715 enabled |= event_enable_on_exec(event, ctx);
4716 event_type |= get_event_type(event);
4717 }
4718
4719 /*
4720 * Unclone and reschedule this context if we enabled any event.
4721 */
4722 if (enabled) {
4723 clone_ctx = unclone_ctx(ctx);
4724 ctx_resched(cpuctx, ctx, NULL, event_type);
4725 }
4726 perf_ctx_unlock(cpuctx, ctx);
4727
4728 out:
4729 local_irq_restore(flags);
4730
4731 if (clone_ctx)
4732 put_ctx(clone_ctx);
4733 }
4734
4735 static void perf_remove_from_owner(struct perf_event *event);
4736 static void perf_event_exit_event(struct perf_event *event,
4737 struct perf_event_context *ctx,
4738 struct task_struct *task,
4739 unsigned long detach_flags);
4740
4741 /*
4742 * Removes all events from the current task that have been marked
4743 * remove-on-exec, and feeds their values back to parent events.
4744 */
perf_event_remove_on_exec(struct perf_event_context * ctx)4745 static void perf_event_remove_on_exec(struct perf_event_context *ctx)
4746 {
4747 struct perf_event_context *clone_ctx = NULL;
4748 struct perf_event *event, *next;
4749 unsigned long flags;
4750 bool modified = false;
4751
4752 mutex_lock(&ctx->mutex);
4753
4754 if (WARN_ON_ONCE(ctx->task != current))
4755 goto unlock;
4756
4757 list_for_each_entry_safe(event, next, &ctx->event_list, event_entry) {
4758 if (!event->attr.remove_on_exec)
4759 continue;
4760
4761 if (!is_kernel_event(event))
4762 perf_remove_from_owner(event);
4763
4764 modified = true;
4765
4766 perf_event_exit_event(event, ctx, ctx->task, DETACH_GROUP);
4767 }
4768
4769 raw_spin_lock_irqsave(&ctx->lock, flags);
4770 if (modified)
4771 clone_ctx = unclone_ctx(ctx);
4772 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4773
4774 unlock:
4775 mutex_unlock(&ctx->mutex);
4776
4777 if (clone_ctx)
4778 put_ctx(clone_ctx);
4779 }
4780
4781 struct perf_read_data {
4782 struct perf_event *event;
4783 bool group;
4784 int ret;
4785 };
4786
4787 static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu);
4788
__perf_event_read_cpu(struct perf_event * event,int event_cpu)4789 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4790 {
4791 int local_cpu = smp_processor_id();
4792 u16 local_pkg, event_pkg;
4793
4794 if ((unsigned)event_cpu >= nr_cpu_ids)
4795 return event_cpu;
4796
4797 if (event->group_caps & PERF_EV_CAP_READ_SCOPE) {
4798 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(event->pmu->scope, event_cpu);
4799
4800 if (cpumask && cpumask_test_cpu(local_cpu, cpumask))
4801 return local_cpu;
4802 }
4803
4804 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4805 event_pkg = topology_physical_package_id(event_cpu);
4806 local_pkg = topology_physical_package_id(local_cpu);
4807
4808 if (event_pkg == local_pkg)
4809 return local_cpu;
4810 }
4811
4812 return event_cpu;
4813 }
4814
4815 /*
4816 * Cross CPU call to read the hardware event
4817 */
__perf_event_read(void * info)4818 static void __perf_event_read(void *info)
4819 {
4820 struct perf_read_data *data = info;
4821 struct perf_event *sub, *event = data->event;
4822 struct perf_event_context *ctx = event->ctx;
4823 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4824 struct pmu *pmu;
4825
4826 /*
4827 * If this is a task context, we need to check whether it is
4828 * the current task context of this cpu. If not it has been
4829 * scheduled out before the smp call arrived. In that case
4830 * event->count would have been updated to a recent sample
4831 * when the event was scheduled out.
4832 */
4833 if (ctx->task && cpuctx->task_ctx != ctx)
4834 return;
4835
4836 guard(raw_spinlock)(&ctx->lock);
4837 ctx_time_update_event(ctx, event);
4838
4839 perf_event_update_time(event);
4840 if (data->group)
4841 perf_event_update_sibling_time(event);
4842
4843 if (event->state != PERF_EVENT_STATE_ACTIVE)
4844 return;
4845
4846 if (!data->group) {
4847 perf_pmu_read(event);
4848 data->ret = 0;
4849 return;
4850 }
4851
4852 pmu = event->pmu_ctx->pmu;
4853 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4854
4855 perf_pmu_read(event);
4856 for_each_sibling_event(sub, event)
4857 perf_pmu_read(sub);
4858
4859 data->ret = pmu->commit_txn(pmu);
4860 }
4861
perf_event_count(struct perf_event * event,bool self)4862 static inline u64 perf_event_count(struct perf_event *event, bool self)
4863 {
4864 if (self)
4865 return local64_read(&event->count);
4866
4867 return local64_read(&event->count) + atomic64_read(&event->child_count);
4868 }
4869
calc_timer_values(struct perf_event * event,u64 * now,u64 * enabled,u64 * running)4870 static void calc_timer_values(struct perf_event *event,
4871 u64 *now,
4872 u64 *enabled,
4873 u64 *running)
4874 {
4875 u64 ctx_time;
4876
4877 *now = perf_clock();
4878 ctx_time = perf_event_time_now(event, *now);
4879 __perf_update_times(event, ctx_time, enabled, running);
4880 }
4881
4882 /*
4883 * NMI-safe method to read a local event, that is an event that
4884 * is:
4885 * - either for the current task, or for this CPU
4886 * - does not have inherit set, for inherited task events
4887 * will not be local and we cannot read them atomically
4888 * - must not have a pmu::count method
4889 */
perf_event_read_local(struct perf_event * event,u64 * value,u64 * enabled,u64 * running)4890 int perf_event_read_local(struct perf_event *event, u64 *value,
4891 u64 *enabled, u64 *running)
4892 {
4893 unsigned long flags;
4894 int event_oncpu;
4895 int event_cpu;
4896 int ret = 0;
4897
4898 /*
4899 * Disabling interrupts avoids all counter scheduling (context
4900 * switches, timer based rotation and IPIs).
4901 */
4902 local_irq_save(flags);
4903
4904 /*
4905 * It must not be an event with inherit set, we cannot read
4906 * all child counters from atomic context.
4907 */
4908 if (event->attr.inherit) {
4909 ret = -EOPNOTSUPP;
4910 goto out;
4911 }
4912
4913 /* If this is a per-task event, it must be for current */
4914 if ((event->attach_state & PERF_ATTACH_TASK) &&
4915 event->hw.target != current) {
4916 ret = -EINVAL;
4917 goto out;
4918 }
4919
4920 /*
4921 * Get the event CPU numbers, and adjust them to local if the event is
4922 * a per-package event that can be read locally
4923 */
4924 event_oncpu = __perf_event_read_cpu(event, event->oncpu);
4925 event_cpu = __perf_event_read_cpu(event, event->cpu);
4926
4927 /* If this is a per-CPU event, it must be for this CPU */
4928 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4929 event_cpu != smp_processor_id()) {
4930 ret = -EINVAL;
4931 goto out;
4932 }
4933
4934 /* If this is a pinned event it must be running on this CPU */
4935 if (event->attr.pinned && event_oncpu != smp_processor_id()) {
4936 ret = -EBUSY;
4937 goto out;
4938 }
4939
4940 /*
4941 * If the event is currently on this CPU, its either a per-task event,
4942 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4943 * oncpu == -1).
4944 */
4945 if (event_oncpu == smp_processor_id())
4946 event->pmu->read(event);
4947
4948 *value = local64_read(&event->count);
4949 if (enabled || running) {
4950 u64 __enabled, __running, __now;
4951
4952 calc_timer_values(event, &__now, &__enabled, &__running);
4953 if (enabled)
4954 *enabled = __enabled;
4955 if (running)
4956 *running = __running;
4957 }
4958 out:
4959 local_irq_restore(flags);
4960
4961 return ret;
4962 }
4963
perf_event_read(struct perf_event * event,bool group)4964 static int perf_event_read(struct perf_event *event, bool group)
4965 {
4966 enum perf_event_state state = READ_ONCE(event->state);
4967 int event_cpu, ret = 0;
4968
4969 /*
4970 * If event is enabled and currently active on a CPU, update the
4971 * value in the event structure:
4972 */
4973 again:
4974 if (state == PERF_EVENT_STATE_ACTIVE) {
4975 struct perf_read_data data;
4976
4977 /*
4978 * Orders the ->state and ->oncpu loads such that if we see
4979 * ACTIVE we must also see the right ->oncpu.
4980 *
4981 * Matches the smp_wmb() from event_sched_in().
4982 */
4983 smp_rmb();
4984
4985 event_cpu = READ_ONCE(event->oncpu);
4986 if ((unsigned)event_cpu >= nr_cpu_ids)
4987 return 0;
4988
4989 data = (struct perf_read_data){
4990 .event = event,
4991 .group = group,
4992 .ret = 0,
4993 };
4994
4995 preempt_disable();
4996 event_cpu = __perf_event_read_cpu(event, event_cpu);
4997
4998 /*
4999 * Purposely ignore the smp_call_function_single() return
5000 * value.
5001 *
5002 * If event_cpu isn't a valid CPU it means the event got
5003 * scheduled out and that will have updated the event count.
5004 *
5005 * Therefore, either way, we'll have an up-to-date event count
5006 * after this.
5007 */
5008 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
5009 preempt_enable();
5010 ret = data.ret;
5011
5012 } else if (state == PERF_EVENT_STATE_INACTIVE) {
5013 struct perf_event_context *ctx = event->ctx;
5014 unsigned long flags;
5015
5016 raw_spin_lock_irqsave(&ctx->lock, flags);
5017 state = event->state;
5018 if (state != PERF_EVENT_STATE_INACTIVE) {
5019 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5020 goto again;
5021 }
5022
5023 /*
5024 * May read while context is not active (e.g., thread is
5025 * blocked), in that case we cannot update context time
5026 */
5027 ctx_time_update_event(ctx, event);
5028
5029 perf_event_update_time(event);
5030 if (group)
5031 perf_event_update_sibling_time(event);
5032 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5033 }
5034
5035 return ret;
5036 }
5037
5038 /*
5039 * Initialize the perf_event context in a task_struct:
5040 */
__perf_event_init_context(struct perf_event_context * ctx)5041 static void __perf_event_init_context(struct perf_event_context *ctx)
5042 {
5043 raw_spin_lock_init(&ctx->lock);
5044 mutex_init(&ctx->mutex);
5045 INIT_LIST_HEAD(&ctx->pmu_ctx_list);
5046 perf_event_groups_init(&ctx->pinned_groups);
5047 perf_event_groups_init(&ctx->flexible_groups);
5048 INIT_LIST_HEAD(&ctx->event_list);
5049 refcount_set(&ctx->refcount, 1);
5050 }
5051
5052 static void
__perf_init_event_pmu_context(struct perf_event_pmu_context * epc,struct pmu * pmu)5053 __perf_init_event_pmu_context(struct perf_event_pmu_context *epc, struct pmu *pmu)
5054 {
5055 epc->pmu = pmu;
5056 INIT_LIST_HEAD(&epc->pmu_ctx_entry);
5057 INIT_LIST_HEAD(&epc->pinned_active);
5058 INIT_LIST_HEAD(&epc->flexible_active);
5059 atomic_set(&epc->refcount, 1);
5060 }
5061
5062 static struct perf_event_context *
alloc_perf_context(struct task_struct * task)5063 alloc_perf_context(struct task_struct *task)
5064 {
5065 struct perf_event_context *ctx;
5066
5067 ctx = kzalloc_obj(struct perf_event_context);
5068 if (!ctx)
5069 return NULL;
5070
5071 __perf_event_init_context(ctx);
5072 if (task)
5073 ctx->task = get_task_struct(task);
5074
5075 return ctx;
5076 }
5077
5078 static struct task_struct *
find_lively_task_by_vpid(pid_t vpid)5079 find_lively_task_by_vpid(pid_t vpid)
5080 {
5081 struct task_struct *task;
5082
5083 rcu_read_lock();
5084 if (!vpid)
5085 task = current;
5086 else
5087 task = find_task_by_vpid(vpid);
5088 if (task)
5089 get_task_struct(task);
5090 rcu_read_unlock();
5091
5092 if (!task)
5093 return ERR_PTR(-ESRCH);
5094
5095 return task;
5096 }
5097
5098 /*
5099 * Returns a matching context with refcount and pincount.
5100 */
5101 static struct perf_event_context *
find_get_context(struct task_struct * task,struct perf_event * event)5102 find_get_context(struct task_struct *task, struct perf_event *event)
5103 {
5104 struct perf_event_context *ctx, *clone_ctx = NULL;
5105 struct perf_cpu_context *cpuctx;
5106 unsigned long flags;
5107 int err;
5108
5109 if (!task) {
5110 /* Must be root to operate on a CPU event: */
5111 err = perf_allow_cpu();
5112 if (err)
5113 return ERR_PTR(err);
5114
5115 cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
5116 ctx = &cpuctx->ctx;
5117 get_ctx(ctx);
5118 raw_spin_lock_irqsave(&ctx->lock, flags);
5119 ++ctx->pin_count;
5120 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5121
5122 return ctx;
5123 }
5124
5125 err = -EINVAL;
5126 retry:
5127 ctx = perf_lock_task_context(task, &flags);
5128 if (ctx) {
5129 clone_ctx = unclone_ctx(ctx);
5130 ++ctx->pin_count;
5131
5132 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5133
5134 if (clone_ctx)
5135 put_ctx(clone_ctx);
5136 } else {
5137 ctx = alloc_perf_context(task);
5138 err = -ENOMEM;
5139 if (!ctx)
5140 goto errout;
5141
5142 err = 0;
5143 mutex_lock(&task->perf_event_mutex);
5144 /*
5145 * If it has already passed perf_event_exit_task().
5146 * we must see PF_EXITING, it takes this mutex too.
5147 */
5148 if (task->flags & PF_EXITING)
5149 err = -ESRCH;
5150 else if (task->perf_event_ctxp)
5151 err = -EAGAIN;
5152 else {
5153 get_ctx(ctx);
5154 ++ctx->pin_count;
5155 rcu_assign_pointer(task->perf_event_ctxp, ctx);
5156 }
5157 mutex_unlock(&task->perf_event_mutex);
5158
5159 if (unlikely(err)) {
5160 put_ctx(ctx);
5161
5162 if (err == -EAGAIN)
5163 goto retry;
5164 goto errout;
5165 }
5166 }
5167
5168 return ctx;
5169
5170 errout:
5171 return ERR_PTR(err);
5172 }
5173
5174 static struct perf_event_pmu_context *
find_get_pmu_context(struct pmu * pmu,struct perf_event_context * ctx,struct perf_event * event)5175 find_get_pmu_context(struct pmu *pmu, struct perf_event_context *ctx,
5176 struct perf_event *event)
5177 {
5178 struct perf_event_pmu_context *new = NULL, *pos = NULL, *epc;
5179
5180 if (!ctx->task) {
5181 /*
5182 * perf_pmu_migrate_context() / __perf_pmu_install_event()
5183 * relies on the fact that find_get_pmu_context() cannot fail
5184 * for CPU contexts.
5185 */
5186 struct perf_cpu_pmu_context *cpc;
5187
5188 cpc = *per_cpu_ptr(pmu->cpu_pmu_context, event->cpu);
5189 epc = &cpc->epc;
5190 raw_spin_lock_irq(&ctx->lock);
5191 if (!epc->ctx) {
5192 /*
5193 * One extra reference for the pmu; see perf_pmu_free().
5194 */
5195 atomic_set(&epc->refcount, 2);
5196 epc->embedded = 1;
5197 list_add(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
5198 epc->ctx = ctx;
5199 } else {
5200 WARN_ON_ONCE(epc->ctx != ctx);
5201 atomic_inc(&epc->refcount);
5202 }
5203 raw_spin_unlock_irq(&ctx->lock);
5204 return epc;
5205 }
5206
5207 new = kzalloc_obj(*epc);
5208 if (!new)
5209 return ERR_PTR(-ENOMEM);
5210
5211 __perf_init_event_pmu_context(new, pmu);
5212
5213 /*
5214 * XXX
5215 *
5216 * lockdep_assert_held(&ctx->mutex);
5217 *
5218 * can't because perf_event_init_task() doesn't actually hold the
5219 * child_ctx->mutex.
5220 */
5221
5222 raw_spin_lock_irq(&ctx->lock);
5223 list_for_each_entry(epc, &ctx->pmu_ctx_list, pmu_ctx_entry) {
5224 if (epc->pmu == pmu) {
5225 WARN_ON_ONCE(epc->ctx != ctx);
5226 atomic_inc(&epc->refcount);
5227 goto found_epc;
5228 }
5229 /* Make sure the pmu_ctx_list is sorted by PMU type: */
5230 if (!pos && epc->pmu->type > pmu->type)
5231 pos = epc;
5232 }
5233
5234 epc = new;
5235 new = NULL;
5236
5237 if (!pos)
5238 list_add_tail(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
5239 else
5240 list_add(&epc->pmu_ctx_entry, pos->pmu_ctx_entry.prev);
5241
5242 epc->ctx = ctx;
5243
5244 found_epc:
5245 raw_spin_unlock_irq(&ctx->lock);
5246 kfree(new);
5247
5248 return epc;
5249 }
5250
get_pmu_ctx(struct perf_event_pmu_context * epc)5251 static void get_pmu_ctx(struct perf_event_pmu_context *epc)
5252 {
5253 WARN_ON_ONCE(!atomic_inc_not_zero(&epc->refcount));
5254 }
5255
free_cpc_rcu(struct rcu_head * head)5256 static void free_cpc_rcu(struct rcu_head *head)
5257 {
5258 struct perf_cpu_pmu_context *cpc =
5259 container_of(head, typeof(*cpc), epc.rcu_head);
5260
5261 kfree(cpc);
5262 }
5263
free_epc_rcu(struct rcu_head * head)5264 static void free_epc_rcu(struct rcu_head *head)
5265 {
5266 struct perf_event_pmu_context *epc = container_of(head, typeof(*epc), rcu_head);
5267
5268 kfree(epc);
5269 }
5270
put_pmu_ctx(struct perf_event_pmu_context * epc)5271 static void put_pmu_ctx(struct perf_event_pmu_context *epc)
5272 {
5273 struct perf_event_context *ctx = epc->ctx;
5274 unsigned long flags;
5275
5276 /*
5277 * XXX
5278 *
5279 * lockdep_assert_held(&ctx->mutex);
5280 *
5281 * can't because of the call-site in _free_event()/put_event()
5282 * which isn't always called under ctx->mutex.
5283 */
5284 if (!atomic_dec_and_raw_lock_irqsave(&epc->refcount, &ctx->lock, flags))
5285 return;
5286
5287 WARN_ON_ONCE(list_empty(&epc->pmu_ctx_entry));
5288
5289 list_del_init(&epc->pmu_ctx_entry);
5290 epc->ctx = NULL;
5291
5292 WARN_ON_ONCE(!list_empty(&epc->pinned_active));
5293 WARN_ON_ONCE(!list_empty(&epc->flexible_active));
5294
5295 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5296
5297 if (epc->embedded) {
5298 call_rcu(&epc->rcu_head, free_cpc_rcu);
5299 return;
5300 }
5301
5302 call_rcu(&epc->rcu_head, free_epc_rcu);
5303 }
5304
5305 static void perf_event_free_filter(struct perf_event *event);
5306
free_event_rcu(struct rcu_head * head)5307 static void free_event_rcu(struct rcu_head *head)
5308 {
5309 struct perf_event *event = container_of(head, typeof(*event), rcu_head);
5310
5311 if (event->ns)
5312 put_pid_ns(event->ns);
5313 perf_event_free_filter(event);
5314 kfree(event->addr_filter_ranges);
5315 kmem_cache_free(perf_event_cache, event);
5316 }
5317
5318 static void ring_buffer_attach(struct perf_event *event,
5319 struct perf_buffer *rb);
5320
detach_sb_event(struct perf_event * event)5321 static void detach_sb_event(struct perf_event *event)
5322 {
5323 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
5324
5325 raw_spin_lock(&pel->lock);
5326 list_del_rcu(&event->sb_list);
5327 raw_spin_unlock(&pel->lock);
5328 }
5329
is_sb_event(struct perf_event * event)5330 static bool is_sb_event(struct perf_event *event)
5331 {
5332 struct perf_event_attr *attr = &event->attr;
5333
5334 if (event->parent)
5335 return false;
5336
5337 if (event->attach_state & PERF_ATTACH_TASK)
5338 return false;
5339
5340 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
5341 attr->comm || attr->comm_exec ||
5342 attr->task || attr->ksymbol ||
5343 attr->context_switch || attr->text_poke ||
5344 attr->bpf_event)
5345 return true;
5346
5347 return false;
5348 }
5349
unaccount_pmu_sb_event(struct perf_event * event)5350 static void unaccount_pmu_sb_event(struct perf_event *event)
5351 {
5352 if (is_sb_event(event))
5353 detach_sb_event(event);
5354 }
5355
5356 #ifdef CONFIG_NO_HZ_FULL
5357 static DEFINE_SPINLOCK(nr_freq_lock);
5358 #endif
5359
unaccount_freq_event_nohz(void)5360 static void unaccount_freq_event_nohz(void)
5361 {
5362 #ifdef CONFIG_NO_HZ_FULL
5363 spin_lock(&nr_freq_lock);
5364 if (atomic_dec_and_test(&nr_freq_events))
5365 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
5366 spin_unlock(&nr_freq_lock);
5367 #endif
5368 }
5369
unaccount_freq_event(void)5370 static void unaccount_freq_event(void)
5371 {
5372 if (tick_nohz_full_enabled())
5373 unaccount_freq_event_nohz();
5374 else
5375 atomic_dec(&nr_freq_events);
5376 }
5377
5378
5379 static struct perf_ctx_data *
alloc_perf_ctx_data(struct kmem_cache * ctx_cache,bool global,gfp_t gfp_flags)5380 alloc_perf_ctx_data(struct kmem_cache *ctx_cache, bool global, gfp_t gfp_flags)
5381 {
5382 struct perf_ctx_data *cd;
5383
5384 cd = kzalloc_obj(*cd, gfp_flags);
5385 if (!cd)
5386 return NULL;
5387
5388 cd->data = kmem_cache_zalloc(ctx_cache, gfp_flags);
5389 if (!cd->data) {
5390 kfree(cd);
5391 return NULL;
5392 }
5393
5394 cd->global = global;
5395 cd->ctx_cache = ctx_cache;
5396 refcount_set(&cd->refcount, 1);
5397
5398 return cd;
5399 }
5400
free_perf_ctx_data(struct perf_ctx_data * cd)5401 static void free_perf_ctx_data(struct perf_ctx_data *cd)
5402 {
5403 kmem_cache_free(cd->ctx_cache, cd->data);
5404 kfree(cd);
5405 }
5406
__free_perf_ctx_data_rcu(struct rcu_head * rcu_head)5407 static void __free_perf_ctx_data_rcu(struct rcu_head *rcu_head)
5408 {
5409 struct perf_ctx_data *cd;
5410
5411 cd = container_of(rcu_head, struct perf_ctx_data, rcu_head);
5412 free_perf_ctx_data(cd);
5413 }
5414
perf_free_ctx_data_rcu(struct perf_ctx_data * cd)5415 static inline void perf_free_ctx_data_rcu(struct perf_ctx_data *cd)
5416 {
5417 call_rcu(&cd->rcu_head, __free_perf_ctx_data_rcu);
5418 }
5419
5420 static int
attach_task_ctx_data(struct task_struct * task,struct kmem_cache * ctx_cache,bool global,gfp_t gfp_flags)5421 attach_task_ctx_data(struct task_struct *task, struct kmem_cache *ctx_cache,
5422 bool global, gfp_t gfp_flags)
5423 {
5424 struct perf_ctx_data *cd, *old = NULL;
5425
5426 cd = alloc_perf_ctx_data(ctx_cache, global, gfp_flags);
5427 if (!cd)
5428 return -ENOMEM;
5429
5430 for (;;) {
5431 if (try_cmpxchg(&task->perf_ctx_data, &old, cd)) {
5432 if (old)
5433 perf_free_ctx_data_rcu(old);
5434 /*
5435 * Above try_cmpxchg() pairs with try_cmpxchg() from
5436 * detach_task_ctx_data() such that
5437 * if we race with perf_event_exit_task(), we must
5438 * observe PF_EXITING.
5439 */
5440 if (task->flags & PF_EXITING) {
5441 /* detach_task_ctx_data() may free it already */
5442 if (try_cmpxchg(&task->perf_ctx_data, &cd, NULL))
5443 perf_free_ctx_data_rcu(cd);
5444 }
5445 return 0;
5446 }
5447
5448 if (!old) {
5449 /*
5450 * After seeing a dead @old, we raced with
5451 * removal and lost, try again to install @cd.
5452 */
5453 continue;
5454 }
5455
5456 if (refcount_inc_not_zero(&old->refcount)) {
5457 free_perf_ctx_data(cd); /* unused */
5458 return 0;
5459 }
5460
5461 /*
5462 * @old is a dead object, refcount==0 is stable, try and
5463 * replace it with @cd.
5464 */
5465 }
5466 return 0;
5467 }
5468
5469 static void __detach_global_ctx_data(void);
5470 DEFINE_STATIC_PERCPU_RWSEM(global_ctx_data_rwsem);
5471 static refcount_t global_ctx_data_ref;
5472
5473 static int
attach_global_ctx_data(struct kmem_cache * ctx_cache)5474 attach_global_ctx_data(struct kmem_cache *ctx_cache)
5475 {
5476 struct task_struct *g, *p;
5477 struct perf_ctx_data *cd;
5478 int ret;
5479
5480 if (refcount_inc_not_zero(&global_ctx_data_ref))
5481 return 0;
5482
5483 guard(percpu_write)(&global_ctx_data_rwsem);
5484 if (refcount_inc_not_zero(&global_ctx_data_ref))
5485 return 0;
5486 again:
5487 /* Allocate everything */
5488 scoped_guard (rcu) {
5489 for_each_process_thread(g, p) {
5490 if (p->flags & PF_EXITING)
5491 continue;
5492 cd = rcu_dereference(p->perf_ctx_data);
5493 if (cd && !cd->global) {
5494 cd->global = 1;
5495 if (!refcount_inc_not_zero(&cd->refcount))
5496 cd = NULL;
5497 }
5498 if (!cd) {
5499 /*
5500 * Try to allocate context quickly before
5501 * traversing the whole thread list again.
5502 */
5503 if (!attach_task_ctx_data(p, ctx_cache, true, GFP_NOWAIT))
5504 continue;
5505 get_task_struct(p);
5506 goto alloc;
5507 }
5508 }
5509 }
5510
5511 refcount_set(&global_ctx_data_ref, 1);
5512
5513 return 0;
5514 alloc:
5515 ret = attach_task_ctx_data(p, ctx_cache, true, GFP_KERNEL);
5516 put_task_struct(p);
5517 if (ret) {
5518 __detach_global_ctx_data();
5519 return ret;
5520 }
5521 goto again;
5522 }
5523
5524 static int
attach_perf_ctx_data(struct perf_event * event)5525 attach_perf_ctx_data(struct perf_event *event)
5526 {
5527 struct task_struct *task = event->hw.target;
5528 struct kmem_cache *ctx_cache = event->pmu->task_ctx_cache;
5529 int ret;
5530
5531 if (!ctx_cache)
5532 return -ENOMEM;
5533
5534 if (task)
5535 return attach_task_ctx_data(task, ctx_cache, false, GFP_KERNEL);
5536
5537 ret = attach_global_ctx_data(ctx_cache);
5538 if (ret)
5539 return ret;
5540
5541 event->attach_state |= PERF_ATTACH_GLOBAL_DATA;
5542 return 0;
5543 }
5544
5545 static void
detach_task_ctx_data(struct task_struct * p)5546 detach_task_ctx_data(struct task_struct *p)
5547 {
5548 struct perf_ctx_data *cd;
5549
5550 scoped_guard (rcu) {
5551 cd = rcu_dereference(p->perf_ctx_data);
5552 if (!cd || !refcount_dec_and_test(&cd->refcount))
5553 return;
5554 }
5555
5556 /*
5557 * The old ctx_data may be lost because of the race.
5558 * Nothing is required to do for the case.
5559 * See attach_task_ctx_data().
5560 */
5561 if (try_cmpxchg((struct perf_ctx_data **)&p->perf_ctx_data, &cd, NULL))
5562 perf_free_ctx_data_rcu(cd);
5563 }
5564
__detach_global_ctx_data(void)5565 static void __detach_global_ctx_data(void)
5566 {
5567 struct task_struct *g, *p;
5568 struct perf_ctx_data *cd;
5569
5570 scoped_guard (rcu) {
5571 for_each_process_thread(g, p) {
5572 cd = rcu_dereference(p->perf_ctx_data);
5573 if (cd && cd->global) {
5574 cd->global = 0;
5575 detach_task_ctx_data(p);
5576 }
5577 }
5578 }
5579 }
5580
detach_global_ctx_data(void)5581 static void detach_global_ctx_data(void)
5582 {
5583 if (refcount_dec_not_one(&global_ctx_data_ref))
5584 return;
5585
5586 guard(percpu_write)(&global_ctx_data_rwsem);
5587 if (!refcount_dec_and_test(&global_ctx_data_ref))
5588 return;
5589
5590 /* remove everything */
5591 __detach_global_ctx_data();
5592 }
5593
detach_perf_ctx_data(struct perf_event * event)5594 static void detach_perf_ctx_data(struct perf_event *event)
5595 {
5596 struct task_struct *task = event->hw.target;
5597
5598 event->attach_state &= ~PERF_ATTACH_TASK_DATA;
5599
5600 if (task)
5601 return detach_task_ctx_data(task);
5602
5603 if (event->attach_state & PERF_ATTACH_GLOBAL_DATA) {
5604 detach_global_ctx_data();
5605 event->attach_state &= ~PERF_ATTACH_GLOBAL_DATA;
5606 }
5607 }
5608
unaccount_event(struct perf_event * event)5609 static void unaccount_event(struct perf_event *event)
5610 {
5611 bool dec = false;
5612
5613 if (event->parent)
5614 return;
5615
5616 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
5617 dec = true;
5618 if (event->attr.mmap || event->attr.mmap_data)
5619 atomic_dec(&nr_mmap_events);
5620 if (event->attr.build_id)
5621 atomic_dec(&nr_build_id_events);
5622 if (event->attr.comm)
5623 atomic_dec(&nr_comm_events);
5624 if (event->attr.namespaces)
5625 atomic_dec(&nr_namespaces_events);
5626 if (event->attr.cgroup)
5627 atomic_dec(&nr_cgroup_events);
5628 if (event->attr.task)
5629 atomic_dec(&nr_task_events);
5630 if (event->attr.freq)
5631 unaccount_freq_event();
5632 if (event->attr.context_switch) {
5633 dec = true;
5634 atomic_dec(&nr_switch_events);
5635 }
5636 if (is_cgroup_event(event))
5637 dec = true;
5638 if (has_branch_stack(event))
5639 dec = true;
5640 if (event->attr.ksymbol)
5641 atomic_dec(&nr_ksymbol_events);
5642 if (event->attr.bpf_event)
5643 atomic_dec(&nr_bpf_events);
5644 if (event->attr.text_poke)
5645 atomic_dec(&nr_text_poke_events);
5646
5647 if (dec) {
5648 if (!atomic_add_unless(&perf_sched_count, -1, 1))
5649 schedule_delayed_work(&perf_sched_work, HZ);
5650 }
5651
5652 unaccount_pmu_sb_event(event);
5653 }
5654
perf_sched_delayed(struct work_struct * work)5655 static void perf_sched_delayed(struct work_struct *work)
5656 {
5657 mutex_lock(&perf_sched_mutex);
5658 if (atomic_dec_and_test(&perf_sched_count))
5659 static_branch_disable(&perf_sched_events);
5660 mutex_unlock(&perf_sched_mutex);
5661 }
5662
5663 /*
5664 * The following implement mutual exclusion of events on "exclusive" pmus
5665 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
5666 * at a time, so we disallow creating events that might conflict, namely:
5667 *
5668 * 1) cpu-wide events in the presence of per-task events,
5669 * 2) per-task events in the presence of cpu-wide events,
5670 * 3) two matching events on the same perf_event_context.
5671 *
5672 * The former two cases are handled in the allocation path (perf_event_alloc(),
5673 * _free_event()), the latter -- before the first perf_install_in_context().
5674 */
exclusive_event_init(struct perf_event * event)5675 static int exclusive_event_init(struct perf_event *event)
5676 {
5677 struct pmu *pmu = event->pmu;
5678
5679 if (!is_exclusive_pmu(pmu))
5680 return 0;
5681
5682 /*
5683 * Prevent co-existence of per-task and cpu-wide events on the
5684 * same exclusive pmu.
5685 *
5686 * Negative pmu::exclusive_cnt means there are cpu-wide
5687 * events on this "exclusive" pmu, positive means there are
5688 * per-task events.
5689 *
5690 * Since this is called in perf_event_alloc() path, event::ctx
5691 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
5692 * to mean "per-task event", because unlike other attach states it
5693 * never gets cleared.
5694 */
5695 if (event->attach_state & PERF_ATTACH_TASK) {
5696 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
5697 return -EBUSY;
5698 } else {
5699 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
5700 return -EBUSY;
5701 }
5702
5703 event->attach_state |= PERF_ATTACH_EXCLUSIVE;
5704
5705 return 0;
5706 }
5707
exclusive_event_destroy(struct perf_event * event)5708 static void exclusive_event_destroy(struct perf_event *event)
5709 {
5710 struct pmu *pmu = event->pmu;
5711
5712 /* see comment in exclusive_event_init() */
5713 if (event->attach_state & PERF_ATTACH_TASK)
5714 atomic_dec(&pmu->exclusive_cnt);
5715 else
5716 atomic_inc(&pmu->exclusive_cnt);
5717
5718 event->attach_state &= ~PERF_ATTACH_EXCLUSIVE;
5719 }
5720
exclusive_event_match(struct perf_event * e1,struct perf_event * e2)5721 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
5722 {
5723 if ((e1->pmu == e2->pmu) &&
5724 (e1->cpu == e2->cpu ||
5725 e1->cpu == -1 ||
5726 e2->cpu == -1))
5727 return true;
5728 return false;
5729 }
5730
exclusive_event_installable(struct perf_event * event,struct perf_event_context * ctx)5731 static bool exclusive_event_installable(struct perf_event *event,
5732 struct perf_event_context *ctx)
5733 {
5734 struct perf_event *iter_event;
5735 struct pmu *pmu = event->pmu;
5736
5737 lockdep_assert_held(&ctx->mutex);
5738
5739 if (!is_exclusive_pmu(pmu))
5740 return true;
5741
5742 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
5743 if (exclusive_event_match(iter_event, event))
5744 return false;
5745 }
5746
5747 return true;
5748 }
5749
5750 static void perf_free_addr_filters(struct perf_event *event);
5751
5752 /* vs perf_event_alloc() error */
__free_event(struct perf_event * event)5753 static void __free_event(struct perf_event *event)
5754 {
5755 struct pmu *pmu = event->pmu;
5756
5757 security_perf_event_free(event);
5758
5759 if (event->attach_state & PERF_ATTACH_CALLCHAIN)
5760 put_callchain_buffers();
5761
5762 if (event->attach_state & PERF_ATTACH_EXCLUSIVE)
5763 exclusive_event_destroy(event);
5764
5765 if (is_cgroup_event(event))
5766 perf_detach_cgroup(event);
5767
5768 if (event->attach_state & PERF_ATTACH_TASK_DATA)
5769 detach_perf_ctx_data(event);
5770
5771 if (event->destroy)
5772 event->destroy(event);
5773
5774 /*
5775 * Must be after ->destroy(), due to uprobe_perf_close() using
5776 * hw.target.
5777 */
5778 if (event->hw.target)
5779 put_task_struct(event->hw.target);
5780
5781 if (event->pmu_ctx) {
5782 /*
5783 * put_pmu_ctx() needs an event->ctx reference, because of
5784 * epc->ctx.
5785 */
5786 WARN_ON_ONCE(!pmu);
5787 WARN_ON_ONCE(!event->ctx);
5788 WARN_ON_ONCE(event->pmu_ctx->ctx != event->ctx);
5789 put_pmu_ctx(event->pmu_ctx);
5790 }
5791
5792 /*
5793 * perf_event_free_task() relies on put_ctx() being 'last', in
5794 * particular all task references must be cleaned up.
5795 */
5796 if (event->ctx)
5797 put_ctx(event->ctx);
5798
5799 if (pmu) {
5800 module_put(pmu->module);
5801 scoped_guard (spinlock, &pmu->events_lock) {
5802 list_del(&event->pmu_list);
5803 wake_up_var(pmu);
5804 }
5805 }
5806
5807 call_rcu(&event->rcu_head, free_event_rcu);
5808 }
5809
5810 static void mediated_pmu_unaccount_event(struct perf_event *event);
5811
DEFINE_FREE(__free_event,struct perf_event *,if (_T)__free_event (_T))5812 DEFINE_FREE(__free_event, struct perf_event *, if (_T) __free_event(_T))
5813
5814 /* vs perf_event_alloc() success */
5815 static void _free_event(struct perf_event *event)
5816 {
5817 irq_work_sync(&event->pending_irq);
5818 irq_work_sync(&event->pending_disable_irq);
5819
5820 unaccount_event(event);
5821 mediated_pmu_unaccount_event(event);
5822
5823 if (event->rb) {
5824 /*
5825 * Can happen when we close an event with re-directed output.
5826 *
5827 * Since we have a 0 refcount, perf_mmap_close() will skip
5828 * over us; possibly making our ring_buffer_put() the last.
5829 */
5830 mutex_lock(&event->mmap_mutex);
5831 ring_buffer_attach(event, NULL);
5832 mutex_unlock(&event->mmap_mutex);
5833 }
5834
5835 perf_event_free_bpf_prog(event);
5836 perf_free_addr_filters(event);
5837
5838 __free_event(event);
5839 }
5840
5841 /*
5842 * Used to free events which have a known refcount of 1, such as in error paths
5843 * of inherited events.
5844 */
free_event(struct perf_event * event)5845 static void free_event(struct perf_event *event)
5846 {
5847 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
5848 "unexpected event refcount: %ld; ptr=%p\n",
5849 atomic_long_read(&event->refcount), event)) {
5850 /* leak to avoid use-after-free */
5851 return;
5852 }
5853
5854 _free_event(event);
5855 }
5856
5857 /*
5858 * Remove user event from the owner task.
5859 */
perf_remove_from_owner(struct perf_event * event)5860 static void perf_remove_from_owner(struct perf_event *event)
5861 {
5862 struct task_struct *owner;
5863
5864 rcu_read_lock();
5865 /*
5866 * Matches the smp_store_release() in perf_event_exit_task(). If we
5867 * observe !owner it means the list deletion is complete and we can
5868 * indeed free this event, otherwise we need to serialize on
5869 * owner->perf_event_mutex.
5870 */
5871 owner = READ_ONCE(event->owner);
5872 if (owner) {
5873 /*
5874 * Since delayed_put_task_struct() also drops the last
5875 * task reference we can safely take a new reference
5876 * while holding the rcu_read_lock().
5877 */
5878 get_task_struct(owner);
5879 }
5880 rcu_read_unlock();
5881
5882 if (owner) {
5883 /*
5884 * If we're here through perf_event_exit_task() we're already
5885 * holding ctx->mutex which would be an inversion wrt. the
5886 * normal lock order.
5887 *
5888 * However we can safely take this lock because its the child
5889 * ctx->mutex.
5890 */
5891 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
5892
5893 /*
5894 * We have to re-check the event->owner field, if it is cleared
5895 * we raced with perf_event_exit_task(), acquiring the mutex
5896 * ensured they're done, and we can proceed with freeing the
5897 * event.
5898 */
5899 if (event->owner) {
5900 list_del_init(&event->owner_entry);
5901 smp_store_release(&event->owner, NULL);
5902 }
5903 mutex_unlock(&owner->perf_event_mutex);
5904 put_task_struct(owner);
5905 }
5906 }
5907
put_event(struct perf_event * event)5908 static void put_event(struct perf_event *event)
5909 {
5910 struct perf_event *parent;
5911
5912 if (!atomic_long_dec_and_test(&event->refcount))
5913 return;
5914
5915 parent = event->parent;
5916 _free_event(event);
5917
5918 /* Matches the refcount bump in inherit_event() */
5919 if (parent)
5920 put_event(parent);
5921 }
5922
5923 /*
5924 * Kill an event dead; while event:refcount will preserve the event
5925 * object, it will not preserve its functionality. Once the last 'user'
5926 * gives up the object, we'll destroy the thing.
5927 */
perf_event_release_kernel(struct perf_event * event)5928 int perf_event_release_kernel(struct perf_event *event)
5929 {
5930 struct perf_event_context *ctx = event->ctx;
5931 struct perf_event *child, *tmp;
5932
5933 /*
5934 * If we got here through err_alloc: free_event(event); we will not
5935 * have attached to a context yet.
5936 */
5937 if (!ctx) {
5938 WARN_ON_ONCE(event->attach_state &
5939 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
5940 goto no_ctx;
5941 }
5942
5943 if (!is_kernel_event(event))
5944 perf_remove_from_owner(event);
5945
5946 ctx = perf_event_ctx_lock(event);
5947 WARN_ON_ONCE(ctx->parent_ctx);
5948
5949 /*
5950 * Mark this event as STATE_DEAD, there is no external reference to it
5951 * anymore.
5952 *
5953 * Anybody acquiring event->child_mutex after the below loop _must_
5954 * also see this, most importantly inherit_event() which will avoid
5955 * placing more children on the list.
5956 *
5957 * Thus this guarantees that we will in fact observe and kill _ALL_
5958 * child events.
5959 */
5960 if (event->state > PERF_EVENT_STATE_REVOKED) {
5961 perf_remove_from_context(event, DETACH_GROUP|DETACH_DEAD);
5962 } else {
5963 event->state = PERF_EVENT_STATE_DEAD;
5964 }
5965
5966 perf_event_ctx_unlock(event, ctx);
5967
5968 again:
5969 mutex_lock(&event->child_mutex);
5970 list_for_each_entry(child, &event->child_list, child_list) {
5971 /*
5972 * Cannot change, child events are not migrated, see the
5973 * comment with perf_event_ctx_lock_nested().
5974 */
5975 ctx = READ_ONCE(child->ctx);
5976 /*
5977 * Since child_mutex nests inside ctx::mutex, we must jump
5978 * through hoops. We start by grabbing a reference on the ctx.
5979 *
5980 * Since the event cannot get freed while we hold the
5981 * child_mutex, the context must also exist and have a !0
5982 * reference count.
5983 */
5984 get_ctx(ctx);
5985
5986 /*
5987 * Now that we have a ctx ref, we can drop child_mutex, and
5988 * acquire ctx::mutex without fear of it going away. Then we
5989 * can re-acquire child_mutex.
5990 */
5991 mutex_unlock(&event->child_mutex);
5992 mutex_lock(&ctx->mutex);
5993 mutex_lock(&event->child_mutex);
5994
5995 /*
5996 * Now that we hold ctx::mutex and child_mutex, revalidate our
5997 * state, if child is still the first entry, it didn't get freed
5998 * and we can continue doing so.
5999 */
6000 tmp = list_first_entry_or_null(&event->child_list,
6001 struct perf_event, child_list);
6002 if (tmp == child) {
6003 perf_remove_from_context(child, DETACH_GROUP | DETACH_CHILD);
6004 } else {
6005 child = NULL;
6006 }
6007
6008 mutex_unlock(&event->child_mutex);
6009 mutex_unlock(&ctx->mutex);
6010
6011 if (child) {
6012 /* Last reference unless ->pending_task work is pending */
6013 put_event(child);
6014 }
6015 put_ctx(ctx);
6016
6017 goto again;
6018 }
6019 mutex_unlock(&event->child_mutex);
6020
6021 no_ctx:
6022 /*
6023 * Last reference unless ->pending_task work is pending on this event
6024 * or any of its children.
6025 */
6026 put_event(event);
6027 return 0;
6028 }
6029 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
6030
6031 /*
6032 * Called when the last reference to the file is gone.
6033 */
perf_release(struct inode * inode,struct file * file)6034 static int perf_release(struct inode *inode, struct file *file)
6035 {
6036 perf_event_release_kernel(file->private_data);
6037 return 0;
6038 }
6039
__perf_event_read_value(struct perf_event * event,u64 * enabled,u64 * running)6040 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
6041 {
6042 struct perf_event *child;
6043 u64 total = 0;
6044
6045 *enabled = 0;
6046 *running = 0;
6047
6048 mutex_lock(&event->child_mutex);
6049
6050 (void)perf_event_read(event, false);
6051 total += perf_event_count(event, false);
6052
6053 *enabled += event->total_time_enabled +
6054 atomic64_read(&event->child_total_time_enabled);
6055 *running += event->total_time_running +
6056 atomic64_read(&event->child_total_time_running);
6057
6058 list_for_each_entry(child, &event->child_list, child_list) {
6059 (void)perf_event_read(child, false);
6060 total += perf_event_count(child, false);
6061 *enabled += child->total_time_enabled;
6062 *running += child->total_time_running;
6063 }
6064 mutex_unlock(&event->child_mutex);
6065
6066 return total;
6067 }
6068
perf_event_read_value(struct perf_event * event,u64 * enabled,u64 * running)6069 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
6070 {
6071 struct perf_event_context *ctx;
6072 u64 count;
6073
6074 ctx = perf_event_ctx_lock(event);
6075 count = __perf_event_read_value(event, enabled, running);
6076 perf_event_ctx_unlock(event, ctx);
6077
6078 return count;
6079 }
6080 EXPORT_SYMBOL_GPL(perf_event_read_value);
6081
__perf_read_group_add(struct perf_event * leader,u64 read_format,u64 * values)6082 static int __perf_read_group_add(struct perf_event *leader,
6083 u64 read_format, u64 *values)
6084 {
6085 struct perf_event_context *ctx = leader->ctx;
6086 struct perf_event *sub, *parent;
6087 unsigned long flags;
6088 int n = 1; /* skip @nr */
6089 int ret;
6090
6091 ret = perf_event_read(leader, true);
6092 if (ret)
6093 return ret;
6094
6095 raw_spin_lock_irqsave(&ctx->lock, flags);
6096 /*
6097 * Verify the grouping between the parent and child (inherited)
6098 * events is still in tact.
6099 *
6100 * Specifically:
6101 * - leader->ctx->lock pins leader->sibling_list
6102 * - parent->child_mutex pins parent->child_list
6103 * - parent->ctx->mutex pins parent->sibling_list
6104 *
6105 * Because parent->ctx != leader->ctx (and child_list nests inside
6106 * ctx->mutex), group destruction is not atomic between children, also
6107 * see perf_event_release_kernel(). Additionally, parent can grow the
6108 * group.
6109 *
6110 * Therefore it is possible to have parent and child groups in a
6111 * different configuration and summing over such a beast makes no sense
6112 * what so ever.
6113 *
6114 * Reject this.
6115 */
6116 parent = leader->parent;
6117 if (parent &&
6118 (parent->group_generation != leader->group_generation ||
6119 parent->nr_siblings != leader->nr_siblings)) {
6120 ret = -ECHILD;
6121 goto unlock;
6122 }
6123
6124 /*
6125 * Since we co-schedule groups, {enabled,running} times of siblings
6126 * will be identical to those of the leader, so we only publish one
6127 * set.
6128 */
6129 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
6130 values[n++] += leader->total_time_enabled +
6131 atomic64_read(&leader->child_total_time_enabled);
6132 }
6133
6134 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
6135 values[n++] += leader->total_time_running +
6136 atomic64_read(&leader->child_total_time_running);
6137 }
6138
6139 /*
6140 * Write {count,id} tuples for every sibling.
6141 */
6142 values[n++] += perf_event_count(leader, false);
6143 if (read_format & PERF_FORMAT_ID)
6144 values[n++] = primary_event_id(leader);
6145 if (read_format & PERF_FORMAT_LOST)
6146 values[n++] = atomic64_read(&leader->lost_samples);
6147
6148 for_each_sibling_event(sub, leader) {
6149 values[n++] += perf_event_count(sub, false);
6150 if (read_format & PERF_FORMAT_ID)
6151 values[n++] = primary_event_id(sub);
6152 if (read_format & PERF_FORMAT_LOST)
6153 values[n++] = atomic64_read(&sub->lost_samples);
6154 }
6155
6156 unlock:
6157 raw_spin_unlock_irqrestore(&ctx->lock, flags);
6158 return ret;
6159 }
6160
perf_read_group(struct perf_event * event,u64 read_format,char __user * buf)6161 static int perf_read_group(struct perf_event *event,
6162 u64 read_format, char __user *buf)
6163 {
6164 struct perf_event *leader = event->group_leader, *child;
6165 struct perf_event_context *ctx = leader->ctx;
6166 int ret;
6167 u64 *values;
6168
6169 lockdep_assert_held(&ctx->mutex);
6170
6171 values = kzalloc(event->read_size, GFP_KERNEL);
6172 if (!values)
6173 return -ENOMEM;
6174
6175 values[0] = 1 + leader->nr_siblings;
6176
6177 mutex_lock(&leader->child_mutex);
6178
6179 ret = __perf_read_group_add(leader, read_format, values);
6180 if (ret)
6181 goto unlock;
6182
6183 list_for_each_entry(child, &leader->child_list, child_list) {
6184 ret = __perf_read_group_add(child, read_format, values);
6185 if (ret)
6186 goto unlock;
6187 }
6188
6189 mutex_unlock(&leader->child_mutex);
6190
6191 ret = event->read_size;
6192 if (copy_to_user(buf, values, event->read_size))
6193 ret = -EFAULT;
6194 goto out;
6195
6196 unlock:
6197 mutex_unlock(&leader->child_mutex);
6198 out:
6199 kfree(values);
6200 return ret;
6201 }
6202
perf_read_one(struct perf_event * event,u64 read_format,char __user * buf)6203 static int perf_read_one(struct perf_event *event,
6204 u64 read_format, char __user *buf)
6205 {
6206 u64 enabled, running;
6207 u64 values[5];
6208 int n = 0;
6209
6210 values[n++] = __perf_event_read_value(event, &enabled, &running);
6211 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6212 values[n++] = enabled;
6213 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6214 values[n++] = running;
6215 if (read_format & PERF_FORMAT_ID)
6216 values[n++] = primary_event_id(event);
6217 if (read_format & PERF_FORMAT_LOST)
6218 values[n++] = atomic64_read(&event->lost_samples);
6219
6220 if (copy_to_user(buf, values, n * sizeof(u64)))
6221 return -EFAULT;
6222
6223 return n * sizeof(u64);
6224 }
6225
is_event_hup(struct perf_event * event)6226 static bool is_event_hup(struct perf_event *event)
6227 {
6228 bool no_children;
6229
6230 if (event->state > PERF_EVENT_STATE_EXIT)
6231 return false;
6232
6233 mutex_lock(&event->child_mutex);
6234 no_children = list_empty(&event->child_list);
6235 mutex_unlock(&event->child_mutex);
6236 return no_children;
6237 }
6238
6239 /*
6240 * Read the performance event - simple non blocking version for now
6241 */
6242 static ssize_t
__perf_read(struct perf_event * event,char __user * buf,size_t count)6243 __perf_read(struct perf_event *event, char __user *buf, size_t count)
6244 {
6245 u64 read_format = event->attr.read_format;
6246 int ret;
6247
6248 /*
6249 * Return end-of-file for a read on an event that is in
6250 * error state (i.e. because it was pinned but it couldn't be
6251 * scheduled on to the CPU at some point).
6252 */
6253 if (event->state == PERF_EVENT_STATE_ERROR)
6254 return 0;
6255
6256 if (count < event->read_size)
6257 return -ENOSPC;
6258
6259 WARN_ON_ONCE(event->ctx->parent_ctx);
6260 if (read_format & PERF_FORMAT_GROUP)
6261 ret = perf_read_group(event, read_format, buf);
6262 else
6263 ret = perf_read_one(event, read_format, buf);
6264
6265 return ret;
6266 }
6267
6268 static ssize_t
perf_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)6269 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
6270 {
6271 struct perf_event *event = file->private_data;
6272 struct perf_event_context *ctx;
6273 int ret;
6274
6275 ret = security_perf_event_read(event);
6276 if (ret)
6277 return ret;
6278
6279 ctx = perf_event_ctx_lock(event);
6280 ret = __perf_read(event, buf, count);
6281 perf_event_ctx_unlock(event, ctx);
6282
6283 return ret;
6284 }
6285
perf_poll(struct file * file,poll_table * wait)6286 static __poll_t perf_poll(struct file *file, poll_table *wait)
6287 {
6288 struct perf_event *event = file->private_data;
6289 struct perf_buffer *rb;
6290 __poll_t events = EPOLLHUP;
6291
6292 if (event->state <= PERF_EVENT_STATE_REVOKED)
6293 return EPOLLERR;
6294
6295 poll_wait(file, &event->waitq, wait);
6296
6297 if (event->state <= PERF_EVENT_STATE_REVOKED)
6298 return EPOLLERR;
6299
6300 if (is_event_hup(event))
6301 return events;
6302
6303 if (unlikely(READ_ONCE(event->state) == PERF_EVENT_STATE_ERROR &&
6304 event->attr.pinned))
6305 return EPOLLERR;
6306
6307 /*
6308 * Pin the event->rb by taking event->mmap_mutex; otherwise
6309 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
6310 */
6311 mutex_lock(&event->mmap_mutex);
6312 rb = event->rb;
6313 if (rb)
6314 events = atomic_xchg(&rb->poll, 0);
6315 mutex_unlock(&event->mmap_mutex);
6316 return events;
6317 }
6318
_perf_event_reset(struct perf_event * event)6319 static void _perf_event_reset(struct perf_event *event)
6320 {
6321 (void)perf_event_read(event, false);
6322 local64_set(&event->count, 0);
6323 perf_event_update_userpage(event);
6324 }
6325
6326 /* Assume it's not an event with inherit set. */
perf_event_pause(struct perf_event * event,bool reset)6327 u64 perf_event_pause(struct perf_event *event, bool reset)
6328 {
6329 struct perf_event_context *ctx;
6330 u64 count;
6331
6332 ctx = perf_event_ctx_lock(event);
6333 WARN_ON_ONCE(event->attr.inherit);
6334 _perf_event_disable(event);
6335 count = local64_read(&event->count);
6336 if (reset)
6337 local64_set(&event->count, 0);
6338 perf_event_ctx_unlock(event, ctx);
6339
6340 return count;
6341 }
6342 EXPORT_SYMBOL_GPL(perf_event_pause);
6343
6344 #ifdef CONFIG_PERF_GUEST_MEDIATED_PMU
6345 static atomic_t nr_include_guest_events __read_mostly;
6346
6347 static atomic_t nr_mediated_pmu_vms __read_mostly;
6348 static DEFINE_MUTEX(perf_mediated_pmu_mutex);
6349
6350 /* !exclude_guest event of PMU with PERF_PMU_CAP_MEDIATED_VPMU */
is_include_guest_event(struct perf_event * event)6351 static inline bool is_include_guest_event(struct perf_event *event)
6352 {
6353 if (!event->pmu)
6354 return false;
6355
6356 if ((event->pmu->capabilities & PERF_PMU_CAP_MEDIATED_VPMU) &&
6357 !event->attr.exclude_guest)
6358 return true;
6359
6360 return false;
6361 }
6362
mediated_pmu_account_event(struct perf_event * event)6363 static int mediated_pmu_account_event(struct perf_event *event)
6364 {
6365 if (!is_include_guest_event(event))
6366 return 0;
6367
6368 if (atomic_inc_not_zero(&nr_include_guest_events))
6369 return 0;
6370
6371 guard(mutex)(&perf_mediated_pmu_mutex);
6372 if (atomic_read(&nr_mediated_pmu_vms))
6373 return -EOPNOTSUPP;
6374
6375 atomic_inc(&nr_include_guest_events);
6376 return 0;
6377 }
6378
mediated_pmu_unaccount_event(struct perf_event * event)6379 static void mediated_pmu_unaccount_event(struct perf_event *event)
6380 {
6381 if (!is_include_guest_event(event))
6382 return;
6383
6384 if (WARN_ON_ONCE(!atomic_read(&nr_include_guest_events)))
6385 return;
6386
6387 atomic_dec(&nr_include_guest_events);
6388 }
6389
6390 /*
6391 * Currently invoked at VM creation to
6392 * - Check whether there are existing !exclude_guest events of PMU with
6393 * PERF_PMU_CAP_MEDIATED_VPMU
6394 * - Set nr_mediated_pmu_vms to prevent !exclude_guest event creation on
6395 * PMUs with PERF_PMU_CAP_MEDIATED_VPMU
6396 *
6397 * No impact for the PMU without PERF_PMU_CAP_MEDIATED_VPMU. The perf
6398 * still owns all the PMU resources.
6399 */
perf_create_mediated_pmu(void)6400 int perf_create_mediated_pmu(void)
6401 {
6402 if (atomic_inc_not_zero(&nr_mediated_pmu_vms))
6403 return 0;
6404
6405 guard(mutex)(&perf_mediated_pmu_mutex);
6406 if (atomic_read(&nr_include_guest_events))
6407 return -EBUSY;
6408
6409 atomic_inc(&nr_mediated_pmu_vms);
6410 return 0;
6411 }
6412 EXPORT_SYMBOL_FOR_KVM(perf_create_mediated_pmu);
6413
perf_release_mediated_pmu(void)6414 void perf_release_mediated_pmu(void)
6415 {
6416 if (WARN_ON_ONCE(!atomic_read(&nr_mediated_pmu_vms)))
6417 return;
6418
6419 atomic_dec(&nr_mediated_pmu_vms);
6420 }
6421 EXPORT_SYMBOL_FOR_KVM(perf_release_mediated_pmu);
6422
6423 /* When loading a guest's mediated PMU, schedule out all exclude_guest events. */
perf_load_guest_context(void)6424 void perf_load_guest_context(void)
6425 {
6426 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
6427
6428 lockdep_assert_irqs_disabled();
6429
6430 guard(perf_ctx_lock)(cpuctx, cpuctx->task_ctx);
6431
6432 if (WARN_ON_ONCE(__this_cpu_read(guest_ctx_loaded)))
6433 return;
6434
6435 perf_ctx_disable(&cpuctx->ctx, EVENT_GUEST);
6436 ctx_sched_out(&cpuctx->ctx, NULL, EVENT_GUEST);
6437 if (cpuctx->task_ctx) {
6438 perf_ctx_disable(cpuctx->task_ctx, EVENT_GUEST);
6439 task_ctx_sched_out(cpuctx->task_ctx, NULL, EVENT_GUEST);
6440 }
6441
6442 perf_ctx_enable(&cpuctx->ctx, EVENT_GUEST);
6443 if (cpuctx->task_ctx)
6444 perf_ctx_enable(cpuctx->task_ctx, EVENT_GUEST);
6445
6446 __this_cpu_write(guest_ctx_loaded, true);
6447 }
6448 EXPORT_SYMBOL_GPL(perf_load_guest_context);
6449
perf_put_guest_context(void)6450 void perf_put_guest_context(void)
6451 {
6452 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
6453
6454 lockdep_assert_irqs_disabled();
6455
6456 guard(perf_ctx_lock)(cpuctx, cpuctx->task_ctx);
6457
6458 if (WARN_ON_ONCE(!__this_cpu_read(guest_ctx_loaded)))
6459 return;
6460
6461 perf_ctx_disable(&cpuctx->ctx, EVENT_GUEST);
6462 if (cpuctx->task_ctx)
6463 perf_ctx_disable(cpuctx->task_ctx, EVENT_GUEST);
6464
6465 perf_event_sched_in(cpuctx, cpuctx->task_ctx, NULL, EVENT_GUEST);
6466
6467 if (cpuctx->task_ctx)
6468 perf_ctx_enable(cpuctx->task_ctx, EVENT_GUEST);
6469 perf_ctx_enable(&cpuctx->ctx, EVENT_GUEST);
6470
6471 __this_cpu_write(guest_ctx_loaded, false);
6472 }
6473 EXPORT_SYMBOL_GPL(perf_put_guest_context);
6474 #else
mediated_pmu_account_event(struct perf_event * event)6475 static int mediated_pmu_account_event(struct perf_event *event) { return 0; }
mediated_pmu_unaccount_event(struct perf_event * event)6476 static void mediated_pmu_unaccount_event(struct perf_event *event) {}
6477 #endif
6478
6479 /*
6480 * Holding the top-level event's child_mutex means that any
6481 * descendant process that has inherited this event will block
6482 * in perf_event_exit_event() if it goes to exit, thus satisfying the
6483 * task existence requirements of perf_event_enable/disable.
6484 */
perf_event_for_each_child(struct perf_event * event,void (* func)(struct perf_event *))6485 static void perf_event_for_each_child(struct perf_event *event,
6486 void (*func)(struct perf_event *))
6487 {
6488 struct perf_event *child;
6489
6490 WARN_ON_ONCE(event->ctx->parent_ctx);
6491
6492 mutex_lock(&event->child_mutex);
6493 func(event);
6494 list_for_each_entry(child, &event->child_list, child_list)
6495 func(child);
6496 mutex_unlock(&event->child_mutex);
6497 }
6498
perf_event_for_each(struct perf_event * event,void (* func)(struct perf_event *))6499 static void perf_event_for_each(struct perf_event *event,
6500 void (*func)(struct perf_event *))
6501 {
6502 struct perf_event_context *ctx = event->ctx;
6503 struct perf_event *sibling;
6504
6505 lockdep_assert_held(&ctx->mutex);
6506
6507 event = event->group_leader;
6508
6509 perf_event_for_each_child(event, func);
6510 for_each_sibling_event(sibling, event)
6511 perf_event_for_each_child(sibling, func);
6512 }
6513
__perf_event_period(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)6514 static void __perf_event_period(struct perf_event *event,
6515 struct perf_cpu_context *cpuctx,
6516 struct perf_event_context *ctx,
6517 void *info)
6518 {
6519 u64 value = *((u64 *)info);
6520 bool active;
6521
6522 if (event->attr.freq) {
6523 event->attr.sample_freq = value;
6524 } else {
6525 event->attr.sample_period = value;
6526 event->hw.sample_period = value;
6527 }
6528
6529 active = (event->state == PERF_EVENT_STATE_ACTIVE);
6530 if (active) {
6531 perf_pmu_disable(event->pmu);
6532 event->pmu->stop(event, PERF_EF_UPDATE);
6533 }
6534
6535 local64_set(&event->hw.period_left, 0);
6536
6537 if (active) {
6538 event->pmu->start(event, PERF_EF_RELOAD);
6539 /*
6540 * Once the period is force-reset, the event starts immediately.
6541 * But the event/group could be throttled. Unthrottle the
6542 * event/group now to avoid the next tick trying to unthrottle
6543 * while we already re-started the event/group.
6544 */
6545 if (event->hw.interrupts == MAX_INTERRUPTS)
6546 perf_event_unthrottle_group(event, true);
6547 perf_pmu_enable(event->pmu);
6548 }
6549 }
6550
perf_event_check_period(struct perf_event * event,u64 value)6551 static int perf_event_check_period(struct perf_event *event, u64 value)
6552 {
6553 return event->pmu->check_period(event, value);
6554 }
6555
_perf_event_period(struct perf_event * event,u64 value)6556 static int _perf_event_period(struct perf_event *event, u64 value)
6557 {
6558 if (!is_sampling_event(event))
6559 return -EINVAL;
6560
6561 if (!value)
6562 return -EINVAL;
6563
6564 if (event->attr.freq) {
6565 if (value > sysctl_perf_event_sample_rate)
6566 return -EINVAL;
6567 } else {
6568 if (perf_event_check_period(event, value))
6569 return -EINVAL;
6570 if (value & (1ULL << 63))
6571 return -EINVAL;
6572 }
6573
6574 event_function_call(event, __perf_event_period, &value);
6575
6576 return 0;
6577 }
6578
perf_event_period(struct perf_event * event,u64 value)6579 int perf_event_period(struct perf_event *event, u64 value)
6580 {
6581 struct perf_event_context *ctx;
6582 int ret;
6583
6584 ctx = perf_event_ctx_lock(event);
6585 ret = _perf_event_period(event, value);
6586 perf_event_ctx_unlock(event, ctx);
6587
6588 return ret;
6589 }
6590 EXPORT_SYMBOL_GPL(perf_event_period);
6591
6592 static const struct file_operations perf_fops;
6593
is_perf_file(struct fd f)6594 static inline bool is_perf_file(struct fd f)
6595 {
6596 return !fd_empty(f) && fd_file(f)->f_op == &perf_fops;
6597 }
6598
6599 static int perf_event_set_output(struct perf_event *event,
6600 struct perf_event *output_event);
6601 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
6602 static int perf_copy_attr(struct perf_event_attr __user *uattr,
6603 struct perf_event_attr *attr);
6604 static int __perf_event_set_bpf_prog(struct perf_event *event,
6605 struct bpf_prog *prog,
6606 u64 bpf_cookie);
6607
_perf_ioctl(struct perf_event * event,unsigned int cmd,unsigned long arg)6608 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
6609 {
6610 void (*func)(struct perf_event *);
6611 u32 flags = arg;
6612
6613 if (event->state <= PERF_EVENT_STATE_REVOKED)
6614 return -ENODEV;
6615
6616 switch (cmd) {
6617 case PERF_EVENT_IOC_ENABLE:
6618 func = _perf_event_enable;
6619 break;
6620 case PERF_EVENT_IOC_DISABLE:
6621 func = _perf_event_disable;
6622 break;
6623 case PERF_EVENT_IOC_RESET:
6624 func = _perf_event_reset;
6625 break;
6626
6627 case PERF_EVENT_IOC_REFRESH:
6628 return _perf_event_refresh(event, arg);
6629
6630 case PERF_EVENT_IOC_PERIOD:
6631 {
6632 u64 value;
6633
6634 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
6635 return -EFAULT;
6636
6637 return _perf_event_period(event, value);
6638 }
6639 case PERF_EVENT_IOC_ID:
6640 {
6641 u64 id = primary_event_id(event);
6642
6643 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
6644 return -EFAULT;
6645 return 0;
6646 }
6647
6648 case PERF_EVENT_IOC_SET_OUTPUT:
6649 {
6650 CLASS(fd, output)(arg); // arg == -1 => empty
6651 struct perf_event *output_event = NULL;
6652 if (arg != -1) {
6653 if (!is_perf_file(output))
6654 return -EBADF;
6655 output_event = fd_file(output)->private_data;
6656 }
6657 return perf_event_set_output(event, output_event);
6658 }
6659
6660 case PERF_EVENT_IOC_SET_FILTER:
6661 return perf_event_set_filter(event, (void __user *)arg);
6662
6663 case PERF_EVENT_IOC_SET_BPF:
6664 {
6665 struct bpf_prog *prog;
6666 int err;
6667
6668 prog = bpf_prog_get(arg);
6669 if (IS_ERR(prog))
6670 return PTR_ERR(prog);
6671
6672 err = __perf_event_set_bpf_prog(event, prog, 0);
6673 if (err) {
6674 bpf_prog_put(prog);
6675 return err;
6676 }
6677
6678 return 0;
6679 }
6680
6681 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
6682 struct perf_buffer *rb;
6683
6684 rcu_read_lock();
6685 rb = rcu_dereference(event->rb);
6686 if (!rb || !rb->nr_pages) {
6687 rcu_read_unlock();
6688 return -EINVAL;
6689 }
6690 rb_toggle_paused(rb, !!arg);
6691 rcu_read_unlock();
6692 return 0;
6693 }
6694
6695 case PERF_EVENT_IOC_QUERY_BPF:
6696 return perf_event_query_prog_array(event, (void __user *)arg);
6697
6698 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
6699 struct perf_event_attr new_attr;
6700 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
6701 &new_attr);
6702
6703 if (err)
6704 return err;
6705
6706 return perf_event_modify_attr(event, &new_attr);
6707 }
6708 default:
6709 return -ENOTTY;
6710 }
6711
6712 if (flags & PERF_IOC_FLAG_GROUP)
6713 perf_event_for_each(event, func);
6714 else
6715 perf_event_for_each_child(event, func);
6716
6717 return 0;
6718 }
6719
perf_ioctl(struct file * file,unsigned int cmd,unsigned long arg)6720 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
6721 {
6722 struct perf_event *event = file->private_data;
6723 struct perf_event_context *ctx;
6724 long ret;
6725
6726 /* Treat ioctl like writes as it is likely a mutating operation. */
6727 ret = security_perf_event_write(event);
6728 if (ret)
6729 return ret;
6730
6731 ctx = perf_event_ctx_lock(event);
6732 ret = _perf_ioctl(event, cmd, arg);
6733 perf_event_ctx_unlock(event, ctx);
6734
6735 return ret;
6736 }
6737
6738 #ifdef CONFIG_COMPAT
perf_compat_ioctl(struct file * file,unsigned int cmd,unsigned long arg)6739 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
6740 unsigned long arg)
6741 {
6742 switch (_IOC_NR(cmd)) {
6743 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
6744 case _IOC_NR(PERF_EVENT_IOC_ID):
6745 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
6746 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
6747 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
6748 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
6749 cmd &= ~IOCSIZE_MASK;
6750 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
6751 }
6752 break;
6753 }
6754 return perf_ioctl(file, cmd, arg);
6755 }
6756 #else
6757 # define perf_compat_ioctl NULL
6758 #endif
6759
perf_event_task_enable(void)6760 int perf_event_task_enable(void)
6761 {
6762 struct perf_event_context *ctx;
6763 struct perf_event *event;
6764
6765 mutex_lock(¤t->perf_event_mutex);
6766 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
6767 ctx = perf_event_ctx_lock(event);
6768 perf_event_for_each_child(event, _perf_event_enable);
6769 perf_event_ctx_unlock(event, ctx);
6770 }
6771 mutex_unlock(¤t->perf_event_mutex);
6772
6773 return 0;
6774 }
6775
perf_event_task_disable(void)6776 int perf_event_task_disable(void)
6777 {
6778 struct perf_event_context *ctx;
6779 struct perf_event *event;
6780
6781 mutex_lock(¤t->perf_event_mutex);
6782 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
6783 ctx = perf_event_ctx_lock(event);
6784 perf_event_for_each_child(event, _perf_event_disable);
6785 perf_event_ctx_unlock(event, ctx);
6786 }
6787 mutex_unlock(¤t->perf_event_mutex);
6788
6789 return 0;
6790 }
6791
perf_event_index(struct perf_event * event)6792 static int perf_event_index(struct perf_event *event)
6793 {
6794 if (event->hw.state & PERF_HES_STOPPED)
6795 return 0;
6796
6797 if (event->state != PERF_EVENT_STATE_ACTIVE)
6798 return 0;
6799
6800 return event->pmu->event_idx(event);
6801 }
6802
perf_event_init_userpage(struct perf_event * event)6803 static void perf_event_init_userpage(struct perf_event *event)
6804 {
6805 struct perf_event_mmap_page *userpg;
6806 struct perf_buffer *rb;
6807
6808 rcu_read_lock();
6809 rb = rcu_dereference(event->rb);
6810 if (!rb)
6811 goto unlock;
6812
6813 userpg = rb->user_page;
6814
6815 /* Allow new userspace to detect that bit 0 is deprecated */
6816 userpg->cap_bit0_is_deprecated = 1;
6817 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
6818 userpg->data_offset = PAGE_SIZE;
6819 userpg->data_size = perf_data_size(rb);
6820
6821 unlock:
6822 rcu_read_unlock();
6823 }
6824
arch_perf_update_userpage(struct perf_event * event,struct perf_event_mmap_page * userpg,u64 now)6825 void __weak arch_perf_update_userpage(
6826 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
6827 {
6828 }
6829
6830 /*
6831 * Callers need to ensure there can be no nesting of this function, otherwise
6832 * the seqlock logic goes bad. We can not serialize this because the arch
6833 * code calls this from NMI context.
6834 */
perf_event_update_userpage(struct perf_event * event)6835 void perf_event_update_userpage(struct perf_event *event)
6836 {
6837 struct perf_event_mmap_page *userpg;
6838 struct perf_buffer *rb;
6839 u64 enabled, running, now;
6840
6841 rcu_read_lock();
6842 rb = rcu_dereference(event->rb);
6843 if (!rb)
6844 goto unlock;
6845
6846 /*
6847 * Disable preemption to guarantee consistent time stamps are stored to
6848 * the user page.
6849 */
6850 preempt_disable();
6851
6852 /*
6853 * Compute total_time_enabled, total_time_running based on snapshot
6854 * values taken when the event was last scheduled in.
6855 *
6856 * We cannot simply call update_context_time() because doing so would
6857 * lead to deadlock when called from NMI context.
6858 */
6859 calc_timer_values(event, &now, &enabled, &running);
6860
6861 userpg = rb->user_page;
6862
6863 ++userpg->lock;
6864 barrier();
6865 userpg->index = perf_event_index(event);
6866 userpg->offset = perf_event_count(event, false);
6867 if (userpg->index)
6868 userpg->offset -= local64_read(&event->hw.prev_count);
6869
6870 userpg->time_enabled = enabled +
6871 atomic64_read(&event->child_total_time_enabled);
6872
6873 userpg->time_running = running +
6874 atomic64_read(&event->child_total_time_running);
6875
6876 arch_perf_update_userpage(event, userpg, now);
6877
6878 barrier();
6879 ++userpg->lock;
6880 preempt_enable();
6881 unlock:
6882 rcu_read_unlock();
6883 }
6884 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
6885
ring_buffer_attach(struct perf_event * event,struct perf_buffer * rb)6886 static void ring_buffer_attach(struct perf_event *event,
6887 struct perf_buffer *rb)
6888 {
6889 struct perf_buffer *old_rb = NULL;
6890 unsigned long flags;
6891
6892 WARN_ON_ONCE(event->parent);
6893
6894 if (event->rb) {
6895 /*
6896 * Should be impossible, we set this when removing
6897 * event->rb_entry and wait/clear when adding event->rb_entry.
6898 */
6899 WARN_ON_ONCE(event->rcu_pending);
6900
6901 old_rb = event->rb;
6902 spin_lock_irqsave(&old_rb->event_lock, flags);
6903 list_del_rcu(&event->rb_entry);
6904 spin_unlock_irqrestore(&old_rb->event_lock, flags);
6905
6906 event->rcu_batches = get_state_synchronize_rcu();
6907 event->rcu_pending = 1;
6908 }
6909
6910 if (rb) {
6911 if (event->rcu_pending) {
6912 cond_synchronize_rcu(event->rcu_batches);
6913 event->rcu_pending = 0;
6914 }
6915
6916 spin_lock_irqsave(&rb->event_lock, flags);
6917 list_add_rcu(&event->rb_entry, &rb->event_list);
6918 spin_unlock_irqrestore(&rb->event_lock, flags);
6919 }
6920
6921 /*
6922 * Avoid racing with perf_mmap_close(AUX): stop the event
6923 * before swizzling the event::rb pointer; if it's getting
6924 * unmapped, its aux_mmap_count will be 0 and it won't
6925 * restart. See the comment in __perf_pmu_output_stop().
6926 *
6927 * Data will inevitably be lost when set_output is done in
6928 * mid-air, but then again, whoever does it like this is
6929 * not in for the data anyway.
6930 */
6931 if (has_aux(event))
6932 perf_event_stop(event, 0);
6933
6934 rcu_assign_pointer(event->rb, rb);
6935
6936 if (old_rb) {
6937 ring_buffer_put(old_rb);
6938 /*
6939 * Since we detached before setting the new rb, so that we
6940 * could attach the new rb, we could have missed a wakeup.
6941 * Provide it now.
6942 */
6943 wake_up_all(&event->waitq);
6944 }
6945 }
6946
ring_buffer_wakeup(struct perf_event * event)6947 static void ring_buffer_wakeup(struct perf_event *event)
6948 {
6949 struct perf_buffer *rb;
6950
6951 if (event->parent)
6952 event = event->parent;
6953
6954 rcu_read_lock();
6955 rb = rcu_dereference(event->rb);
6956 if (rb) {
6957 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
6958 wake_up_all(&event->waitq);
6959 }
6960 rcu_read_unlock();
6961 }
6962
ring_buffer_get(struct perf_event * event)6963 struct perf_buffer *ring_buffer_get(struct perf_event *event)
6964 {
6965 struct perf_buffer *rb;
6966
6967 if (event->parent)
6968 event = event->parent;
6969
6970 rcu_read_lock();
6971 rb = rcu_dereference(event->rb);
6972 if (rb) {
6973 if (!refcount_inc_not_zero(&rb->refcount))
6974 rb = NULL;
6975 }
6976 rcu_read_unlock();
6977
6978 return rb;
6979 }
6980
ring_buffer_put(struct perf_buffer * rb)6981 void ring_buffer_put(struct perf_buffer *rb)
6982 {
6983 if (!refcount_dec_and_test(&rb->refcount))
6984 return;
6985
6986 WARN_ON_ONCE(!list_empty(&rb->event_list));
6987
6988 call_rcu(&rb->rcu_head, rb_free_rcu);
6989 }
6990
6991 typedef void (*mapped_f)(struct perf_event *event, struct mm_struct *mm);
6992
6993 #define get_mapped(event, func) \
6994 ({ struct pmu *pmu; \
6995 mapped_f f = NULL; \
6996 guard(rcu)(); \
6997 pmu = READ_ONCE(event->pmu); \
6998 if (pmu) \
6999 f = pmu->func; \
7000 f; \
7001 })
7002
perf_mmap_open(struct vm_area_struct * vma)7003 static void perf_mmap_open(struct vm_area_struct *vma)
7004 {
7005 struct perf_event *event = vma->vm_file->private_data;
7006 mapped_f mapped = get_mapped(event, event_mapped);
7007
7008 refcount_inc(&event->mmap_count);
7009 refcount_inc(&event->rb->mmap_count);
7010
7011 if (vma_start_pgoff(vma))
7012 refcount_inc(&event->rb->aux_mmap_count);
7013
7014 if (mapped)
7015 mapped(event, vma->vm_mm);
7016 }
7017
7018 static void perf_pmu_output_stop(struct perf_event *event);
7019 static void perf_mmap_unaccount(struct vm_area_struct *vma, struct perf_buffer *rb);
7020
7021 /*
7022 * A buffer can be mmap()ed multiple times; either directly through the same
7023 * event, or through other events by use of perf_event_set_output().
7024 *
7025 * In order to undo the VM accounting done by perf_mmap() we need to destroy
7026 * the buffer here, where we still have a VM context. This means we need
7027 * to detach all events redirecting to us.
7028 */
perf_mmap_close(struct vm_area_struct * vma)7029 static void perf_mmap_close(struct vm_area_struct *vma)
7030 {
7031 struct perf_event *event = vma->vm_file->private_data;
7032 mapped_f unmapped = get_mapped(event, event_unmapped);
7033 struct perf_buffer *rb = ring_buffer_get(event);
7034 struct user_struct *mmap_user = rb->mmap_user;
7035
7036 /* FIXIES vs perf_pmu_unregister() */
7037 if (unmapped)
7038 unmapped(event, vma->vm_mm);
7039
7040 /*
7041 * The AUX buffer is strictly a sub-buffer, serialize using aux_mutex
7042 * to avoid complications.
7043 */
7044 if (rb_has_aux(rb) && vma_start_pgoff(vma) == rb->aux_pgoff &&
7045 refcount_dec_and_mutex_lock(&rb->aux_mmap_count, &rb->aux_mutex)) {
7046 /*
7047 * Stop all AUX events that are writing to this buffer,
7048 * so that we can free its AUX pages and corresponding PMU
7049 * data. Note that after rb::aux_mmap_count dropped to zero,
7050 * they won't start any more (see perf_aux_output_begin()).
7051 */
7052 perf_pmu_output_stop(event);
7053
7054 /* now it's safe to free the pages */
7055 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
7056 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
7057
7058 /* this has to be the last one */
7059 rb_free_aux(rb);
7060 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
7061
7062 mutex_unlock(&rb->aux_mutex);
7063 }
7064
7065 /*
7066 * Drop references in reverse order of perf_mmap() to prevent
7067 * rb revival after rb->mmap_count reaches zero.
7068 */
7069 if (refcount_dec_and_mutex_lock(&event->mmap_count,
7070 &event->mmap_mutex)) {
7071 ring_buffer_attach(event, NULL);
7072 mutex_unlock(&event->mmap_mutex);
7073 }
7074
7075 /* If there's still other mmap()s of this buffer, we're done. */
7076 if (!refcount_dec_and_test(&rb->mmap_count))
7077 goto out_put;
7078
7079 /*
7080 * No other mmap()s, detach from all other events that might redirect
7081 * into the now unreachable buffer. Somewhat complicated by the
7082 * fact that rb::event_lock otherwise nests inside mmap_mutex.
7083 */
7084 again:
7085 rcu_read_lock();
7086 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
7087 if (!atomic_long_inc_not_zero(&event->refcount)) {
7088 /*
7089 * This event is en-route to free_event() which will
7090 * detach it and remove it from the list.
7091 */
7092 continue;
7093 }
7094 rcu_read_unlock();
7095
7096 mutex_lock(&event->mmap_mutex);
7097 /*
7098 * Check we didn't race with perf_event_set_output() which can
7099 * swizzle the rb from under us while we were waiting to
7100 * acquire mmap_mutex.
7101 *
7102 * If we find a different rb; ignore this event, a next
7103 * iteration will no longer find it on the list. We have to
7104 * still restart the iteration to make sure we're not now
7105 * iterating the wrong list.
7106 */
7107 if (event->rb == rb)
7108 ring_buffer_attach(event, NULL);
7109
7110 mutex_unlock(&event->mmap_mutex);
7111 put_event(event);
7112
7113 /*
7114 * Restart the iteration; either we're on the wrong list or
7115 * destroyed its integrity by doing a deletion.
7116 */
7117 goto again;
7118 }
7119 rcu_read_unlock();
7120
7121 /*
7122 * It could be there's still a few 0-ref events on the list; they'll
7123 * get cleaned up by free_event() -- they'll also still have their
7124 * ref on the rb and will free it whenever they are done with it.
7125 *
7126 * Aside from that, this buffer is 'fully' detached and unmapped,
7127 * undo the VM accounting.
7128 */
7129 perf_mmap_unaccount(vma, rb);
7130
7131 out_put:
7132 ring_buffer_put(rb); /* could be last */
7133 }
7134
perf_mmap_pfn_mkwrite(struct vm_fault * vmf)7135 static vm_fault_t perf_mmap_pfn_mkwrite(struct vm_fault *vmf)
7136 {
7137 /* The first page is the user control page, others are read-only. */
7138 return vmf->pgoff == 0 ? 0 : VM_FAULT_SIGBUS;
7139 }
7140
perf_mmap_may_split(struct vm_area_struct * vma,unsigned long addr)7141 static int perf_mmap_may_split(struct vm_area_struct *vma, unsigned long addr)
7142 {
7143 /*
7144 * Forbid splitting perf mappings to prevent refcount leaks due to
7145 * the resulting non-matching offsets and sizes. See open()/close().
7146 */
7147 return -EINVAL;
7148 }
7149
7150 static const struct vm_operations_struct perf_mmap_vmops = {
7151 .open = perf_mmap_open,
7152 .close = perf_mmap_close, /* non mergeable */
7153 .pfn_mkwrite = perf_mmap_pfn_mkwrite,
7154 .may_split = perf_mmap_may_split,
7155 };
7156
map_range(struct perf_buffer * rb,struct vm_area_struct * vma)7157 static int map_range(struct perf_buffer *rb, struct vm_area_struct *vma)
7158 {
7159 unsigned long nr_pages = vma_pages(vma);
7160 int err = 0;
7161 unsigned long pagenum;
7162
7163 guard(mutex)(&rb->aux_mutex);
7164
7165 /*
7166 * We map this as a VM_PFNMAP VMA.
7167 *
7168 * This is not ideal as this is designed broadly for mappings of PFNs
7169 * referencing memory-mapped I/O ranges or non-system RAM i.e. for which
7170 * !pfn_valid(pfn).
7171 *
7172 * We are mapping kernel-allocated memory (memory we manage ourselves)
7173 * which would more ideally be mapped using vm_insert_page() or a
7174 * similar mechanism, that is as a VM_MIXEDMAP mapping.
7175 *
7176 * However this won't work here, because:
7177 *
7178 * 1. It uses vma->vm_page_prot, but this field has not been completely
7179 * setup at the point of the f_op->mmp() hook, so we are unable to
7180 * indicate that this should be mapped CoW in order that the
7181 * mkwrite() hook can be invoked to make the first page R/W and the
7182 * rest R/O as desired.
7183 *
7184 * 2. Anything other than a VM_PFNMAP of valid PFNs will result in
7185 * vm_normal_page() returning a struct page * pointer, which means
7186 * vm_ops->page_mkwrite() will be invoked rather than
7187 * vm_ops->pfn_mkwrite(), and this means we have to set page->mapping
7188 * to work around retry logic in the fault handler, however this
7189 * field is no longer allowed to be used within struct page.
7190 *
7191 * 3. Having a struct page * made available in the fault logic also
7192 * means that the page gets put on the rmap and becomes
7193 * inappropriately accessible and subject to map and ref counting.
7194 *
7195 * Ideally we would have a mechanism that could explicitly express our
7196 * desires, but this is not currently the case, so we instead use
7197 * VM_PFNMAP.
7198 *
7199 * We manage the lifetime of these mappings with internal refcounts (see
7200 * perf_mmap_open() and perf_mmap_close()) so we ensure the lifetime of
7201 * this mapping is maintained correctly.
7202 */
7203 for (pagenum = 0; pagenum < nr_pages; pagenum++) {
7204 unsigned long va = vma->vm_start + PAGE_SIZE * pagenum;
7205 struct page *page = perf_mmap_to_page(rb,
7206 vma_start_pgoff(vma) + pagenum);
7207
7208 if (page == NULL) {
7209 err = -EINVAL;
7210 break;
7211 }
7212
7213 /* Map readonly, perf_mmap_pfn_mkwrite() called on write fault. */
7214 err = remap_pfn_range(vma, va, page_to_pfn(page), PAGE_SIZE,
7215 vm_get_page_prot(vma->vm_flags & ~VM_SHARED));
7216 if (err)
7217 break;
7218 }
7219
7220 #ifdef CONFIG_MMU
7221 /* Clear any partial mappings on error. */
7222 if (err)
7223 zap_vma_range(vma, vma->vm_start, nr_pages * PAGE_SIZE);
7224 #endif
7225
7226 return err;
7227 }
7228
perf_mmap_calc_limits(struct vm_area_struct * vma,long * user_extra,long * extra)7229 static bool perf_mmap_calc_limits(struct vm_area_struct *vma, long *user_extra, long *extra)
7230 {
7231 unsigned long user_locked, user_lock_limit, locked, lock_limit;
7232 struct user_struct *user = current_user();
7233
7234 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
7235 /* Increase the limit linearly with more CPUs */
7236 user_lock_limit *= num_online_cpus();
7237
7238 user_locked = atomic_long_read(&user->locked_vm);
7239
7240 /*
7241 * sysctl_perf_event_mlock may have changed, so that
7242 * user->locked_vm > user_lock_limit
7243 */
7244 if (user_locked > user_lock_limit)
7245 user_locked = user_lock_limit;
7246 user_locked += *user_extra;
7247
7248 if (user_locked > user_lock_limit) {
7249 /*
7250 * charge locked_vm until it hits user_lock_limit;
7251 * charge the rest from pinned_vm
7252 */
7253 *extra = user_locked - user_lock_limit;
7254 *user_extra -= *extra;
7255 }
7256
7257 lock_limit = rlimit(RLIMIT_MEMLOCK);
7258 lock_limit >>= PAGE_SHIFT;
7259 locked = atomic64_read(&vma->vm_mm->pinned_vm) + *extra;
7260
7261 return locked <= lock_limit || !perf_is_paranoid() || capable(CAP_IPC_LOCK);
7262 }
7263
perf_mmap_account(struct vm_area_struct * vma,long user_extra,long extra)7264 static void perf_mmap_account(struct vm_area_struct *vma, long user_extra, long extra)
7265 {
7266 struct user_struct *user = current_user();
7267
7268 atomic_long_add(user_extra, &user->locked_vm);
7269 atomic64_add(extra, &vma->vm_mm->pinned_vm);
7270 }
7271
perf_mmap_unaccount(struct vm_area_struct * vma,struct perf_buffer * rb)7272 static void perf_mmap_unaccount(struct vm_area_struct *vma, struct perf_buffer *rb)
7273 {
7274 struct user_struct *user = rb->mmap_user;
7275
7276 atomic_long_sub((perf_data_size(rb) >> PAGE_SHIFT) + 1 - rb->mmap_locked,
7277 &user->locked_vm);
7278 atomic64_sub(rb->mmap_locked, &vma->vm_mm->pinned_vm);
7279 }
7280
perf_mmap_rb(struct vm_area_struct * vma,struct perf_event * event,unsigned long nr_pages)7281 static int perf_mmap_rb(struct vm_area_struct *vma, struct perf_event *event,
7282 unsigned long nr_pages)
7283 {
7284 long extra = 0, user_extra = nr_pages;
7285 struct perf_buffer *rb;
7286 int rb_flags = 0;
7287
7288 nr_pages -= 1;
7289
7290 /*
7291 * If we have rb pages ensure they're a power-of-two number, so we
7292 * can do bitmasks instead of modulo.
7293 */
7294 if (nr_pages != 0 && !is_power_of_2(nr_pages))
7295 return -EINVAL;
7296
7297 WARN_ON_ONCE(event->ctx->parent_ctx);
7298
7299 if (event->rb) {
7300 if (data_page_nr(event->rb) != nr_pages)
7301 return -EINVAL;
7302
7303 /*
7304 * If this event doesn't have mmap_count, we're attempting to
7305 * create an alias of another event's mmap(); this would mean
7306 * both events will end up scribbling the same user_page;
7307 * which makes no sense.
7308 */
7309 if (!refcount_read(&event->mmap_count))
7310 return -EBUSY;
7311
7312 if (refcount_inc_not_zero(&event->rb->mmap_count)) {
7313 /*
7314 * Success -- managed to mmap() the same buffer
7315 * multiple times.
7316 */
7317 perf_mmap_account(vma, user_extra, extra);
7318 refcount_inc(&event->mmap_count);
7319 return 0;
7320 }
7321
7322 /*
7323 * Raced against perf_mmap_close()'s
7324 * refcount_dec_and_mutex_lock() remove the
7325 * event and continue as if !event->rb
7326 */
7327 ring_buffer_attach(event, NULL);
7328 }
7329
7330 if (!perf_mmap_calc_limits(vma, &user_extra, &extra))
7331 return -EPERM;
7332
7333 if (vma->vm_flags & VM_WRITE)
7334 rb_flags |= RING_BUFFER_WRITABLE;
7335
7336 rb = rb_alloc(nr_pages,
7337 event->attr.watermark ? event->attr.wakeup_watermark : 0,
7338 event->cpu, rb_flags);
7339
7340 if (!rb)
7341 return -ENOMEM;
7342
7343 rb->mmap_locked = extra;
7344
7345 ring_buffer_attach(event, rb);
7346
7347 perf_event_update_time(event);
7348 perf_event_init_userpage(event);
7349 perf_event_update_userpage(event);
7350
7351 perf_mmap_account(vma, user_extra, extra);
7352 refcount_set(&event->mmap_count, 1);
7353
7354 return 0;
7355 }
7356
perf_mmap_aux(struct vm_area_struct * vma,struct perf_event * event,unsigned long nr_pages)7357 static int perf_mmap_aux(struct vm_area_struct *vma, struct perf_event *event,
7358 unsigned long nr_pages)
7359 {
7360 const pgoff_t pgoff_start = vma_start_pgoff(vma);
7361 long extra = 0, user_extra = nr_pages;
7362 u64 aux_offset, aux_size;
7363 struct perf_buffer *rb;
7364 int ret, rb_flags = 0;
7365
7366 rb = event->rb;
7367 if (!rb)
7368 return -EINVAL;
7369
7370 guard(mutex)(&rb->aux_mutex);
7371
7372 /*
7373 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
7374 * mapped, all subsequent mappings should have the same size
7375 * and offset. Must be above the normal perf buffer.
7376 */
7377 aux_offset = READ_ONCE(rb->user_page->aux_offset);
7378 aux_size = READ_ONCE(rb->user_page->aux_size);
7379
7380 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
7381 return -EINVAL;
7382
7383 if (aux_offset != pgoff_start << PAGE_SHIFT)
7384 return -EINVAL;
7385
7386 /* already mapped with a different offset */
7387 if (rb_has_aux(rb) && rb->aux_pgoff != pgoff_start)
7388 return -EINVAL;
7389
7390 if (aux_size != nr_pages * PAGE_SIZE)
7391 return -EINVAL;
7392
7393 /* already mapped with a different size */
7394 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
7395 return -EINVAL;
7396
7397 if (!is_power_of_2(nr_pages))
7398 return -EINVAL;
7399
7400 if (!refcount_inc_not_zero(&rb->mmap_count))
7401 return -EINVAL;
7402
7403 if (rb_has_aux(rb)) {
7404 refcount_inc(&rb->aux_mmap_count);
7405
7406 } else {
7407 if (!perf_mmap_calc_limits(vma, &user_extra, &extra)) {
7408 refcount_dec(&rb->mmap_count);
7409 return -EPERM;
7410 }
7411
7412 WARN_ON(!rb && event->rb);
7413
7414 if (vma->vm_flags & VM_WRITE)
7415 rb_flags |= RING_BUFFER_WRITABLE;
7416
7417 ret = rb_alloc_aux(rb, event, pgoff_start, nr_pages,
7418 event->attr.aux_watermark, rb_flags);
7419 if (ret) {
7420 refcount_dec(&rb->mmap_count);
7421 return ret;
7422 }
7423
7424 refcount_set(&rb->aux_mmap_count, 1);
7425 rb->aux_mmap_locked = extra;
7426 }
7427
7428 perf_mmap_account(vma, user_extra, extra);
7429 refcount_inc(&event->mmap_count);
7430
7431 return 0;
7432 }
7433
perf_mmap(struct file * file,struct vm_area_struct * vma)7434 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
7435 {
7436 struct perf_event *event = file->private_data;
7437 unsigned long vma_size, nr_pages;
7438 mapped_f mapped;
7439 int ret;
7440
7441 /*
7442 * Don't allow mmap() of inherited per-task counters. This would
7443 * create a performance issue due to all children writing to the
7444 * same rb.
7445 */
7446 if (event->cpu == -1 && event->attr.inherit)
7447 return -EINVAL;
7448
7449 if (!(vma->vm_flags & VM_SHARED))
7450 return -EINVAL;
7451
7452 ret = security_perf_event_read(event);
7453 if (ret)
7454 return ret;
7455
7456 vma_size = vma->vm_end - vma->vm_start;
7457 nr_pages = vma_size / PAGE_SIZE;
7458
7459 if (nr_pages > INT_MAX)
7460 return -ENOMEM;
7461
7462 if (vma_size != PAGE_SIZE * nr_pages)
7463 return -EINVAL;
7464
7465 scoped_guard (mutex, &event->mmap_mutex) {
7466 /*
7467 * This relies on __pmu_detach_event() taking mmap_mutex after marking
7468 * the event REVOKED. Either we observe the state, or __pmu_detach_event()
7469 * will detach the rb created here.
7470 */
7471 if (event->state <= PERF_EVENT_STATE_REVOKED)
7472 return -ENODEV;
7473
7474 if (!vma_start_pgoff(vma))
7475 ret = perf_mmap_rb(vma, event, nr_pages);
7476 else
7477 ret = perf_mmap_aux(vma, event, nr_pages);
7478 if (ret)
7479 return ret;
7480
7481 /*
7482 * Since pinned accounting is per vm we cannot allow fork() to copy our
7483 * vma.
7484 */
7485 vm_flags_set(vma, VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP);
7486 vma->vm_ops = &perf_mmap_vmops;
7487
7488 mapped = get_mapped(event, event_mapped);
7489 if (mapped)
7490 mapped(event, vma->vm_mm);
7491
7492 /*
7493 * Try to map it into the page table. On fail undo the above,
7494 * as the callsite expects full cleanup in this case and
7495 * therefore does not invoke vmops::close().
7496 */
7497 ret = map_range(event->rb, vma);
7498 if (likely(!ret))
7499 return 0;
7500
7501 /* Error path */
7502
7503 /*
7504 * If this is the first mmap(), then event->mmap_count should
7505 * be stable at 1. It is only modified by:
7506 * perf_mmap_{open,close}() and perf_mmap().
7507 *
7508 * The former are not possible because this mmap() hasn't been
7509 * successful yet, and the latter is serialized by
7510 * event->mmap_mutex which we still hold (note that mmap_lock
7511 * is not strictly sufficient here, because the event fd can
7512 * be passed to another process through trivial means like
7513 * fork(), leading to concurrent mmap() from different mm).
7514 *
7515 * Make sure to remove event->rb before releasing
7516 * event->mmap_mutex, such that any concurrent mmap() will not
7517 * attempt use this failed buffer.
7518 */
7519 if (refcount_read(&event->mmap_count) == 1) {
7520 /*
7521 * Minimal perf_mmap_close(); there can't be AUX or
7522 * other events on account of this being the first.
7523 */
7524 mapped = get_mapped(event, event_unmapped);
7525 if (mapped)
7526 mapped(event, vma->vm_mm);
7527 perf_mmap_unaccount(vma, event->rb);
7528 ring_buffer_attach(event, NULL); /* drops last rb->refcount */
7529 refcount_set(&event->mmap_count, 0);
7530 return ret;
7531 }
7532
7533 /*
7534 * Otherwise this is an already existing buffer, and there is
7535 * no race vs first exposure, so fall-through and call
7536 * perf_mmap_close().
7537 */
7538 }
7539
7540 perf_mmap_close(vma);
7541 return ret;
7542 }
7543
perf_fasync(int fd,struct file * filp,int on)7544 static int perf_fasync(int fd, struct file *filp, int on)
7545 {
7546 struct inode *inode = file_inode(filp);
7547 struct perf_event *event = filp->private_data;
7548 int retval;
7549
7550 if (event->state <= PERF_EVENT_STATE_REVOKED)
7551 return -ENODEV;
7552
7553 inode_lock(inode);
7554 retval = fasync_helper(fd, filp, on, &event->fasync);
7555 inode_unlock(inode);
7556
7557 if (retval < 0)
7558 return retval;
7559
7560 return 0;
7561 }
7562
perf_show_fdinfo(struct seq_file * m,struct file * f)7563 static void perf_show_fdinfo(struct seq_file *m, struct file *f)
7564 {
7565 struct perf_event *event = f->private_data;
7566 struct perf_event_context *ctx;
7567 struct mutex *child_mutex;
7568
7569 ctx = perf_event_ctx_lock(event);
7570 child_mutex = event->parent ? &event->parent->child_mutex : &event->child_mutex;
7571 mutex_lock(child_mutex);
7572
7573 seq_printf(m, "perf_event_attr.type:\t%u\n", event->orig_type);
7574 if (event->pmu)
7575 seq_printf(m, "pmu_type:\t%u\n", event->pmu->type);
7576 seq_printf(m, "perf_event_attr.config:\t0x%llx\n", (unsigned long long)event->attr.config);
7577 seq_printf(m, "perf_event_attr.config1:\t0x%llx\n",
7578 (unsigned long long)event->attr.config1);
7579 seq_printf(m, "perf_event_attr.config2:\t0x%llx\n",
7580 (unsigned long long)event->attr.config2);
7581 seq_printf(m, "perf_event_attr.config3:\t0x%llx\n",
7582 (unsigned long long)event->attr.config3);
7583 seq_printf(m, "perf_event_attr.config4:\t0x%llx\n",
7584 (unsigned long long)event->attr.config4);
7585
7586 mutex_unlock(child_mutex);
7587 perf_event_ctx_unlock(event, ctx);
7588 }
7589
7590 static const struct file_operations perf_fops = {
7591 .release = perf_release,
7592 .read = perf_read,
7593 .poll = perf_poll,
7594 .unlocked_ioctl = perf_ioctl,
7595 .compat_ioctl = perf_compat_ioctl,
7596 .mmap = perf_mmap,
7597 .fasync = perf_fasync,
7598 .show_fdinfo = perf_show_fdinfo,
7599 };
7600
7601 /*
7602 * Perf event wakeup
7603 *
7604 * If there's data, ensure we set the poll() state and publish everything
7605 * to user-space before waking everybody up.
7606 */
7607
perf_event_wakeup(struct perf_event * event)7608 void perf_event_wakeup(struct perf_event *event)
7609 {
7610 ring_buffer_wakeup(event);
7611
7612 if (event->pending_kill) {
7613 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
7614 event->pending_kill = 0;
7615 }
7616 }
7617
perf_sigtrap(struct perf_event * event)7618 static void perf_sigtrap(struct perf_event *event)
7619 {
7620 /*
7621 * Both perf_pending_task() and perf_pending_irq() can race with the
7622 * task exiting.
7623 */
7624 if (current->flags & PF_EXITING)
7625 return;
7626
7627 /*
7628 * We'd expect this to only occur if the irq_work is delayed and either
7629 * ctx->task or current has changed in the meantime. This can be the
7630 * case on architectures that do not implement arch_irq_work_raise().
7631 */
7632 if (WARN_ON_ONCE(event->ctx->task != current))
7633 return;
7634
7635 send_sig_perf((void __user *)event->pending_addr,
7636 event->orig_type, event->attr.sig_data);
7637 }
7638
7639 /*
7640 * Deliver the pending work in-event-context or follow the context.
7641 */
__perf_pending_disable(struct perf_event * event)7642 static void __perf_pending_disable(struct perf_event *event)
7643 {
7644 int cpu = READ_ONCE(event->oncpu);
7645
7646 /*
7647 * If the event isn't running; we done. event_sched_out() will have
7648 * taken care of things.
7649 */
7650 if (cpu < 0)
7651 return;
7652
7653 /*
7654 * Yay, we hit home and are in the context of the event.
7655 */
7656 if (cpu == smp_processor_id()) {
7657 if (event->pending_disable) {
7658 event->pending_disable = 0;
7659 perf_event_disable_local(event);
7660 }
7661 return;
7662 }
7663
7664 /*
7665 * CPU-A CPU-B
7666 *
7667 * perf_event_disable_inatomic()
7668 * @pending_disable = 1;
7669 * irq_work_queue();
7670 *
7671 * sched-out
7672 * @pending_disable = 0;
7673 *
7674 * sched-in
7675 * perf_event_disable_inatomic()
7676 * @pending_disable = 1;
7677 * irq_work_queue(); // FAILS
7678 *
7679 * irq_work_run()
7680 * perf_pending_disable()
7681 *
7682 * But the event runs on CPU-B and wants disabling there.
7683 */
7684 irq_work_queue_on(&event->pending_disable_irq, cpu);
7685 }
7686
perf_pending_disable(struct irq_work * entry)7687 static void perf_pending_disable(struct irq_work *entry)
7688 {
7689 struct perf_event *event = container_of(entry, struct perf_event, pending_disable_irq);
7690 int rctx;
7691
7692 /*
7693 * If we 'fail' here, that's OK, it means recursion is already disabled
7694 * and we won't recurse 'further'.
7695 */
7696 rctx = perf_swevent_get_recursion_context();
7697 __perf_pending_disable(event);
7698 if (rctx >= 0)
7699 perf_swevent_put_recursion_context(rctx);
7700 }
7701
perf_pending_irq(struct irq_work * entry)7702 static void perf_pending_irq(struct irq_work *entry)
7703 {
7704 struct perf_event *event = container_of(entry, struct perf_event, pending_irq);
7705 int rctx;
7706
7707 /*
7708 * If we 'fail' here, that's OK, it means recursion is already disabled
7709 * and we won't recurse 'further'.
7710 */
7711 rctx = perf_swevent_get_recursion_context();
7712
7713 /*
7714 * The wakeup isn't bound to the context of the event -- it can happen
7715 * irrespective of where the event is.
7716 */
7717 if (event->pending_wakeup) {
7718 event->pending_wakeup = 0;
7719 perf_event_wakeup(event);
7720 }
7721
7722 if (rctx >= 0)
7723 perf_swevent_put_recursion_context(rctx);
7724 }
7725
perf_pending_task(struct callback_head * head)7726 static void perf_pending_task(struct callback_head *head)
7727 {
7728 struct perf_event *event = container_of(head, struct perf_event, pending_task);
7729 int rctx;
7730
7731 /*
7732 * If we 'fail' here, that's OK, it means recursion is already disabled
7733 * and we won't recurse 'further'.
7734 */
7735 rctx = perf_swevent_get_recursion_context();
7736
7737 if (event->pending_work) {
7738 event->pending_work = 0;
7739 perf_sigtrap(event);
7740 local_dec(&event->ctx->nr_no_switch_fast);
7741 }
7742 put_event(event);
7743
7744 if (rctx >= 0)
7745 perf_swevent_put_recursion_context(rctx);
7746 }
7747
7748 #ifdef CONFIG_GUEST_PERF_EVENTS
7749 struct perf_guest_info_callbacks __rcu *perf_guest_cbs;
7750
7751 DEFINE_STATIC_CALL_RET0(__perf_guest_state, *perf_guest_cbs->state);
7752 DEFINE_STATIC_CALL_RET0(__perf_guest_get_ip, *perf_guest_cbs->get_ip);
7753 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr);
7754 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_mediated_pmi, *perf_guest_cbs->handle_mediated_pmi);
7755
perf_register_guest_info_callbacks(struct perf_guest_info_callbacks * cbs)7756 void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
7757 {
7758 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs)))
7759 return;
7760
7761 rcu_assign_pointer(perf_guest_cbs, cbs);
7762 static_call_update(__perf_guest_state, cbs->state);
7763 static_call_update(__perf_guest_get_ip, cbs->get_ip);
7764
7765 /* Implementing ->handle_intel_pt_intr is optional. */
7766 if (cbs->handle_intel_pt_intr)
7767 static_call_update(__perf_guest_handle_intel_pt_intr,
7768 cbs->handle_intel_pt_intr);
7769
7770 if (cbs->handle_mediated_pmi)
7771 static_call_update(__perf_guest_handle_mediated_pmi,
7772 cbs->handle_mediated_pmi);
7773 }
7774 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
7775
perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks * cbs)7776 void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
7777 {
7778 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs) != cbs))
7779 return;
7780
7781 rcu_assign_pointer(perf_guest_cbs, NULL);
7782 static_call_update(__perf_guest_state, (void *)&__static_call_return0);
7783 static_call_update(__perf_guest_get_ip, (void *)&__static_call_return0);
7784 static_call_update(__perf_guest_handle_intel_pt_intr, (void *)&__static_call_return0);
7785 static_call_update(__perf_guest_handle_mediated_pmi, (void *)&__static_call_return0);
7786 synchronize_rcu();
7787 }
7788 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
7789 #endif
7790
should_sample_guest(struct perf_event * event)7791 static bool should_sample_guest(struct perf_event *event)
7792 {
7793 return !event->attr.exclude_guest && perf_guest_state();
7794 }
7795
perf_misc_flags(struct perf_event * event,struct pt_regs * regs)7796 unsigned long perf_misc_flags(struct perf_event *event,
7797 struct pt_regs *regs)
7798 {
7799 if (should_sample_guest(event))
7800 return perf_arch_guest_misc_flags(regs);
7801
7802 return perf_arch_misc_flags(regs);
7803 }
7804
perf_instruction_pointer(struct perf_event * event,struct pt_regs * regs)7805 unsigned long perf_instruction_pointer(struct perf_event *event,
7806 struct pt_regs *regs)
7807 {
7808 /*
7809 * Hardware skid can lead to a scenario where a PMI is
7810 * delivered after the CPU has already entered kernel mode.
7811 * In that case, user-space sampling must not expose kernel
7812 * register state.
7813 */
7814 if (should_sample_guest(event)) {
7815 return event->attr.exclude_kernel &&
7816 !(perf_guest_state() & PERF_GUEST_USER) ?
7817 0 : perf_guest_get_ip();
7818 }
7819
7820 return event->attr.exclude_kernel && !user_mode(regs) ?
7821 0 : perf_arch_instruction_pointer(regs);
7822 }
7823
7824 static void
perf_output_sample_regs(struct perf_output_handle * handle,struct pt_regs * regs,u64 mask)7825 perf_output_sample_regs(struct perf_output_handle *handle,
7826 struct pt_regs *regs, u64 mask)
7827 {
7828 int bit;
7829 DECLARE_BITMAP(_mask, 64);
7830
7831 bitmap_from_u64(_mask, mask);
7832 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
7833 u64 val;
7834
7835 val = perf_reg_value(regs, bit);
7836 perf_output_put(handle, val);
7837 }
7838 }
7839
perf_sample_regs_user(struct perf_regs * regs_user,struct pt_regs * regs)7840 static void perf_sample_regs_user(struct perf_regs *regs_user,
7841 struct pt_regs *regs)
7842 {
7843 if (user_mode(regs)) {
7844 regs_user->abi = perf_reg_abi(current);
7845 regs_user->regs = regs;
7846 } else if (is_user_task(current)) {
7847 perf_get_regs_user(regs_user, regs);
7848 } else {
7849 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
7850 regs_user->regs = NULL;
7851 }
7852 }
7853
perf_sample_regs_intr(struct perf_regs * regs_intr,struct pt_regs * regs,bool exclude_kernel)7854 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
7855 struct pt_regs *regs,
7856 bool exclude_kernel)
7857 {
7858 /*
7859 * Hardware skid can lead to a scenario where a PMI is
7860 * delivered after the CPU has already entered kernel mode.
7861 * In that case, user-space sampling must not expose kernel
7862 * register state.
7863 */
7864 if (exclude_kernel && !user_mode(regs)) {
7865 regs_intr->abi = PERF_SAMPLE_REGS_ABI_NONE;
7866 regs_intr->regs = NULL;
7867 } else {
7868 regs_intr->regs = regs;
7869 regs_intr->abi = perf_reg_abi(current);
7870 }
7871 }
7872
7873
7874 /*
7875 * Get remaining task size from user stack pointer.
7876 *
7877 * It'd be better to take stack vma map and limit this more
7878 * precisely, but there's no way to get it safely under interrupt,
7879 * so using TASK_SIZE as limit.
7880 */
perf_ustack_task_size(struct pt_regs * regs)7881 static u64 perf_ustack_task_size(struct pt_regs *regs)
7882 {
7883 unsigned long addr = perf_user_stack_pointer(regs);
7884
7885 if (!addr || addr >= TASK_SIZE)
7886 return 0;
7887
7888 return TASK_SIZE - addr;
7889 }
7890
7891 static u16
perf_sample_ustack_size(u16 stack_size,u16 header_size,struct pt_regs * regs)7892 perf_sample_ustack_size(u16 stack_size, u16 header_size,
7893 struct pt_regs *regs)
7894 {
7895 u64 task_size;
7896
7897 /* No regs, no stack pointer, no dump. */
7898 if (!regs)
7899 return 0;
7900
7901 /* No mm, no stack, no dump. */
7902 if (!current->mm)
7903 return 0;
7904
7905 /*
7906 * Check if we fit in with the requested stack size into the:
7907 * - TASK_SIZE
7908 * If we don't, we limit the size to the TASK_SIZE.
7909 *
7910 * - remaining sample size
7911 * If we don't, we customize the stack size to
7912 * fit in to the remaining sample size.
7913 */
7914
7915 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
7916 stack_size = min(stack_size, (u16) task_size);
7917
7918 /* Current header size plus static size and dynamic size. */
7919 header_size += 2 * sizeof(u64);
7920
7921 /* Do we fit in with the current stack dump size? */
7922 if ((u16) (header_size + stack_size) < header_size) {
7923 /*
7924 * If we overflow the maximum size for the sample,
7925 * we customize the stack dump size to fit in.
7926 */
7927 stack_size = USHRT_MAX - header_size - sizeof(u64);
7928 stack_size = round_up(stack_size, sizeof(u64));
7929 }
7930
7931 return stack_size;
7932 }
7933
7934 static void
perf_output_sample_ustack(struct perf_output_handle * handle,u64 dump_size,struct pt_regs * regs)7935 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
7936 struct pt_regs *regs)
7937 {
7938 /* Case of a kernel thread, nothing to dump */
7939 if (!regs) {
7940 u64 size = 0;
7941 perf_output_put(handle, size);
7942 } else {
7943 unsigned long sp;
7944 unsigned int rem;
7945 u64 dyn_size;
7946
7947 /*
7948 * We dump:
7949 * static size
7950 * - the size requested by user or the best one we can fit
7951 * in to the sample max size
7952 * data
7953 * - user stack dump data
7954 * dynamic size
7955 * - the actual dumped size
7956 */
7957
7958 /* Static size. */
7959 perf_output_put(handle, dump_size);
7960
7961 /* Data. */
7962 sp = perf_user_stack_pointer(regs);
7963 rem = __output_copy_user(handle, (void *) sp, dump_size);
7964 dyn_size = dump_size - rem;
7965
7966 perf_output_skip(handle, rem);
7967
7968 /* Dynamic size. */
7969 perf_output_put(handle, dyn_size);
7970 }
7971 }
7972
perf_prepare_sample_aux(struct perf_event * event,struct perf_sample_data * data,size_t size)7973 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
7974 struct perf_sample_data *data,
7975 size_t size)
7976 {
7977 struct perf_event *sampler = event->aux_event;
7978 struct perf_buffer *rb;
7979
7980 data->aux_size = 0;
7981
7982 if (!sampler)
7983 goto out;
7984
7985 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
7986 goto out;
7987
7988 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
7989 goto out;
7990
7991 rb = ring_buffer_get(sampler);
7992 if (!rb)
7993 goto out;
7994
7995 /*
7996 * If this is an NMI hit inside sampling code, don't take
7997 * the sample. See also perf_aux_sample_output().
7998 */
7999 if (READ_ONCE(rb->aux_in_sampling)) {
8000 data->aux_size = 0;
8001 } else {
8002 size = min_t(size_t, size, perf_aux_size(rb));
8003 data->aux_size = ALIGN(size, sizeof(u64));
8004 }
8005 ring_buffer_put(rb);
8006
8007 out:
8008 return data->aux_size;
8009 }
8010
perf_pmu_snapshot_aux(struct perf_buffer * rb,struct perf_event * event,struct perf_output_handle * handle,unsigned long size)8011 static long perf_pmu_snapshot_aux(struct perf_buffer *rb,
8012 struct perf_event *event,
8013 struct perf_output_handle *handle,
8014 unsigned long size)
8015 {
8016 unsigned long flags;
8017 long ret;
8018
8019 /*
8020 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
8021 * paths. If we start calling them in NMI context, they may race with
8022 * the IRQ ones, that is, for example, re-starting an event that's just
8023 * been stopped, which is why we're using a separate callback that
8024 * doesn't change the event state.
8025 *
8026 * IRQs need to be disabled to prevent IPIs from racing with us.
8027 */
8028 local_irq_save(flags);
8029 /*
8030 * Guard against NMI hits inside the critical section;
8031 * see also perf_prepare_sample_aux().
8032 */
8033 WRITE_ONCE(rb->aux_in_sampling, 1);
8034 barrier();
8035
8036 ret = event->pmu->snapshot_aux(event, handle, size);
8037
8038 barrier();
8039 WRITE_ONCE(rb->aux_in_sampling, 0);
8040 local_irq_restore(flags);
8041
8042 return ret;
8043 }
8044
perf_aux_sample_output(struct perf_event * event,struct perf_output_handle * handle,struct perf_sample_data * data)8045 static void perf_aux_sample_output(struct perf_event *event,
8046 struct perf_output_handle *handle,
8047 struct perf_sample_data *data)
8048 {
8049 struct perf_event *sampler = event->aux_event;
8050 struct perf_buffer *rb;
8051 unsigned long pad;
8052 long size;
8053
8054 if (WARN_ON_ONCE(!sampler || !data->aux_size))
8055 return;
8056
8057 rb = ring_buffer_get(sampler);
8058 if (!rb)
8059 return;
8060
8061 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
8062
8063 /*
8064 * An error here means that perf_output_copy() failed (returned a
8065 * non-zero surplus that it didn't copy), which in its current
8066 * enlightened implementation is not possible. If that changes, we'd
8067 * like to know.
8068 */
8069 if (WARN_ON_ONCE(size < 0))
8070 goto out_put;
8071
8072 /*
8073 * The pad comes from ALIGN()ing data->aux_size up to u64 in
8074 * perf_prepare_sample_aux(), so should not be more than that.
8075 */
8076 pad = data->aux_size - size;
8077 if (WARN_ON_ONCE(pad >= sizeof(u64)))
8078 pad = 8;
8079
8080 if (pad) {
8081 u64 zero = 0;
8082 perf_output_copy(handle, &zero, pad);
8083 }
8084
8085 out_put:
8086 ring_buffer_put(rb);
8087 }
8088
8089 /*
8090 * A set of common sample data types saved even for non-sample records
8091 * when event->attr.sample_id_all is set.
8092 */
8093 #define PERF_SAMPLE_ID_ALL (PERF_SAMPLE_TID | PERF_SAMPLE_TIME | \
8094 PERF_SAMPLE_ID | PERF_SAMPLE_STREAM_ID | \
8095 PERF_SAMPLE_CPU | PERF_SAMPLE_IDENTIFIER)
8096
__perf_event_header__init_id(struct perf_sample_data * data,struct perf_event * event,u64 sample_type)8097 static void __perf_event_header__init_id(struct perf_sample_data *data,
8098 struct perf_event *event,
8099 u64 sample_type)
8100 {
8101 data->type = event->attr.sample_type;
8102 data->sample_flags |= data->type & PERF_SAMPLE_ID_ALL;
8103
8104 if (sample_type & PERF_SAMPLE_TID) {
8105 /* namespace issues */
8106 data->tid_entry.pid = perf_event_pid(event, current);
8107 data->tid_entry.tid = perf_event_tid(event, current);
8108 }
8109
8110 if (sample_type & PERF_SAMPLE_TIME)
8111 data->time = perf_event_clock(event);
8112
8113 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
8114 data->id = primary_event_id(event);
8115
8116 if (sample_type & PERF_SAMPLE_STREAM_ID)
8117 data->stream_id = event->id;
8118
8119 if (sample_type & PERF_SAMPLE_CPU) {
8120 data->cpu_entry.cpu = raw_smp_processor_id();
8121 data->cpu_entry.reserved = 0;
8122 }
8123 }
8124
perf_event_header__init_id(struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event)8125 void perf_event_header__init_id(struct perf_event_header *header,
8126 struct perf_sample_data *data,
8127 struct perf_event *event)
8128 {
8129 if (event->attr.sample_id_all) {
8130 header->size += event->id_header_size;
8131 __perf_event_header__init_id(data, event, event->attr.sample_type);
8132 }
8133 }
8134
__perf_event__output_id_sample(struct perf_output_handle * handle,struct perf_sample_data * data)8135 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
8136 struct perf_sample_data *data)
8137 {
8138 u64 sample_type = data->type;
8139
8140 if (sample_type & PERF_SAMPLE_TID)
8141 perf_output_put(handle, data->tid_entry);
8142
8143 if (sample_type & PERF_SAMPLE_TIME)
8144 perf_output_put(handle, data->time);
8145
8146 if (sample_type & PERF_SAMPLE_ID)
8147 perf_output_put(handle, data->id);
8148
8149 if (sample_type & PERF_SAMPLE_STREAM_ID)
8150 perf_output_put(handle, data->stream_id);
8151
8152 if (sample_type & PERF_SAMPLE_CPU)
8153 perf_output_put(handle, data->cpu_entry);
8154
8155 if (sample_type & PERF_SAMPLE_IDENTIFIER)
8156 perf_output_put(handle, data->id);
8157 }
8158
perf_event__output_id_sample(struct perf_event * event,struct perf_output_handle * handle,struct perf_sample_data * sample)8159 void perf_event__output_id_sample(struct perf_event *event,
8160 struct perf_output_handle *handle,
8161 struct perf_sample_data *sample)
8162 {
8163 if (event->attr.sample_id_all)
8164 __perf_event__output_id_sample(handle, sample);
8165 }
8166
perf_output_read_one(struct perf_output_handle * handle,struct perf_event * event,u64 enabled,u64 running)8167 static void perf_output_read_one(struct perf_output_handle *handle,
8168 struct perf_event *event,
8169 u64 enabled, u64 running)
8170 {
8171 u64 read_format = event->attr.read_format;
8172 u64 values[5];
8173 int n = 0;
8174
8175 values[n++] = perf_event_count(event, has_inherit_and_sample_read(&event->attr));
8176 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
8177 values[n++] = enabled +
8178 atomic64_read(&event->child_total_time_enabled);
8179 }
8180 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
8181 values[n++] = running +
8182 atomic64_read(&event->child_total_time_running);
8183 }
8184 if (read_format & PERF_FORMAT_ID)
8185 values[n++] = primary_event_id(event);
8186 if (read_format & PERF_FORMAT_LOST)
8187 values[n++] = atomic64_read(&event->lost_samples);
8188
8189 __output_copy(handle, values, n * sizeof(u64));
8190 }
8191
perf_output_read_group(struct perf_output_handle * handle,struct perf_event * event,u64 enabled,u64 running)8192 static void perf_output_read_group(struct perf_output_handle *handle,
8193 struct perf_event *event,
8194 u64 enabled, u64 running)
8195 {
8196 struct perf_event *leader = event->group_leader, *sub;
8197 u64 read_format = event->attr.read_format;
8198 unsigned long flags;
8199 u64 values[6];
8200 int n = 0;
8201 bool self = has_inherit_and_sample_read(&event->attr);
8202
8203 /*
8204 * Disabling interrupts avoids all counter scheduling
8205 * (context switches, timer based rotation and IPIs).
8206 */
8207 local_irq_save(flags);
8208
8209 values[n++] = 1 + leader->nr_siblings;
8210
8211 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
8212 values[n++] = enabled;
8213
8214 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
8215 values[n++] = running;
8216
8217 if ((leader != event) && !handle->skip_read)
8218 perf_pmu_read(leader);
8219
8220 values[n++] = perf_event_count(leader, self);
8221 if (read_format & PERF_FORMAT_ID)
8222 values[n++] = primary_event_id(leader);
8223 if (read_format & PERF_FORMAT_LOST)
8224 values[n++] = atomic64_read(&leader->lost_samples);
8225
8226 __output_copy(handle, values, n * sizeof(u64));
8227
8228 for_each_sibling_event(sub, leader) {
8229 n = 0;
8230
8231 if ((sub != event) && !handle->skip_read)
8232 perf_pmu_read(sub);
8233
8234 values[n++] = perf_event_count(sub, self);
8235 if (read_format & PERF_FORMAT_ID)
8236 values[n++] = primary_event_id(sub);
8237 if (read_format & PERF_FORMAT_LOST)
8238 values[n++] = atomic64_read(&sub->lost_samples);
8239
8240 __output_copy(handle, values, n * sizeof(u64));
8241 }
8242
8243 local_irq_restore(flags);
8244 }
8245
8246 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
8247 PERF_FORMAT_TOTAL_TIME_RUNNING)
8248
8249 /*
8250 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
8251 *
8252 * The problem is that its both hard and excessively expensive to iterate the
8253 * child list, not to mention that its impossible to IPI the children running
8254 * on another CPU, from interrupt/NMI context.
8255 *
8256 * Instead the combination of PERF_SAMPLE_READ and inherit will track per-thread
8257 * counts rather than attempting to accumulate some value across all children on
8258 * all cores.
8259 */
perf_output_read(struct perf_output_handle * handle,struct perf_event * event)8260 static void perf_output_read(struct perf_output_handle *handle,
8261 struct perf_event *event)
8262 {
8263 u64 enabled = 0, running = 0, now;
8264 u64 read_format = event->attr.read_format;
8265
8266 /*
8267 * Compute total_time_enabled, total_time_running based on snapshot
8268 * values taken when the event was last scheduled in.
8269 *
8270 * We cannot simply call update_context_time() because doing so would
8271 * lead to deadlock when called from NMI context.
8272 */
8273 if (read_format & PERF_FORMAT_TOTAL_TIMES)
8274 calc_timer_values(event, &now, &enabled, &running);
8275
8276 if (event->attr.read_format & PERF_FORMAT_GROUP)
8277 perf_output_read_group(handle, event, enabled, running);
8278 else
8279 perf_output_read_one(handle, event, enabled, running);
8280 }
8281
perf_output_sample(struct perf_output_handle * handle,struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event)8282 void perf_output_sample(struct perf_output_handle *handle,
8283 struct perf_event_header *header,
8284 struct perf_sample_data *data,
8285 struct perf_event *event)
8286 {
8287 u64 sample_type = data->type;
8288
8289 if (data->sample_flags & PERF_SAMPLE_READ)
8290 handle->skip_read = 1;
8291
8292 perf_output_put(handle, *header);
8293
8294 if (sample_type & PERF_SAMPLE_IDENTIFIER)
8295 perf_output_put(handle, data->id);
8296
8297 if (sample_type & PERF_SAMPLE_IP)
8298 perf_output_put(handle, data->ip);
8299
8300 if (sample_type & PERF_SAMPLE_TID)
8301 perf_output_put(handle, data->tid_entry);
8302
8303 if (sample_type & PERF_SAMPLE_TIME)
8304 perf_output_put(handle, data->time);
8305
8306 if (sample_type & PERF_SAMPLE_ADDR)
8307 perf_output_put(handle, data->addr);
8308
8309 if (sample_type & PERF_SAMPLE_ID)
8310 perf_output_put(handle, data->id);
8311
8312 if (sample_type & PERF_SAMPLE_STREAM_ID)
8313 perf_output_put(handle, data->stream_id);
8314
8315 if (sample_type & PERF_SAMPLE_CPU)
8316 perf_output_put(handle, data->cpu_entry);
8317
8318 if (sample_type & PERF_SAMPLE_PERIOD)
8319 perf_output_put(handle, data->period);
8320
8321 if (sample_type & PERF_SAMPLE_READ)
8322 perf_output_read(handle, event);
8323
8324 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
8325 int size = 1;
8326
8327 size += data->callchain->nr;
8328 size *= sizeof(u64);
8329 __output_copy(handle, data->callchain, size);
8330 }
8331
8332 if (sample_type & PERF_SAMPLE_RAW) {
8333 struct perf_raw_record *raw = data->raw;
8334
8335 if (raw) {
8336 struct perf_raw_frag *frag = &raw->frag;
8337
8338 perf_output_put(handle, raw->size);
8339 do {
8340 if (frag->copy) {
8341 __output_custom(handle, frag->copy,
8342 frag->data, frag->size);
8343 } else {
8344 __output_copy(handle, frag->data,
8345 frag->size);
8346 }
8347 if (perf_raw_frag_last(frag))
8348 break;
8349 frag = frag->next;
8350 } while (1);
8351 if (frag->pad)
8352 __output_skip(handle, NULL, frag->pad);
8353 } else {
8354 struct {
8355 u32 size;
8356 u32 data;
8357 } raw = {
8358 .size = sizeof(u32),
8359 .data = 0,
8360 };
8361 perf_output_put(handle, raw);
8362 }
8363 }
8364
8365 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
8366 if (data->br_stack) {
8367 size_t size;
8368
8369 size = data->br_stack->nr
8370 * sizeof(struct perf_branch_entry);
8371
8372 perf_output_put(handle, data->br_stack->nr);
8373 if (branch_sample_hw_index(event))
8374 perf_output_put(handle, data->br_stack->hw_idx);
8375 perf_output_copy(handle, data->br_stack->entries, size);
8376 /*
8377 * Add the extension space which is appended
8378 * right after the struct perf_branch_stack.
8379 */
8380 if (data->br_stack_cntr) {
8381 size = data->br_stack->nr * sizeof(u64);
8382 perf_output_copy(handle, data->br_stack_cntr, size);
8383 }
8384 } else {
8385 /*
8386 * we always store at least the value of nr
8387 */
8388 u64 nr = 0;
8389 perf_output_put(handle, nr);
8390 }
8391 }
8392
8393 if (sample_type & PERF_SAMPLE_REGS_USER) {
8394 u64 abi = data->regs_user.abi;
8395
8396 /*
8397 * If there are no regs to dump, notice it through
8398 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
8399 */
8400 perf_output_put(handle, abi);
8401
8402 if (abi) {
8403 u64 mask = event->attr.sample_regs_user;
8404 perf_output_sample_regs(handle,
8405 data->regs_user.regs,
8406 mask);
8407 }
8408 }
8409
8410 if (sample_type & PERF_SAMPLE_STACK_USER) {
8411 perf_output_sample_ustack(handle,
8412 data->stack_user_size,
8413 data->regs_user.regs);
8414 }
8415
8416 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
8417 perf_output_put(handle, data->weight.full);
8418
8419 if (sample_type & PERF_SAMPLE_DATA_SRC)
8420 perf_output_put(handle, data->data_src.val);
8421
8422 if (sample_type & PERF_SAMPLE_TRANSACTION)
8423 perf_output_put(handle, data->txn);
8424
8425 if (sample_type & PERF_SAMPLE_REGS_INTR) {
8426 u64 abi = data->regs_intr.abi;
8427 /*
8428 * If there are no regs to dump, notice it through
8429 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
8430 */
8431 perf_output_put(handle, abi);
8432
8433 if (abi) {
8434 u64 mask = event->attr.sample_regs_intr;
8435
8436 perf_output_sample_regs(handle,
8437 data->regs_intr.regs,
8438 mask);
8439 }
8440 }
8441
8442 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
8443 perf_output_put(handle, data->phys_addr);
8444
8445 if (sample_type & PERF_SAMPLE_CGROUP)
8446 perf_output_put(handle, data->cgroup);
8447
8448 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
8449 perf_output_put(handle, data->data_page_size);
8450
8451 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
8452 perf_output_put(handle, data->code_page_size);
8453
8454 if (sample_type & PERF_SAMPLE_AUX) {
8455 perf_output_put(handle, data->aux_size);
8456
8457 if (data->aux_size)
8458 perf_aux_sample_output(event, handle, data);
8459 }
8460
8461 if (!event->attr.watermark) {
8462 int wakeup_events = event->attr.wakeup_events;
8463
8464 if (wakeup_events) {
8465 struct perf_buffer *rb = handle->rb;
8466 int events = local_inc_return(&rb->events);
8467
8468 if (events >= wakeup_events) {
8469 local_sub(wakeup_events, &rb->events);
8470 local_inc(&rb->wakeup);
8471 }
8472 }
8473 }
8474 }
8475
perf_virt_to_phys(u64 virt)8476 static u64 perf_virt_to_phys(u64 virt)
8477 {
8478 u64 phys_addr = 0;
8479
8480 if (!virt)
8481 return 0;
8482
8483 if (virt >= TASK_SIZE) {
8484 /* If it's vmalloc()d memory, leave phys_addr as 0 */
8485 if (virt_addr_valid((void *)(uintptr_t)virt) &&
8486 !(virt >= VMALLOC_START && virt < VMALLOC_END))
8487 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
8488 } else {
8489 /*
8490 * Walking the pages tables for user address.
8491 * Interrupts are disabled, so it prevents any tear down
8492 * of the page tables.
8493 * Try IRQ-safe get_user_page_fast_only first.
8494 * If failed, leave phys_addr as 0.
8495 */
8496 if (is_user_task(current)) {
8497 struct page *p;
8498
8499 pagefault_disable();
8500 if (get_user_page_fast_only(virt, 0, &p)) {
8501 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
8502 put_page(p);
8503 }
8504 pagefault_enable();
8505 }
8506 }
8507
8508 return phys_addr;
8509 }
8510
8511 /*
8512 * Return the pagetable size of a given virtual address.
8513 */
perf_get_pgtable_size(struct mm_struct * mm,unsigned long addr)8514 static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
8515 {
8516 u64 size = 0;
8517
8518 #ifdef CONFIG_HAVE_GUP_FAST
8519 pgd_t *pgdp, pgd;
8520 p4d_t *p4dp, p4d;
8521 pud_t *pudp, pud;
8522 pmd_t *pmdp, pmd;
8523 pte_t *ptep, pte;
8524
8525 pgdp = pgd_offset(mm, addr);
8526 pgd = pgdp_get(pgdp);
8527 if (pgd_none(pgd))
8528 return 0;
8529
8530 if (pgd_leaf(pgd))
8531 return pgd_leaf_size(pgd);
8532
8533 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
8534 p4d = p4dp_get(p4dp);
8535 if (!p4d_present(p4d))
8536 return 0;
8537
8538 if (p4d_leaf(p4d))
8539 return p4d_leaf_size(p4d);
8540
8541 pudp = pud_offset_lockless(p4dp, p4d, addr);
8542 pud = pudp_get(pudp);
8543 if (!pud_present(pud))
8544 return 0;
8545
8546 if (pud_leaf(pud))
8547 return pud_leaf_size(pud);
8548
8549 pmdp = pmd_offset_lockless(pudp, pud, addr);
8550 again:
8551 pmd = pmdp_get_lockless(pmdp);
8552 if (!pmd_present(pmd))
8553 return 0;
8554
8555 if (pmd_leaf(pmd))
8556 return pmd_leaf_size(pmd);
8557
8558 ptep = pte_offset_map(&pmd, addr);
8559 if (!ptep)
8560 goto again;
8561
8562 pte = ptep_get_lockless(ptep);
8563 if (pte_present(pte))
8564 size = __pte_leaf_size(pmd, pte);
8565 pte_unmap(ptep);
8566 #endif /* CONFIG_HAVE_GUP_FAST */
8567
8568 return size;
8569 }
8570
perf_get_page_size(unsigned long addr)8571 static u64 perf_get_page_size(unsigned long addr)
8572 {
8573 struct mm_struct *mm;
8574 unsigned long flags;
8575 u64 size;
8576
8577 if (!addr)
8578 return 0;
8579
8580 /*
8581 * Software page-table walkers must disable IRQs,
8582 * which prevents any tear down of the page tables.
8583 */
8584 local_irq_save(flags);
8585
8586 mm = current->mm;
8587 if (!mm) {
8588 /*
8589 * For kernel threads and the like, use init_mm so that
8590 * we can find kernel memory.
8591 */
8592 mm = &init_mm;
8593 }
8594
8595 size = perf_get_pgtable_size(mm, addr);
8596
8597 local_irq_restore(flags);
8598
8599 return size;
8600 }
8601
8602 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
8603
8604 static struct unwind_work perf_unwind_work;
8605
8606 struct perf_callchain_entry *
perf_callchain(struct perf_event * event,struct pt_regs * regs)8607 perf_callchain(struct perf_event *event, struct pt_regs *regs)
8608 {
8609 bool kernel = !event->attr.exclude_callchain_kernel;
8610 bool user = !event->attr.exclude_callchain_user &&
8611 is_user_task(current);
8612 /* Disallow cross-task user callchains. */
8613 bool crosstask = event->ctx->task && event->ctx->task != current;
8614 bool defer_user = IS_ENABLED(CONFIG_UNWIND_USER) && user &&
8615 event->attr.defer_callchain;
8616 const u32 max_stack = event->attr.sample_max_stack;
8617 struct perf_callchain_entry *callchain;
8618 u64 defer_cookie;
8619
8620 if (!current->mm)
8621 user = false;
8622
8623 if (!kernel && !user)
8624 return &__empty_callchain;
8625
8626 if (!(user && defer_user && !crosstask &&
8627 unwind_deferred_request(&perf_unwind_work, &defer_cookie) >= 0))
8628 defer_cookie = 0;
8629
8630 callchain = get_perf_callchain(regs, kernel, user, max_stack,
8631 crosstask, true, defer_cookie);
8632
8633 return callchain ?: &__empty_callchain;
8634 }
8635
__cond_set(u64 flags,u64 s,u64 d)8636 static __always_inline u64 __cond_set(u64 flags, u64 s, u64 d)
8637 {
8638 return d * !!(flags & s);
8639 }
8640
perf_prepare_sample(struct perf_sample_data * data,struct perf_event * event,struct pt_regs * regs)8641 void perf_prepare_sample(struct perf_sample_data *data,
8642 struct perf_event *event,
8643 struct pt_regs *regs)
8644 {
8645 u64 sample_type = event->attr.sample_type;
8646 u64 filtered_sample_type;
8647
8648 /*
8649 * Add the sample flags that are dependent to others. And clear the
8650 * sample flags that have already been done by the PMU driver.
8651 */
8652 filtered_sample_type = sample_type;
8653 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_CODE_PAGE_SIZE,
8654 PERF_SAMPLE_IP);
8655 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_DATA_PAGE_SIZE |
8656 PERF_SAMPLE_PHYS_ADDR, PERF_SAMPLE_ADDR);
8657 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_STACK_USER,
8658 PERF_SAMPLE_REGS_USER);
8659 filtered_sample_type &= ~data->sample_flags;
8660
8661 if (filtered_sample_type == 0) {
8662 /* Make sure it has the correct data->type for output */
8663 data->type = event->attr.sample_type;
8664 return;
8665 }
8666
8667 __perf_event_header__init_id(data, event, filtered_sample_type);
8668
8669 if (filtered_sample_type & PERF_SAMPLE_IP) {
8670 data->ip = perf_instruction_pointer(event, regs);
8671 data->sample_flags |= PERF_SAMPLE_IP;
8672 }
8673
8674 if (filtered_sample_type & PERF_SAMPLE_CALLCHAIN)
8675 perf_sample_save_callchain(data, event, regs);
8676
8677 if (filtered_sample_type & PERF_SAMPLE_RAW) {
8678 data->raw = NULL;
8679 data->dyn_size += sizeof(u64);
8680 data->sample_flags |= PERF_SAMPLE_RAW;
8681 }
8682
8683 if (filtered_sample_type & PERF_SAMPLE_BRANCH_STACK) {
8684 data->br_stack = NULL;
8685 data->dyn_size += sizeof(u64);
8686 data->sample_flags |= PERF_SAMPLE_BRANCH_STACK;
8687 }
8688
8689 if (filtered_sample_type & PERF_SAMPLE_REGS_USER)
8690 perf_sample_regs_user(&data->regs_user, regs);
8691
8692 /*
8693 * It cannot use the filtered_sample_type here as REGS_USER can be set
8694 * by STACK_USER (using __cond_set() above) and we don't want to update
8695 * the dyn_size if it's not requested by users.
8696 */
8697 if ((sample_type & ~data->sample_flags) & PERF_SAMPLE_REGS_USER) {
8698 /* regs dump ABI info */
8699 int size = sizeof(u64);
8700
8701 if (data->regs_user.regs) {
8702 u64 mask = event->attr.sample_regs_user;
8703 size += hweight64(mask) * sizeof(u64);
8704 }
8705
8706 data->dyn_size += size;
8707 data->sample_flags |= PERF_SAMPLE_REGS_USER;
8708 }
8709
8710 if (filtered_sample_type & PERF_SAMPLE_STACK_USER) {
8711 /*
8712 * Either we need PERF_SAMPLE_STACK_USER bit to be always
8713 * processed as the last one or have additional check added
8714 * in case new sample type is added, because we could eat
8715 * up the rest of the sample size.
8716 */
8717 u16 stack_size = event->attr.sample_stack_user;
8718 u16 header_size = perf_sample_data_size(data, event);
8719 u16 size = sizeof(u64);
8720
8721 stack_size = perf_sample_ustack_size(stack_size, header_size,
8722 data->regs_user.regs);
8723
8724 /*
8725 * If there is something to dump, add space for the dump
8726 * itself and for the field that tells the dynamic size,
8727 * which is how many have been actually dumped.
8728 */
8729 if (stack_size)
8730 size += sizeof(u64) + stack_size;
8731
8732 data->stack_user_size = stack_size;
8733 data->dyn_size += size;
8734 data->sample_flags |= PERF_SAMPLE_STACK_USER;
8735 }
8736
8737 if (filtered_sample_type & PERF_SAMPLE_WEIGHT_TYPE) {
8738 data->weight.full = 0;
8739 data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE;
8740 }
8741
8742 if (filtered_sample_type & PERF_SAMPLE_DATA_SRC) {
8743 data->data_src.val = PERF_MEM_NA;
8744 data->sample_flags |= PERF_SAMPLE_DATA_SRC;
8745 }
8746
8747 if (filtered_sample_type & PERF_SAMPLE_TRANSACTION) {
8748 data->txn = 0;
8749 data->sample_flags |= PERF_SAMPLE_TRANSACTION;
8750 }
8751
8752 if (filtered_sample_type & PERF_SAMPLE_ADDR) {
8753 data->addr = 0;
8754 data->sample_flags |= PERF_SAMPLE_ADDR;
8755 }
8756
8757 if (filtered_sample_type & PERF_SAMPLE_REGS_INTR) {
8758 /* regs dump ABI info */
8759 int size = sizeof(u64);
8760
8761 perf_sample_regs_intr(&data->regs_intr, regs,
8762 event->attr.exclude_kernel);
8763
8764 if (data->regs_intr.regs) {
8765 u64 mask = event->attr.sample_regs_intr;
8766
8767 size += hweight64(mask) * sizeof(u64);
8768 }
8769
8770 data->dyn_size += size;
8771 data->sample_flags |= PERF_SAMPLE_REGS_INTR;
8772 }
8773
8774 if (filtered_sample_type & PERF_SAMPLE_PHYS_ADDR) {
8775 data->phys_addr = perf_virt_to_phys(data->addr);
8776 data->sample_flags |= PERF_SAMPLE_PHYS_ADDR;
8777 }
8778
8779 #ifdef CONFIG_CGROUP_PERF
8780 if (filtered_sample_type & PERF_SAMPLE_CGROUP) {
8781 struct cgroup *cgrp;
8782
8783 /* protected by RCU */
8784 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
8785 data->cgroup = cgroup_id(cgrp);
8786 data->sample_flags |= PERF_SAMPLE_CGROUP;
8787 }
8788 #endif
8789
8790 /*
8791 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't
8792 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr,
8793 * but the value will not dump to the userspace.
8794 */
8795 if (filtered_sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) {
8796 data->data_page_size = perf_get_page_size(data->addr);
8797 data->sample_flags |= PERF_SAMPLE_DATA_PAGE_SIZE;
8798 }
8799
8800 if (filtered_sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) {
8801 data->code_page_size = perf_get_page_size(data->ip);
8802 data->sample_flags |= PERF_SAMPLE_CODE_PAGE_SIZE;
8803 }
8804
8805 if (filtered_sample_type & PERF_SAMPLE_AUX) {
8806 u64 size;
8807 u16 header_size = perf_sample_data_size(data, event);
8808
8809 header_size += sizeof(u64); /* size */
8810
8811 /*
8812 * Given the 16bit nature of header::size, an AUX sample can
8813 * easily overflow it, what with all the preceding sample bits.
8814 * Make sure this doesn't happen by using up to U16_MAX bytes
8815 * per sample in total (rounded down to 8 byte boundary).
8816 */
8817 size = min_t(size_t, U16_MAX - header_size,
8818 event->attr.aux_sample_size);
8819 size = rounddown(size, 8);
8820 size = perf_prepare_sample_aux(event, data, size);
8821
8822 WARN_ON_ONCE(size + header_size > U16_MAX);
8823 data->dyn_size += size + sizeof(u64); /* size above */
8824 data->sample_flags |= PERF_SAMPLE_AUX;
8825 }
8826 }
8827
perf_prepare_header(struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event,struct pt_regs * regs)8828 void perf_prepare_header(struct perf_event_header *header,
8829 struct perf_sample_data *data,
8830 struct perf_event *event,
8831 struct pt_regs *regs)
8832 {
8833 header->type = PERF_RECORD_SAMPLE;
8834 header->size = perf_sample_data_size(data, event);
8835 header->misc = perf_misc_flags(event, regs);
8836
8837 /*
8838 * If you're adding more sample types here, you likely need to do
8839 * something about the overflowing header::size, like repurpose the
8840 * lowest 3 bits of size, which should be always zero at the moment.
8841 * This raises a more important question, do we really need 512k sized
8842 * samples and why, so good argumentation is in order for whatever you
8843 * do here next.
8844 */
8845 WARN_ON_ONCE(header->size & 7);
8846 }
8847
__perf_event_aux_pause(struct perf_event * event,bool pause)8848 static void __perf_event_aux_pause(struct perf_event *event, bool pause)
8849 {
8850 if (pause) {
8851 if (!event->hw.aux_paused) {
8852 event->hw.aux_paused = 1;
8853 event->pmu->stop(event, PERF_EF_PAUSE);
8854 }
8855 } else {
8856 if (event->hw.aux_paused) {
8857 event->hw.aux_paused = 0;
8858 event->pmu->start(event, PERF_EF_RESUME);
8859 }
8860 }
8861 }
8862
perf_event_aux_pause(struct perf_event * event,bool pause)8863 static void perf_event_aux_pause(struct perf_event *event, bool pause)
8864 {
8865 struct perf_buffer *rb;
8866
8867 if (WARN_ON_ONCE(!event))
8868 return;
8869
8870 rb = ring_buffer_get(event);
8871 if (!rb)
8872 return;
8873
8874 scoped_guard (irqsave) {
8875 /*
8876 * Guard against self-recursion here. Another event could trip
8877 * this same from NMI context.
8878 */
8879 if (READ_ONCE(rb->aux_in_pause_resume))
8880 break;
8881
8882 WRITE_ONCE(rb->aux_in_pause_resume, 1);
8883 barrier();
8884 __perf_event_aux_pause(event, pause);
8885 barrier();
8886 WRITE_ONCE(rb->aux_in_pause_resume, 0);
8887 }
8888 ring_buffer_put(rb);
8889 }
8890
8891 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))8892 __perf_event_output(struct perf_event *event,
8893 struct perf_sample_data *data,
8894 struct pt_regs *regs,
8895 int (*output_begin)(struct perf_output_handle *,
8896 struct perf_sample_data *,
8897 struct perf_event *,
8898 unsigned int))
8899 {
8900 struct perf_output_handle handle;
8901 struct perf_event_header header;
8902 int err;
8903
8904 /* protect the callchain buffers */
8905 rcu_read_lock();
8906
8907 perf_prepare_sample(data, event, regs);
8908 perf_prepare_header(&header, data, event, regs);
8909
8910 err = output_begin(&handle, data, event, header.size);
8911 if (err)
8912 goto exit;
8913
8914 perf_output_sample(&handle, &header, data, event);
8915
8916 perf_output_end(&handle);
8917
8918 exit:
8919 rcu_read_unlock();
8920 return err;
8921 }
8922
8923 void
perf_event_output_forward(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)8924 perf_event_output_forward(struct perf_event *event,
8925 struct perf_sample_data *data,
8926 struct pt_regs *regs)
8927 {
8928 __perf_event_output(event, data, regs, perf_output_begin_forward);
8929 }
8930
8931 void
perf_event_output_backward(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)8932 perf_event_output_backward(struct perf_event *event,
8933 struct perf_sample_data *data,
8934 struct pt_regs *regs)
8935 {
8936 __perf_event_output(event, data, regs, perf_output_begin_backward);
8937 }
8938
8939 int
perf_event_output(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)8940 perf_event_output(struct perf_event *event,
8941 struct perf_sample_data *data,
8942 struct pt_regs *regs)
8943 {
8944 return __perf_event_output(event, data, regs, perf_output_begin);
8945 }
8946
8947 /*
8948 * read event_id
8949 */
8950
8951 struct perf_read_event {
8952 struct perf_event_header header;
8953
8954 u32 pid;
8955 u32 tid;
8956 };
8957
8958 static void
perf_event_read_event(struct perf_event * event,struct task_struct * task)8959 perf_event_read_event(struct perf_event *event,
8960 struct task_struct *task)
8961 {
8962 struct perf_output_handle handle;
8963 struct perf_sample_data sample;
8964 struct perf_read_event read_event = {
8965 .header = {
8966 .type = PERF_RECORD_READ,
8967 .misc = 0,
8968 .size = sizeof(read_event) + event->read_size,
8969 },
8970 .pid = perf_event_pid(event, task),
8971 .tid = perf_event_tid(event, task),
8972 };
8973 int ret;
8974
8975 perf_event_header__init_id(&read_event.header, &sample, event);
8976 ret = perf_output_begin(&handle, &sample, event, read_event.header.size);
8977 if (ret)
8978 return;
8979
8980 perf_output_put(&handle, read_event);
8981 perf_output_read(&handle, event);
8982 perf_event__output_id_sample(event, &handle, &sample);
8983
8984 perf_output_end(&handle);
8985 }
8986
8987 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
8988
8989 static void
perf_iterate_ctx(struct perf_event_context * ctx,perf_iterate_f output,void * data,bool all)8990 perf_iterate_ctx(struct perf_event_context *ctx,
8991 perf_iterate_f output,
8992 void *data, bool all)
8993 {
8994 struct perf_event *event;
8995
8996 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
8997 if (!all) {
8998 if (event->state < PERF_EVENT_STATE_INACTIVE)
8999 continue;
9000 if (!event_filter_match(event))
9001 continue;
9002 }
9003
9004 output(event, data);
9005 }
9006 }
9007
perf_iterate_sb_cpu(perf_iterate_f output,void * data)9008 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
9009 {
9010 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
9011 struct perf_event *event;
9012
9013 list_for_each_entry_rcu(event, &pel->list, sb_list) {
9014 /*
9015 * Skip events that are not fully formed yet; ensure that
9016 * if we observe event->ctx, both event and ctx will be
9017 * complete enough. See perf_install_in_context().
9018 */
9019 if (!smp_load_acquire(&event->ctx))
9020 continue;
9021
9022 if (event->state < PERF_EVENT_STATE_INACTIVE)
9023 continue;
9024 if (!event_filter_match(event))
9025 continue;
9026 output(event, data);
9027 }
9028 }
9029
9030 /*
9031 * Iterate all events that need to receive side-band events.
9032 *
9033 * For new callers; ensure that account_pmu_sb_event() includes
9034 * your event, otherwise it might not get delivered.
9035 */
9036 static void
perf_iterate_sb(perf_iterate_f output,void * data,struct perf_event_context * task_ctx)9037 perf_iterate_sb(perf_iterate_f output, void *data,
9038 struct perf_event_context *task_ctx)
9039 {
9040 struct perf_event_context *ctx;
9041
9042 rcu_read_lock();
9043 preempt_disable();
9044
9045 /*
9046 * If we have task_ctx != NULL we only notify the task context itself.
9047 * The task_ctx is set only for EXIT events before releasing task
9048 * context.
9049 */
9050 if (task_ctx) {
9051 perf_iterate_ctx(task_ctx, output, data, false);
9052 goto done;
9053 }
9054
9055 perf_iterate_sb_cpu(output, data);
9056
9057 ctx = rcu_dereference(current->perf_event_ctxp);
9058 if (ctx)
9059 perf_iterate_ctx(ctx, output, data, false);
9060 done:
9061 preempt_enable();
9062 rcu_read_unlock();
9063 }
9064
9065 /*
9066 * Clear all file-based filters at exec, they'll have to be
9067 * re-instated when/if these objects are mmapped again.
9068 */
perf_event_addr_filters_exec(struct perf_event * event,void * data)9069 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
9070 {
9071 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
9072 struct perf_addr_filter *filter;
9073 unsigned int restart = 0, count = 0;
9074 unsigned long flags;
9075
9076 if (!has_addr_filter(event))
9077 return;
9078
9079 raw_spin_lock_irqsave(&ifh->lock, flags);
9080 list_for_each_entry(filter, &ifh->list, entry) {
9081 if (filter->path.dentry) {
9082 event->addr_filter_ranges[count].start = 0;
9083 event->addr_filter_ranges[count].size = 0;
9084 restart++;
9085 }
9086
9087 count++;
9088 }
9089
9090 if (restart)
9091 event->addr_filters_gen++;
9092 raw_spin_unlock_irqrestore(&ifh->lock, flags);
9093
9094 if (restart)
9095 perf_event_stop(event, 1);
9096 }
9097
perf_event_exec(void)9098 void perf_event_exec(void)
9099 {
9100 struct perf_event_context *ctx;
9101
9102 ctx = perf_pin_task_context(current);
9103 if (!ctx)
9104 return;
9105
9106 perf_event_enable_on_exec(ctx);
9107 perf_event_remove_on_exec(ctx);
9108 scoped_guard(rcu)
9109 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL, true);
9110
9111 perf_unpin_context(ctx);
9112 put_ctx(ctx);
9113 }
9114
9115 struct remote_output {
9116 struct perf_buffer *rb;
9117 int err;
9118 };
9119
__perf_event_output_stop(struct perf_event * event,void * data)9120 static void __perf_event_output_stop(struct perf_event *event, void *data)
9121 {
9122 struct perf_event *parent = event->parent;
9123 struct remote_output *ro = data;
9124 struct perf_buffer *rb = ro->rb;
9125 struct stop_event_data sd = {
9126 .event = event,
9127 };
9128
9129 if (!has_aux(event))
9130 return;
9131
9132 if (!parent)
9133 parent = event;
9134
9135 /*
9136 * In case of inheritance, it will be the parent that links to the
9137 * ring-buffer, but it will be the child that's actually using it.
9138 *
9139 * We are using event::rb to determine if the event should be stopped,
9140 * however this may race with ring_buffer_attach() (through set_output),
9141 * which will make us skip the event that actually needs to be stopped.
9142 * So ring_buffer_attach() has to stop an aux event before re-assigning
9143 * its rb pointer.
9144 */
9145 if (rcu_dereference(parent->rb) == rb)
9146 ro->err = __perf_event_stop(&sd);
9147 }
9148
__perf_pmu_output_stop(void * info)9149 static int __perf_pmu_output_stop(void *info)
9150 {
9151 struct perf_event *event = info;
9152 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
9153 struct remote_output ro = {
9154 .rb = event->rb,
9155 };
9156
9157 rcu_read_lock();
9158 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
9159 if (cpuctx->task_ctx)
9160 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
9161 &ro, false);
9162 rcu_read_unlock();
9163
9164 return ro.err;
9165 }
9166
perf_pmu_output_stop(struct perf_event * event)9167 static void perf_pmu_output_stop(struct perf_event *event)
9168 {
9169 struct perf_event *iter;
9170 int err, cpu;
9171
9172 restart:
9173 rcu_read_lock();
9174 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
9175 /*
9176 * For per-CPU events, we need to make sure that neither they
9177 * nor their children are running; for cpu==-1 events it's
9178 * sufficient to stop the event itself if it's active, since
9179 * it can't have children.
9180 */
9181 cpu = iter->cpu;
9182 if (cpu == -1)
9183 cpu = READ_ONCE(iter->oncpu);
9184
9185 if (cpu == -1)
9186 continue;
9187
9188 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
9189 if (err == -EAGAIN) {
9190 rcu_read_unlock();
9191 goto restart;
9192 }
9193 }
9194 rcu_read_unlock();
9195 }
9196
9197 /*
9198 * task tracking -- fork/exit
9199 *
9200 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
9201 */
9202
9203 struct perf_task_event {
9204 struct task_struct *task;
9205 struct perf_event_context *task_ctx;
9206
9207 struct {
9208 struct perf_event_header header;
9209
9210 u32 pid;
9211 u32 ppid;
9212 u32 tid;
9213 u32 ptid;
9214 u64 time;
9215 } event_id;
9216 };
9217
perf_event_task_match(struct perf_event * event)9218 static int perf_event_task_match(struct perf_event *event)
9219 {
9220 return event->attr.comm || event->attr.mmap ||
9221 event->attr.mmap2 || event->attr.mmap_data ||
9222 event->attr.task;
9223 }
9224
perf_event_task_output(struct perf_event * event,void * data)9225 static void perf_event_task_output(struct perf_event *event,
9226 void *data)
9227 {
9228 struct perf_task_event *task_event = data;
9229 struct perf_output_handle handle;
9230 struct perf_sample_data sample;
9231 struct task_struct *task = task_event->task;
9232 int ret, size = task_event->event_id.header.size;
9233
9234 if (!perf_event_task_match(event))
9235 return;
9236
9237 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
9238
9239 ret = perf_output_begin(&handle, &sample, event,
9240 task_event->event_id.header.size);
9241 if (ret)
9242 goto out;
9243
9244 task_event->event_id.pid = perf_event_pid(event, task);
9245 task_event->event_id.tid = perf_event_tid(event, task);
9246
9247 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
9248 task_event->event_id.ppid = perf_event_pid(event,
9249 task->real_parent);
9250 task_event->event_id.ptid = perf_event_pid(event,
9251 task->real_parent);
9252 } else { /* PERF_RECORD_FORK */
9253 task_event->event_id.ppid = perf_event_pid(event, current);
9254 task_event->event_id.ptid = perf_event_tid(event, current);
9255 }
9256
9257 task_event->event_id.time = perf_event_clock(event);
9258
9259 perf_output_put(&handle, task_event->event_id);
9260
9261 perf_event__output_id_sample(event, &handle, &sample);
9262
9263 perf_output_end(&handle);
9264 out:
9265 task_event->event_id.header.size = size;
9266 }
9267
perf_event_task(struct task_struct * task,struct perf_event_context * task_ctx,int new)9268 static void perf_event_task(struct task_struct *task,
9269 struct perf_event_context *task_ctx,
9270 int new)
9271 {
9272 struct perf_task_event task_event;
9273
9274 if (!atomic_read(&nr_comm_events) &&
9275 !atomic_read(&nr_mmap_events) &&
9276 !atomic_read(&nr_task_events))
9277 return;
9278
9279 task_event = (struct perf_task_event){
9280 .task = task,
9281 .task_ctx = task_ctx,
9282 .event_id = {
9283 .header = {
9284 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
9285 .misc = 0,
9286 .size = sizeof(task_event.event_id),
9287 },
9288 /* .pid */
9289 /* .ppid */
9290 /* .tid */
9291 /* .ptid */
9292 /* .time */
9293 },
9294 };
9295
9296 perf_iterate_sb(perf_event_task_output,
9297 &task_event,
9298 task_ctx);
9299 }
9300
9301 /*
9302 * Allocate data for a new task when profiling system-wide
9303 * events which require PMU specific data
9304 */
9305 static void
perf_event_alloc_task_data(struct task_struct * child,struct task_struct * parent)9306 perf_event_alloc_task_data(struct task_struct *child,
9307 struct task_struct *parent)
9308 {
9309 struct kmem_cache *ctx_cache = NULL;
9310 struct perf_ctx_data *cd;
9311
9312 if (!refcount_read(&global_ctx_data_ref))
9313 return;
9314
9315 scoped_guard (rcu) {
9316 cd = rcu_dereference(parent->perf_ctx_data);
9317 if (cd)
9318 ctx_cache = cd->ctx_cache;
9319 }
9320
9321 if (!ctx_cache)
9322 return;
9323
9324 guard(percpu_read)(&global_ctx_data_rwsem);
9325 scoped_guard (rcu) {
9326 cd = rcu_dereference(child->perf_ctx_data);
9327 if (!cd) {
9328 /*
9329 * A system-wide event may be unaccount,
9330 * when attaching the perf_ctx_data.
9331 */
9332 if (!refcount_read(&global_ctx_data_ref))
9333 return;
9334 goto attach;
9335 }
9336
9337 if (!cd->global) {
9338 cd->global = 1;
9339 refcount_inc(&cd->refcount);
9340 }
9341 }
9342
9343 return;
9344 attach:
9345 attach_task_ctx_data(child, ctx_cache, true, GFP_KERNEL);
9346 }
9347
perf_event_fork(struct task_struct * task)9348 void perf_event_fork(struct task_struct *task)
9349 {
9350 perf_event_task(task, NULL, 1);
9351 perf_event_namespaces(task);
9352 perf_event_alloc_task_data(task, current);
9353 }
9354
9355 /*
9356 * comm tracking
9357 */
9358
9359 struct perf_comm_event {
9360 struct task_struct *task;
9361 char *comm;
9362 int comm_size;
9363
9364 struct {
9365 struct perf_event_header header;
9366
9367 u32 pid;
9368 u32 tid;
9369 } event_id;
9370 };
9371
perf_event_comm_match(struct perf_event * event)9372 static int perf_event_comm_match(struct perf_event *event)
9373 {
9374 return event->attr.comm;
9375 }
9376
perf_event_comm_output(struct perf_event * event,void * data)9377 static void perf_event_comm_output(struct perf_event *event,
9378 void *data)
9379 {
9380 struct perf_comm_event *comm_event = data;
9381 struct perf_output_handle handle;
9382 struct perf_sample_data sample;
9383 int size = comm_event->event_id.header.size;
9384 int ret;
9385
9386 if (!perf_event_comm_match(event))
9387 return;
9388
9389 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
9390 ret = perf_output_begin(&handle, &sample, event,
9391 comm_event->event_id.header.size);
9392
9393 if (ret)
9394 goto out;
9395
9396 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
9397 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
9398
9399 perf_output_put(&handle, comm_event->event_id);
9400 __output_copy(&handle, comm_event->comm,
9401 comm_event->comm_size);
9402
9403 perf_event__output_id_sample(event, &handle, &sample);
9404
9405 perf_output_end(&handle);
9406 out:
9407 comm_event->event_id.header.size = size;
9408 }
9409
perf_event_comm_event(struct perf_comm_event * comm_event)9410 static void perf_event_comm_event(struct perf_comm_event *comm_event)
9411 {
9412 char comm[TASK_COMM_LEN];
9413 unsigned int size;
9414
9415 memset(comm, 0, sizeof(comm));
9416 strscpy(comm, comm_event->task->comm);
9417 size = ALIGN(strlen(comm)+1, sizeof(u64));
9418
9419 comm_event->comm = comm;
9420 comm_event->comm_size = size;
9421
9422 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
9423
9424 perf_iterate_sb(perf_event_comm_output,
9425 comm_event,
9426 NULL);
9427 }
9428
perf_event_comm(struct task_struct * task,bool exec)9429 void perf_event_comm(struct task_struct *task, bool exec)
9430 {
9431 struct perf_comm_event comm_event;
9432
9433 if (!atomic_read(&nr_comm_events))
9434 return;
9435
9436 comm_event = (struct perf_comm_event){
9437 .task = task,
9438 /* .comm */
9439 /* .comm_size */
9440 .event_id = {
9441 .header = {
9442 .type = PERF_RECORD_COMM,
9443 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
9444 /* .size */
9445 },
9446 /* .pid */
9447 /* .tid */
9448 },
9449 };
9450
9451 perf_event_comm_event(&comm_event);
9452 }
9453
9454 /*
9455 * namespaces tracking
9456 */
9457
9458 struct perf_namespaces_event {
9459 struct task_struct *task;
9460
9461 struct {
9462 struct perf_event_header header;
9463
9464 u32 pid;
9465 u32 tid;
9466 u64 nr_namespaces;
9467 struct perf_ns_link_info link_info[NR_NAMESPACES];
9468 } event_id;
9469 };
9470
perf_event_namespaces_match(struct perf_event * event)9471 static int perf_event_namespaces_match(struct perf_event *event)
9472 {
9473 return event->attr.namespaces;
9474 }
9475
perf_event_namespaces_output(struct perf_event * event,void * data)9476 static void perf_event_namespaces_output(struct perf_event *event,
9477 void *data)
9478 {
9479 struct perf_namespaces_event *namespaces_event = data;
9480 struct perf_output_handle handle;
9481 struct perf_sample_data sample;
9482 u16 header_size = namespaces_event->event_id.header.size;
9483 int ret;
9484
9485 if (!perf_event_namespaces_match(event))
9486 return;
9487
9488 perf_event_header__init_id(&namespaces_event->event_id.header,
9489 &sample, event);
9490 ret = perf_output_begin(&handle, &sample, event,
9491 namespaces_event->event_id.header.size);
9492 if (ret)
9493 goto out;
9494
9495 namespaces_event->event_id.pid = perf_event_pid(event,
9496 namespaces_event->task);
9497 namespaces_event->event_id.tid = perf_event_tid(event,
9498 namespaces_event->task);
9499
9500 perf_output_put(&handle, namespaces_event->event_id);
9501
9502 perf_event__output_id_sample(event, &handle, &sample);
9503
9504 perf_output_end(&handle);
9505 out:
9506 namespaces_event->event_id.header.size = header_size;
9507 }
9508
perf_fill_ns_link_info(struct perf_ns_link_info * ns_link_info,struct task_struct * task,const struct proc_ns_operations * ns_ops)9509 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
9510 struct task_struct *task,
9511 const struct proc_ns_operations *ns_ops)
9512 {
9513 struct path ns_path;
9514 struct inode *ns_inode;
9515 int error;
9516
9517 error = ns_get_path(&ns_path, task, ns_ops);
9518 if (!error) {
9519 ns_inode = ns_path.dentry->d_inode;
9520 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
9521 ns_link_info->ino = ns_inode->i_ino;
9522 path_put(&ns_path);
9523 }
9524 }
9525
perf_event_namespaces(struct task_struct * task)9526 void perf_event_namespaces(struct task_struct *task)
9527 {
9528 struct perf_namespaces_event namespaces_event;
9529 struct perf_ns_link_info *ns_link_info;
9530
9531 if (!atomic_read(&nr_namespaces_events))
9532 return;
9533
9534 namespaces_event = (struct perf_namespaces_event){
9535 .task = task,
9536 .event_id = {
9537 .header = {
9538 .type = PERF_RECORD_NAMESPACES,
9539 .misc = 0,
9540 .size = sizeof(namespaces_event.event_id),
9541 },
9542 /* .pid */
9543 /* .tid */
9544 .nr_namespaces = NR_NAMESPACES,
9545 /* .link_info[NR_NAMESPACES] */
9546 },
9547 };
9548
9549 ns_link_info = namespaces_event.event_id.link_info;
9550
9551 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
9552 task, &mntns_operations);
9553
9554 #ifdef CONFIG_USER_NS
9555 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
9556 task, &userns_operations);
9557 #endif
9558 #ifdef CONFIG_NET_NS
9559 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
9560 task, &netns_operations);
9561 #endif
9562 #ifdef CONFIG_UTS_NS
9563 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
9564 task, &utsns_operations);
9565 #endif
9566 #ifdef CONFIG_IPC_NS
9567 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
9568 task, &ipcns_operations);
9569 #endif
9570 #ifdef CONFIG_PID_NS
9571 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
9572 task, &pidns_operations);
9573 #endif
9574 #ifdef CONFIG_CGROUPS
9575 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
9576 task, &cgroupns_operations);
9577 #endif
9578
9579 perf_iterate_sb(perf_event_namespaces_output,
9580 &namespaces_event,
9581 NULL);
9582 }
9583
9584 /*
9585 * cgroup tracking
9586 */
9587 #ifdef CONFIG_CGROUP_PERF
9588
9589 struct perf_cgroup_event {
9590 char *path;
9591 int path_size;
9592 struct {
9593 struct perf_event_header header;
9594 u64 id;
9595 char path[];
9596 } event_id;
9597 };
9598
perf_event_cgroup_match(struct perf_event * event)9599 static int perf_event_cgroup_match(struct perf_event *event)
9600 {
9601 return event->attr.cgroup;
9602 }
9603
perf_event_cgroup_output(struct perf_event * event,void * data)9604 static void perf_event_cgroup_output(struct perf_event *event, void *data)
9605 {
9606 struct perf_cgroup_event *cgroup_event = data;
9607 struct perf_output_handle handle;
9608 struct perf_sample_data sample;
9609 u16 header_size = cgroup_event->event_id.header.size;
9610 int ret;
9611
9612 if (!perf_event_cgroup_match(event))
9613 return;
9614
9615 perf_event_header__init_id(&cgroup_event->event_id.header,
9616 &sample, event);
9617 ret = perf_output_begin(&handle, &sample, event,
9618 cgroup_event->event_id.header.size);
9619 if (ret)
9620 goto out;
9621
9622 perf_output_put(&handle, cgroup_event->event_id);
9623 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
9624
9625 perf_event__output_id_sample(event, &handle, &sample);
9626
9627 perf_output_end(&handle);
9628 out:
9629 cgroup_event->event_id.header.size = header_size;
9630 }
9631
perf_event_cgroup(struct cgroup * cgrp)9632 static void perf_event_cgroup(struct cgroup *cgrp)
9633 {
9634 struct perf_cgroup_event cgroup_event;
9635 char path_enomem[16] = "//enomem";
9636 char *pathname;
9637 size_t size;
9638
9639 if (!atomic_read(&nr_cgroup_events))
9640 return;
9641
9642 cgroup_event = (struct perf_cgroup_event){
9643 .event_id = {
9644 .header = {
9645 .type = PERF_RECORD_CGROUP,
9646 .misc = 0,
9647 .size = sizeof(cgroup_event.event_id),
9648 },
9649 .id = cgroup_id(cgrp),
9650 },
9651 };
9652
9653 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
9654 if (pathname == NULL) {
9655 cgroup_event.path = path_enomem;
9656 } else {
9657 /* just to be sure to have enough space for alignment */
9658 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
9659 cgroup_event.path = pathname;
9660 }
9661
9662 /*
9663 * Since our buffer works in 8 byte units we need to align our string
9664 * size to a multiple of 8. However, we must guarantee the tail end is
9665 * zero'd out to avoid leaking random bits to userspace.
9666 */
9667 size = strlen(cgroup_event.path) + 1;
9668 while (!IS_ALIGNED(size, sizeof(u64)))
9669 cgroup_event.path[size++] = '\0';
9670
9671 cgroup_event.event_id.header.size += size;
9672 cgroup_event.path_size = size;
9673
9674 perf_iterate_sb(perf_event_cgroup_output,
9675 &cgroup_event,
9676 NULL);
9677
9678 kfree(pathname);
9679 }
9680
9681 #endif
9682
9683 /*
9684 * mmap tracking
9685 */
9686
9687 struct perf_mmap_event {
9688 struct vm_area_struct *vma;
9689
9690 const char *file_name;
9691 int file_size;
9692 int maj, min;
9693 u64 ino;
9694 u64 ino_generation;
9695 u32 prot, flags;
9696 u8 build_id[BUILD_ID_SIZE_MAX];
9697 u32 build_id_size;
9698
9699 struct {
9700 struct perf_event_header header;
9701
9702 u32 pid;
9703 u32 tid;
9704 u64 start;
9705 u64 len;
9706 u64 pgoff;
9707 } event_id;
9708 };
9709
perf_event_mmap_match(struct perf_event * event,void * data)9710 static int perf_event_mmap_match(struct perf_event *event,
9711 void *data)
9712 {
9713 struct perf_mmap_event *mmap_event = data;
9714 struct vm_area_struct *vma = mmap_event->vma;
9715 int executable = vma->vm_flags & VM_EXEC;
9716
9717 return (!executable && event->attr.mmap_data) ||
9718 (executable && (event->attr.mmap || event->attr.mmap2));
9719 }
9720
perf_event_mmap_output(struct perf_event * event,void * data)9721 static void perf_event_mmap_output(struct perf_event *event,
9722 void *data)
9723 {
9724 struct perf_mmap_event *mmap_event = data;
9725 struct perf_output_handle handle;
9726 struct perf_sample_data sample;
9727 int size = mmap_event->event_id.header.size;
9728 u32 type = mmap_event->event_id.header.type;
9729 bool use_build_id;
9730 int ret;
9731
9732 if (!perf_event_mmap_match(event, data))
9733 return;
9734
9735 if (event->attr.mmap2) {
9736 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
9737 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
9738 mmap_event->event_id.header.size += sizeof(mmap_event->min);
9739 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
9740 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
9741 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
9742 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
9743 }
9744
9745 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
9746 ret = perf_output_begin(&handle, &sample, event,
9747 mmap_event->event_id.header.size);
9748 if (ret)
9749 goto out;
9750
9751 mmap_event->event_id.pid = perf_event_pid(event, current);
9752 mmap_event->event_id.tid = perf_event_tid(event, current);
9753
9754 use_build_id = event->attr.build_id && mmap_event->build_id_size;
9755
9756 if (event->attr.mmap2 && use_build_id)
9757 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID;
9758
9759 perf_output_put(&handle, mmap_event->event_id);
9760
9761 if (event->attr.mmap2) {
9762 if (use_build_id) {
9763 u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 };
9764
9765 __output_copy(&handle, size, 4);
9766 __output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX);
9767 } else {
9768 perf_output_put(&handle, mmap_event->maj);
9769 perf_output_put(&handle, mmap_event->min);
9770 perf_output_put(&handle, mmap_event->ino);
9771 perf_output_put(&handle, mmap_event->ino_generation);
9772 }
9773 perf_output_put(&handle, mmap_event->prot);
9774 perf_output_put(&handle, mmap_event->flags);
9775 }
9776
9777 __output_copy(&handle, mmap_event->file_name,
9778 mmap_event->file_size);
9779
9780 perf_event__output_id_sample(event, &handle, &sample);
9781
9782 perf_output_end(&handle);
9783 out:
9784 mmap_event->event_id.header.size = size;
9785 mmap_event->event_id.header.type = type;
9786 }
9787
perf_event_mmap_event(struct perf_mmap_event * mmap_event)9788 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
9789 {
9790 struct vm_area_struct *vma = mmap_event->vma;
9791 struct file *file = vma->vm_file;
9792 int maj = 0, min = 0;
9793 u64 ino = 0, gen = 0;
9794 u32 prot = 0, flags = 0;
9795 unsigned int size;
9796 char tmp[16];
9797 char *buf = NULL;
9798 char *name = NULL;
9799
9800 if (vma->vm_flags & VM_READ)
9801 prot |= PROT_READ;
9802 if (vma->vm_flags & VM_WRITE)
9803 prot |= PROT_WRITE;
9804 if (vma->vm_flags & VM_EXEC)
9805 prot |= PROT_EXEC;
9806
9807 if (vma->vm_flags & VM_MAYSHARE)
9808 flags = MAP_SHARED;
9809 else
9810 flags = MAP_PRIVATE;
9811
9812 if (vma->vm_flags & VM_LOCKED)
9813 flags |= MAP_LOCKED;
9814 if (is_vm_hugetlb_page(vma))
9815 flags |= MAP_HUGETLB;
9816
9817 if (file) {
9818 const struct inode *inode;
9819 dev_t dev;
9820
9821 buf = kmalloc(PATH_MAX, GFP_KERNEL);
9822 if (!buf) {
9823 name = "//enomem";
9824 goto cpy_name;
9825 }
9826 /*
9827 * d_path() works from the end of the rb backwards, so we
9828 * need to add enough zero bytes after the string to handle
9829 * the 64bit alignment we do later.
9830 */
9831 name = d_path(file_user_path(file), buf, PATH_MAX - sizeof(u64));
9832 if (IS_ERR(name)) {
9833 name = "//toolong";
9834 goto cpy_name;
9835 }
9836 inode = file_user_inode(vma->vm_file);
9837 dev = inode->i_sb->s_dev;
9838 ino = inode->i_ino;
9839 gen = inode->i_generation;
9840 maj = MAJOR(dev);
9841 min = MINOR(dev);
9842
9843 goto got_name;
9844 } else {
9845 if (vma->vm_ops && vma->vm_ops->name)
9846 name = (char *) vma->vm_ops->name(vma);
9847 if (!name)
9848 name = (char *)arch_vma_name(vma);
9849 if (!name) {
9850 if (vma_is_initial_heap(vma))
9851 name = "[heap]";
9852 else if (vma_is_initial_stack(vma))
9853 name = "[stack]";
9854 else
9855 name = "//anon";
9856 }
9857 }
9858
9859 cpy_name:
9860 strscpy(tmp, name);
9861 name = tmp;
9862 got_name:
9863 /*
9864 * Since our buffer works in 8 byte units we need to align our string
9865 * size to a multiple of 8. However, we must guarantee the tail end is
9866 * zero'd out to avoid leaking random bits to userspace.
9867 */
9868 size = strlen(name)+1;
9869 while (!IS_ALIGNED(size, sizeof(u64)))
9870 name[size++] = '\0';
9871
9872 mmap_event->file_name = name;
9873 mmap_event->file_size = size;
9874 mmap_event->maj = maj;
9875 mmap_event->min = min;
9876 mmap_event->ino = ino;
9877 mmap_event->ino_generation = gen;
9878 mmap_event->prot = prot;
9879 mmap_event->flags = flags;
9880
9881 if (!(vma->vm_flags & VM_EXEC))
9882 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
9883
9884 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
9885
9886 if (atomic_read(&nr_build_id_events))
9887 build_id_parse_nofault(vma, mmap_event->build_id, &mmap_event->build_id_size);
9888
9889 perf_iterate_sb(perf_event_mmap_output,
9890 mmap_event,
9891 NULL);
9892
9893 kfree(buf);
9894 }
9895
9896 /*
9897 * Check whether inode and address range match filter criteria.
9898 */
perf_addr_filter_match(struct perf_addr_filter * filter,struct file * file,unsigned long offset,unsigned long size)9899 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
9900 struct file *file, unsigned long offset,
9901 unsigned long size)
9902 {
9903 /* d_inode(NULL) won't be equal to any mapped user-space file */
9904 if (!filter->path.dentry)
9905 return false;
9906
9907 if (d_inode(filter->path.dentry) != file_user_inode(file))
9908 return false;
9909
9910 if (filter->offset > offset + size)
9911 return false;
9912
9913 if (filter->offset + filter->size < offset)
9914 return false;
9915
9916 return true;
9917 }
9918
perf_addr_filter_vma_adjust(struct perf_addr_filter * filter,struct vm_area_struct * vma,struct perf_addr_filter_range * fr)9919 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
9920 struct vm_area_struct *vma,
9921 struct perf_addr_filter_range *fr)
9922 {
9923 unsigned long vma_size = vma->vm_end - vma->vm_start;
9924 unsigned long off = vma_start_pgoff(vma) << PAGE_SHIFT;
9925 struct file *file = vma->vm_file;
9926
9927 if (!perf_addr_filter_match(filter, file, off, vma_size))
9928 return false;
9929
9930 if (filter->offset < off) {
9931 fr->start = vma->vm_start;
9932 fr->size = min(vma_size, filter->size - (off - filter->offset));
9933 } else {
9934 fr->start = vma->vm_start + filter->offset - off;
9935 fr->size = min(vma->vm_end - fr->start, filter->size);
9936 }
9937
9938 return true;
9939 }
9940
__perf_addr_filters_adjust(struct perf_event * event,void * data)9941 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
9942 {
9943 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
9944 struct vm_area_struct *vma = data;
9945 struct perf_addr_filter *filter;
9946 unsigned int restart = 0, count = 0;
9947 unsigned long flags;
9948
9949 if (!has_addr_filter(event))
9950 return;
9951
9952 if (!vma->vm_file)
9953 return;
9954
9955 raw_spin_lock_irqsave(&ifh->lock, flags);
9956 list_for_each_entry(filter, &ifh->list, entry) {
9957 if (perf_addr_filter_vma_adjust(filter, vma,
9958 &event->addr_filter_ranges[count]))
9959 restart++;
9960
9961 count++;
9962 }
9963
9964 if (restart)
9965 event->addr_filters_gen++;
9966 raw_spin_unlock_irqrestore(&ifh->lock, flags);
9967
9968 if (restart)
9969 perf_event_stop(event, 1);
9970 }
9971
9972 /*
9973 * Adjust all task's events' filters to the new vma
9974 */
perf_addr_filters_adjust(struct vm_area_struct * vma)9975 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
9976 {
9977 struct perf_event_context *ctx;
9978
9979 /*
9980 * Data tracing isn't supported yet and as such there is no need
9981 * to keep track of anything that isn't related to executable code:
9982 */
9983 if (!(vma->vm_flags & VM_EXEC))
9984 return;
9985
9986 rcu_read_lock();
9987 ctx = rcu_dereference(current->perf_event_ctxp);
9988 if (ctx)
9989 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
9990 rcu_read_unlock();
9991 }
9992
perf_event_mmap(struct vm_area_struct * vma)9993 void perf_event_mmap(struct vm_area_struct *vma)
9994 {
9995 struct perf_mmap_event mmap_event;
9996
9997 if (!atomic_read(&nr_mmap_events))
9998 return;
9999
10000 mmap_event = (struct perf_mmap_event){
10001 .vma = vma,
10002 /* .file_name */
10003 /* .file_size */
10004 .event_id = {
10005 .header = {
10006 .type = PERF_RECORD_MMAP,
10007 .misc = PERF_RECORD_MISC_USER,
10008 /* .size */
10009 },
10010 /* .pid */
10011 /* .tid */
10012 .start = vma->vm_start,
10013 .len = vma->vm_end - vma->vm_start,
10014 .pgoff = (u64)vma_start_pgoff(vma) << PAGE_SHIFT,
10015 },
10016 /* .maj (attr_mmap2 only) */
10017 /* .min (attr_mmap2 only) */
10018 /* .ino (attr_mmap2 only) */
10019 /* .ino_generation (attr_mmap2 only) */
10020 /* .prot (attr_mmap2 only) */
10021 /* .flags (attr_mmap2 only) */
10022 };
10023
10024 perf_addr_filters_adjust(vma);
10025 perf_event_mmap_event(&mmap_event);
10026 }
10027
perf_event_aux_event(struct perf_event * event,unsigned long head,unsigned long size,u64 flags)10028 void perf_event_aux_event(struct perf_event *event, unsigned long head,
10029 unsigned long size, u64 flags)
10030 {
10031 struct perf_output_handle handle;
10032 struct perf_sample_data sample;
10033 struct perf_aux_event {
10034 struct perf_event_header header;
10035 u64 offset;
10036 u64 size;
10037 u64 flags;
10038 } rec = {
10039 .header = {
10040 .type = PERF_RECORD_AUX,
10041 .misc = 0,
10042 .size = sizeof(rec),
10043 },
10044 .offset = head,
10045 .size = size,
10046 .flags = flags,
10047 };
10048 int ret;
10049
10050 perf_event_header__init_id(&rec.header, &sample, event);
10051 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
10052
10053 if (ret)
10054 return;
10055
10056 perf_output_put(&handle, rec);
10057 perf_event__output_id_sample(event, &handle, &sample);
10058
10059 perf_output_end(&handle);
10060 }
10061
10062 /*
10063 * Lost/dropped samples logging
10064 */
perf_log_lost_samples(struct perf_event * event,u64 lost)10065 void perf_log_lost_samples(struct perf_event *event, u64 lost)
10066 {
10067 struct perf_output_handle handle;
10068 struct perf_sample_data sample;
10069 int ret;
10070
10071 struct {
10072 struct perf_event_header header;
10073 u64 lost;
10074 } lost_samples_event = {
10075 .header = {
10076 .type = PERF_RECORD_LOST_SAMPLES,
10077 .misc = 0,
10078 .size = sizeof(lost_samples_event),
10079 },
10080 .lost = lost,
10081 };
10082
10083 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
10084
10085 ret = perf_output_begin(&handle, &sample, event,
10086 lost_samples_event.header.size);
10087 if (ret)
10088 return;
10089
10090 perf_output_put(&handle, lost_samples_event);
10091 perf_event__output_id_sample(event, &handle, &sample);
10092 perf_output_end(&handle);
10093 }
10094
10095 /*
10096 * context_switch tracking
10097 */
10098
10099 struct perf_switch_event {
10100 struct task_struct *task;
10101 struct task_struct *next_prev;
10102
10103 struct {
10104 struct perf_event_header header;
10105 u32 next_prev_pid;
10106 u32 next_prev_tid;
10107 } event_id;
10108 };
10109
perf_event_switch_match(struct perf_event * event)10110 static int perf_event_switch_match(struct perf_event *event)
10111 {
10112 return event->attr.context_switch;
10113 }
10114
perf_event_switch_output(struct perf_event * event,void * data)10115 static void perf_event_switch_output(struct perf_event *event, void *data)
10116 {
10117 struct perf_switch_event *se = data;
10118 struct perf_output_handle handle;
10119 struct perf_sample_data sample;
10120 int ret;
10121
10122 if (!perf_event_switch_match(event))
10123 return;
10124
10125 /* Only CPU-wide events are allowed to see next/prev pid/tid */
10126 if (event->ctx->task) {
10127 se->event_id.header.type = PERF_RECORD_SWITCH;
10128 se->event_id.header.size = sizeof(se->event_id.header);
10129 } else {
10130 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
10131 se->event_id.header.size = sizeof(se->event_id);
10132 se->event_id.next_prev_pid =
10133 perf_event_pid(event, se->next_prev);
10134 se->event_id.next_prev_tid =
10135 perf_event_tid(event, se->next_prev);
10136 }
10137
10138 perf_event_header__init_id(&se->event_id.header, &sample, event);
10139
10140 ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size);
10141 if (ret)
10142 return;
10143
10144 if (event->ctx->task)
10145 perf_output_put(&handle, se->event_id.header);
10146 else
10147 perf_output_put(&handle, se->event_id);
10148
10149 perf_event__output_id_sample(event, &handle, &sample);
10150
10151 perf_output_end(&handle);
10152 }
10153
perf_event_switch(struct task_struct * task,struct task_struct * next_prev,bool sched_in)10154 static void perf_event_switch(struct task_struct *task,
10155 struct task_struct *next_prev, bool sched_in)
10156 {
10157 struct perf_switch_event switch_event;
10158
10159 /* N.B. caller checks nr_switch_events != 0 */
10160
10161 switch_event = (struct perf_switch_event){
10162 .task = task,
10163 .next_prev = next_prev,
10164 .event_id = {
10165 .header = {
10166 /* .type */
10167 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
10168 /* .size */
10169 },
10170 /* .next_prev_pid */
10171 /* .next_prev_tid */
10172 },
10173 };
10174
10175 if (!sched_in && task_is_runnable(task)) {
10176 switch_event.event_id.header.misc |=
10177 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
10178 }
10179
10180 perf_iterate_sb(perf_event_switch_output, &switch_event, NULL);
10181 }
10182
10183 /*
10184 * IRQ throttle logging
10185 */
10186
perf_log_throttle(struct perf_event * event,int enable)10187 static void perf_log_throttle(struct perf_event *event, int enable)
10188 {
10189 struct perf_output_handle handle;
10190 struct perf_sample_data sample;
10191 int ret;
10192
10193 struct {
10194 struct perf_event_header header;
10195 u64 time;
10196 u64 id;
10197 u64 stream_id;
10198 } throttle_event = {
10199 .header = {
10200 .type = PERF_RECORD_THROTTLE,
10201 .misc = 0,
10202 .size = sizeof(throttle_event),
10203 },
10204 .time = perf_event_clock(event),
10205 .id = primary_event_id(event),
10206 .stream_id = event->id,
10207 };
10208
10209 if (enable)
10210 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
10211
10212 perf_event_header__init_id(&throttle_event.header, &sample, event);
10213
10214 ret = perf_output_begin(&handle, &sample, event,
10215 throttle_event.header.size);
10216 if (ret)
10217 return;
10218
10219 perf_output_put(&handle, throttle_event);
10220 perf_event__output_id_sample(event, &handle, &sample);
10221 perf_output_end(&handle);
10222 }
10223
10224 /*
10225 * ksymbol register/unregister tracking
10226 */
10227
10228 struct perf_ksymbol_event {
10229 const char *name;
10230 int name_len;
10231 struct {
10232 struct perf_event_header header;
10233 u64 addr;
10234 u32 len;
10235 u16 ksym_type;
10236 u16 flags;
10237 } event_id;
10238 };
10239
perf_event_ksymbol_match(struct perf_event * event)10240 static int perf_event_ksymbol_match(struct perf_event *event)
10241 {
10242 return event->attr.ksymbol;
10243 }
10244
perf_event_ksymbol_output(struct perf_event * event,void * data)10245 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
10246 {
10247 struct perf_ksymbol_event *ksymbol_event = data;
10248 struct perf_output_handle handle;
10249 struct perf_sample_data sample;
10250 int ret;
10251
10252 if (!perf_event_ksymbol_match(event))
10253 return;
10254
10255 perf_event_header__init_id(&ksymbol_event->event_id.header,
10256 &sample, event);
10257 ret = perf_output_begin(&handle, &sample, event,
10258 ksymbol_event->event_id.header.size);
10259 if (ret)
10260 return;
10261
10262 perf_output_put(&handle, ksymbol_event->event_id);
10263 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
10264 perf_event__output_id_sample(event, &handle, &sample);
10265
10266 perf_output_end(&handle);
10267 }
10268
perf_event_ksymbol(u16 ksym_type,u64 addr,u32 len,bool unregister,const char * sym)10269 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
10270 const char *sym)
10271 {
10272 struct perf_ksymbol_event ksymbol_event;
10273 char name[KSYM_NAME_LEN];
10274 u16 flags = 0;
10275 int name_len;
10276
10277 if (!atomic_read(&nr_ksymbol_events))
10278 return;
10279
10280 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
10281 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
10282 goto err;
10283
10284 strscpy(name, sym);
10285 name_len = strlen(name) + 1;
10286 while (!IS_ALIGNED(name_len, sizeof(u64)))
10287 name[name_len++] = '\0';
10288 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
10289
10290 if (unregister)
10291 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
10292
10293 ksymbol_event = (struct perf_ksymbol_event){
10294 .name = name,
10295 .name_len = name_len,
10296 .event_id = {
10297 .header = {
10298 .type = PERF_RECORD_KSYMBOL,
10299 .size = sizeof(ksymbol_event.event_id) +
10300 name_len,
10301 },
10302 .addr = addr,
10303 .len = len,
10304 .ksym_type = ksym_type,
10305 .flags = flags,
10306 },
10307 };
10308
10309 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
10310 return;
10311 err:
10312 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
10313 }
10314
10315 /*
10316 * bpf program load/unload tracking
10317 */
10318
10319 struct perf_bpf_event {
10320 struct bpf_prog *prog;
10321 struct {
10322 struct perf_event_header header;
10323 u16 type;
10324 u16 flags;
10325 u32 id;
10326 u8 tag[BPF_TAG_SIZE];
10327 } event_id;
10328 };
10329
perf_event_bpf_match(struct perf_event * event)10330 static int perf_event_bpf_match(struct perf_event *event)
10331 {
10332 return event->attr.bpf_event;
10333 }
10334
perf_event_bpf_output(struct perf_event * event,void * data)10335 static void perf_event_bpf_output(struct perf_event *event, void *data)
10336 {
10337 struct perf_bpf_event *bpf_event = data;
10338 struct perf_output_handle handle;
10339 struct perf_sample_data sample;
10340 int ret;
10341
10342 if (!perf_event_bpf_match(event))
10343 return;
10344
10345 perf_event_header__init_id(&bpf_event->event_id.header,
10346 &sample, event);
10347 ret = perf_output_begin(&handle, &sample, event,
10348 bpf_event->event_id.header.size);
10349 if (ret)
10350 return;
10351
10352 perf_output_put(&handle, bpf_event->event_id);
10353 perf_event__output_id_sample(event, &handle, &sample);
10354
10355 perf_output_end(&handle);
10356 }
10357
perf_event_bpf_emit_ksymbols(struct bpf_prog * prog,enum perf_bpf_event_type type)10358 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
10359 enum perf_bpf_event_type type)
10360 {
10361 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
10362 int i;
10363
10364 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
10365 (u64)(unsigned long)prog->bpf_func,
10366 prog->jited_len, unregister,
10367 prog->aux->ksym.name);
10368
10369 for (i = 1; i < prog->aux->func_cnt; i++) {
10370 struct bpf_prog *subprog = prog->aux->func[i];
10371
10372 perf_event_ksymbol(
10373 PERF_RECORD_KSYMBOL_TYPE_BPF,
10374 (u64)(unsigned long)subprog->bpf_func,
10375 subprog->jited_len, unregister,
10376 subprog->aux->ksym.name);
10377 }
10378 }
10379
perf_event_bpf_event(struct bpf_prog * prog,enum perf_bpf_event_type type,u16 flags)10380 void perf_event_bpf_event(struct bpf_prog *prog,
10381 enum perf_bpf_event_type type,
10382 u16 flags)
10383 {
10384 struct perf_bpf_event bpf_event;
10385
10386 switch (type) {
10387 case PERF_BPF_EVENT_PROG_LOAD:
10388 case PERF_BPF_EVENT_PROG_UNLOAD:
10389 if (atomic_read(&nr_ksymbol_events))
10390 perf_event_bpf_emit_ksymbols(prog, type);
10391 break;
10392 default:
10393 return;
10394 }
10395
10396 if (!atomic_read(&nr_bpf_events))
10397 return;
10398
10399 bpf_event = (struct perf_bpf_event){
10400 .prog = prog,
10401 .event_id = {
10402 .header = {
10403 .type = PERF_RECORD_BPF_EVENT,
10404 .size = sizeof(bpf_event.event_id),
10405 },
10406 .type = type,
10407 .flags = flags,
10408 .id = prog->aux->id,
10409 },
10410 };
10411
10412 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
10413
10414 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
10415 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
10416 }
10417
10418 struct perf_callchain_deferred_event {
10419 struct unwind_stacktrace *trace;
10420 struct {
10421 struct perf_event_header header;
10422 u64 cookie;
10423 u64 nr;
10424 u64 ips[];
10425 } event;
10426 };
10427
perf_callchain_deferred_output(struct perf_event * event,void * data)10428 static void perf_callchain_deferred_output(struct perf_event *event, void *data)
10429 {
10430 struct perf_callchain_deferred_event *deferred_event = data;
10431 struct perf_output_handle handle;
10432 struct perf_sample_data sample;
10433 int ret, size = deferred_event->event.header.size;
10434
10435 if (!event->attr.defer_output)
10436 return;
10437
10438 /* XXX do we really need sample_id_all for this ??? */
10439 perf_event_header__init_id(&deferred_event->event.header, &sample, event);
10440
10441 ret = perf_output_begin(&handle, &sample, event,
10442 deferred_event->event.header.size);
10443 if (ret)
10444 goto out;
10445
10446 perf_output_put(&handle, deferred_event->event);
10447 for (int i = 0; i < deferred_event->trace->nr; i++) {
10448 u64 entry = deferred_event->trace->entries[i];
10449 perf_output_put(&handle, entry);
10450 }
10451 perf_event__output_id_sample(event, &handle, &sample);
10452
10453 perf_output_end(&handle);
10454 out:
10455 deferred_event->event.header.size = size;
10456 }
10457
perf_unwind_deferred_callback(struct unwind_work * work,struct unwind_stacktrace * trace,u64 cookie)10458 static void perf_unwind_deferred_callback(struct unwind_work *work,
10459 struct unwind_stacktrace *trace, u64 cookie)
10460 {
10461 struct perf_callchain_deferred_event deferred_event = {
10462 .trace = trace,
10463 .event = {
10464 .header = {
10465 .type = PERF_RECORD_CALLCHAIN_DEFERRED,
10466 .misc = PERF_RECORD_MISC_USER,
10467 .size = sizeof(deferred_event.event) +
10468 (trace->nr * sizeof(u64)),
10469 },
10470 .cookie = cookie,
10471 .nr = trace->nr,
10472 },
10473 };
10474
10475 perf_iterate_sb(perf_callchain_deferred_output, &deferred_event, NULL);
10476 }
10477
10478 struct perf_text_poke_event {
10479 const void *old_bytes;
10480 const void *new_bytes;
10481 size_t pad;
10482 u16 old_len;
10483 u16 new_len;
10484
10485 struct {
10486 struct perf_event_header header;
10487
10488 u64 addr;
10489 } event_id;
10490 };
10491
perf_event_text_poke_match(struct perf_event * event)10492 static int perf_event_text_poke_match(struct perf_event *event)
10493 {
10494 return event->attr.text_poke;
10495 }
10496
perf_event_text_poke_output(struct perf_event * event,void * data)10497 static void perf_event_text_poke_output(struct perf_event *event, void *data)
10498 {
10499 struct perf_text_poke_event *text_poke_event = data;
10500 struct perf_output_handle handle;
10501 struct perf_sample_data sample;
10502 u64 padding = 0;
10503 int ret;
10504
10505 if (!perf_event_text_poke_match(event))
10506 return;
10507
10508 perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
10509
10510 ret = perf_output_begin(&handle, &sample, event,
10511 text_poke_event->event_id.header.size);
10512 if (ret)
10513 return;
10514
10515 perf_output_put(&handle, text_poke_event->event_id);
10516 perf_output_put(&handle, text_poke_event->old_len);
10517 perf_output_put(&handle, text_poke_event->new_len);
10518
10519 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
10520 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
10521
10522 if (text_poke_event->pad)
10523 __output_copy(&handle, &padding, text_poke_event->pad);
10524
10525 perf_event__output_id_sample(event, &handle, &sample);
10526
10527 perf_output_end(&handle);
10528 }
10529
perf_event_text_poke(const void * addr,const void * old_bytes,size_t old_len,const void * new_bytes,size_t new_len)10530 void perf_event_text_poke(const void *addr, const void *old_bytes,
10531 size_t old_len, const void *new_bytes, size_t new_len)
10532 {
10533 struct perf_text_poke_event text_poke_event;
10534 size_t tot, pad;
10535
10536 if (!atomic_read(&nr_text_poke_events))
10537 return;
10538
10539 tot = sizeof(text_poke_event.old_len) + old_len;
10540 tot += sizeof(text_poke_event.new_len) + new_len;
10541 pad = ALIGN(tot, sizeof(u64)) - tot;
10542
10543 text_poke_event = (struct perf_text_poke_event){
10544 .old_bytes = old_bytes,
10545 .new_bytes = new_bytes,
10546 .pad = pad,
10547 .old_len = old_len,
10548 .new_len = new_len,
10549 .event_id = {
10550 .header = {
10551 .type = PERF_RECORD_TEXT_POKE,
10552 .misc = PERF_RECORD_MISC_KERNEL,
10553 .size = sizeof(text_poke_event.event_id) + tot + pad,
10554 },
10555 .addr = (unsigned long)addr,
10556 },
10557 };
10558
10559 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
10560 }
10561
perf_event_itrace_started(struct perf_event * event)10562 void perf_event_itrace_started(struct perf_event *event)
10563 {
10564 WRITE_ONCE(event->attach_state, event->attach_state | PERF_ATTACH_ITRACE);
10565 }
10566
perf_log_itrace_start(struct perf_event * event)10567 static void perf_log_itrace_start(struct perf_event *event)
10568 {
10569 struct perf_output_handle handle;
10570 struct perf_sample_data sample;
10571 struct perf_aux_event {
10572 struct perf_event_header header;
10573 u32 pid;
10574 u32 tid;
10575 } rec;
10576 int ret;
10577
10578 if (event->parent)
10579 event = event->parent;
10580
10581 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
10582 event->attach_state & PERF_ATTACH_ITRACE)
10583 return;
10584
10585 rec.header.type = PERF_RECORD_ITRACE_START;
10586 rec.header.misc = 0;
10587 rec.header.size = sizeof(rec);
10588 rec.pid = perf_event_pid(event, current);
10589 rec.tid = perf_event_tid(event, current);
10590
10591 perf_event_header__init_id(&rec.header, &sample, event);
10592 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
10593
10594 if (ret)
10595 return;
10596
10597 perf_output_put(&handle, rec);
10598 perf_event__output_id_sample(event, &handle, &sample);
10599
10600 perf_output_end(&handle);
10601 }
10602
perf_report_aux_output_id(struct perf_event * event,u64 hw_id)10603 void perf_report_aux_output_id(struct perf_event *event, u64 hw_id)
10604 {
10605 struct perf_output_handle handle;
10606 struct perf_sample_data sample;
10607 struct perf_aux_event {
10608 struct perf_event_header header;
10609 u64 hw_id;
10610 } rec;
10611 int ret;
10612
10613 if (event->parent)
10614 event = event->parent;
10615
10616 rec.header.type = PERF_RECORD_AUX_OUTPUT_HW_ID;
10617 rec.header.misc = 0;
10618 rec.header.size = sizeof(rec);
10619 rec.hw_id = hw_id;
10620
10621 perf_event_header__init_id(&rec.header, &sample, event);
10622 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
10623
10624 if (ret)
10625 return;
10626
10627 perf_output_put(&handle, rec);
10628 perf_event__output_id_sample(event, &handle, &sample);
10629
10630 perf_output_end(&handle);
10631 }
10632 EXPORT_SYMBOL_GPL(perf_report_aux_output_id);
10633
10634 static int
__perf_event_account_interrupt(struct perf_event * event,int throttle)10635 __perf_event_account_interrupt(struct perf_event *event, int throttle)
10636 {
10637 struct hw_perf_event *hwc = &event->hw;
10638 int ret = 0;
10639 u64 seq;
10640
10641 seq = __this_cpu_read(perf_throttled_seq);
10642 if (seq != hwc->interrupts_seq) {
10643 hwc->interrupts_seq = seq;
10644 hwc->interrupts = 1;
10645 } else {
10646 hwc->interrupts++;
10647 }
10648
10649 if (unlikely(throttle && hwc->interrupts >= max_samples_per_tick)) {
10650 __this_cpu_inc(perf_throttled_count);
10651 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
10652 perf_event_throttle_group(event);
10653 ret = 1;
10654 }
10655
10656 if (event->attr.freq) {
10657 u64 now = perf_clock();
10658 s64 delta = now - hwc->freq_time_stamp;
10659
10660 hwc->freq_time_stamp = now;
10661
10662 if (delta > 0 && delta < 2*TICK_NSEC)
10663 perf_adjust_period(event, delta, hwc->last_period, true);
10664 }
10665
10666 return ret;
10667 }
10668
perf_event_account_interrupt(struct perf_event * event)10669 int perf_event_account_interrupt(struct perf_event *event)
10670 {
10671 return __perf_event_account_interrupt(event, 1);
10672 }
10673
sample_is_allowed(struct perf_event * event,struct pt_regs * regs)10674 static inline bool sample_is_allowed(struct perf_event *event, struct pt_regs *regs)
10675 {
10676 /*
10677 * Due to interrupt latency (AKA "skid"), we may enter the
10678 * kernel before taking an overflow, even if the PMU is only
10679 * counting user events.
10680 */
10681 if (event->attr.exclude_kernel && !user_mode(regs))
10682 return false;
10683
10684 return true;
10685 }
10686
10687 #ifdef CONFIG_BPF_SYSCALL
bpf_overflow_handler(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)10688 static int bpf_overflow_handler(struct perf_event *event,
10689 struct perf_sample_data *data,
10690 struct pt_regs *regs)
10691 {
10692 struct bpf_perf_event_data_kern ctx = {
10693 .data = data,
10694 .event = event,
10695 };
10696 struct bpf_prog *prog;
10697 int ret = 0;
10698
10699 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
10700 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
10701 goto out;
10702 rcu_read_lock();
10703 prog = READ_ONCE(event->prog);
10704 if (prog) {
10705 perf_prepare_sample(data, event, regs);
10706 ret = bpf_prog_run(prog, &ctx);
10707 }
10708 rcu_read_unlock();
10709 out:
10710 __this_cpu_dec(bpf_prog_active);
10711
10712 return ret;
10713 }
10714
perf_event_set_bpf_handler(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)10715 static inline int perf_event_set_bpf_handler(struct perf_event *event,
10716 struct bpf_prog *prog,
10717 u64 bpf_cookie)
10718 {
10719 if (event->overflow_handler_context)
10720 /* hw breakpoint or kernel counter */
10721 return -EINVAL;
10722
10723 if (event->prog)
10724 return -EEXIST;
10725
10726 if (prog->type != BPF_PROG_TYPE_PERF_EVENT)
10727 return -EINVAL;
10728
10729 if (event->attr.precise_ip &&
10730 prog->call_get_stack &&
10731 (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) ||
10732 event->attr.exclude_callchain_kernel ||
10733 event->attr.exclude_callchain_user)) {
10734 /*
10735 * On perf_event with precise_ip, calling bpf_get_stack()
10736 * may trigger unwinder warnings and occasional crashes.
10737 * bpf_get_[stack|stackid] works around this issue by using
10738 * callchain attached to perf_sample_data. If the
10739 * perf_event does not full (kernel and user) callchain
10740 * attached to perf_sample_data, do not allow attaching BPF
10741 * program that calls bpf_get_[stack|stackid].
10742 */
10743 return -EPROTO;
10744 }
10745
10746 event->prog = prog;
10747 event->bpf_cookie = bpf_cookie;
10748 return 0;
10749 }
10750
perf_event_free_bpf_handler(struct perf_event * event)10751 static inline void perf_event_free_bpf_handler(struct perf_event *event)
10752 {
10753 struct bpf_prog *prog = event->prog;
10754
10755 if (!prog)
10756 return;
10757
10758 event->prog = NULL;
10759 bpf_prog_put(prog);
10760 }
10761 #else
bpf_overflow_handler(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)10762 static inline int bpf_overflow_handler(struct perf_event *event,
10763 struct perf_sample_data *data,
10764 struct pt_regs *regs)
10765 {
10766 return 1;
10767 }
10768
perf_event_set_bpf_handler(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)10769 static inline int perf_event_set_bpf_handler(struct perf_event *event,
10770 struct bpf_prog *prog,
10771 u64 bpf_cookie)
10772 {
10773 return -EOPNOTSUPP;
10774 }
10775
perf_event_free_bpf_handler(struct perf_event * event)10776 static inline void perf_event_free_bpf_handler(struct perf_event *event)
10777 {
10778 }
10779 #endif
10780
10781 /*
10782 * Generic event overflow handling, sampling.
10783 */
10784
__perf_event_overflow(struct perf_event * event,int throttle,struct perf_sample_data * data,struct pt_regs * regs)10785 static int __perf_event_overflow(struct perf_event *event,
10786 int throttle, struct perf_sample_data *data,
10787 struct pt_regs *regs)
10788 {
10789 int events = atomic_read(&event->event_limit);
10790 int ret = 0;
10791
10792 /*
10793 * Non-sampling counters might still use the PMI to fold short
10794 * hardware counters, ignore those.
10795 */
10796 if (unlikely(!is_sampling_event(event)))
10797 return 0;
10798
10799 ret = __perf_event_account_interrupt(event, throttle);
10800
10801 if (event->attr.aux_pause)
10802 perf_event_aux_pause(event->aux_event, true);
10803
10804 if (event->prog && event->prog->type == BPF_PROG_TYPE_PERF_EVENT &&
10805 !bpf_overflow_handler(event, data, regs))
10806 goto out;
10807
10808 /*
10809 * XXX event_limit might not quite work as expected on inherited
10810 * events
10811 */
10812
10813 event->pending_kill = POLL_IN;
10814 if (events && atomic_dec_and_test(&event->event_limit)) {
10815 ret = 1;
10816 event->pending_kill = POLL_HUP;
10817 perf_event_disable_inatomic(event);
10818 event->pmu->stop(event, 0);
10819 }
10820
10821 if (event->attr.sigtrap) {
10822 /*
10823 * The desired behaviour of sigtrap vs invalid samples is a bit
10824 * tricky; on the one hand, one should not loose the SIGTRAP if
10825 * it is the first event, on the other hand, we should also not
10826 * trigger the WARN or override the data address.
10827 */
10828 bool valid_sample = sample_is_allowed(event, regs);
10829 unsigned int pending_id = 1;
10830 enum task_work_notify_mode notify_mode;
10831
10832 if (regs)
10833 pending_id = hash32_ptr((void *)instruction_pointer(regs)) ?: 1;
10834
10835 notify_mode = in_nmi() ? TWA_NMI_CURRENT : TWA_RESUME;
10836
10837 if (!event->pending_work &&
10838 !task_work_add(current, &event->pending_task, notify_mode)) {
10839 event->pending_work = pending_id;
10840 local_inc(&event->ctx->nr_no_switch_fast);
10841 WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount));
10842
10843 event->pending_addr = 0;
10844 if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR))
10845 event->pending_addr = data->addr;
10846
10847 } else if (event->attr.exclude_kernel && valid_sample) {
10848 /*
10849 * Should not be able to return to user space without
10850 * consuming pending_work; with exceptions:
10851 *
10852 * 1. Where !exclude_kernel, events can overflow again
10853 * in the kernel without returning to user space.
10854 *
10855 * 2. Events that can overflow again before the IRQ-
10856 * work without user space progress (e.g. hrtimer).
10857 * To approximate progress (with false negatives),
10858 * check 32-bit hash of the current IP.
10859 */
10860 WARN_ON_ONCE(event->pending_work != pending_id);
10861 }
10862 }
10863
10864 READ_ONCE(event->overflow_handler)(event, data, regs);
10865
10866 if (*perf_event_fasync(event) && event->pending_kill) {
10867 event->pending_wakeup = 1;
10868 irq_work_queue(&event->pending_irq);
10869 }
10870 out:
10871 if (event->attr.aux_resume)
10872 perf_event_aux_pause(event->aux_event, false);
10873
10874 return ret;
10875 }
10876
perf_event_overflow(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)10877 int perf_event_overflow(struct perf_event *event,
10878 struct perf_sample_data *data,
10879 struct pt_regs *regs)
10880 {
10881 /*
10882 * Entry point from hardware PMI, interrupts should be disabled here.
10883 * This serializes us against perf_event_remove_from_context() in
10884 * things like perf_event_release_kernel().
10885 */
10886 lockdep_assert_irqs_disabled();
10887
10888 return __perf_event_overflow(event, 1, data, regs);
10889 }
10890
10891 /*
10892 * Generic software event infrastructure
10893 */
10894
10895 struct swevent_htable {
10896 struct swevent_hlist *swevent_hlist;
10897 struct mutex hlist_mutex;
10898 int hlist_refcount;
10899 };
10900 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
10901
10902 /*
10903 * We directly increment event->count and keep a second value in
10904 * event->hw.period_left to count intervals. This period event
10905 * is kept in the range [-sample_period, 0] so that we can use the
10906 * sign as trigger.
10907 */
10908
perf_swevent_set_period(struct perf_event * event)10909 u64 perf_swevent_set_period(struct perf_event *event)
10910 {
10911 struct hw_perf_event *hwc = &event->hw;
10912 u64 period = hwc->last_period;
10913 u64 nr, offset;
10914 s64 old, val;
10915
10916 hwc->last_period = hwc->sample_period;
10917
10918 old = local64_read(&hwc->period_left);
10919 do {
10920 val = old;
10921 if (val < 0)
10922 return 0;
10923
10924 nr = div64_u64(period + val, period);
10925 offset = nr * period;
10926 val -= offset;
10927 } while (!local64_try_cmpxchg(&hwc->period_left, &old, val));
10928
10929 return nr;
10930 }
10931
perf_swevent_overflow(struct perf_event * event,u64 overflow,struct perf_sample_data * data,struct pt_regs * regs)10932 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
10933 struct perf_sample_data *data,
10934 struct pt_regs *regs)
10935 {
10936 struct hw_perf_event *hwc = &event->hw;
10937 int throttle = 0;
10938
10939 if (!overflow)
10940 overflow = perf_swevent_set_period(event);
10941
10942 if (hwc->interrupts == MAX_INTERRUPTS)
10943 return;
10944
10945 for (; overflow; overflow--) {
10946 if (__perf_event_overflow(event, throttle,
10947 data, regs)) {
10948 /*
10949 * We inhibit the overflow from happening when
10950 * hwc->interrupts == MAX_INTERRUPTS.
10951 */
10952 break;
10953 }
10954 throttle = 1;
10955 }
10956 }
10957
perf_swevent_event(struct perf_event * event,u64 nr,struct perf_sample_data * data,struct pt_regs * regs)10958 static void perf_swevent_event(struct perf_event *event, u64 nr,
10959 struct perf_sample_data *data,
10960 struct pt_regs *regs)
10961 {
10962 struct hw_perf_event *hwc = &event->hw;
10963
10964 /*
10965 * This is:
10966 * - software preempt
10967 * - tracepoint preempt
10968 * - tp_target_task irq (ctx->lock)
10969 * - uprobes preempt/irq
10970 * - kprobes preempt/irq
10971 * - hw_breakpoint irq
10972 *
10973 * Any of these are sufficient to hold off RCU and thus ensure @event
10974 * exists.
10975 */
10976 lockdep_assert_preemption_disabled();
10977 local64_add(nr, &event->count);
10978
10979 if (!regs)
10980 return;
10981
10982 if (!is_sampling_event(event))
10983 return;
10984
10985 /*
10986 * Serialize against event_function_call() IPIs like normal overflow
10987 * event handling. Specifically, must not allow
10988 * perf_event_release_kernel() -> perf_remove_from_context() to make
10989 * progress and 'release' the event from under us.
10990 */
10991 guard(irqsave)();
10992 if (event->state != PERF_EVENT_STATE_ACTIVE)
10993 return;
10994
10995 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
10996 data->period = nr;
10997 return perf_swevent_overflow(event, 1, data, regs);
10998 } else
10999 data->period = event->hw.last_period;
11000
11001 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
11002 return perf_swevent_overflow(event, 1, data, regs);
11003
11004 if (local64_add_negative(nr, &hwc->period_left))
11005 return;
11006
11007 perf_swevent_overflow(event, 0, data, regs);
11008 }
11009
perf_exclude_event(struct perf_event * event,struct pt_regs * regs)11010 int perf_exclude_event(struct perf_event *event, struct pt_regs *regs)
11011 {
11012 if (event->hw.state & PERF_HES_STOPPED)
11013 return 1;
11014
11015 if (regs) {
11016 if (event->attr.exclude_user && user_mode(regs))
11017 return 1;
11018
11019 if (event->attr.exclude_kernel && !user_mode(regs))
11020 return 1;
11021 }
11022
11023 return 0;
11024 }
11025
perf_swevent_match(struct perf_event * event,enum perf_type_id type,u32 event_id,struct perf_sample_data * data,struct pt_regs * regs)11026 static int perf_swevent_match(struct perf_event *event,
11027 enum perf_type_id type,
11028 u32 event_id,
11029 struct perf_sample_data *data,
11030 struct pt_regs *regs)
11031 {
11032 if (event->attr.type != type)
11033 return 0;
11034
11035 if (event->attr.config != event_id)
11036 return 0;
11037
11038 if (perf_exclude_event(event, regs))
11039 return 0;
11040
11041 return 1;
11042 }
11043
swevent_hash(u64 type,u32 event_id)11044 static inline u64 swevent_hash(u64 type, u32 event_id)
11045 {
11046 u64 val = event_id | (type << 32);
11047
11048 return hash_64(val, SWEVENT_HLIST_BITS);
11049 }
11050
11051 static inline struct hlist_head *
__find_swevent_head(struct swevent_hlist * hlist,u64 type,u32 event_id)11052 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
11053 {
11054 u64 hash = swevent_hash(type, event_id);
11055
11056 return &hlist->heads[hash];
11057 }
11058
11059 /* For the read side: events when they trigger */
11060 static inline struct hlist_head *
find_swevent_head_rcu(struct swevent_htable * swhash,u64 type,u32 event_id)11061 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
11062 {
11063 struct swevent_hlist *hlist;
11064
11065 hlist = rcu_dereference(swhash->swevent_hlist);
11066 if (!hlist)
11067 return NULL;
11068
11069 return __find_swevent_head(hlist, type, event_id);
11070 }
11071
11072 /* For the event head insertion and removal in the hlist */
11073 static inline struct hlist_head *
find_swevent_head(struct swevent_htable * swhash,struct perf_event * event)11074 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
11075 {
11076 struct swevent_hlist *hlist;
11077 u32 event_id = event->attr.config;
11078 u64 type = event->attr.type;
11079
11080 /*
11081 * Event scheduling is always serialized against hlist allocation
11082 * and release. Which makes the protected version suitable here.
11083 * The context lock guarantees that.
11084 */
11085 hlist = rcu_dereference_protected(swhash->swevent_hlist,
11086 lockdep_is_held(&event->ctx->lock));
11087 if (!hlist)
11088 return NULL;
11089
11090 return __find_swevent_head(hlist, type, event_id);
11091 }
11092
do_perf_sw_event(enum perf_type_id type,u32 event_id,u64 nr,struct perf_sample_data * data,struct pt_regs * regs)11093 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
11094 u64 nr,
11095 struct perf_sample_data *data,
11096 struct pt_regs *regs)
11097 {
11098 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
11099 struct perf_event *event;
11100 struct hlist_head *head;
11101
11102 rcu_read_lock();
11103 head = find_swevent_head_rcu(swhash, type, event_id);
11104 if (!head)
11105 goto end;
11106
11107 hlist_for_each_entry_rcu(event, head, hlist_entry) {
11108 if (perf_swevent_match(event, type, event_id, data, regs))
11109 perf_swevent_event(event, nr, data, regs);
11110 }
11111 end:
11112 rcu_read_unlock();
11113 }
11114
11115 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
11116
perf_swevent_get_recursion_context(void)11117 int perf_swevent_get_recursion_context(void)
11118 {
11119 return get_recursion_context(current->perf_recursion);
11120 }
11121 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
11122
perf_swevent_put_recursion_context(int rctx)11123 void perf_swevent_put_recursion_context(int rctx)
11124 {
11125 put_recursion_context(current->perf_recursion, rctx);
11126 }
11127
___perf_sw_event(u32 event_id,u64 nr,struct pt_regs * regs,u64 addr)11128 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
11129 {
11130 struct perf_sample_data data;
11131
11132 if (WARN_ON_ONCE(!regs))
11133 return;
11134
11135 perf_sample_data_init(&data, addr, 0);
11136 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
11137 }
11138
__perf_sw_event(u32 event_id,u64 nr,struct pt_regs * regs,u64 addr)11139 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
11140 {
11141 int rctx;
11142
11143 preempt_disable_notrace();
11144 rctx = perf_swevent_get_recursion_context();
11145 if (unlikely(rctx < 0))
11146 goto fail;
11147
11148 ___perf_sw_event(event_id, nr, regs, addr);
11149
11150 perf_swevent_put_recursion_context(rctx);
11151 fail:
11152 preempt_enable_notrace();
11153 }
11154
perf_swevent_read(struct perf_event * event)11155 static void perf_swevent_read(struct perf_event *event)
11156 {
11157 }
11158
perf_swevent_add(struct perf_event * event,int flags)11159 static int perf_swevent_add(struct perf_event *event, int flags)
11160 {
11161 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
11162 struct hw_perf_event *hwc = &event->hw;
11163 struct hlist_head *head;
11164
11165 if (is_sampling_event(event)) {
11166 hwc->last_period = hwc->sample_period;
11167 perf_swevent_set_period(event);
11168 }
11169
11170 hwc->state = !(flags & PERF_EF_START);
11171
11172 head = find_swevent_head(swhash, event);
11173 if (WARN_ON_ONCE(!head))
11174 return -EINVAL;
11175
11176 hlist_add_head_rcu(&event->hlist_entry, head);
11177 perf_event_update_userpage(event);
11178
11179 return 0;
11180 }
11181
perf_swevent_del(struct perf_event * event,int flags)11182 static void perf_swevent_del(struct perf_event *event, int flags)
11183 {
11184 hlist_del_rcu(&event->hlist_entry);
11185 }
11186
perf_swevent_start(struct perf_event * event,int flags)11187 static void perf_swevent_start(struct perf_event *event, int flags)
11188 {
11189 event->hw.state = 0;
11190 }
11191
perf_swevent_stop(struct perf_event * event,int flags)11192 static void perf_swevent_stop(struct perf_event *event, int flags)
11193 {
11194 event->hw.state = PERF_HES_STOPPED;
11195 }
11196
11197 /* Deref the hlist from the update side */
11198 static inline struct swevent_hlist *
swevent_hlist_deref(struct swevent_htable * swhash)11199 swevent_hlist_deref(struct swevent_htable *swhash)
11200 {
11201 return rcu_dereference_protected(swhash->swevent_hlist,
11202 lockdep_is_held(&swhash->hlist_mutex));
11203 }
11204
swevent_hlist_release(struct swevent_htable * swhash)11205 static void swevent_hlist_release(struct swevent_htable *swhash)
11206 {
11207 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
11208
11209 if (!hlist)
11210 return;
11211
11212 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
11213 kfree_rcu(hlist, rcu_head);
11214 }
11215
swevent_hlist_put_cpu(int cpu)11216 static void swevent_hlist_put_cpu(int cpu)
11217 {
11218 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
11219
11220 mutex_lock(&swhash->hlist_mutex);
11221
11222 if (!--swhash->hlist_refcount)
11223 swevent_hlist_release(swhash);
11224
11225 mutex_unlock(&swhash->hlist_mutex);
11226 }
11227
swevent_hlist_put(void)11228 static void swevent_hlist_put(void)
11229 {
11230 int cpu;
11231
11232 for_each_possible_cpu(cpu)
11233 swevent_hlist_put_cpu(cpu);
11234 }
11235
swevent_hlist_get_cpu(int cpu)11236 static int swevent_hlist_get_cpu(int cpu)
11237 {
11238 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
11239 int err = 0;
11240
11241 mutex_lock(&swhash->hlist_mutex);
11242 if (!swevent_hlist_deref(swhash) &&
11243 cpumask_test_cpu(cpu, perf_online_mask)) {
11244 struct swevent_hlist *hlist;
11245
11246 hlist = kzalloc_obj(*hlist);
11247 if (!hlist) {
11248 err = -ENOMEM;
11249 goto exit;
11250 }
11251 rcu_assign_pointer(swhash->swevent_hlist, hlist);
11252 }
11253 swhash->hlist_refcount++;
11254 exit:
11255 mutex_unlock(&swhash->hlist_mutex);
11256
11257 return err;
11258 }
11259
swevent_hlist_get(void)11260 static int swevent_hlist_get(void)
11261 {
11262 int err, cpu, failed_cpu;
11263
11264 mutex_lock(&pmus_lock);
11265 for_each_possible_cpu(cpu) {
11266 err = swevent_hlist_get_cpu(cpu);
11267 if (err) {
11268 failed_cpu = cpu;
11269 goto fail;
11270 }
11271 }
11272 mutex_unlock(&pmus_lock);
11273 return 0;
11274 fail:
11275 for_each_possible_cpu(cpu) {
11276 if (cpu == failed_cpu)
11277 break;
11278 swevent_hlist_put_cpu(cpu);
11279 }
11280 mutex_unlock(&pmus_lock);
11281 return err;
11282 }
11283
11284 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
11285
sw_perf_event_destroy(struct perf_event * event)11286 static void sw_perf_event_destroy(struct perf_event *event)
11287 {
11288 u64 event_id = event->attr.config;
11289
11290 WARN_ON(event->parent);
11291
11292 static_key_slow_dec(&perf_swevent_enabled[event_id]);
11293 swevent_hlist_put();
11294 }
11295
11296 static struct pmu perf_cpu_clock; /* fwd declaration */
11297 static struct pmu perf_task_clock;
11298
perf_swevent_init(struct perf_event * event)11299 static int perf_swevent_init(struct perf_event *event)
11300 {
11301 u64 event_id = event->attr.config;
11302
11303 if (event->attr.type != PERF_TYPE_SOFTWARE)
11304 return -ENOENT;
11305
11306 /*
11307 * no branch sampling for software events
11308 */
11309 if (has_branch_stack(event))
11310 return -EOPNOTSUPP;
11311
11312 switch (event_id) {
11313 case PERF_COUNT_SW_CPU_CLOCK:
11314 event->attr.type = perf_cpu_clock.type;
11315 return -ENOENT;
11316 case PERF_COUNT_SW_TASK_CLOCK:
11317 event->attr.type = perf_task_clock.type;
11318 return -ENOENT;
11319
11320 default:
11321 break;
11322 }
11323
11324 if (event_id >= PERF_COUNT_SW_MAX)
11325 return -ENOENT;
11326
11327 if (!event->parent) {
11328 int err;
11329
11330 err = swevent_hlist_get();
11331 if (err)
11332 return err;
11333
11334 static_key_slow_inc(&perf_swevent_enabled[event_id]);
11335 event->destroy = sw_perf_event_destroy;
11336 }
11337
11338 return 0;
11339 }
11340
11341 static struct pmu perf_swevent = {
11342 .task_ctx_nr = perf_sw_context,
11343
11344 .capabilities = PERF_PMU_CAP_NO_NMI,
11345
11346 .event_init = perf_swevent_init,
11347 .add = perf_swevent_add,
11348 .del = perf_swevent_del,
11349 .start = perf_swevent_start,
11350 .stop = perf_swevent_stop,
11351 .read = perf_swevent_read,
11352 };
11353
11354 #ifdef CONFIG_EVENT_TRACING
11355
tp_perf_event_destroy(struct perf_event * event)11356 static void tp_perf_event_destroy(struct perf_event *event)
11357 {
11358 perf_trace_destroy(event);
11359 }
11360
perf_tp_event_init(struct perf_event * event)11361 static int perf_tp_event_init(struct perf_event *event)
11362 {
11363 int err;
11364
11365 if (event->attr.type != PERF_TYPE_TRACEPOINT)
11366 return -ENOENT;
11367
11368 /*
11369 * no branch sampling for tracepoint events
11370 */
11371 if (has_branch_stack(event))
11372 return -EOPNOTSUPP;
11373
11374 err = perf_trace_init(event);
11375 if (err)
11376 return err;
11377
11378 event->destroy = tp_perf_event_destroy;
11379
11380 return 0;
11381 }
11382
11383 static struct pmu perf_tracepoint = {
11384 .task_ctx_nr = perf_sw_context,
11385
11386 .event_init = perf_tp_event_init,
11387 .add = perf_trace_add,
11388 .del = perf_trace_del,
11389 .start = perf_swevent_start,
11390 .stop = perf_swevent_stop,
11391 .read = perf_swevent_read,
11392 };
11393
perf_tp_filter_match(struct perf_event * event,struct perf_raw_record * raw)11394 static int perf_tp_filter_match(struct perf_event *event,
11395 struct perf_raw_record *raw)
11396 {
11397 void *record = raw->frag.data;
11398
11399 /* only top level events have filters set */
11400 if (event->parent)
11401 event = event->parent;
11402
11403 if (likely(!event->filter) || filter_match_preds(event->filter, record))
11404 return 1;
11405 return 0;
11406 }
11407
perf_tp_event_match(struct perf_event * event,struct perf_raw_record * raw,struct pt_regs * regs)11408 static int perf_tp_event_match(struct perf_event *event,
11409 struct perf_raw_record *raw,
11410 struct pt_regs *regs)
11411 {
11412 if (event->hw.state & PERF_HES_STOPPED)
11413 return 0;
11414 /*
11415 * If exclude_kernel, only trace user-space tracepoints (uprobes)
11416 */
11417 if (event->attr.exclude_kernel && !user_mode(regs))
11418 return 0;
11419
11420 if (!perf_tp_filter_match(event, raw))
11421 return 0;
11422
11423 return 1;
11424 }
11425
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)11426 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
11427 struct trace_event_call *call, u64 count,
11428 struct pt_regs *regs, struct hlist_head *head,
11429 struct task_struct *task)
11430 {
11431 if (bpf_prog_array_valid(call)) {
11432 *(struct pt_regs **)raw_data = regs;
11433 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
11434 perf_swevent_put_recursion_context(rctx);
11435 return;
11436 }
11437 }
11438 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
11439 rctx, task);
11440 }
11441 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
11442
__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)11443 static void __perf_tp_event_target_task(u64 count, void *record,
11444 struct pt_regs *regs,
11445 struct perf_sample_data *data,
11446 struct perf_raw_record *raw,
11447 struct perf_event *event)
11448 {
11449 struct trace_entry *entry = record;
11450
11451 if (event->attr.config != entry->type)
11452 return;
11453 /* Cannot deliver synchronous signal to other task. */
11454 if (event->attr.sigtrap)
11455 return;
11456 if (perf_tp_event_match(event, raw, regs)) {
11457 perf_sample_data_init(data, 0, 0);
11458 perf_sample_save_raw_data(data, event, raw);
11459 perf_swevent_event(event, count, data, regs);
11460 }
11461 }
11462
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)11463 static void perf_tp_event_target_task(u64 count, void *record,
11464 struct pt_regs *regs,
11465 struct perf_sample_data *data,
11466 struct perf_raw_record *raw,
11467 struct perf_event_context *ctx)
11468 {
11469 unsigned int cpu = smp_processor_id();
11470 struct pmu *pmu = &perf_tracepoint;
11471 struct perf_event *event, *sibling;
11472
11473 perf_event_groups_for_cpu_pmu(event, &ctx->pinned_groups, cpu, pmu) {
11474 __perf_tp_event_target_task(count, record, regs, data, raw, event);
11475 for_each_sibling_event(sibling, event)
11476 __perf_tp_event_target_task(count, record, regs, data, raw, sibling);
11477 }
11478
11479 perf_event_groups_for_cpu_pmu(event, &ctx->flexible_groups, cpu, pmu) {
11480 __perf_tp_event_target_task(count, record, regs, data, raw, event);
11481 for_each_sibling_event(sibling, event)
11482 __perf_tp_event_target_task(count, record, regs, data, raw, sibling);
11483 }
11484 }
11485
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)11486 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
11487 struct pt_regs *regs, struct hlist_head *head, int rctx,
11488 struct task_struct *task)
11489 {
11490 struct perf_sample_data data;
11491 struct perf_event *event;
11492
11493 /*
11494 * Per being a tracepoint, this runs with preemption disabled.
11495 */
11496 lockdep_assert_preemption_disabled();
11497
11498 struct perf_raw_record raw = {
11499 .frag = {
11500 .size = entry_size,
11501 .data = record,
11502 },
11503 };
11504
11505 perf_trace_buf_update(record, event_type);
11506
11507 hlist_for_each_entry_rcu(event, head, hlist_entry) {
11508 if (perf_tp_event_match(event, &raw, regs)) {
11509 /*
11510 * Here use the same on-stack perf_sample_data,
11511 * some members in data are event-specific and
11512 * need to be re-computed for different sweveents.
11513 * Re-initialize data->sample_flags safely to avoid
11514 * the problem that next event skips preparing data
11515 * because data->sample_flags is set.
11516 */
11517 perf_sample_data_init(&data, 0, 0);
11518 perf_sample_save_raw_data(&data, event, &raw);
11519 perf_swevent_event(event, count, &data, regs);
11520 }
11521 }
11522
11523 /*
11524 * If we got specified a target task, also iterate its context and
11525 * deliver this event there too.
11526 */
11527 if (task && task != current) {
11528 struct perf_event_context *ctx;
11529
11530 rcu_read_lock();
11531 ctx = rcu_dereference(task->perf_event_ctxp);
11532 if (!ctx)
11533 goto unlock;
11534
11535 raw_spin_lock(&ctx->lock);
11536 perf_tp_event_target_task(count, record, regs, &data, &raw, ctx);
11537 raw_spin_unlock(&ctx->lock);
11538 unlock:
11539 rcu_read_unlock();
11540 }
11541
11542 perf_swevent_put_recursion_context(rctx);
11543 }
11544 EXPORT_SYMBOL_GPL(perf_tp_event);
11545
11546 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
11547 /*
11548 * Flags in config, used by dynamic PMU kprobe and uprobe
11549 * The flags should match following PMU_FORMAT_ATTR().
11550 *
11551 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
11552 * if not set, create kprobe/uprobe
11553 *
11554 * The following values specify a reference counter (or semaphore in the
11555 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
11556 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
11557 *
11558 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
11559 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
11560 */
11561 enum perf_probe_config {
11562 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
11563 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
11564 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
11565 };
11566
11567 PMU_FORMAT_ATTR(retprobe, "config:0");
11568 #endif
11569
11570 #ifdef CONFIG_KPROBE_EVENTS
11571 static struct attribute *kprobe_attrs[] = {
11572 &format_attr_retprobe.attr,
11573 NULL,
11574 };
11575
11576 static struct attribute_group kprobe_format_group = {
11577 .name = "format",
11578 .attrs = kprobe_attrs,
11579 };
11580
11581 static const struct attribute_group *kprobe_attr_groups[] = {
11582 &kprobe_format_group,
11583 NULL,
11584 };
11585
11586 static int perf_kprobe_event_init(struct perf_event *event);
11587 static struct pmu perf_kprobe = {
11588 .task_ctx_nr = perf_sw_context,
11589 .event_init = perf_kprobe_event_init,
11590 .add = perf_trace_add,
11591 .del = perf_trace_del,
11592 .start = perf_swevent_start,
11593 .stop = perf_swevent_stop,
11594 .read = perf_swevent_read,
11595 .attr_groups = kprobe_attr_groups,
11596 };
11597
perf_kprobe_event_init(struct perf_event * event)11598 static int perf_kprobe_event_init(struct perf_event *event)
11599 {
11600 int err;
11601 bool is_retprobe;
11602
11603 if (event->attr.type != perf_kprobe.type)
11604 return -ENOENT;
11605
11606 if (!perfmon_capable())
11607 return -EACCES;
11608
11609 /*
11610 * no branch sampling for probe events
11611 */
11612 if (has_branch_stack(event))
11613 return -EOPNOTSUPP;
11614
11615 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
11616 err = perf_kprobe_init(event, is_retprobe);
11617 if (err)
11618 return err;
11619
11620 event->destroy = perf_kprobe_destroy;
11621
11622 return 0;
11623 }
11624 #endif /* CONFIG_KPROBE_EVENTS */
11625
11626 #ifdef CONFIG_UPROBE_EVENTS
11627 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
11628
11629 static struct attribute *uprobe_attrs[] = {
11630 &format_attr_retprobe.attr,
11631 &format_attr_ref_ctr_offset.attr,
11632 NULL,
11633 };
11634
11635 static struct attribute_group uprobe_format_group = {
11636 .name = "format",
11637 .attrs = uprobe_attrs,
11638 };
11639
11640 static const struct attribute_group *uprobe_attr_groups[] = {
11641 &uprobe_format_group,
11642 NULL,
11643 };
11644
11645 static int perf_uprobe_event_init(struct perf_event *event);
11646 static struct pmu perf_uprobe = {
11647 .task_ctx_nr = perf_sw_context,
11648 .event_init = perf_uprobe_event_init,
11649 .add = perf_trace_add,
11650 .del = perf_trace_del,
11651 .start = perf_swevent_start,
11652 .stop = perf_swevent_stop,
11653 .read = perf_swevent_read,
11654 .attr_groups = uprobe_attr_groups,
11655 };
11656
perf_uprobe_event_init(struct perf_event * event)11657 static int perf_uprobe_event_init(struct perf_event *event)
11658 {
11659 int err;
11660 unsigned long ref_ctr_offset;
11661 bool is_retprobe;
11662
11663 if (event->attr.type != perf_uprobe.type)
11664 return -ENOENT;
11665
11666 if (!capable(CAP_SYS_ADMIN))
11667 return -EACCES;
11668
11669 /*
11670 * no branch sampling for probe events
11671 */
11672 if (has_branch_stack(event))
11673 return -EOPNOTSUPP;
11674
11675 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
11676 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
11677 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
11678 if (err)
11679 return err;
11680
11681 event->destroy = perf_uprobe_destroy;
11682
11683 return 0;
11684 }
11685 #endif /* CONFIG_UPROBE_EVENTS */
11686
perf_tp_register(void)11687 static inline void perf_tp_register(void)
11688 {
11689 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
11690 #ifdef CONFIG_KPROBE_EVENTS
11691 perf_pmu_register(&perf_kprobe, "kprobe", -1);
11692 #endif
11693 #ifdef CONFIG_UPROBE_EVENTS
11694 perf_pmu_register(&perf_uprobe, "uprobe", -1);
11695 #endif
11696 }
11697
perf_event_free_filter(struct perf_event * event)11698 static void perf_event_free_filter(struct perf_event *event)
11699 {
11700 ftrace_profile_free_filter(event);
11701 }
11702
11703 /*
11704 * returns true if the event is a tracepoint, or a kprobe/upprobe created
11705 * with perf_event_open()
11706 */
perf_event_is_tracing(struct perf_event * event)11707 static inline bool perf_event_is_tracing(struct perf_event *event)
11708 {
11709 if (event->pmu == &perf_tracepoint)
11710 return true;
11711 #ifdef CONFIG_KPROBE_EVENTS
11712 if (event->pmu == &perf_kprobe)
11713 return true;
11714 #endif
11715 #ifdef CONFIG_UPROBE_EVENTS
11716 if (event->pmu == &perf_uprobe)
11717 return true;
11718 #endif
11719 return false;
11720 }
11721
__perf_event_set_bpf_prog(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)11722 static int __perf_event_set_bpf_prog(struct perf_event *event,
11723 struct bpf_prog *prog,
11724 u64 bpf_cookie)
11725 {
11726 bool is_kprobe, is_uprobe, is_tracepoint, is_syscall_tp;
11727
11728 if (event->state <= PERF_EVENT_STATE_REVOKED)
11729 return -ENODEV;
11730
11731 if (!perf_event_is_tracing(event))
11732 return perf_event_set_bpf_handler(event, prog, bpf_cookie);
11733
11734 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_KPROBE;
11735 is_uprobe = event->tp_event->flags & TRACE_EVENT_FL_UPROBE;
11736 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
11737 is_syscall_tp = is_syscall_trace_event(event->tp_event);
11738 if (!is_kprobe && !is_uprobe && !is_tracepoint && !is_syscall_tp)
11739 /* bpf programs can only be attached to u/kprobe or tracepoint */
11740 return -EINVAL;
11741
11742 if (((is_kprobe || is_uprobe) && prog->type != BPF_PROG_TYPE_KPROBE) ||
11743 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
11744 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT))
11745 return -EINVAL;
11746
11747 if (prog->type == BPF_PROG_TYPE_KPROBE && prog->sleepable && !is_uprobe)
11748 /* only uprobe programs are allowed to be sleepable */
11749 return -EINVAL;
11750
11751 if (prog->type == BPF_PROG_TYPE_TRACEPOINT && prog->sleepable) {
11752 /*
11753 * Sleepable tracepoint programs can only attach to faultable
11754 * tracepoints. Currently only syscall tracepoints are faultable.
11755 */
11756 if (!is_syscall_tp)
11757 return -EINVAL;
11758 }
11759
11760 /* Kprobe override only works for kprobes, not uprobes. */
11761 if (prog->kprobe_override && !is_kprobe)
11762 return -EINVAL;
11763
11764 /* Writing to context allowed only for uprobes. */
11765 if (prog->aux->kprobe_write_ctx && !is_uprobe)
11766 return -EINVAL;
11767
11768 if (is_tracepoint || is_syscall_tp) {
11769 int off = trace_event_get_offsets(event->tp_event);
11770
11771 if (prog->aux->max_ctx_offset > off)
11772 return -EACCES;
11773 }
11774
11775 return perf_event_attach_bpf_prog(event, prog, bpf_cookie);
11776 }
11777
perf_event_set_bpf_prog(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)11778 int perf_event_set_bpf_prog(struct perf_event *event,
11779 struct bpf_prog *prog,
11780 u64 bpf_cookie)
11781 {
11782 struct perf_event_context *ctx;
11783 int ret;
11784
11785 ctx = perf_event_ctx_lock(event);
11786 ret = __perf_event_set_bpf_prog(event, prog, bpf_cookie);
11787 perf_event_ctx_unlock(event, ctx);
11788
11789 return ret;
11790 }
11791
perf_event_free_bpf_prog(struct perf_event * event)11792 void perf_event_free_bpf_prog(struct perf_event *event)
11793 {
11794 if (!event->prog)
11795 return;
11796
11797 if (!perf_event_is_tracing(event)) {
11798 perf_event_free_bpf_handler(event);
11799 return;
11800 }
11801 perf_event_detach_bpf_prog(event);
11802 }
11803
11804 #else
11805
perf_tp_register(void)11806 static inline void perf_tp_register(void)
11807 {
11808 }
11809
perf_event_free_filter(struct perf_event * event)11810 static void perf_event_free_filter(struct perf_event *event)
11811 {
11812 }
11813
__perf_event_set_bpf_prog(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)11814 static int __perf_event_set_bpf_prog(struct perf_event *event,
11815 struct bpf_prog *prog,
11816 u64 bpf_cookie)
11817 {
11818 return -ENOENT;
11819 }
11820
perf_event_set_bpf_prog(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)11821 int perf_event_set_bpf_prog(struct perf_event *event,
11822 struct bpf_prog *prog,
11823 u64 bpf_cookie)
11824 {
11825 return -ENOENT;
11826 }
11827
perf_event_free_bpf_prog(struct perf_event * event)11828 void perf_event_free_bpf_prog(struct perf_event *event)
11829 {
11830 }
11831 #endif /* CONFIG_EVENT_TRACING */
11832
11833 #ifdef CONFIG_HAVE_HW_BREAKPOINT
perf_bp_event(struct perf_event * bp,void * data)11834 void perf_bp_event(struct perf_event *bp, void *data)
11835 {
11836 struct perf_sample_data sample;
11837 struct pt_regs *regs = data;
11838
11839 /*
11840 * Exception context, will have interrupts disabled.
11841 */
11842 lockdep_assert_irqs_disabled();
11843
11844 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
11845
11846 if (!bp->hw.state && !perf_exclude_event(bp, regs))
11847 perf_swevent_event(bp, 1, &sample, regs);
11848 }
11849 #endif
11850
11851 /*
11852 * Allocate a new address filter
11853 */
11854 static struct perf_addr_filter *
perf_addr_filter_new(struct perf_event * event,struct list_head * filters)11855 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
11856 {
11857 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
11858 struct perf_addr_filter *filter;
11859
11860 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
11861 if (!filter)
11862 return NULL;
11863
11864 INIT_LIST_HEAD(&filter->entry);
11865 list_add_tail(&filter->entry, filters);
11866
11867 return filter;
11868 }
11869
free_filters_list(struct list_head * filters)11870 static void free_filters_list(struct list_head *filters)
11871 {
11872 struct perf_addr_filter *filter, *iter;
11873
11874 list_for_each_entry_safe(filter, iter, filters, entry) {
11875 path_put(&filter->path);
11876 list_del(&filter->entry);
11877 kfree(filter);
11878 }
11879 }
11880
11881 /*
11882 * Free existing address filters and optionally install new ones
11883 */
perf_addr_filters_splice(struct perf_event * event,struct list_head * head)11884 static void perf_addr_filters_splice(struct perf_event *event,
11885 struct list_head *head)
11886 {
11887 unsigned long flags;
11888 LIST_HEAD(list);
11889
11890 if (!has_addr_filter(event))
11891 return;
11892
11893 /* don't bother with children, they don't have their own filters */
11894 if (event->parent)
11895 return;
11896
11897 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
11898
11899 list_splice_init(&event->addr_filters.list, &list);
11900 if (head)
11901 list_splice(head, &event->addr_filters.list);
11902
11903 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
11904
11905 free_filters_list(&list);
11906 }
11907
perf_free_addr_filters(struct perf_event * event)11908 static void perf_free_addr_filters(struct perf_event *event)
11909 {
11910 /*
11911 * Used during free paths, there is no concurrency.
11912 */
11913 if (list_empty(&event->addr_filters.list))
11914 return;
11915
11916 perf_addr_filters_splice(event, NULL);
11917 }
11918
11919 /*
11920 * Scan through mm's vmas and see if one of them matches the
11921 * @filter; if so, adjust filter's address range.
11922 * Called with mm::mmap_lock down for reading.
11923 */
perf_addr_filter_apply(struct perf_addr_filter * filter,struct mm_struct * mm,struct perf_addr_filter_range * fr)11924 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
11925 struct mm_struct *mm,
11926 struct perf_addr_filter_range *fr)
11927 {
11928 struct vm_area_struct *vma;
11929 VMA_ITERATOR(vmi, mm, 0);
11930
11931 for_each_vma(vmi, vma) {
11932 if (!vma->vm_file)
11933 continue;
11934
11935 if (perf_addr_filter_vma_adjust(filter, vma, fr))
11936 return;
11937 }
11938 }
11939
11940 /*
11941 * Update event's address range filters based on the
11942 * task's existing mappings, if any.
11943 */
perf_event_addr_filters_apply(struct perf_event * event)11944 static void perf_event_addr_filters_apply(struct perf_event *event)
11945 {
11946 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11947 struct task_struct *task = READ_ONCE(event->ctx->task);
11948 struct perf_addr_filter *filter;
11949 struct mm_struct *mm = NULL;
11950 unsigned int count = 0;
11951 unsigned long flags;
11952
11953 /*
11954 * We may observe TASK_TOMBSTONE, which means that the event tear-down
11955 * will stop on the parent's child_mutex that our caller is also holding
11956 */
11957 if (task == TASK_TOMBSTONE)
11958 return;
11959
11960 if (ifh->nr_file_filters) {
11961 mm = get_task_mm(task);
11962 if (!mm)
11963 goto restart;
11964
11965 mmap_read_lock(mm);
11966 }
11967
11968 raw_spin_lock_irqsave(&ifh->lock, flags);
11969 list_for_each_entry(filter, &ifh->list, entry) {
11970 if (filter->path.dentry) {
11971 /*
11972 * Adjust base offset if the filter is associated to a
11973 * binary that needs to be mapped:
11974 */
11975 event->addr_filter_ranges[count].start = 0;
11976 event->addr_filter_ranges[count].size = 0;
11977
11978 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
11979 } else {
11980 event->addr_filter_ranges[count].start = filter->offset;
11981 event->addr_filter_ranges[count].size = filter->size;
11982 }
11983
11984 count++;
11985 }
11986
11987 event->addr_filters_gen++;
11988 raw_spin_unlock_irqrestore(&ifh->lock, flags);
11989
11990 if (ifh->nr_file_filters) {
11991 mmap_read_unlock(mm);
11992
11993 mmput(mm);
11994 }
11995
11996 restart:
11997 perf_event_stop(event, 1);
11998 }
11999
12000 /*
12001 * Address range filtering: limiting the data to certain
12002 * instruction address ranges. Filters are ioctl()ed to us from
12003 * userspace as ascii strings.
12004 *
12005 * Filter string format:
12006 *
12007 * ACTION RANGE_SPEC
12008 * where ACTION is one of the
12009 * * "filter": limit the trace to this region
12010 * * "start": start tracing from this address
12011 * * "stop": stop tracing at this address/region;
12012 * RANGE_SPEC is
12013 * * for kernel addresses: <start address>[/<size>]
12014 * * for object files: <start address>[/<size>]@</path/to/object/file>
12015 *
12016 * if <size> is not specified or is zero, the range is treated as a single
12017 * address; not valid for ACTION=="filter".
12018 */
12019 enum {
12020 IF_ACT_NONE = -1,
12021 IF_ACT_FILTER,
12022 IF_ACT_START,
12023 IF_ACT_STOP,
12024 IF_SRC_FILE,
12025 IF_SRC_KERNEL,
12026 IF_SRC_FILEADDR,
12027 IF_SRC_KERNELADDR,
12028 };
12029
12030 enum {
12031 IF_STATE_ACTION = 0,
12032 IF_STATE_SOURCE,
12033 IF_STATE_END,
12034 };
12035
12036 static const match_table_t if_tokens = {
12037 { IF_ACT_FILTER, "filter" },
12038 { IF_ACT_START, "start" },
12039 { IF_ACT_STOP, "stop" },
12040 { IF_SRC_FILE, "%u/%u@%s" },
12041 { IF_SRC_KERNEL, "%u/%u" },
12042 { IF_SRC_FILEADDR, "%u@%s" },
12043 { IF_SRC_KERNELADDR, "%u" },
12044 { IF_ACT_NONE, NULL },
12045 };
12046
12047 /*
12048 * Address filter string parser
12049 */
12050 static int
perf_event_parse_addr_filter(struct perf_event * event,char * fstr,struct list_head * filters)12051 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
12052 struct list_head *filters)
12053 {
12054 struct perf_addr_filter *filter = NULL;
12055 char *start, *orig, *filename = NULL;
12056 substring_t args[MAX_OPT_ARGS];
12057 int state = IF_STATE_ACTION, token;
12058 unsigned int kernel = 0;
12059 int ret = -EINVAL;
12060
12061 orig = fstr = kstrdup(fstr, GFP_KERNEL);
12062 if (!fstr)
12063 return -ENOMEM;
12064
12065 while ((start = strsep(&fstr, " ,\n")) != NULL) {
12066 static const enum perf_addr_filter_action_t actions[] = {
12067 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
12068 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
12069 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
12070 };
12071 ret = -EINVAL;
12072
12073 if (!*start)
12074 continue;
12075
12076 /* filter definition begins */
12077 if (state == IF_STATE_ACTION) {
12078 filter = perf_addr_filter_new(event, filters);
12079 if (!filter)
12080 goto fail;
12081 }
12082
12083 token = match_token(start, if_tokens, args);
12084 switch (token) {
12085 case IF_ACT_FILTER:
12086 case IF_ACT_START:
12087 case IF_ACT_STOP:
12088 if (state != IF_STATE_ACTION)
12089 goto fail;
12090
12091 filter->action = actions[token];
12092 state = IF_STATE_SOURCE;
12093 break;
12094
12095 case IF_SRC_KERNELADDR:
12096 case IF_SRC_KERNEL:
12097 kernel = 1;
12098 fallthrough;
12099
12100 case IF_SRC_FILEADDR:
12101 case IF_SRC_FILE:
12102 if (state != IF_STATE_SOURCE)
12103 goto fail;
12104
12105 *args[0].to = 0;
12106 ret = kstrtoul(args[0].from, 0, &filter->offset);
12107 if (ret)
12108 goto fail;
12109
12110 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
12111 *args[1].to = 0;
12112 ret = kstrtoul(args[1].from, 0, &filter->size);
12113 if (ret)
12114 goto fail;
12115 }
12116
12117 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
12118 int fpos = token == IF_SRC_FILE ? 2 : 1;
12119
12120 kfree(filename);
12121 filename = match_strdup(&args[fpos]);
12122 if (!filename) {
12123 ret = -ENOMEM;
12124 goto fail;
12125 }
12126 }
12127
12128 state = IF_STATE_END;
12129 break;
12130
12131 default:
12132 goto fail;
12133 }
12134
12135 /*
12136 * Filter definition is fully parsed, validate and install it.
12137 * Make sure that it doesn't contradict itself or the event's
12138 * attribute.
12139 */
12140 if (state == IF_STATE_END) {
12141 ret = -EINVAL;
12142
12143 /*
12144 * ACTION "filter" must have a non-zero length region
12145 * specified.
12146 */
12147 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
12148 !filter->size)
12149 goto fail;
12150
12151 if (!kernel) {
12152 if (!filename)
12153 goto fail;
12154
12155 /*
12156 * For now, we only support file-based filters
12157 * in per-task events; doing so for CPU-wide
12158 * events requires additional context switching
12159 * trickery, since same object code will be
12160 * mapped at different virtual addresses in
12161 * different processes.
12162 */
12163 ret = -EOPNOTSUPP;
12164 if (!event->ctx->task)
12165 goto fail;
12166
12167 /* look up the path and grab its inode */
12168 ret = kern_path(filename, LOOKUP_FOLLOW,
12169 &filter->path);
12170 if (ret)
12171 goto fail;
12172
12173 ret = -EINVAL;
12174 if (!filter->path.dentry ||
12175 !S_ISREG(d_inode(filter->path.dentry)
12176 ->i_mode))
12177 goto fail;
12178
12179 event->addr_filters.nr_file_filters++;
12180 }
12181
12182 /* ready to consume more filters */
12183 kfree(filename);
12184 filename = NULL;
12185 state = IF_STATE_ACTION;
12186 filter = NULL;
12187 kernel = 0;
12188 }
12189 }
12190
12191 if (state != IF_STATE_ACTION)
12192 goto fail;
12193
12194 kfree(filename);
12195 kfree(orig);
12196
12197 return 0;
12198
12199 fail:
12200 kfree(filename);
12201 free_filters_list(filters);
12202 kfree(orig);
12203
12204 return ret;
12205 }
12206
12207 static int
perf_event_set_addr_filter(struct perf_event * event,char * filter_str)12208 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
12209 {
12210 LIST_HEAD(filters);
12211 int ret;
12212
12213 /*
12214 * Since this is called in perf_ioctl() path, we're already holding
12215 * ctx::mutex.
12216 */
12217 lockdep_assert_held(&event->ctx->mutex);
12218
12219 if (WARN_ON_ONCE(event->parent))
12220 return -EINVAL;
12221
12222 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
12223 if (ret)
12224 goto fail_clear_files;
12225
12226 ret = event->pmu->addr_filters_validate(&filters);
12227 if (ret)
12228 goto fail_free_filters;
12229
12230 /* remove existing filters, if any */
12231 perf_addr_filters_splice(event, &filters);
12232
12233 /* install new filters */
12234 perf_event_for_each_child(event, perf_event_addr_filters_apply);
12235
12236 return ret;
12237
12238 fail_free_filters:
12239 free_filters_list(&filters);
12240
12241 fail_clear_files:
12242 event->addr_filters.nr_file_filters = 0;
12243
12244 return ret;
12245 }
12246
perf_event_set_filter(struct perf_event * event,void __user * arg)12247 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
12248 {
12249 int ret = -EINVAL;
12250 char *filter_str;
12251
12252 filter_str = strndup_user(arg, PAGE_SIZE);
12253 if (IS_ERR(filter_str))
12254 return PTR_ERR(filter_str);
12255
12256 #ifdef CONFIG_EVENT_TRACING
12257 if (perf_event_is_tracing(event)) {
12258 struct perf_event_context *ctx = event->ctx;
12259
12260 /*
12261 * Beware, here be dragons!!
12262 *
12263 * the tracepoint muck will deadlock against ctx->mutex, but
12264 * the tracepoint stuff does not actually need it. So
12265 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
12266 * already have a reference on ctx.
12267 *
12268 * This can result in event getting moved to a different ctx,
12269 * but that does not affect the tracepoint state.
12270 */
12271 mutex_unlock(&ctx->mutex);
12272 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
12273 mutex_lock(&ctx->mutex);
12274 } else
12275 #endif
12276 if (has_addr_filter(event))
12277 ret = perf_event_set_addr_filter(event, filter_str);
12278
12279 kfree(filter_str);
12280 return ret;
12281 }
12282
12283 /*
12284 * hrtimer based swevent callback
12285 */
12286
perf_swevent_hrtimer(struct hrtimer * hrtimer)12287 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
12288 {
12289 enum hrtimer_restart ret = HRTIMER_RESTART;
12290 struct perf_sample_data data;
12291 struct pt_regs *regs;
12292 struct perf_event *event;
12293 u64 period;
12294
12295 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
12296
12297 if (event->state != PERF_EVENT_STATE_ACTIVE ||
12298 event->hw.state & PERF_HES_STOPPED)
12299 return HRTIMER_NORESTART;
12300
12301 event->pmu->read(event);
12302
12303 perf_sample_data_init(&data, 0, event->hw.last_period);
12304 regs = get_irq_regs();
12305
12306 if (regs && !perf_exclude_event(event, regs)) {
12307 if (!(event->attr.exclude_idle && is_idle_task(current)))
12308 if (perf_event_overflow(event, &data, regs))
12309 ret = HRTIMER_NORESTART;
12310 }
12311
12312 period = max_t(u64, 10000, event->hw.sample_period);
12313 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
12314
12315 return ret;
12316 }
12317
perf_swevent_start_hrtimer(struct perf_event * event)12318 static void perf_swevent_start_hrtimer(struct perf_event *event)
12319 {
12320 struct hw_perf_event *hwc = &event->hw;
12321 s64 period;
12322
12323 if (!is_sampling_event(event))
12324 return;
12325
12326 period = local64_read(&hwc->period_left);
12327 if (period) {
12328 if (period < 0)
12329 period = 10000;
12330
12331 local64_set(&hwc->period_left, 0);
12332 } else {
12333 period = max_t(u64, 10000, hwc->sample_period);
12334 }
12335 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
12336 HRTIMER_MODE_REL_PINNED_HARD);
12337 }
12338
perf_swevent_cancel_hrtimer(struct perf_event * event)12339 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
12340 {
12341 struct hw_perf_event *hwc = &event->hw;
12342
12343 /*
12344 * Careful: this function can be triggered in the hrtimer handler,
12345 * for cpu-clock events, so hrtimer_cancel() would cause a
12346 * deadlock.
12347 *
12348 * So use hrtimer_try_to_cancel() to try to stop the hrtimer,
12349 * and the cpu-clock handler also sets the PERF_HES_STOPPED flag,
12350 * which guarantees that perf_swevent_hrtimer() will stop the
12351 * hrtimer once it sees the PERF_HES_STOPPED flag.
12352 */
12353 if (is_sampling_event(event) && (hwc->interrupts != MAX_INTERRUPTS)) {
12354 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
12355 local64_set(&hwc->period_left, ktime_to_ns(remaining));
12356
12357 hrtimer_try_to_cancel(&hwc->hrtimer);
12358 }
12359 }
12360
perf_swevent_destroy_hrtimer(struct perf_event * event)12361 static void perf_swevent_destroy_hrtimer(struct perf_event *event)
12362 {
12363 hrtimer_cancel(&event->hw.hrtimer);
12364 }
12365
perf_swevent_init_hrtimer(struct perf_event * event)12366 static void perf_swevent_init_hrtimer(struct perf_event *event)
12367 {
12368 struct hw_perf_event *hwc = &event->hw;
12369
12370 if (!is_sampling_event(event))
12371 return;
12372
12373 hrtimer_setup(&hwc->hrtimer, perf_swevent_hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
12374 event->destroy = perf_swevent_destroy_hrtimer;
12375
12376 /*
12377 * Since hrtimers have a fixed rate, we can do a static freq->period
12378 * mapping and avoid the whole period adjust feedback stuff.
12379 */
12380 if (event->attr.freq) {
12381 long freq = event->attr.sample_freq;
12382
12383 event->attr.sample_period = NSEC_PER_SEC / freq;
12384 hwc->sample_period = event->attr.sample_period;
12385 local64_set(&hwc->period_left, hwc->sample_period);
12386 hwc->last_period = hwc->sample_period;
12387 event->attr.freq = 0;
12388 }
12389 }
12390
12391 /*
12392 * Software event: cpu wall time clock
12393 */
12394
cpu_clock_event_update(struct perf_event * event)12395 static void cpu_clock_event_update(struct perf_event *event)
12396 {
12397 s64 prev;
12398 u64 now;
12399
12400 now = local_clock();
12401 prev = local64_xchg(&event->hw.prev_count, now);
12402 local64_add(now - prev, &event->count);
12403 }
12404
cpu_clock_event_start(struct perf_event * event,int flags)12405 static void cpu_clock_event_start(struct perf_event *event, int flags)
12406 {
12407 event->hw.state = 0;
12408 local64_set(&event->hw.prev_count, local_clock());
12409 perf_swevent_start_hrtimer(event);
12410 }
12411
cpu_clock_event_stop(struct perf_event * event,int flags)12412 static void cpu_clock_event_stop(struct perf_event *event, int flags)
12413 {
12414 event->hw.state = PERF_HES_STOPPED;
12415 perf_swevent_cancel_hrtimer(event);
12416 if (flags & PERF_EF_UPDATE)
12417 cpu_clock_event_update(event);
12418 }
12419
cpu_clock_event_add(struct perf_event * event,int flags)12420 static int cpu_clock_event_add(struct perf_event *event, int flags)
12421 {
12422 if (flags & PERF_EF_START)
12423 cpu_clock_event_start(event, flags);
12424 perf_event_update_userpage(event);
12425
12426 return 0;
12427 }
12428
cpu_clock_event_del(struct perf_event * event,int flags)12429 static void cpu_clock_event_del(struct perf_event *event, int flags)
12430 {
12431 cpu_clock_event_stop(event, PERF_EF_UPDATE);
12432 }
12433
cpu_clock_event_read(struct perf_event * event)12434 static void cpu_clock_event_read(struct perf_event *event)
12435 {
12436 cpu_clock_event_update(event);
12437 }
12438
cpu_clock_event_init(struct perf_event * event)12439 static int cpu_clock_event_init(struct perf_event *event)
12440 {
12441 if (event->attr.type != perf_cpu_clock.type)
12442 return -ENOENT;
12443
12444 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
12445 return -ENOENT;
12446
12447 /*
12448 * no branch sampling for software events
12449 */
12450 if (has_branch_stack(event))
12451 return -EOPNOTSUPP;
12452
12453 perf_swevent_init_hrtimer(event);
12454
12455 return 0;
12456 }
12457
12458 static struct pmu perf_cpu_clock = {
12459 .task_ctx_nr = perf_sw_context,
12460
12461 .capabilities = PERF_PMU_CAP_NO_NMI,
12462 .dev = PMU_NULL_DEV,
12463
12464 .event_init = cpu_clock_event_init,
12465 .add = cpu_clock_event_add,
12466 .del = cpu_clock_event_del,
12467 .start = cpu_clock_event_start,
12468 .stop = cpu_clock_event_stop,
12469 .read = cpu_clock_event_read,
12470 };
12471
12472 /*
12473 * Software event: task time clock
12474 */
12475
task_clock_event_update(struct perf_event * event,u64 now)12476 static void task_clock_event_update(struct perf_event *event, u64 now)
12477 {
12478 u64 prev;
12479 s64 delta;
12480
12481 prev = local64_xchg(&event->hw.prev_count, now);
12482 delta = now - prev;
12483 local64_add(delta, &event->count);
12484 }
12485
task_clock_event_start(struct perf_event * event,int flags)12486 static void task_clock_event_start(struct perf_event *event, int flags)
12487 {
12488 event->hw.state = 0;
12489 local64_set(&event->hw.prev_count, event->ctx->time.time);
12490 perf_swevent_start_hrtimer(event);
12491 }
12492
task_clock_event_stop(struct perf_event * event,int flags)12493 static void task_clock_event_stop(struct perf_event *event, int flags)
12494 {
12495 event->hw.state = PERF_HES_STOPPED;
12496 perf_swevent_cancel_hrtimer(event);
12497 if (flags & PERF_EF_UPDATE)
12498 task_clock_event_update(event, event->ctx->time.time);
12499 }
12500
task_clock_event_add(struct perf_event * event,int flags)12501 static int task_clock_event_add(struct perf_event *event, int flags)
12502 {
12503 if (flags & PERF_EF_START)
12504 task_clock_event_start(event, flags);
12505 perf_event_update_userpage(event);
12506
12507 return 0;
12508 }
12509
task_clock_event_del(struct perf_event * event,int flags)12510 static void task_clock_event_del(struct perf_event *event, int flags)
12511 {
12512 task_clock_event_stop(event, PERF_EF_UPDATE);
12513 }
12514
task_clock_event_read(struct perf_event * event)12515 static void task_clock_event_read(struct perf_event *event)
12516 {
12517 u64 now = perf_clock();
12518 u64 delta = now - event->ctx->time.stamp;
12519 u64 time = event->ctx->time.time + delta;
12520
12521 task_clock_event_update(event, time);
12522 }
12523
task_clock_event_init(struct perf_event * event)12524 static int task_clock_event_init(struct perf_event *event)
12525 {
12526 if (event->attr.type != perf_task_clock.type)
12527 return -ENOENT;
12528
12529 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
12530 return -ENOENT;
12531
12532 /*
12533 * no branch sampling for software events
12534 */
12535 if (has_branch_stack(event))
12536 return -EOPNOTSUPP;
12537
12538 perf_swevent_init_hrtimer(event);
12539
12540 return 0;
12541 }
12542
12543 static struct pmu perf_task_clock = {
12544 .task_ctx_nr = perf_sw_context,
12545
12546 .capabilities = PERF_PMU_CAP_NO_NMI,
12547 .dev = PMU_NULL_DEV,
12548
12549 .event_init = task_clock_event_init,
12550 .add = task_clock_event_add,
12551 .del = task_clock_event_del,
12552 .start = task_clock_event_start,
12553 .stop = task_clock_event_stop,
12554 .read = task_clock_event_read,
12555 };
12556
perf_pmu_nop_void(struct pmu * pmu)12557 static void perf_pmu_nop_void(struct pmu *pmu)
12558 {
12559 }
12560
perf_pmu_nop_txn(struct pmu * pmu,unsigned int flags)12561 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
12562 {
12563 }
12564
perf_pmu_nop_int(struct pmu * pmu)12565 static int perf_pmu_nop_int(struct pmu *pmu)
12566 {
12567 return 0;
12568 }
12569
perf_event_nop_int(struct perf_event * event,u64 value)12570 static int perf_event_nop_int(struct perf_event *event, u64 value)
12571 {
12572 return 0;
12573 }
12574
12575 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
12576
perf_pmu_start_txn(struct pmu * pmu,unsigned int flags)12577 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
12578 {
12579 __this_cpu_write(nop_txn_flags, flags);
12580
12581 if (flags & ~PERF_PMU_TXN_ADD)
12582 return;
12583
12584 perf_pmu_disable(pmu);
12585 }
12586
perf_pmu_commit_txn(struct pmu * pmu)12587 static int perf_pmu_commit_txn(struct pmu *pmu)
12588 {
12589 unsigned int flags = __this_cpu_read(nop_txn_flags);
12590
12591 __this_cpu_write(nop_txn_flags, 0);
12592
12593 if (flags & ~PERF_PMU_TXN_ADD)
12594 return 0;
12595
12596 perf_pmu_enable(pmu);
12597 return 0;
12598 }
12599
perf_pmu_cancel_txn(struct pmu * pmu)12600 static void perf_pmu_cancel_txn(struct pmu *pmu)
12601 {
12602 unsigned int flags = __this_cpu_read(nop_txn_flags);
12603
12604 __this_cpu_write(nop_txn_flags, 0);
12605
12606 if (flags & ~PERF_PMU_TXN_ADD)
12607 return;
12608
12609 perf_pmu_enable(pmu);
12610 }
12611
perf_event_idx_default(struct perf_event * event)12612 static int perf_event_idx_default(struct perf_event *event)
12613 {
12614 return 0;
12615 }
12616
12617 /*
12618 * Let userspace know that this PMU supports address range filtering:
12619 */
nr_addr_filters_show(struct device * dev,struct device_attribute * attr,char * page)12620 static ssize_t nr_addr_filters_show(struct device *dev,
12621 struct device_attribute *attr,
12622 char *page)
12623 {
12624 struct pmu *pmu = dev_get_drvdata(dev);
12625
12626 return sysfs_emit(page, "%d\n", pmu->nr_addr_filters);
12627 }
12628 DEVICE_ATTR_RO(nr_addr_filters);
12629
12630 static struct idr pmu_idr;
12631
12632 static ssize_t
type_show(struct device * dev,struct device_attribute * attr,char * page)12633 type_show(struct device *dev, struct device_attribute *attr, char *page)
12634 {
12635 struct pmu *pmu = dev_get_drvdata(dev);
12636
12637 return sysfs_emit(page, "%d\n", pmu->type);
12638 }
12639 static DEVICE_ATTR_RO(type);
12640
12641 static ssize_t
perf_event_mux_interval_ms_show(struct device * dev,struct device_attribute * attr,char * page)12642 perf_event_mux_interval_ms_show(struct device *dev,
12643 struct device_attribute *attr,
12644 char *page)
12645 {
12646 struct pmu *pmu = dev_get_drvdata(dev);
12647
12648 return sysfs_emit(page, "%d\n", pmu->hrtimer_interval_ms);
12649 }
12650
12651 static DEFINE_MUTEX(mux_interval_mutex);
12652
12653 static ssize_t
perf_event_mux_interval_ms_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)12654 perf_event_mux_interval_ms_store(struct device *dev,
12655 struct device_attribute *attr,
12656 const char *buf, size_t count)
12657 {
12658 struct pmu *pmu = dev_get_drvdata(dev);
12659 int timer, cpu, ret;
12660
12661 ret = kstrtoint(buf, 0, &timer);
12662 if (ret)
12663 return ret;
12664
12665 if (timer < 1)
12666 return -EINVAL;
12667
12668 /* same value, noting to do */
12669 if (timer == pmu->hrtimer_interval_ms)
12670 return count;
12671
12672 mutex_lock(&mux_interval_mutex);
12673 pmu->hrtimer_interval_ms = timer;
12674
12675 /* update all cpuctx for this PMU */
12676 cpus_read_lock();
12677 for_each_online_cpu(cpu) {
12678 struct perf_cpu_pmu_context *cpc;
12679 cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu);
12680 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
12681
12682 cpu_function_call(cpu, perf_mux_hrtimer_restart_ipi, cpc);
12683 }
12684 cpus_read_unlock();
12685 mutex_unlock(&mux_interval_mutex);
12686
12687 return count;
12688 }
12689 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
12690
perf_scope_cpu_topology_cpumask(unsigned int scope,int cpu)12691 static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu)
12692 {
12693 switch (scope) {
12694 case PERF_PMU_SCOPE_CORE:
12695 return topology_sibling_cpumask(cpu);
12696 case PERF_PMU_SCOPE_DIE:
12697 return topology_die_cpumask(cpu);
12698 case PERF_PMU_SCOPE_CLUSTER:
12699 return topology_cluster_cpumask(cpu);
12700 case PERF_PMU_SCOPE_PKG:
12701 return topology_core_cpumask(cpu);
12702 case PERF_PMU_SCOPE_SYS_WIDE:
12703 return cpu_online_mask;
12704 }
12705
12706 return NULL;
12707 }
12708
perf_scope_cpumask(unsigned int scope)12709 static inline struct cpumask *perf_scope_cpumask(unsigned int scope)
12710 {
12711 switch (scope) {
12712 case PERF_PMU_SCOPE_CORE:
12713 return perf_online_core_mask;
12714 case PERF_PMU_SCOPE_DIE:
12715 return perf_online_die_mask;
12716 case PERF_PMU_SCOPE_CLUSTER:
12717 return perf_online_cluster_mask;
12718 case PERF_PMU_SCOPE_PKG:
12719 return perf_online_pkg_mask;
12720 case PERF_PMU_SCOPE_SYS_WIDE:
12721 return perf_online_sys_mask;
12722 }
12723
12724 return NULL;
12725 }
12726
cpumask_show(struct device * dev,struct device_attribute * attr,char * buf)12727 static ssize_t cpumask_show(struct device *dev, struct device_attribute *attr,
12728 char *buf)
12729 {
12730 struct pmu *pmu = dev_get_drvdata(dev);
12731 struct cpumask *mask = perf_scope_cpumask(pmu->scope);
12732
12733 if (mask)
12734 return sysfs_emit(buf, "%*pbl\n", cpumask_pr_args(mask));
12735 return 0;
12736 }
12737
12738 static DEVICE_ATTR_RO(cpumask);
12739
12740 static struct attribute *pmu_dev_attrs[] = {
12741 &dev_attr_type.attr,
12742 &dev_attr_perf_event_mux_interval_ms.attr,
12743 &dev_attr_nr_addr_filters.attr,
12744 &dev_attr_cpumask.attr,
12745 NULL,
12746 };
12747
pmu_dev_is_visible(struct kobject * kobj,struct attribute * a,int n)12748 static umode_t pmu_dev_is_visible(struct kobject *kobj, struct attribute *a, int n)
12749 {
12750 struct device *dev = kobj_to_dev(kobj);
12751 struct pmu *pmu = dev_get_drvdata(dev);
12752
12753 if (n == 2 && !pmu->nr_addr_filters)
12754 return 0;
12755
12756 /* cpumask */
12757 if (n == 3 && pmu->scope == PERF_PMU_SCOPE_NONE)
12758 return 0;
12759
12760 return a->mode;
12761 }
12762
12763 static struct attribute_group pmu_dev_attr_group = {
12764 .is_visible = pmu_dev_is_visible,
12765 .attrs = pmu_dev_attrs,
12766 };
12767
12768 static const struct attribute_group *pmu_dev_groups[] = {
12769 &pmu_dev_attr_group,
12770 NULL,
12771 };
12772
12773 static int pmu_bus_running;
12774 static const struct bus_type pmu_bus = {
12775 .name = "event_source",
12776 .dev_groups = pmu_dev_groups,
12777 };
12778
pmu_dev_release(struct device * dev)12779 static void pmu_dev_release(struct device *dev)
12780 {
12781 kfree(dev);
12782 }
12783
pmu_dev_alloc(struct pmu * pmu)12784 static int pmu_dev_alloc(struct pmu *pmu)
12785 {
12786 int ret = -ENOMEM;
12787
12788 pmu->dev = kzalloc_obj(struct device);
12789 if (!pmu->dev)
12790 goto out;
12791
12792 pmu->dev->groups = pmu->attr_groups;
12793 device_initialize(pmu->dev);
12794
12795 dev_set_drvdata(pmu->dev, pmu);
12796 pmu->dev->bus = &pmu_bus;
12797 pmu->dev->parent = pmu->parent;
12798 pmu->dev->release = pmu_dev_release;
12799
12800 ret = dev_set_name(pmu->dev, "%s", pmu->name);
12801 if (ret)
12802 goto free_dev;
12803
12804 ret = device_add(pmu->dev);
12805 if (ret)
12806 goto free_dev;
12807
12808 if (pmu->attr_update) {
12809 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
12810 if (ret)
12811 goto del_dev;
12812 }
12813
12814 out:
12815 return ret;
12816
12817 del_dev:
12818 device_del(pmu->dev);
12819
12820 free_dev:
12821 put_device(pmu->dev);
12822 pmu->dev = NULL;
12823 goto out;
12824 }
12825
12826 static struct lock_class_key cpuctx_mutex;
12827 static struct lock_class_key cpuctx_lock;
12828
idr_cmpxchg(struct idr * idr,unsigned long id,void * old,void * new)12829 static bool idr_cmpxchg(struct idr *idr, unsigned long id, void *old, void *new)
12830 {
12831 void *tmp, *val = idr_find(idr, id);
12832
12833 if (val != old)
12834 return false;
12835
12836 tmp = idr_replace(idr, new, id);
12837 if (IS_ERR(tmp))
12838 return false;
12839
12840 WARN_ON_ONCE(tmp != val);
12841 return true;
12842 }
12843
perf_pmu_free(struct pmu * pmu)12844 static void perf_pmu_free(struct pmu *pmu)
12845 {
12846 if (pmu_bus_running && pmu->dev && pmu->dev != PMU_NULL_DEV) {
12847 if (pmu->nr_addr_filters)
12848 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
12849 device_del(pmu->dev);
12850 put_device(pmu->dev);
12851 }
12852
12853 if (pmu->cpu_pmu_context) {
12854 int cpu;
12855
12856 for_each_possible_cpu(cpu) {
12857 struct perf_cpu_pmu_context *cpc;
12858
12859 cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu);
12860 if (!cpc)
12861 continue;
12862 if (cpc->epc.embedded) {
12863 /* refcount managed */
12864 put_pmu_ctx(&cpc->epc);
12865 continue;
12866 }
12867 kfree(cpc);
12868 }
12869 free_percpu(pmu->cpu_pmu_context);
12870 }
12871 }
12872
DEFINE_FREE(pmu_unregister,struct pmu *,if (_T)perf_pmu_free (_T))12873 DEFINE_FREE(pmu_unregister, struct pmu *, if (_T) perf_pmu_free(_T))
12874
12875 int perf_pmu_register(struct pmu *_pmu, const char *name, int type)
12876 {
12877 int cpu, max = PERF_TYPE_MAX;
12878
12879 struct pmu *pmu __free(pmu_unregister) = _pmu;
12880 guard(mutex)(&pmus_lock);
12881
12882 if (WARN_ONCE(!name, "Can not register anonymous pmu.\n"))
12883 return -EINVAL;
12884
12885 if (WARN_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE,
12886 "Can not register a pmu with an invalid scope.\n"))
12887 return -EINVAL;
12888
12889 pmu->name = name;
12890
12891 if (type >= 0)
12892 max = type;
12893
12894 CLASS(idr_alloc, pmu_type)(&pmu_idr, NULL, max, 0, GFP_KERNEL);
12895 if (pmu_type.id < 0)
12896 return pmu_type.id;
12897
12898 WARN_ON(type >= 0 && pmu_type.id != type);
12899
12900 pmu->type = pmu_type.id;
12901 atomic_set(&pmu->exclusive_cnt, 0);
12902
12903 if (pmu_bus_running && !pmu->dev) {
12904 int ret = pmu_dev_alloc(pmu);
12905 if (ret)
12906 return ret;
12907 }
12908
12909 pmu->cpu_pmu_context = alloc_percpu(struct perf_cpu_pmu_context *);
12910 if (!pmu->cpu_pmu_context)
12911 return -ENOMEM;
12912
12913 for_each_possible_cpu(cpu) {
12914 struct perf_cpu_pmu_context *cpc =
12915 kmalloc_node(sizeof(struct perf_cpu_pmu_context),
12916 GFP_KERNEL | __GFP_ZERO,
12917 cpu_to_node(cpu));
12918
12919 if (!cpc)
12920 return -ENOMEM;
12921
12922 *per_cpu_ptr(pmu->cpu_pmu_context, cpu) = cpc;
12923 __perf_init_event_pmu_context(&cpc->epc, pmu);
12924 __perf_mux_hrtimer_init(cpc, cpu);
12925 }
12926
12927 if (!pmu->start_txn) {
12928 if (pmu->pmu_enable) {
12929 /*
12930 * If we have pmu_enable/pmu_disable calls, install
12931 * transaction stubs that use that to try and batch
12932 * hardware accesses.
12933 */
12934 pmu->start_txn = perf_pmu_start_txn;
12935 pmu->commit_txn = perf_pmu_commit_txn;
12936 pmu->cancel_txn = perf_pmu_cancel_txn;
12937 } else {
12938 pmu->start_txn = perf_pmu_nop_txn;
12939 pmu->commit_txn = perf_pmu_nop_int;
12940 pmu->cancel_txn = perf_pmu_nop_void;
12941 }
12942 }
12943
12944 if (!pmu->pmu_enable) {
12945 pmu->pmu_enable = perf_pmu_nop_void;
12946 pmu->pmu_disable = perf_pmu_nop_void;
12947 }
12948
12949 if (!pmu->check_period)
12950 pmu->check_period = perf_event_nop_int;
12951
12952 if (!pmu->event_idx)
12953 pmu->event_idx = perf_event_idx_default;
12954
12955 INIT_LIST_HEAD(&pmu->events);
12956 spin_lock_init(&pmu->events_lock);
12957
12958 /*
12959 * Now that the PMU is complete, make it visible to perf_try_init_event().
12960 */
12961 if (!idr_cmpxchg(&pmu_idr, pmu->type, NULL, pmu))
12962 return -EINVAL;
12963 list_add_rcu(&pmu->entry, &pmus);
12964
12965 take_idr_id(pmu_type);
12966 _pmu = no_free_ptr(pmu); // let it rip
12967 return 0;
12968 }
12969 EXPORT_SYMBOL_GPL(perf_pmu_register);
12970
__pmu_detach_event(struct pmu * pmu,struct perf_event * event,struct perf_event_context * ctx)12971 static void __pmu_detach_event(struct pmu *pmu, struct perf_event *event,
12972 struct perf_event_context *ctx)
12973 {
12974 /*
12975 * De-schedule the event and mark it REVOKED.
12976 */
12977 perf_event_exit_event(event, ctx, ctx->task, DETACH_REVOKE);
12978
12979 /*
12980 * All _free_event() bits that rely on event->pmu:
12981 *
12982 * Notably, perf_mmap() relies on the ordering here.
12983 */
12984 scoped_guard (mutex, &event->mmap_mutex) {
12985 WARN_ON_ONCE(pmu->event_unmapped);
12986 /*
12987 * Mostly an empty lock sequence, such that perf_mmap(), which
12988 * relies on mmap_mutex, is sure to observe the state change.
12989 */
12990 }
12991
12992 perf_event_free_bpf_prog(event);
12993 perf_free_addr_filters(event);
12994
12995 if (event->destroy) {
12996 event->destroy(event);
12997 event->destroy = NULL;
12998 }
12999
13000 if (event->pmu_ctx) {
13001 put_pmu_ctx(event->pmu_ctx);
13002 event->pmu_ctx = NULL;
13003 }
13004
13005 exclusive_event_destroy(event);
13006 module_put(pmu->module);
13007
13008 mediated_pmu_unaccount_event(event);
13009 event->pmu = NULL; /* force fault instead of UAF */
13010 }
13011
pmu_detach_event(struct pmu * pmu,struct perf_event * event)13012 static void pmu_detach_event(struct pmu *pmu, struct perf_event *event)
13013 {
13014 struct perf_event_context *ctx;
13015
13016 ctx = perf_event_ctx_lock(event);
13017 __pmu_detach_event(pmu, event, ctx);
13018 perf_event_ctx_unlock(event, ctx);
13019
13020 scoped_guard (spinlock, &pmu->events_lock)
13021 list_del(&event->pmu_list);
13022 }
13023
pmu_get_event(struct pmu * pmu)13024 static struct perf_event *pmu_get_event(struct pmu *pmu)
13025 {
13026 struct perf_event *event;
13027
13028 guard(spinlock)(&pmu->events_lock);
13029 list_for_each_entry(event, &pmu->events, pmu_list) {
13030 if (atomic_long_inc_not_zero(&event->refcount))
13031 return event;
13032 }
13033
13034 return NULL;
13035 }
13036
pmu_empty(struct pmu * pmu)13037 static bool pmu_empty(struct pmu *pmu)
13038 {
13039 guard(spinlock)(&pmu->events_lock);
13040 return list_empty(&pmu->events);
13041 }
13042
pmu_detach_events(struct pmu * pmu)13043 static void pmu_detach_events(struct pmu *pmu)
13044 {
13045 struct perf_event *event;
13046
13047 for (;;) {
13048 event = pmu_get_event(pmu);
13049 if (!event)
13050 break;
13051
13052 pmu_detach_event(pmu, event);
13053 put_event(event);
13054 }
13055
13056 /*
13057 * wait for pending _free_event()s
13058 */
13059 wait_var_event(pmu, pmu_empty(pmu));
13060 }
13061
perf_pmu_unregister(struct pmu * pmu)13062 int perf_pmu_unregister(struct pmu *pmu)
13063 {
13064 scoped_guard (mutex, &pmus_lock) {
13065 if (!idr_cmpxchg(&pmu_idr, pmu->type, pmu, NULL))
13066 return -EINVAL;
13067
13068 list_del_rcu(&pmu->entry);
13069 }
13070
13071 /*
13072 * We dereference the pmu list under both SRCU and regular RCU, so
13073 * synchronize against both of those.
13074 *
13075 * Notably, the entirety of event creation, from perf_init_event()
13076 * (which will now fail, because of the above) until
13077 * perf_install_in_context() should be under SRCU such that
13078 * this synchronizes against event creation. This avoids trying to
13079 * detach events that are not fully formed.
13080 */
13081 synchronize_srcu(&pmus_srcu);
13082 synchronize_rcu();
13083
13084 if (pmu->event_unmapped && !pmu_empty(pmu)) {
13085 /*
13086 * Can't force remove events when pmu::event_unmapped()
13087 * is used in perf_mmap_close().
13088 */
13089 guard(mutex)(&pmus_lock);
13090 idr_cmpxchg(&pmu_idr, pmu->type, NULL, pmu);
13091 list_add_rcu(&pmu->entry, &pmus);
13092 return -EBUSY;
13093 }
13094
13095 scoped_guard (mutex, &pmus_lock)
13096 idr_remove(&pmu_idr, pmu->type);
13097
13098 /*
13099 * PMU is removed from the pmus list, so no new events will
13100 * be created, now take care of the existing ones.
13101 */
13102 pmu_detach_events(pmu);
13103
13104 /*
13105 * PMU is unused, make it go away.
13106 */
13107 perf_pmu_free(pmu);
13108 return 0;
13109 }
13110 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
13111
has_extended_regs(struct perf_event * event)13112 static inline bool has_extended_regs(struct perf_event *event)
13113 {
13114 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
13115 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
13116 }
13117
perf_try_init_event(struct pmu * pmu,struct perf_event * event)13118 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
13119 {
13120 struct perf_event_context *ctx = NULL;
13121 int ret;
13122
13123 if (!try_module_get(pmu->module))
13124 return -ENODEV;
13125
13126 /*
13127 * A number of pmu->event_init() methods iterate the sibling_list to,
13128 * for example, validate if the group fits on the PMU. Therefore,
13129 * if this is a sibling event, acquire the ctx->mutex to protect
13130 * the sibling_list.
13131 */
13132 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
13133 /*
13134 * This ctx->mutex can nest when we're called through
13135 * inheritance. See the perf_event_ctx_lock_nested() comment.
13136 */
13137 ctx = perf_event_ctx_lock_nested(event->group_leader,
13138 SINGLE_DEPTH_NESTING);
13139 BUG_ON(!ctx);
13140 }
13141
13142 event->pmu = pmu;
13143 ret = pmu->event_init(event);
13144
13145 if (ctx)
13146 perf_event_ctx_unlock(event->group_leader, ctx);
13147
13148 if (ret)
13149 goto err_pmu;
13150
13151 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
13152 has_extended_regs(event)) {
13153 ret = -EOPNOTSUPP;
13154 goto err_destroy;
13155 }
13156
13157 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
13158 event_has_any_exclude_flag(event)) {
13159 ret = -EINVAL;
13160 goto err_destroy;
13161 }
13162
13163 if (pmu->scope != PERF_PMU_SCOPE_NONE && event->cpu >= 0) {
13164 const struct cpumask *cpumask;
13165 struct cpumask *pmu_cpumask;
13166 int cpu;
13167
13168 cpumask = perf_scope_cpu_topology_cpumask(pmu->scope, event->cpu);
13169 pmu_cpumask = perf_scope_cpumask(pmu->scope);
13170
13171 ret = -ENODEV;
13172 if (!pmu_cpumask || !cpumask)
13173 goto err_destroy;
13174
13175 cpu = cpumask_any_and(pmu_cpumask, cpumask);
13176 if (cpu >= nr_cpu_ids)
13177 goto err_destroy;
13178
13179 event->event_caps |= PERF_EV_CAP_READ_SCOPE;
13180 }
13181
13182 return 0;
13183
13184 err_destroy:
13185 if (event->destroy) {
13186 event->destroy(event);
13187 event->destroy = NULL;
13188 }
13189
13190 err_pmu:
13191 event->pmu = NULL;
13192 module_put(pmu->module);
13193 return ret;
13194 }
13195
perf_init_event(struct perf_event * event)13196 static struct pmu *perf_init_event(struct perf_event *event)
13197 {
13198 bool extended_type = false;
13199 struct pmu *pmu;
13200 int type, ret;
13201
13202 guard(srcu)(&pmus_srcu); /* pmu idr/list access */
13203
13204 /*
13205 * Save original type before calling pmu->event_init() since certain
13206 * pmus overwrites event->attr.type to forward event to another pmu.
13207 */
13208 event->orig_type = event->attr.type;
13209
13210 /* Try parent's PMU first: */
13211 if (event->parent && event->parent->pmu) {
13212 pmu = event->parent->pmu;
13213 ret = perf_try_init_event(pmu, event);
13214 if (!ret)
13215 return pmu;
13216 }
13217
13218 /*
13219 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
13220 * are often aliases for PERF_TYPE_RAW.
13221 */
13222 type = event->attr.type;
13223 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE) {
13224 type = event->attr.config >> PERF_PMU_TYPE_SHIFT;
13225 if (!type) {
13226 type = PERF_TYPE_RAW;
13227 } else {
13228 extended_type = true;
13229 event->attr.config &= PERF_HW_EVENT_MASK;
13230 }
13231 }
13232
13233 again:
13234 scoped_guard (rcu)
13235 pmu = idr_find(&pmu_idr, type);
13236 if (pmu) {
13237 if (event->attr.type != type && type != PERF_TYPE_RAW &&
13238 !(pmu->capabilities & PERF_PMU_CAP_EXTENDED_HW_TYPE))
13239 return ERR_PTR(-ENOENT);
13240
13241 ret = perf_try_init_event(pmu, event);
13242 if (ret == -ENOENT && event->attr.type != type && !extended_type) {
13243 type = event->attr.type;
13244 goto again;
13245 }
13246
13247 if (ret)
13248 return ERR_PTR(ret);
13249
13250 return pmu;
13251 }
13252
13253 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
13254 ret = perf_try_init_event(pmu, event);
13255 if (!ret)
13256 return pmu;
13257
13258 if (ret != -ENOENT)
13259 return ERR_PTR(ret);
13260 }
13261
13262 return ERR_PTR(-ENOENT);
13263 }
13264
attach_sb_event(struct perf_event * event)13265 static void attach_sb_event(struct perf_event *event)
13266 {
13267 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
13268
13269 raw_spin_lock(&pel->lock);
13270 list_add_rcu(&event->sb_list, &pel->list);
13271 raw_spin_unlock(&pel->lock);
13272 }
13273
13274 /*
13275 * We keep a list of all !task (and therefore per-cpu) events
13276 * that need to receive side-band records.
13277 *
13278 * This avoids having to scan all the various PMU per-cpu contexts
13279 * looking for them.
13280 */
account_pmu_sb_event(struct perf_event * event)13281 static void account_pmu_sb_event(struct perf_event *event)
13282 {
13283 if (is_sb_event(event))
13284 attach_sb_event(event);
13285 }
13286
13287 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
account_freq_event_nohz(void)13288 static void account_freq_event_nohz(void)
13289 {
13290 #ifdef CONFIG_NO_HZ_FULL
13291 /* Lock so we don't race with concurrent unaccount */
13292 spin_lock(&nr_freq_lock);
13293 if (atomic_inc_return(&nr_freq_events) == 1)
13294 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
13295 spin_unlock(&nr_freq_lock);
13296 #endif
13297 }
13298
account_freq_event(void)13299 static void account_freq_event(void)
13300 {
13301 if (tick_nohz_full_enabled())
13302 account_freq_event_nohz();
13303 else
13304 atomic_inc(&nr_freq_events);
13305 }
13306
13307
account_event(struct perf_event * event)13308 static void account_event(struct perf_event *event)
13309 {
13310 bool inc = false;
13311
13312 if (event->parent)
13313 return;
13314
13315 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
13316 inc = true;
13317 if (event->attr.mmap || event->attr.mmap_data)
13318 atomic_inc(&nr_mmap_events);
13319 if (event->attr.build_id)
13320 atomic_inc(&nr_build_id_events);
13321 if (event->attr.comm)
13322 atomic_inc(&nr_comm_events);
13323 if (event->attr.namespaces)
13324 atomic_inc(&nr_namespaces_events);
13325 if (event->attr.cgroup)
13326 atomic_inc(&nr_cgroup_events);
13327 if (event->attr.task)
13328 atomic_inc(&nr_task_events);
13329 if (event->attr.freq)
13330 account_freq_event();
13331 if (event->attr.context_switch) {
13332 atomic_inc(&nr_switch_events);
13333 inc = true;
13334 }
13335 if (has_branch_stack(event))
13336 inc = true;
13337 if (is_cgroup_event(event))
13338 inc = true;
13339 if (event->attr.ksymbol)
13340 atomic_inc(&nr_ksymbol_events);
13341 if (event->attr.bpf_event)
13342 atomic_inc(&nr_bpf_events);
13343 if (event->attr.text_poke)
13344 atomic_inc(&nr_text_poke_events);
13345
13346 if (inc) {
13347 /*
13348 * We need the mutex here because static_branch_enable()
13349 * must complete *before* the perf_sched_count increment
13350 * becomes visible.
13351 */
13352 if (atomic_inc_not_zero(&perf_sched_count))
13353 goto enabled;
13354
13355 mutex_lock(&perf_sched_mutex);
13356 if (!atomic_read(&perf_sched_count)) {
13357 static_branch_enable(&perf_sched_events);
13358 /*
13359 * Guarantee that all CPUs observe they key change and
13360 * call the perf scheduling hooks before proceeding to
13361 * install events that need them.
13362 */
13363 synchronize_rcu();
13364 }
13365 /*
13366 * Now that we have waited for the sync_sched(), allow further
13367 * increments to by-pass the mutex.
13368 */
13369 atomic_inc(&perf_sched_count);
13370 mutex_unlock(&perf_sched_mutex);
13371 }
13372 enabled:
13373
13374 account_pmu_sb_event(event);
13375 }
13376
13377 /*
13378 * Allocate and initialize an event structure
13379 */
13380 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)13381 perf_event_alloc(struct perf_event_attr *attr, int cpu,
13382 struct task_struct *task,
13383 struct perf_event *group_leader,
13384 struct perf_event *parent_event,
13385 perf_overflow_handler_t overflow_handler,
13386 void *context, int cgroup_fd)
13387 {
13388 struct pmu *pmu;
13389 struct hw_perf_event *hwc;
13390 long err = -EINVAL;
13391 int node;
13392
13393 if ((unsigned)cpu >= nr_cpu_ids) {
13394 if (!task || cpu != -1)
13395 return ERR_PTR(-EINVAL);
13396 }
13397 if (attr->sigtrap && !task) {
13398 /* Requires a task: avoid signalling random tasks. */
13399 return ERR_PTR(-EINVAL);
13400 }
13401
13402 node = (cpu >= 0) ? cpu_to_node(cpu) : -1;
13403 struct perf_event *event __free(__free_event) =
13404 kmem_cache_alloc_node(perf_event_cache, GFP_KERNEL | __GFP_ZERO, node);
13405 if (!event)
13406 return ERR_PTR(-ENOMEM);
13407
13408 /*
13409 * Single events are their own group leaders, with an
13410 * empty sibling list:
13411 */
13412 if (!group_leader)
13413 group_leader = event;
13414
13415 mutex_init(&event->child_mutex);
13416 INIT_LIST_HEAD(&event->child_list);
13417
13418 INIT_LIST_HEAD(&event->event_entry);
13419 INIT_LIST_HEAD(&event->sibling_list);
13420 INIT_LIST_HEAD(&event->active_list);
13421 init_event_group(event);
13422 INIT_LIST_HEAD(&event->rb_entry);
13423 INIT_LIST_HEAD(&event->active_entry);
13424 INIT_LIST_HEAD(&event->addr_filters.list);
13425 INIT_HLIST_NODE(&event->hlist_entry);
13426 INIT_LIST_HEAD(&event->pmu_list);
13427
13428
13429 init_waitqueue_head(&event->waitq);
13430 init_irq_work(&event->pending_irq, perf_pending_irq);
13431 event->pending_disable_irq = IRQ_WORK_INIT_HARD(perf_pending_disable);
13432 init_task_work(&event->pending_task, perf_pending_task);
13433
13434 mutex_init(&event->mmap_mutex);
13435 raw_spin_lock_init(&event->addr_filters.lock);
13436
13437 atomic_long_set(&event->refcount, 1);
13438 event->cpu = cpu;
13439 event->attr = *attr;
13440 event->group_leader = group_leader;
13441 event->pmu = NULL;
13442 event->oncpu = -1;
13443
13444 event->parent = parent_event;
13445
13446 event->ns = get_pid_ns(task_active_pid_ns(current));
13447 event->id = atomic64_inc_return(&perf_event_id);
13448
13449 event->state = PERF_EVENT_STATE_INACTIVE;
13450
13451 if (parent_event)
13452 event->event_caps = parent_event->event_caps;
13453
13454 if (task) {
13455 event->attach_state = PERF_ATTACH_TASK;
13456 /*
13457 * XXX pmu::event_init needs to know what task to account to
13458 * and we cannot use the ctx information because we need the
13459 * pmu before we get a ctx.
13460 */
13461 event->hw.target = get_task_struct(task);
13462 }
13463
13464 event->clock = &local_clock;
13465 if (parent_event)
13466 event->clock = parent_event->clock;
13467
13468 if (!overflow_handler && parent_event) {
13469 overflow_handler = parent_event->overflow_handler;
13470 context = parent_event->overflow_handler_context;
13471 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
13472 if (parent_event->prog) {
13473 struct bpf_prog *prog = parent_event->prog;
13474
13475 bpf_prog_inc(prog);
13476 event->prog = prog;
13477 }
13478 #endif
13479 }
13480
13481 if (overflow_handler) {
13482 event->overflow_handler = overflow_handler;
13483 event->overflow_handler_context = context;
13484 } else if (is_write_backward(event)){
13485 event->overflow_handler = perf_event_output_backward;
13486 event->overflow_handler_context = NULL;
13487 } else {
13488 event->overflow_handler = perf_event_output_forward;
13489 event->overflow_handler_context = NULL;
13490 }
13491
13492 perf_event__state_init(event);
13493
13494 pmu = NULL;
13495
13496 hwc = &event->hw;
13497 hwc->sample_period = attr->sample_period;
13498 if (is_event_in_freq_mode(event))
13499 hwc->sample_period = 1;
13500 hwc->last_period = hwc->sample_period;
13501
13502 local64_set(&hwc->period_left, hwc->sample_period);
13503
13504 /*
13505 * We do not support PERF_SAMPLE_READ on inherited events unless
13506 * PERF_SAMPLE_TID is also selected, which allows inherited events to
13507 * collect per-thread samples.
13508 * See perf_output_read().
13509 */
13510 if (has_inherit_and_sample_read(attr) && !(attr->sample_type & PERF_SAMPLE_TID))
13511 return ERR_PTR(-EINVAL);
13512
13513 if (!has_branch_stack(event))
13514 event->attr.branch_sample_type = 0;
13515
13516 pmu = perf_init_event(event);
13517 if (IS_ERR(pmu))
13518 return (void*)pmu;
13519
13520 /*
13521 * The PERF_ATTACH_TASK_DATA is set in the event_init()->hw_config().
13522 * The attach should be right after the perf_init_event().
13523 * Otherwise, the __free_event() would mistakenly detach the non-exist
13524 * perf_ctx_data because of the other errors between them.
13525 */
13526 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
13527 err = attach_perf_ctx_data(event);
13528 if (err)
13529 return ERR_PTR(err);
13530 }
13531
13532 /*
13533 * Disallow uncore-task events. Similarly, disallow uncore-cgroup
13534 * events (they don't make sense as the cgroup will be different
13535 * on other CPUs in the uncore mask).
13536 */
13537 if (pmu->task_ctx_nr == perf_invalid_context && (task || cgroup_fd != -1))
13538 return ERR_PTR(-EINVAL);
13539
13540 if (event->attr.aux_output &&
13541 (!(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT) ||
13542 event->attr.aux_pause || event->attr.aux_resume))
13543 return ERR_PTR(-EOPNOTSUPP);
13544
13545 if (event->attr.aux_pause && event->attr.aux_resume)
13546 return ERR_PTR(-EINVAL);
13547
13548 if (event->attr.aux_start_paused) {
13549 if (!(pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE))
13550 return ERR_PTR(-EOPNOTSUPP);
13551 event->hw.aux_paused = 1;
13552 }
13553
13554 if (cgroup_fd != -1) {
13555 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
13556 if (err)
13557 return ERR_PTR(err);
13558 }
13559
13560 err = exclusive_event_init(event);
13561 if (err)
13562 return ERR_PTR(err);
13563
13564 if (has_addr_filter(event)) {
13565 event->addr_filter_ranges = kzalloc_objs(struct perf_addr_filter_range,
13566 pmu->nr_addr_filters);
13567 if (!event->addr_filter_ranges)
13568 return ERR_PTR(-ENOMEM);
13569
13570 /*
13571 * Clone the parent's vma offsets: they are valid until exec()
13572 * even if the mm is not shared with the parent.
13573 */
13574 if (event->parent) {
13575 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
13576
13577 raw_spin_lock_irq(&ifh->lock);
13578 memcpy(event->addr_filter_ranges,
13579 event->parent->addr_filter_ranges,
13580 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
13581 raw_spin_unlock_irq(&ifh->lock);
13582 }
13583
13584 /* force hw sync on the address filters */
13585 event->addr_filters_gen = 1;
13586 }
13587
13588 if (!event->parent) {
13589 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
13590 err = get_callchain_buffers(attr->sample_max_stack);
13591 if (err)
13592 return ERR_PTR(err);
13593 event->attach_state |= PERF_ATTACH_CALLCHAIN;
13594 }
13595 }
13596
13597 err = security_perf_event_alloc(event);
13598 if (err)
13599 return ERR_PTR(err);
13600
13601 err = mediated_pmu_account_event(event);
13602 if (err)
13603 return ERR_PTR(err);
13604
13605 /* symmetric to unaccount_event() in _free_event() */
13606 account_event(event);
13607
13608 /*
13609 * Event creation should be under SRCU, see perf_pmu_unregister().
13610 */
13611 lockdep_assert_held(&pmus_srcu);
13612 scoped_guard (spinlock, &pmu->events_lock)
13613 list_add(&event->pmu_list, &pmu->events);
13614
13615 return_ptr(event);
13616 }
13617
perf_copy_attr(struct perf_event_attr __user * uattr,struct perf_event_attr * attr)13618 static int perf_copy_attr(struct perf_event_attr __user *uattr,
13619 struct perf_event_attr *attr)
13620 {
13621 u32 size;
13622 int ret;
13623
13624 /* Zero the full structure, so that a short copy will be nice. */
13625 memset(attr, 0, sizeof(*attr));
13626
13627 ret = get_user(size, &uattr->size);
13628 if (ret)
13629 return ret;
13630
13631 /* ABI compatibility quirk: */
13632 if (!size)
13633 size = PERF_ATTR_SIZE_VER0;
13634 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
13635 goto err_size;
13636
13637 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
13638 if (ret) {
13639 if (ret == -E2BIG)
13640 goto err_size;
13641 return ret;
13642 }
13643
13644 attr->size = size;
13645
13646 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
13647 return -EINVAL;
13648
13649 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
13650 return -EINVAL;
13651
13652 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
13653 return -EINVAL;
13654
13655 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
13656 u64 mask = attr->branch_sample_type;
13657
13658 /* only using defined bits */
13659 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
13660 return -EINVAL;
13661
13662 /* at least one branch bit must be set */
13663 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
13664 return -EINVAL;
13665
13666 /* propagate priv level, when not set for branch */
13667 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
13668
13669 /* exclude_kernel checked on syscall entry */
13670 if (!attr->exclude_kernel)
13671 mask |= PERF_SAMPLE_BRANCH_KERNEL;
13672
13673 if (!attr->exclude_user)
13674 mask |= PERF_SAMPLE_BRANCH_USER;
13675
13676 if (!attr->exclude_hv)
13677 mask |= PERF_SAMPLE_BRANCH_HV;
13678 /*
13679 * adjust user setting (for HW filter setup)
13680 */
13681 attr->branch_sample_type = mask;
13682 }
13683 /* privileged levels capture (kernel, hv): check permissions */
13684 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
13685 ret = perf_allow_kernel();
13686 if (ret)
13687 return ret;
13688 }
13689 }
13690
13691 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
13692 ret = perf_reg_validate(attr->sample_regs_user);
13693 if (ret)
13694 return ret;
13695 }
13696
13697 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
13698 if (!arch_perf_have_user_stack_dump())
13699 return -ENOSYS;
13700
13701 /*
13702 * We have __u32 type for the size, but so far
13703 * we can only use __u16 as maximum due to the
13704 * __u16 sample size limit.
13705 */
13706 if (attr->sample_stack_user >= USHRT_MAX)
13707 return -EINVAL;
13708 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
13709 return -EINVAL;
13710 }
13711
13712 if (!attr->sample_max_stack)
13713 attr->sample_max_stack = sysctl_perf_event_max_stack;
13714
13715 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
13716 ret = perf_reg_validate(attr->sample_regs_intr);
13717
13718 #ifndef CONFIG_CGROUP_PERF
13719 if (attr->sample_type & PERF_SAMPLE_CGROUP)
13720 return -EINVAL;
13721 #endif
13722 if ((attr->sample_type & PERF_SAMPLE_WEIGHT) &&
13723 (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT))
13724 return -EINVAL;
13725
13726 if (!attr->inherit && attr->inherit_thread)
13727 return -EINVAL;
13728
13729 if (attr->remove_on_exec && attr->enable_on_exec)
13730 return -EINVAL;
13731
13732 if (attr->sigtrap && !attr->remove_on_exec)
13733 return -EINVAL;
13734
13735 out:
13736 return ret;
13737
13738 err_size:
13739 put_user(sizeof(*attr), &uattr->size);
13740 ret = -E2BIG;
13741 goto out;
13742 }
13743
mutex_lock_double(struct mutex * a,struct mutex * b)13744 static void mutex_lock_double(struct mutex *a, struct mutex *b)
13745 {
13746 if (b < a)
13747 swap(a, b);
13748
13749 mutex_lock(a);
13750 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
13751 }
13752
13753 static int
perf_event_set_output(struct perf_event * event,struct perf_event * output_event)13754 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
13755 {
13756 struct perf_buffer *rb = NULL;
13757 int ret = -EINVAL;
13758
13759 if (!output_event) {
13760 mutex_lock(&event->mmap_mutex);
13761 goto set;
13762 }
13763
13764 /* don't allow circular references */
13765 if (event == output_event)
13766 goto out;
13767
13768 /*
13769 * Don't allow cross-cpu buffers
13770 */
13771 if (output_event->cpu != event->cpu)
13772 goto out;
13773
13774 /*
13775 * If its not a per-cpu rb, it must be the same task.
13776 */
13777 if (output_event->cpu == -1 && output_event->hw.target != event->hw.target)
13778 goto out;
13779
13780 /*
13781 * Mixing clocks in the same buffer is trouble you don't need.
13782 */
13783 if (output_event->clock != event->clock)
13784 goto out;
13785
13786 /*
13787 * Either writing ring buffer from beginning or from end.
13788 * Mixing is not allowed.
13789 */
13790 if (is_write_backward(output_event) != is_write_backward(event))
13791 goto out;
13792
13793 /*
13794 * If both events generate aux data, they must be on the same PMU
13795 */
13796 if (has_aux(event) && has_aux(output_event) &&
13797 event->pmu != output_event->pmu)
13798 goto out;
13799
13800 /*
13801 * Hold both mmap_mutex to serialize against perf_mmap_close(). Since
13802 * output_event is already on rb->event_list, and the list iteration
13803 * restarts after every removal, it is guaranteed this new event is
13804 * observed *OR* if output_event is already removed, it's guaranteed we
13805 * observe !rb->mmap_count.
13806 */
13807 mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex);
13808 set:
13809 /* Can't redirect output if we've got an active mmap() */
13810 if (refcount_read(&event->mmap_count))
13811 goto unlock;
13812
13813 if (output_event) {
13814 if (output_event->state <= PERF_EVENT_STATE_REVOKED)
13815 goto unlock;
13816
13817 /* get the rb we want to redirect to */
13818 rb = ring_buffer_get(output_event);
13819 if (!rb)
13820 goto unlock;
13821
13822 /* did we race against perf_mmap_close() */
13823 if (!refcount_read(&rb->mmap_count)) {
13824 ring_buffer_put(rb);
13825 goto unlock;
13826 }
13827 }
13828
13829 ring_buffer_attach(event, rb);
13830
13831 ret = 0;
13832 unlock:
13833 mutex_unlock(&event->mmap_mutex);
13834 if (output_event)
13835 mutex_unlock(&output_event->mmap_mutex);
13836
13837 out:
13838 return ret;
13839 }
13840
perf_event_set_clock(struct perf_event * event,clockid_t clk_id)13841 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
13842 {
13843 bool nmi_safe = false;
13844
13845 switch (clk_id) {
13846 case CLOCK_MONOTONIC:
13847 event->clock = &ktime_get_mono_fast_ns;
13848 nmi_safe = true;
13849 break;
13850
13851 case CLOCK_MONOTONIC_RAW:
13852 event->clock = &ktime_get_raw_fast_ns;
13853 nmi_safe = true;
13854 break;
13855
13856 case CLOCK_REALTIME:
13857 event->clock = &ktime_get_real_ns;
13858 break;
13859
13860 case CLOCK_BOOTTIME:
13861 event->clock = &ktime_get_boottime_ns;
13862 break;
13863
13864 case CLOCK_TAI:
13865 event->clock = &ktime_get_clocktai_ns;
13866 break;
13867
13868 default:
13869 return -EINVAL;
13870 }
13871
13872 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
13873 return -EINVAL;
13874
13875 return 0;
13876 }
13877
13878 static bool
perf_check_permission(struct perf_event_attr * attr,struct task_struct * task)13879 perf_check_permission(struct perf_event_attr *attr, struct task_struct *task)
13880 {
13881 unsigned int ptrace_mode = PTRACE_MODE_READ_REALCREDS;
13882 bool is_capable = perfmon_capable();
13883
13884 if (attr->sigtrap) {
13885 /*
13886 * perf_event_attr::sigtrap sends signals to the other task.
13887 * Require the current task to also have CAP_KILL.
13888 */
13889 rcu_read_lock();
13890 is_capable &= ns_capable(__task_cred(task)->user_ns, CAP_KILL);
13891 rcu_read_unlock();
13892
13893 /*
13894 * If the required capabilities aren't available, checks for
13895 * ptrace permissions: upgrade to ATTACH, since sending signals
13896 * can effectively change the target task.
13897 */
13898 ptrace_mode = PTRACE_MODE_ATTACH_REALCREDS;
13899 }
13900
13901 /*
13902 * Preserve ptrace permission check for backwards compatibility. The
13903 * ptrace check also includes checks that the current task and other
13904 * task have matching uids, and is therefore not done here explicitly.
13905 */
13906 return is_capable || ptrace_may_access(task, ptrace_mode);
13907 }
13908
13909 /**
13910 * sys_perf_event_open - open a performance event, associate it to a task/cpu
13911 *
13912 * @attr_uptr: event_id type attributes for monitoring/sampling
13913 * @pid: target pid
13914 * @cpu: target cpu
13915 * @group_fd: group leader event fd
13916 * @flags: perf event open flags
13917 */
SYSCALL_DEFINE5(perf_event_open,struct perf_event_attr __user *,attr_uptr,pid_t,pid,int,cpu,int,group_fd,unsigned long,flags)13918 SYSCALL_DEFINE5(perf_event_open,
13919 struct perf_event_attr __user *, attr_uptr,
13920 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
13921 {
13922 struct perf_event *group_leader = NULL, *output_event = NULL;
13923 struct perf_event_pmu_context *pmu_ctx;
13924 struct perf_event *event, *sibling;
13925 struct perf_event_attr attr;
13926 struct perf_event_context *ctx;
13927 struct file *event_file = NULL;
13928 struct task_struct *task = NULL;
13929 struct pmu *pmu;
13930 int event_fd;
13931 int move_group = 0;
13932 int err;
13933 int f_flags = O_RDWR;
13934 int cgroup_fd = -1;
13935
13936 /* for future expandability... */
13937 if (flags & ~PERF_FLAG_ALL)
13938 return -EINVAL;
13939
13940 err = perf_copy_attr(attr_uptr, &attr);
13941 if (err)
13942 return err;
13943
13944 /* Do we allow access to perf_event_open(2) ? */
13945 err = security_perf_event_open(PERF_SECURITY_OPEN);
13946 if (err)
13947 return err;
13948
13949 if (!attr.exclude_kernel ||
13950 ((attr.sample_type & PERF_SAMPLE_CALLCHAIN) &&
13951 !attr.exclude_callchain_kernel)) {
13952 err = perf_allow_kernel();
13953 if (err)
13954 return err;
13955 }
13956
13957 if (attr.namespaces) {
13958 if (!perfmon_capable())
13959 return -EACCES;
13960 }
13961
13962 if (attr.freq) {
13963 if (attr.sample_freq > sysctl_perf_event_sample_rate)
13964 return -EINVAL;
13965 } else {
13966 if (attr.sample_period & (1ULL << 63))
13967 return -EINVAL;
13968 }
13969
13970 /* Only privileged users can get physical addresses */
13971 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
13972 err = perf_allow_kernel();
13973 if (err)
13974 return err;
13975 }
13976
13977 /* REGS_INTR can leak data, lockdown must prevent this */
13978 if (attr.sample_type & PERF_SAMPLE_REGS_INTR) {
13979 err = security_locked_down(LOCKDOWN_PERF);
13980 if (err)
13981 return err;
13982 }
13983
13984 /*
13985 * In cgroup mode, the pid argument is used to pass the fd
13986 * opened to the cgroup directory in cgroupfs. The cpu argument
13987 * designates the cpu on which to monitor threads from that
13988 * cgroup.
13989 */
13990 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
13991 return -EINVAL;
13992
13993 if (flags & PERF_FLAG_FD_CLOEXEC)
13994 f_flags |= O_CLOEXEC;
13995
13996 event_fd = get_unused_fd_flags(f_flags);
13997 if (event_fd < 0)
13998 return event_fd;
13999
14000 /*
14001 * Event creation should be under SRCU, see perf_pmu_unregister().
14002 */
14003 guard(srcu)(&pmus_srcu);
14004
14005 CLASS(fd, group)(group_fd); // group_fd == -1 => empty
14006 if (group_fd != -1) {
14007 if (!is_perf_file(group)) {
14008 err = -EBADF;
14009 goto err_fd;
14010 }
14011 group_leader = fd_file(group)->private_data;
14012 if (group_leader->state <= PERF_EVENT_STATE_EXIT) {
14013 err = -ENODEV;
14014 goto err_fd;
14015 }
14016 if (flags & PERF_FLAG_FD_OUTPUT)
14017 output_event = group_leader;
14018 if (flags & PERF_FLAG_FD_NO_GROUP)
14019 group_leader = NULL;
14020 }
14021
14022 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
14023 task = find_lively_task_by_vpid(pid);
14024 if (IS_ERR(task)) {
14025 err = PTR_ERR(task);
14026 goto err_fd;
14027 }
14028 }
14029
14030 if (task && group_leader &&
14031 group_leader->attr.inherit != attr.inherit) {
14032 err = -EINVAL;
14033 goto err_task;
14034 }
14035
14036 if (flags & PERF_FLAG_PID_CGROUP)
14037 cgroup_fd = pid;
14038
14039 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
14040 NULL, NULL, cgroup_fd);
14041 if (IS_ERR(event)) {
14042 err = PTR_ERR(event);
14043 goto err_task;
14044 }
14045
14046 if (is_sampling_event(event)) {
14047 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
14048 err = -EOPNOTSUPP;
14049 goto err_alloc;
14050 }
14051 }
14052
14053 /*
14054 * Special case software events and allow them to be part of
14055 * any hardware group.
14056 */
14057 pmu = event->pmu;
14058
14059 if (attr.use_clockid) {
14060 err = perf_event_set_clock(event, attr.clockid);
14061 if (err)
14062 goto err_alloc;
14063 }
14064
14065 if (pmu->task_ctx_nr == perf_sw_context)
14066 event->event_caps |= PERF_EV_CAP_SOFTWARE;
14067
14068 if (task) {
14069 err = down_read_interruptible(&task->signal->exec_update_lock);
14070 if (err)
14071 goto err_alloc;
14072
14073 /*
14074 * We must hold exec_update_lock across this and any potential
14075 * perf_install_in_context() call for this new event to
14076 * serialize against exec() altering our credentials (and the
14077 * perf_event_exit_task() that could imply).
14078 */
14079 err = -EACCES;
14080 if (!perf_check_permission(&attr, task))
14081 goto err_cred;
14082 }
14083
14084 /*
14085 * Get the target context (task or percpu):
14086 */
14087 ctx = find_get_context(task, event);
14088 if (IS_ERR(ctx)) {
14089 err = PTR_ERR(ctx);
14090 goto err_cred;
14091 }
14092
14093 mutex_lock(&ctx->mutex);
14094
14095 if (ctx->task == TASK_TOMBSTONE) {
14096 err = -ESRCH;
14097 goto err_locked;
14098 }
14099
14100 if (!task) {
14101 /*
14102 * Check if the @cpu we're creating an event for is online.
14103 *
14104 * We use the perf_cpu_context::ctx::mutex to serialize against
14105 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
14106 */
14107 struct perf_cpu_context *cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
14108
14109 if (!cpuctx->online) {
14110 err = -ENODEV;
14111 goto err_locked;
14112 }
14113 }
14114
14115 if (group_leader) {
14116 err = -EINVAL;
14117
14118 /*
14119 * Do not allow a recursive hierarchy (this new sibling
14120 * becoming part of another group-sibling):
14121 */
14122 if (group_leader->group_leader != group_leader)
14123 goto err_locked;
14124
14125 /* All events in a group should have the same clock */
14126 if (group_leader->clock != event->clock)
14127 goto err_locked;
14128
14129 /*
14130 * Make sure we're both events for the same CPU;
14131 * grouping events for different CPUs is broken; since
14132 * you can never concurrently schedule them anyhow.
14133 */
14134 if (group_leader->cpu != event->cpu)
14135 goto err_locked;
14136
14137 /*
14138 * Make sure we're both on the same context; either task or cpu.
14139 */
14140 if (group_leader->ctx != ctx)
14141 goto err_locked;
14142
14143 /* Recheck under ctx::mutex to serialize against remove-on-exec. */
14144 if (group_leader->state <= PERF_EVENT_STATE_EXIT) {
14145 err = -ENODEV;
14146 goto err_locked;
14147 }
14148
14149 /*
14150 * Only a group leader can be exclusive or pinned
14151 */
14152 if (attr.exclusive || attr.pinned)
14153 goto err_locked;
14154
14155 if (is_software_event(event) &&
14156 !in_software_context(group_leader)) {
14157 /*
14158 * If the event is a sw event, but the group_leader
14159 * is on hw context.
14160 *
14161 * Allow the addition of software events to hw
14162 * groups, this is safe because software events
14163 * never fail to schedule.
14164 *
14165 * Note the comment that goes with struct
14166 * perf_event_pmu_context.
14167 */
14168 pmu = group_leader->pmu_ctx->pmu;
14169 } else if (!is_software_event(event)) {
14170 if (is_software_event(group_leader) &&
14171 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
14172 /*
14173 * In case the group is a pure software group, and we
14174 * try to add a hardware event, move the whole group to
14175 * the hardware context.
14176 */
14177 move_group = 1;
14178 }
14179
14180 /* Don't allow group of multiple hw events from different pmus */
14181 if (!in_software_context(group_leader) &&
14182 group_leader->pmu_ctx->pmu != pmu)
14183 goto err_locked;
14184 }
14185 }
14186
14187 /*
14188 * Now that we're certain of the pmu; find the pmu_ctx.
14189 */
14190 pmu_ctx = find_get_pmu_context(pmu, ctx, event);
14191 if (IS_ERR(pmu_ctx)) {
14192 err = PTR_ERR(pmu_ctx);
14193 goto err_locked;
14194 }
14195 event->pmu_ctx = pmu_ctx;
14196
14197 if (output_event) {
14198 err = perf_event_set_output(event, output_event);
14199 if (err)
14200 goto err_context;
14201 }
14202
14203 if (!perf_event_validate_size(event)) {
14204 err = -E2BIG;
14205 goto err_context;
14206 }
14207
14208 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
14209 err = -EINVAL;
14210 goto err_context;
14211 }
14212
14213 /*
14214 * Must be under the same ctx::mutex as perf_install_in_context(),
14215 * because we need to serialize with concurrent event creation.
14216 */
14217 if (!exclusive_event_installable(event, ctx)) {
14218 err = -EBUSY;
14219 goto err_context;
14220 }
14221
14222 WARN_ON_ONCE(ctx->parent_ctx);
14223
14224 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags);
14225 if (IS_ERR(event_file)) {
14226 err = PTR_ERR(event_file);
14227 event_file = NULL;
14228 goto err_context;
14229 }
14230
14231 /*
14232 * This is the point on no return; we cannot fail hereafter. This is
14233 * where we start modifying current state.
14234 */
14235
14236 if (move_group) {
14237 perf_remove_from_context(group_leader, 0);
14238 put_pmu_ctx(group_leader->pmu_ctx);
14239
14240 for_each_sibling_event(sibling, group_leader) {
14241 perf_remove_from_context(sibling, 0);
14242 put_pmu_ctx(sibling->pmu_ctx);
14243 }
14244
14245 /*
14246 * Install the group siblings before the group leader.
14247 *
14248 * Because a group leader will try and install the entire group
14249 * (through the sibling list, which is still in-tact), we can
14250 * end up with siblings installed in the wrong context.
14251 *
14252 * By installing siblings first we NO-OP because they're not
14253 * reachable through the group lists.
14254 */
14255 for_each_sibling_event(sibling, group_leader) {
14256 sibling->pmu_ctx = pmu_ctx;
14257 get_pmu_ctx(pmu_ctx);
14258 perf_event__state_init(sibling);
14259 perf_install_in_context(ctx, sibling, sibling->cpu);
14260 }
14261
14262 /*
14263 * Removing from the context ends up with disabled
14264 * event. What we want here is event in the initial
14265 * startup state, ready to be add into new context.
14266 */
14267 group_leader->pmu_ctx = pmu_ctx;
14268 get_pmu_ctx(pmu_ctx);
14269 perf_event__state_init(group_leader);
14270 perf_install_in_context(ctx, group_leader, group_leader->cpu);
14271 }
14272
14273 /*
14274 * Precalculate sample_data sizes; do while holding ctx::mutex such
14275 * that we're serialized against further additions and before
14276 * perf_install_in_context() which is the point the event is active and
14277 * can use these values.
14278 */
14279 perf_event__header_size(event);
14280 perf_event__id_header_size(event);
14281
14282 event->owner = current;
14283
14284 perf_install_in_context(ctx, event, event->cpu);
14285 perf_unpin_context(ctx);
14286
14287 mutex_unlock(&ctx->mutex);
14288
14289 if (task) {
14290 up_read(&task->signal->exec_update_lock);
14291 put_task_struct(task);
14292 }
14293
14294 mutex_lock(¤t->perf_event_mutex);
14295 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
14296 mutex_unlock(¤t->perf_event_mutex);
14297
14298 /*
14299 * File reference in group guarantees that group_leader has been
14300 * kept alive until we place the new event on the sibling_list.
14301 * This ensures destruction of the group leader will find
14302 * the pointer to itself in perf_group_detach().
14303 */
14304 fd_install(event_fd, event_file);
14305 return event_fd;
14306
14307 err_context:
14308 put_pmu_ctx(event->pmu_ctx);
14309 event->pmu_ctx = NULL; /* _free_event() */
14310 err_locked:
14311 mutex_unlock(&ctx->mutex);
14312 perf_unpin_context(ctx);
14313 put_ctx(ctx);
14314 err_cred:
14315 if (task)
14316 up_read(&task->signal->exec_update_lock);
14317 err_alloc:
14318 put_event(event);
14319 err_task:
14320 if (task)
14321 put_task_struct(task);
14322 err_fd:
14323 put_unused_fd(event_fd);
14324 return err;
14325 }
14326
14327 /**
14328 * perf_event_create_kernel_counter
14329 *
14330 * @attr: attributes of the counter to create
14331 * @cpu: cpu in which the counter is bound
14332 * @task: task to profile (NULL for percpu)
14333 * @overflow_handler: callback to trigger when we hit the event
14334 * @context: context data could be used in overflow_handler callback
14335 */
14336 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)14337 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
14338 struct task_struct *task,
14339 perf_overflow_handler_t overflow_handler,
14340 void *context)
14341 {
14342 struct perf_event_pmu_context *pmu_ctx;
14343 struct perf_event_context *ctx;
14344 struct perf_event *event;
14345 struct pmu *pmu;
14346 int err;
14347
14348 /*
14349 * Grouping is not supported for kernel events, neither is 'AUX',
14350 * make sure the caller's intentions are adjusted.
14351 */
14352 if (attr->aux_output || attr->aux_action)
14353 return ERR_PTR(-EINVAL);
14354
14355 /*
14356 * Event creation should be under SRCU, see perf_pmu_unregister().
14357 */
14358 guard(srcu)(&pmus_srcu);
14359
14360 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
14361 overflow_handler, context, -1);
14362 if (IS_ERR(event)) {
14363 err = PTR_ERR(event);
14364 goto err;
14365 }
14366
14367 /* Mark owner so we could distinguish it from user events. */
14368 event->owner = TASK_TOMBSTONE;
14369 pmu = event->pmu;
14370
14371 if (pmu->task_ctx_nr == perf_sw_context)
14372 event->event_caps |= PERF_EV_CAP_SOFTWARE;
14373
14374 /*
14375 * Get the target context (task or percpu):
14376 */
14377 ctx = find_get_context(task, event);
14378 if (IS_ERR(ctx)) {
14379 err = PTR_ERR(ctx);
14380 goto err_alloc;
14381 }
14382
14383 WARN_ON_ONCE(ctx->parent_ctx);
14384 mutex_lock(&ctx->mutex);
14385 if (ctx->task == TASK_TOMBSTONE) {
14386 err = -ESRCH;
14387 goto err_unlock;
14388 }
14389
14390 pmu_ctx = find_get_pmu_context(pmu, ctx, event);
14391 if (IS_ERR(pmu_ctx)) {
14392 err = PTR_ERR(pmu_ctx);
14393 goto err_unlock;
14394 }
14395 event->pmu_ctx = pmu_ctx;
14396
14397 if (!task) {
14398 /*
14399 * Check if the @cpu we're creating an event for is online.
14400 *
14401 * We use the perf_cpu_context::ctx::mutex to serialize against
14402 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
14403 */
14404 struct perf_cpu_context *cpuctx =
14405 container_of(ctx, struct perf_cpu_context, ctx);
14406 if (!cpuctx->online) {
14407 err = -ENODEV;
14408 goto err_pmu_ctx;
14409 }
14410 }
14411
14412 if (!exclusive_event_installable(event, ctx)) {
14413 err = -EBUSY;
14414 goto err_pmu_ctx;
14415 }
14416
14417 perf_install_in_context(ctx, event, event->cpu);
14418 perf_unpin_context(ctx);
14419 mutex_unlock(&ctx->mutex);
14420
14421 return event;
14422
14423 err_pmu_ctx:
14424 put_pmu_ctx(pmu_ctx);
14425 event->pmu_ctx = NULL; /* _free_event() */
14426 err_unlock:
14427 mutex_unlock(&ctx->mutex);
14428 perf_unpin_context(ctx);
14429 put_ctx(ctx);
14430 err_alloc:
14431 put_event(event);
14432 err:
14433 return ERR_PTR(err);
14434 }
14435 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
14436
__perf_pmu_remove(struct perf_event_context * ctx,int cpu,struct pmu * pmu,struct perf_event_groups * groups,struct list_head * events)14437 static void __perf_pmu_remove(struct perf_event_context *ctx,
14438 int cpu, struct pmu *pmu,
14439 struct perf_event_groups *groups,
14440 struct list_head *events)
14441 {
14442 struct perf_event *event, *sibling;
14443
14444 perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) {
14445 perf_remove_from_context(event, 0);
14446 put_pmu_ctx(event->pmu_ctx);
14447 list_add(&event->migrate_entry, events);
14448
14449 for_each_sibling_event(sibling, event) {
14450 perf_remove_from_context(sibling, 0);
14451 put_pmu_ctx(sibling->pmu_ctx);
14452 list_add(&sibling->migrate_entry, events);
14453 }
14454 }
14455 }
14456
__perf_pmu_install_event(struct pmu * pmu,struct perf_event_context * ctx,int cpu,struct perf_event * event)14457 static void __perf_pmu_install_event(struct pmu *pmu,
14458 struct perf_event_context *ctx,
14459 int cpu, struct perf_event *event)
14460 {
14461 struct perf_event_pmu_context *epc;
14462 struct perf_event_context *old_ctx = event->ctx;
14463
14464 get_ctx(ctx); /* normally find_get_context() */
14465
14466 event->cpu = cpu;
14467 epc = find_get_pmu_context(pmu, ctx, event);
14468 event->pmu_ctx = epc;
14469
14470 if (event->state >= PERF_EVENT_STATE_OFF)
14471 event->state = PERF_EVENT_STATE_INACTIVE;
14472 perf_install_in_context(ctx, event, cpu);
14473
14474 /*
14475 * Now that event->ctx is updated and visible, put the old ctx.
14476 */
14477 put_ctx(old_ctx);
14478 }
14479
__perf_pmu_install(struct perf_event_context * ctx,int cpu,struct pmu * pmu,struct list_head * events)14480 static void __perf_pmu_install(struct perf_event_context *ctx,
14481 int cpu, struct pmu *pmu, struct list_head *events)
14482 {
14483 struct perf_event *event, *tmp;
14484
14485 /*
14486 * Re-instate events in 2 passes.
14487 *
14488 * Skip over group leaders and only install siblings on this first
14489 * pass, siblings will not get enabled without a leader, however a
14490 * leader will enable its siblings, even if those are still on the old
14491 * context.
14492 */
14493 list_for_each_entry_safe(event, tmp, events, migrate_entry) {
14494 if (event->group_leader == event)
14495 continue;
14496
14497 list_del(&event->migrate_entry);
14498 __perf_pmu_install_event(pmu, ctx, cpu, event);
14499 }
14500
14501 /*
14502 * Once all the siblings are setup properly, install the group leaders
14503 * to make it go.
14504 */
14505 list_for_each_entry_safe(event, tmp, events, migrate_entry) {
14506 list_del(&event->migrate_entry);
14507 __perf_pmu_install_event(pmu, ctx, cpu, event);
14508 }
14509 }
14510
perf_pmu_migrate_context(struct pmu * pmu,int src_cpu,int dst_cpu)14511 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
14512 {
14513 struct perf_event_context *src_ctx, *dst_ctx;
14514 LIST_HEAD(events);
14515
14516 /*
14517 * Since per-cpu context is persistent, no need to grab an extra
14518 * reference.
14519 */
14520 src_ctx = &per_cpu_ptr(&perf_cpu_context, src_cpu)->ctx;
14521 dst_ctx = &per_cpu_ptr(&perf_cpu_context, dst_cpu)->ctx;
14522
14523 /*
14524 * See perf_event_ctx_lock() for comments on the details
14525 * of swizzling perf_event::ctx.
14526 */
14527 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
14528
14529 __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->pinned_groups, &events);
14530 __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->flexible_groups, &events);
14531
14532 if (!list_empty(&events)) {
14533 /*
14534 * Wait for the events to quiesce before re-instating them.
14535 */
14536 synchronize_rcu();
14537
14538 __perf_pmu_install(dst_ctx, dst_cpu, pmu, &events);
14539 }
14540
14541 mutex_unlock(&dst_ctx->mutex);
14542 mutex_unlock(&src_ctx->mutex);
14543 }
14544 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
14545
sync_child_event(struct perf_event * child_event,struct task_struct * task)14546 static void sync_child_event(struct perf_event *child_event,
14547 struct task_struct *task)
14548 {
14549 struct perf_event *parent_event = child_event->parent;
14550 u64 child_val;
14551
14552 if (child_event->attr.inherit_stat) {
14553 if (task && task != TASK_TOMBSTONE)
14554 perf_event_read_event(child_event, task);
14555 }
14556
14557 child_val = perf_event_count(child_event, false);
14558
14559 /*
14560 * Add back the child's count to the parent's count:
14561 */
14562 atomic64_add(child_val, &parent_event->child_count);
14563 atomic64_add(child_event->total_time_enabled,
14564 &parent_event->child_total_time_enabled);
14565 atomic64_add(child_event->total_time_running,
14566 &parent_event->child_total_time_running);
14567 }
14568
14569 static void
perf_event_exit_event(struct perf_event * event,struct perf_event_context * ctx,struct task_struct * task,unsigned long detach_flags)14570 perf_event_exit_event(struct perf_event *event,
14571 struct perf_event_context *ctx,
14572 struct task_struct *task,
14573 unsigned long detach_flags)
14574 {
14575 struct perf_event *parent_event = event->parent;
14576 unsigned int attach_state;
14577
14578 detach_flags |= DETACH_EXIT;
14579
14580 if (parent_event) {
14581 /*
14582 * Do not destroy the 'original' grouping; because of the
14583 * context switch optimization the original events could've
14584 * ended up in a random child task.
14585 *
14586 * If we were to destroy the original group, all group related
14587 * operations would cease to function properly after this
14588 * random child dies.
14589 *
14590 * Do destroy all inherited groups, we don't care about those
14591 * and being thorough is better.
14592 */
14593 detach_flags |= DETACH_GROUP | DETACH_CHILD;
14594 mutex_lock(&parent_event->child_mutex);
14595 /* PERF_ATTACH_ITRACE might be set concurrently */
14596 attach_state = READ_ONCE(event->attach_state);
14597
14598 if (attach_state & PERF_ATTACH_CHILD)
14599 sync_child_event(event, task);
14600 }
14601
14602 if (detach_flags & DETACH_REVOKE)
14603 detach_flags |= DETACH_GROUP;
14604
14605 perf_remove_from_context(event, detach_flags);
14606 /*
14607 * Child events can be freed.
14608 */
14609 if (parent_event) {
14610 mutex_unlock(&parent_event->child_mutex);
14611
14612 /*
14613 * Match the refcount initialization. Make sure it doesn't happen
14614 * twice if pmu_detach_event() calls it on an already exited task.
14615 */
14616 if (attach_state & PERF_ATTACH_CHILD) {
14617 /*
14618 * Kick perf_poll() for is_event_hup();
14619 */
14620 perf_event_wakeup(parent_event);
14621 /*
14622 * pmu_detach_event() will have an extra refcount.
14623 * perf_pending_task() might have one too.
14624 */
14625 put_event(event);
14626 }
14627
14628 return;
14629 }
14630
14631 /*
14632 * Parent events are governed by their filedesc, retain them.
14633 */
14634 perf_event_wakeup(event);
14635 }
14636
perf_event_exit_task_context(struct task_struct * task,bool exit)14637 static void perf_event_exit_task_context(struct task_struct *task, bool exit)
14638 {
14639 struct perf_event_context *ctx, *clone_ctx = NULL;
14640 struct perf_event *child_event, *next;
14641
14642 ctx = perf_pin_task_context(task);
14643 if (!ctx)
14644 return;
14645
14646 /*
14647 * In order to reduce the amount of tricky in ctx tear-down, we hold
14648 * ctx::mutex over the entire thing. This serializes against almost
14649 * everything that wants to access the ctx.
14650 *
14651 * The exception is sys_perf_event_open() /
14652 * perf_event_create_kernel_count() which does find_get_context()
14653 * without ctx::mutex (it cannot because of the move_group double mutex
14654 * lock thing). See the comments in perf_install_in_context().
14655 */
14656 mutex_lock(&ctx->mutex);
14657
14658 /*
14659 * In a single ctx::lock section, de-schedule the events and detach the
14660 * context from the task such that we cannot ever get it scheduled back
14661 * in.
14662 */
14663 raw_spin_lock_irq(&ctx->lock);
14664 if (exit)
14665 task_ctx_sched_out(ctx, NULL, EVENT_ALL);
14666
14667 /*
14668 * Now that the context is inactive, destroy the task <-> ctx relation
14669 * and mark the context dead.
14670 */
14671 RCU_INIT_POINTER(task->perf_event_ctxp, NULL);
14672 put_ctx(ctx); /* cannot be last */
14673 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
14674 put_task_struct(task); /* cannot be last */
14675
14676 clone_ctx = unclone_ctx(ctx);
14677 raw_spin_unlock_irq(&ctx->lock);
14678
14679 if (clone_ctx)
14680 put_ctx(clone_ctx);
14681
14682 /*
14683 * Report the task dead after unscheduling the events so that we
14684 * won't get any samples after PERF_RECORD_EXIT. We can however still
14685 * get a few PERF_RECORD_READ events.
14686 */
14687 if (exit)
14688 perf_event_task(task, ctx, 0);
14689
14690 list_for_each_entry_safe(child_event, next, &ctx->event_list, event_entry)
14691 perf_event_exit_event(child_event, ctx, exit ? task : NULL, 0);
14692
14693 mutex_unlock(&ctx->mutex);
14694
14695 if (!exit) {
14696 /*
14697 * perf_event_release_kernel() could still have a reference on
14698 * this context. In that case we must wait for these events to
14699 * have been freed (in particular all their references to this
14700 * task must've been dropped).
14701 *
14702 * Without this copy_process() will unconditionally free this
14703 * task (irrespective of its reference count) and
14704 * _free_event()'s put_task_struct(event->hw.target) will be a
14705 * use-after-free.
14706 *
14707 * Wait for all events to drop their context reference.
14708 */
14709 wait_var_event(&ctx->refcount,
14710 refcount_read(&ctx->refcount) == 1);
14711 }
14712 put_ctx(ctx);
14713 }
14714
14715 /*
14716 * When a task exits, feed back event values to parent events.
14717 *
14718 * Can be called with exec_update_lock held when called from
14719 * setup_new_exec().
14720 */
perf_event_exit_task(struct task_struct * task)14721 void perf_event_exit_task(struct task_struct *task)
14722 {
14723 struct perf_event *event, *tmp;
14724
14725 WARN_ON_ONCE(task != current);
14726
14727 mutex_lock(&task->perf_event_mutex);
14728 list_for_each_entry_safe(event, tmp, &task->perf_event_list,
14729 owner_entry) {
14730 list_del_init(&event->owner_entry);
14731
14732 /*
14733 * Ensure the list deletion is visible before we clear
14734 * the owner, closes a race against perf_release() where
14735 * we need to serialize on the owner->perf_event_mutex.
14736 */
14737 smp_store_release(&event->owner, NULL);
14738 }
14739 mutex_unlock(&task->perf_event_mutex);
14740
14741 perf_event_exit_task_context(task, true);
14742
14743 /*
14744 * The perf_event_exit_task_context calls perf_event_task
14745 * with task's task_ctx, which generates EXIT events for
14746 * task contexts and sets task->perf_event_ctxp[] to NULL.
14747 * At this point we need to send EXIT events to cpu contexts.
14748 */
14749 perf_event_task(task, NULL, 0);
14750
14751 /*
14752 * Detach the perf_ctx_data for the system-wide event.
14753 *
14754 * Done without holding global_ctx_data_rwsem; typically
14755 * attach_global_ctx_data() will skip over this task, but otherwise
14756 * attach_task_ctx_data() will observe PF_EXITING.
14757 */
14758 detach_task_ctx_data(task);
14759 }
14760
14761 /*
14762 * Free a context as created by inheritance by perf_event_init_task() below,
14763 * used by fork() in case of fail.
14764 *
14765 * Even though the task has never lived, the context and events have been
14766 * exposed through the child_list, so we must take care tearing it all down.
14767 */
perf_event_free_task(struct task_struct * task)14768 void perf_event_free_task(struct task_struct *task)
14769 {
14770 perf_event_exit_task_context(task, false);
14771 }
14772
perf_event_delayed_put(struct task_struct * task)14773 void perf_event_delayed_put(struct task_struct *task)
14774 {
14775 WARN_ON_ONCE(task->perf_event_ctxp);
14776 }
14777
perf_event_get(unsigned int fd)14778 struct file *perf_event_get(unsigned int fd)
14779 {
14780 struct file *file = fget(fd);
14781 if (!file)
14782 return ERR_PTR(-EBADF);
14783
14784 if (file->f_op != &perf_fops) {
14785 fput(file);
14786 return ERR_PTR(-EBADF);
14787 }
14788
14789 return file;
14790 }
14791
perf_get_event(struct file * file)14792 const struct perf_event *perf_get_event(struct file *file)
14793 {
14794 if (file->f_op != &perf_fops)
14795 return ERR_PTR(-EINVAL);
14796
14797 return file->private_data;
14798 }
14799
perf_event_attrs(struct perf_event * event)14800 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
14801 {
14802 if (!event)
14803 return ERR_PTR(-EINVAL);
14804
14805 return &event->attr;
14806 }
14807
perf_allow_kernel(void)14808 int perf_allow_kernel(void)
14809 {
14810 if (sysctl_perf_event_paranoid > 1 && !perfmon_capable())
14811 return -EACCES;
14812
14813 return security_perf_event_open(PERF_SECURITY_KERNEL);
14814 }
14815 EXPORT_SYMBOL_GPL(perf_allow_kernel);
14816
perf_allow_cpu(void)14817 int perf_allow_cpu(void)
14818 {
14819 if (sysctl_perf_event_paranoid > 0 && !perfmon_capable())
14820 return -EACCES;
14821
14822 return security_perf_event_open(PERF_SECURITY_CPU);
14823 }
14824 EXPORT_SYMBOL_GPL(perf_allow_cpu);
14825
perf_allow_tracepoint(void)14826 int perf_allow_tracepoint(void)
14827 {
14828 if (sysctl_perf_event_paranoid > -1 && !perfmon_capable())
14829 return -EPERM;
14830
14831 return security_perf_event_open(PERF_SECURITY_TRACEPOINT);
14832 }
14833 EXPORT_SYMBOL_GPL(perf_allow_tracepoint);
14834
14835 /*
14836 * Inherit an event from parent task to child task.
14837 *
14838 * Returns:
14839 * - valid pointer on success
14840 * - NULL for orphaned events
14841 * - IS_ERR() on error
14842 */
14843 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)14844 inherit_event(struct perf_event *parent_event,
14845 struct task_struct *parent,
14846 struct perf_event_context *parent_ctx,
14847 struct task_struct *child,
14848 struct perf_event *group_leader,
14849 struct perf_event_context *child_ctx)
14850 {
14851 enum perf_event_state parent_state = parent_event->state;
14852 struct perf_event_pmu_context *pmu_ctx;
14853 struct perf_event *child_event;
14854 unsigned long flags;
14855
14856 /*
14857 * Instead of creating recursive hierarchies of events,
14858 * we link inherited events back to the original parent,
14859 * which has a filp for sure, which we use as the reference
14860 * count:
14861 */
14862 if (parent_event->parent)
14863 parent_event = parent_event->parent;
14864
14865 if (parent_event->state <= PERF_EVENT_STATE_REVOKED)
14866 return NULL;
14867
14868 /*
14869 * Event creation should be under SRCU, see perf_pmu_unregister().
14870 */
14871 guard(srcu)(&pmus_srcu);
14872
14873 child_event = perf_event_alloc(&parent_event->attr,
14874 parent_event->cpu,
14875 child,
14876 group_leader, parent_event,
14877 NULL, NULL, -1);
14878 if (IS_ERR(child_event))
14879 return child_event;
14880
14881 get_ctx(child_ctx);
14882 child_event->ctx = child_ctx;
14883
14884 pmu_ctx = find_get_pmu_context(parent_event->pmu_ctx->pmu, child_ctx, child_event);
14885 if (IS_ERR(pmu_ctx)) {
14886 free_event(child_event);
14887 return ERR_CAST(pmu_ctx);
14888 }
14889 child_event->pmu_ctx = pmu_ctx;
14890
14891 /*
14892 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
14893 * must be under the same lock in order to serialize against
14894 * perf_event_release_kernel(), such that either we must observe
14895 * is_orphaned_event() or they will observe us on the child_list.
14896 */
14897 mutex_lock(&parent_event->child_mutex);
14898 if (is_orphaned_event(parent_event) ||
14899 !atomic_long_inc_not_zero(&parent_event->refcount)) {
14900 mutex_unlock(&parent_event->child_mutex);
14901 free_event(child_event);
14902 return NULL;
14903 }
14904
14905 /*
14906 * Make the child state follow the state of the parent event,
14907 * not its attr.disabled bit. We hold the parent's mutex,
14908 * so we won't race with perf_event_{en, dis}able_family.
14909 */
14910 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
14911 child_event->state = PERF_EVENT_STATE_INACTIVE;
14912 else
14913 child_event->state = PERF_EVENT_STATE_OFF;
14914
14915 if (parent_event->attr.freq) {
14916 u64 sample_period = parent_event->hw.sample_period;
14917 struct hw_perf_event *hwc = &child_event->hw;
14918
14919 hwc->sample_period = sample_period;
14920 hwc->last_period = sample_period;
14921
14922 local64_set(&hwc->period_left, sample_period);
14923 }
14924
14925 child_event->overflow_handler = parent_event->overflow_handler;
14926 child_event->overflow_handler_context
14927 = parent_event->overflow_handler_context;
14928
14929 /*
14930 * Precalculate sample_data sizes
14931 */
14932 perf_event__header_size(child_event);
14933 perf_event__id_header_size(child_event);
14934
14935 /*
14936 * Link it up in the child's context:
14937 */
14938 raw_spin_lock_irqsave(&child_ctx->lock, flags);
14939 add_event_to_ctx(child_event, child_ctx);
14940 child_event->attach_state |= PERF_ATTACH_CHILD;
14941 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
14942
14943 /*
14944 * Link this into the parent event's child list
14945 */
14946 list_add_tail(&child_event->child_list, &parent_event->child_list);
14947 mutex_unlock(&parent_event->child_mutex);
14948
14949 return child_event;
14950 }
14951
14952 /*
14953 * Inherits an event group.
14954 *
14955 * This will quietly suppress orphaned events; !inherit_event() is not an error.
14956 * This matches with perf_event_release_kernel() removing all child events.
14957 *
14958 * Returns:
14959 * - 0 on success
14960 * - <0 on error
14961 */
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)14962 static int inherit_group(struct perf_event *parent_event,
14963 struct task_struct *parent,
14964 struct perf_event_context *parent_ctx,
14965 struct task_struct *child,
14966 struct perf_event_context *child_ctx)
14967 {
14968 struct perf_event *leader;
14969 struct perf_event *sub;
14970 struct perf_event *child_ctr;
14971
14972 leader = inherit_event(parent_event, parent, parent_ctx,
14973 child, NULL, child_ctx);
14974 if (IS_ERR(leader))
14975 return PTR_ERR(leader);
14976 /*
14977 * @leader can be NULL here because of is_orphaned_event(). In this
14978 * case inherit_event() will create individual events, similar to what
14979 * perf_group_detach() would do anyway.
14980 */
14981 for_each_sibling_event(sub, parent_event) {
14982 child_ctr = inherit_event(sub, parent, parent_ctx,
14983 child, leader, child_ctx);
14984 if (IS_ERR(child_ctr))
14985 return PTR_ERR(child_ctr);
14986
14987 if (sub->aux_event == parent_event && child_ctr &&
14988 !perf_get_aux_event(child_ctr, leader))
14989 return -EINVAL;
14990 }
14991 if (leader)
14992 leader->group_generation = parent_event->group_generation;
14993 return 0;
14994 }
14995
14996 /*
14997 * Creates the child task context and tries to inherit the event-group.
14998 *
14999 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
15000 * inherited_all set when we 'fail' to inherit an orphaned event; this is
15001 * consistent with perf_event_release_kernel() removing all child events.
15002 *
15003 * Returns:
15004 * - 0 on success
15005 * - <0 on error
15006 */
15007 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)15008 inherit_task_group(struct perf_event *event, struct task_struct *parent,
15009 struct perf_event_context *parent_ctx,
15010 struct task_struct *child,
15011 u64 clone_flags, int *inherited_all)
15012 {
15013 struct perf_event_context *child_ctx;
15014 int ret;
15015
15016 if (!event->attr.inherit ||
15017 (event->attr.inherit_thread && !(clone_flags & CLONE_THREAD)) ||
15018 /* Do not inherit if sigtrap and signal handlers were cleared. */
15019 (event->attr.sigtrap && (clone_flags & CLONE_CLEAR_SIGHAND))) {
15020 *inherited_all = 0;
15021 return 0;
15022 }
15023
15024 child_ctx = child->perf_event_ctxp;
15025 if (!child_ctx) {
15026 /*
15027 * This is executed from the parent task context, so
15028 * inherit events that have been marked for cloning.
15029 * First allocate and initialize a context for the
15030 * child.
15031 */
15032 child_ctx = alloc_perf_context(child);
15033 if (!child_ctx)
15034 return -ENOMEM;
15035
15036 child->perf_event_ctxp = child_ctx;
15037 }
15038
15039 ret = inherit_group(event, parent, parent_ctx, child, child_ctx);
15040 if (ret)
15041 *inherited_all = 0;
15042
15043 return ret;
15044 }
15045
15046 /*
15047 * Initialize the perf_event context in task_struct
15048 */
perf_event_init_context(struct task_struct * child,u64 clone_flags)15049 static int perf_event_init_context(struct task_struct *child, u64 clone_flags)
15050 {
15051 struct perf_event_context *child_ctx, *parent_ctx;
15052 struct perf_event_context *cloned_ctx;
15053 struct perf_event *event;
15054 struct task_struct *parent = current;
15055 int inherited_all = 1;
15056 unsigned long flags;
15057 int ret = 0;
15058
15059 if (likely(!parent->perf_event_ctxp))
15060 return 0;
15061
15062 /*
15063 * If the parent's context is a clone, pin it so it won't get
15064 * swapped under us.
15065 */
15066 parent_ctx = perf_pin_task_context(parent);
15067 if (!parent_ctx)
15068 return 0;
15069
15070 /*
15071 * No need to check if parent_ctx != NULL here; since we saw
15072 * it non-NULL earlier, the only reason for it to become NULL
15073 * is if we exit, and since we're currently in the middle of
15074 * a fork we can't be exiting at the same time.
15075 */
15076
15077 /*
15078 * Lock the parent list. No need to lock the child - not PID
15079 * hashed yet and not running, so nobody can access it.
15080 */
15081 mutex_lock(&parent_ctx->mutex);
15082
15083 /*
15084 * We dont have to disable NMIs - we are only looking at
15085 * the list, not manipulating it:
15086 */
15087 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
15088 ret = inherit_task_group(event, parent, parent_ctx,
15089 child, clone_flags, &inherited_all);
15090 if (ret)
15091 goto out_unlock;
15092 }
15093
15094 /*
15095 * We can't hold ctx->lock when iterating the ->flexible_group list due
15096 * to allocations, but we need to prevent rotation because
15097 * rotate_ctx() will change the list from interrupt context.
15098 */
15099 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
15100 parent_ctx->rotate_disable = 1;
15101 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
15102
15103 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
15104 ret = inherit_task_group(event, parent, parent_ctx,
15105 child, clone_flags, &inherited_all);
15106 if (ret)
15107 goto out_unlock;
15108 }
15109
15110 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
15111 parent_ctx->rotate_disable = 0;
15112
15113 child_ctx = child->perf_event_ctxp;
15114
15115 if (child_ctx && inherited_all) {
15116 /*
15117 * Mark the child context as a clone of the parent
15118 * context, or of whatever the parent is a clone of.
15119 *
15120 * Note that if the parent is a clone, the holding of
15121 * parent_ctx->lock avoids it from being uncloned.
15122 */
15123 cloned_ctx = parent_ctx->parent_ctx;
15124 if (cloned_ctx) {
15125 child_ctx->parent_ctx = cloned_ctx;
15126 child_ctx->parent_gen = parent_ctx->parent_gen;
15127 } else {
15128 child_ctx->parent_ctx = parent_ctx;
15129 child_ctx->parent_gen = parent_ctx->generation;
15130 }
15131 get_ctx(child_ctx->parent_ctx);
15132 }
15133
15134 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
15135 out_unlock:
15136 mutex_unlock(&parent_ctx->mutex);
15137
15138 perf_unpin_context(parent_ctx);
15139 put_ctx(parent_ctx);
15140
15141 return ret;
15142 }
15143
15144 /*
15145 * Initialize the perf_event context in task_struct
15146 */
perf_event_init_task(struct task_struct * child,u64 clone_flags)15147 int perf_event_init_task(struct task_struct *child, u64 clone_flags)
15148 {
15149 int ret;
15150
15151 memset(child->perf_recursion, 0, sizeof(child->perf_recursion));
15152 child->perf_event_ctxp = NULL;
15153 mutex_init(&child->perf_event_mutex);
15154 INIT_LIST_HEAD(&child->perf_event_list);
15155 child->perf_ctx_data = NULL;
15156
15157 ret = perf_event_init_context(child, clone_flags);
15158 if (ret) {
15159 perf_event_free_task(child);
15160 return ret;
15161 }
15162
15163 return 0;
15164 }
15165
perf_event_init_all_cpus(void)15166 static void __init perf_event_init_all_cpus(void)
15167 {
15168 struct swevent_htable *swhash;
15169 struct perf_cpu_context *cpuctx;
15170 int cpu;
15171
15172 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
15173 zalloc_cpumask_var(&perf_online_core_mask, GFP_KERNEL);
15174 zalloc_cpumask_var(&perf_online_die_mask, GFP_KERNEL);
15175 zalloc_cpumask_var(&perf_online_cluster_mask, GFP_KERNEL);
15176 zalloc_cpumask_var(&perf_online_pkg_mask, GFP_KERNEL);
15177 zalloc_cpumask_var(&perf_online_sys_mask, GFP_KERNEL);
15178
15179
15180 for_each_possible_cpu(cpu) {
15181 swhash = &per_cpu(swevent_htable, cpu);
15182 mutex_init(&swhash->hlist_mutex);
15183
15184 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
15185 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
15186
15187 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
15188
15189 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
15190 __perf_event_init_context(&cpuctx->ctx);
15191 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
15192 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
15193 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
15194 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
15195 cpuctx->heap = cpuctx->heap_default;
15196 }
15197 }
15198
perf_swevent_init_cpu(unsigned int cpu)15199 static void perf_swevent_init_cpu(unsigned int cpu)
15200 {
15201 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
15202
15203 mutex_lock(&swhash->hlist_mutex);
15204 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
15205 struct swevent_hlist *hlist;
15206
15207 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
15208 WARN_ON(!hlist);
15209 rcu_assign_pointer(swhash->swevent_hlist, hlist);
15210 }
15211 mutex_unlock(&swhash->hlist_mutex);
15212 }
15213
15214 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
__perf_event_exit_context(void * __info)15215 static void __perf_event_exit_context(void *__info)
15216 {
15217 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
15218 struct perf_event_context *ctx = __info;
15219 struct perf_event *event;
15220
15221 raw_spin_lock(&ctx->lock);
15222 ctx_sched_out(ctx, NULL, EVENT_TIME);
15223 list_for_each_entry(event, &ctx->event_list, event_entry)
15224 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
15225 raw_spin_unlock(&ctx->lock);
15226 }
15227
perf_event_clear_cpumask(unsigned int cpu)15228 static void perf_event_clear_cpumask(unsigned int cpu)
15229 {
15230 int target[PERF_PMU_MAX_SCOPE];
15231 unsigned int scope;
15232 struct pmu *pmu;
15233
15234 cpumask_clear_cpu(cpu, perf_online_mask);
15235
15236 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) {
15237 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu);
15238 struct cpumask *pmu_cpumask = perf_scope_cpumask(scope);
15239
15240 target[scope] = -1;
15241 if (WARN_ON_ONCE(!pmu_cpumask || !cpumask))
15242 continue;
15243
15244 if (!cpumask_test_and_clear_cpu(cpu, pmu_cpumask))
15245 continue;
15246 target[scope] = cpumask_any_but(cpumask, cpu);
15247 if (target[scope] < nr_cpu_ids)
15248 cpumask_set_cpu(target[scope], pmu_cpumask);
15249 }
15250
15251 /* migrate */
15252 list_for_each_entry(pmu, &pmus, entry) {
15253 if (pmu->scope == PERF_PMU_SCOPE_NONE ||
15254 WARN_ON_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE))
15255 continue;
15256
15257 if (target[pmu->scope] >= 0 && target[pmu->scope] < nr_cpu_ids)
15258 perf_pmu_migrate_context(pmu, cpu, target[pmu->scope]);
15259 }
15260 }
15261
perf_event_exit_cpu_context(int cpu)15262 static void perf_event_exit_cpu_context(int cpu)
15263 {
15264 struct perf_cpu_context *cpuctx;
15265 struct perf_event_context *ctx;
15266
15267 // XXX simplify cpuctx->online
15268 mutex_lock(&pmus_lock);
15269 /*
15270 * Clear the cpumasks, and migrate to other CPUs if possible.
15271 * Must be invoked before the __perf_event_exit_context.
15272 */
15273 perf_event_clear_cpumask(cpu);
15274 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
15275 ctx = &cpuctx->ctx;
15276
15277 mutex_lock(&ctx->mutex);
15278 if (ctx->nr_events)
15279 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
15280 cpuctx->online = 0;
15281 mutex_unlock(&ctx->mutex);
15282 mutex_unlock(&pmus_lock);
15283 }
15284 #else
15285
perf_event_exit_cpu_context(int cpu)15286 static void perf_event_exit_cpu_context(int cpu) { }
15287
15288 #endif
15289
perf_event_setup_cpumask(unsigned int cpu)15290 static void perf_event_setup_cpumask(unsigned int cpu)
15291 {
15292 struct cpumask *pmu_cpumask;
15293 unsigned int scope;
15294
15295 /*
15296 * Early boot stage, the cpumask hasn't been set yet.
15297 * The perf_online_<domain>_masks includes the first CPU of each domain.
15298 * Always unconditionally set the boot CPU for the perf_online_<domain>_masks.
15299 */
15300 if (cpumask_empty(perf_online_mask)) {
15301 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) {
15302 pmu_cpumask = perf_scope_cpumask(scope);
15303 if (WARN_ON_ONCE(!pmu_cpumask))
15304 continue;
15305 cpumask_set_cpu(cpu, pmu_cpumask);
15306 }
15307 goto end;
15308 }
15309
15310 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) {
15311 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu);
15312
15313 pmu_cpumask = perf_scope_cpumask(scope);
15314
15315 if (WARN_ON_ONCE(!pmu_cpumask || !cpumask))
15316 continue;
15317
15318 if (!cpumask_empty(cpumask) &&
15319 cpumask_any_and(pmu_cpumask, cpumask) >= nr_cpu_ids)
15320 cpumask_set_cpu(cpu, pmu_cpumask);
15321 }
15322 end:
15323 cpumask_set_cpu(cpu, perf_online_mask);
15324 }
15325
perf_event_init_cpu(unsigned int cpu)15326 int perf_event_init_cpu(unsigned int cpu)
15327 {
15328 struct perf_cpu_context *cpuctx;
15329 struct perf_event_context *ctx;
15330
15331 perf_swevent_init_cpu(cpu);
15332
15333 mutex_lock(&pmus_lock);
15334 perf_event_setup_cpumask(cpu);
15335 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
15336 ctx = &cpuctx->ctx;
15337
15338 mutex_lock(&ctx->mutex);
15339 cpuctx->online = 1;
15340 mutex_unlock(&ctx->mutex);
15341 mutex_unlock(&pmus_lock);
15342
15343 return 0;
15344 }
15345
perf_event_exit_cpu(unsigned int cpu)15346 int perf_event_exit_cpu(unsigned int cpu)
15347 {
15348 perf_event_exit_cpu_context(cpu);
15349 return 0;
15350 }
15351
15352 static int
perf_reboot(struct notifier_block * notifier,unsigned long val,void * v)15353 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
15354 {
15355 int cpu;
15356
15357 for_each_online_cpu(cpu)
15358 perf_event_exit_cpu(cpu);
15359
15360 return NOTIFY_OK;
15361 }
15362
15363 /*
15364 * Run the perf reboot notifier at the very last possible moment so that
15365 * the generic watchdog code runs as long as possible.
15366 */
15367 static struct notifier_block perf_reboot_notifier = {
15368 .notifier_call = perf_reboot,
15369 .priority = INT_MIN,
15370 };
15371
perf_event_init(void)15372 void __init perf_event_init(void)
15373 {
15374 int ret;
15375
15376 idr_init(&pmu_idr);
15377
15378 unwind_deferred_init(&perf_unwind_work,
15379 perf_unwind_deferred_callback);
15380
15381 perf_event_init_all_cpus();
15382 init_srcu_struct(&pmus_srcu);
15383 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
15384 perf_pmu_register(&perf_cpu_clock, "cpu_clock", -1);
15385 perf_pmu_register(&perf_task_clock, "task_clock", -1);
15386 perf_tp_register();
15387 perf_event_init_cpu(smp_processor_id());
15388 register_reboot_notifier(&perf_reboot_notifier);
15389
15390 ret = init_hw_breakpoint();
15391 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
15392
15393 perf_event_cache = KMEM_CACHE(perf_event, SLAB_PANIC);
15394
15395 /*
15396 * Build time assertion that we keep the data_head at the intended
15397 * location. IOW, validation we got the __reserved[] size right.
15398 */
15399 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
15400 != 1024);
15401 }
15402
perf_event_sysfs_show(struct device * dev,struct device_attribute * attr,char * page)15403 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
15404 char *page)
15405 {
15406 struct perf_pmu_events_attr *pmu_attr =
15407 container_of(attr, struct perf_pmu_events_attr, attr);
15408
15409 if (pmu_attr->event_str)
15410 return sprintf(page, "%s\n", pmu_attr->event_str);
15411
15412 return 0;
15413 }
15414 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
15415
perf_event_sysfs_init(void)15416 static int __init perf_event_sysfs_init(void)
15417 {
15418 struct pmu *pmu;
15419 int ret;
15420
15421 mutex_lock(&pmus_lock);
15422
15423 ret = bus_register(&pmu_bus);
15424 if (ret)
15425 goto unlock;
15426
15427 list_for_each_entry(pmu, &pmus, entry) {
15428 if (pmu->dev)
15429 continue;
15430
15431 ret = pmu_dev_alloc(pmu);
15432 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
15433 }
15434 pmu_bus_running = 1;
15435 ret = 0;
15436
15437 unlock:
15438 mutex_unlock(&pmus_lock);
15439
15440 return ret;
15441 }
15442 device_initcall(perf_event_sysfs_init);
15443
15444 #ifdef CONFIG_CGROUP_PERF
15445 static struct cgroup_subsys_state *
perf_cgroup_css_alloc(struct cgroup_subsys_state * parent_css)15446 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
15447 {
15448 struct perf_cgroup *jc;
15449
15450 jc = kzalloc_obj(*jc);
15451 if (!jc)
15452 return ERR_PTR(-ENOMEM);
15453
15454 jc->info = alloc_percpu(struct perf_cgroup_info);
15455 if (!jc->info) {
15456 kfree(jc);
15457 return ERR_PTR(-ENOMEM);
15458 }
15459
15460 return &jc->css;
15461 }
15462
perf_cgroup_css_free(struct cgroup_subsys_state * css)15463 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
15464 {
15465 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
15466
15467 free_percpu(jc->info);
15468 kfree(jc);
15469 }
15470
perf_cgroup_css_online(struct cgroup_subsys_state * css)15471 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
15472 {
15473 perf_event_cgroup(css->cgroup);
15474 return 0;
15475 }
15476
__perf_cgroup_move(void * info)15477 static int __perf_cgroup_move(void *info)
15478 {
15479 struct task_struct *task = info;
15480
15481 preempt_disable();
15482 perf_cgroup_switch(task);
15483 preempt_enable();
15484
15485 return 0;
15486 }
15487
perf_cgroup_attach(struct cgroup_taskset * tset)15488 static void perf_cgroup_attach(struct cgroup_taskset *tset)
15489 {
15490 struct task_struct *task;
15491 struct cgroup_subsys_state *css;
15492
15493 cgroup_taskset_for_each(task, css, tset)
15494 task_function_call(task, __perf_cgroup_move, task);
15495 }
15496
15497 struct cgroup_subsys perf_event_cgrp_subsys = {
15498 .css_alloc = perf_cgroup_css_alloc,
15499 .css_free = perf_cgroup_css_free,
15500 .css_online = perf_cgroup_css_online,
15501 .attach = perf_cgroup_attach,
15502 /*
15503 * Implicitly enable on dfl hierarchy so that perf events can
15504 * always be filtered by cgroup2 path as long as perf_event
15505 * controller is not mounted on a legacy hierarchy.
15506 */
15507 .implicit_on_dfl = true,
15508 .threaded = true,
15509 };
15510 #endif /* CONFIG_CGROUP_PERF */
15511
15512 DEFINE_STATIC_CALL_RET0(perf_snapshot_branch_stack, perf_snapshot_branch_stack_t);
15513