xref: /linux/kernel/events/core.c (revision 17ef32ae66b1afc9fa6dbea40eb18a13edba9c31)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Performance events core code:
4  *
5  *  Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
6  *  Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
7  *  Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
8  *  Copyright  ©  2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
9  */
10 
11 #include <linux/fs.h>
12 #include <linux/mm.h>
13 #include <linux/cpu.h>
14 #include <linux/smp.h>
15 #include <linux/idr.h>
16 #include <linux/file.h>
17 #include <linux/poll.h>
18 #include <linux/slab.h>
19 #include <linux/hash.h>
20 #include <linux/tick.h>
21 #include <linux/sysfs.h>
22 #include <linux/dcache.h>
23 #include <linux/percpu.h>
24 #include <linux/ptrace.h>
25 #include <linux/reboot.h>
26 #include <linux/vmstat.h>
27 #include <linux/device.h>
28 #include <linux/export.h>
29 #include <linux/vmalloc.h>
30 #include <linux/hardirq.h>
31 #include <linux/hugetlb.h>
32 #include <linux/rculist.h>
33 #include <linux/uaccess.h>
34 #include <linux/syscalls.h>
35 #include <linux/anon_inodes.h>
36 #include <linux/kernel_stat.h>
37 #include <linux/cgroup.h>
38 #include <linux/perf_event.h>
39 #include <linux/trace_events.h>
40 #include <linux/hw_breakpoint.h>
41 #include <linux/mm_types.h>
42 #include <linux/module.h>
43 #include <linux/mman.h>
44 #include <linux/compat.h>
45 #include <linux/bpf.h>
46 #include <linux/filter.h>
47 #include <linux/namei.h>
48 #include <linux/parser.h>
49 #include <linux/sched/clock.h>
50 #include <linux/sched/mm.h>
51 #include <linux/proc_ns.h>
52 #include <linux/mount.h>
53 #include <linux/min_heap.h>
54 #include <linux/highmem.h>
55 #include <linux/pgtable.h>
56 #include <linux/buildid.h>
57 #include <linux/task_work.h>
58 #include <linux/percpu-rwsem.h>
59 
60 #include "internal.h"
61 
62 #include <asm/irq_regs.h>
63 
64 typedef int (*remote_function_f)(void *);
65 
66 struct remote_function_call {
67 	struct task_struct	*p;
68 	remote_function_f	func;
69 	void			*info;
70 	int			ret;
71 };
72 
remote_function(void * data)73 static void remote_function(void *data)
74 {
75 	struct remote_function_call *tfc = data;
76 	struct task_struct *p = tfc->p;
77 
78 	if (p) {
79 		/* -EAGAIN */
80 		if (task_cpu(p) != smp_processor_id())
81 			return;
82 
83 		/*
84 		 * Now that we're on right CPU with IRQs disabled, we can test
85 		 * if we hit the right task without races.
86 		 */
87 
88 		tfc->ret = -ESRCH; /* No such (running) process */
89 		if (p != current)
90 			return;
91 	}
92 
93 	tfc->ret = tfc->func(tfc->info);
94 }
95 
96 /**
97  * task_function_call - call a function on the cpu on which a task runs
98  * @p:		the task to evaluate
99  * @func:	the function to be called
100  * @info:	the function call argument
101  *
102  * Calls the function @func when the task is currently running. This might
103  * be on the current CPU, which just calls the function directly.  This will
104  * retry due to any failures in smp_call_function_single(), such as if the
105  * task_cpu() goes offline concurrently.
106  *
107  * returns @func return value or -ESRCH or -ENXIO when the process isn't running
108  */
109 static int
task_function_call(struct task_struct * p,remote_function_f func,void * info)110 task_function_call(struct task_struct *p, remote_function_f func, void *info)
111 {
112 	struct remote_function_call data = {
113 		.p	= p,
114 		.func	= func,
115 		.info	= info,
116 		.ret	= -EAGAIN,
117 	};
118 	int ret;
119 
120 	for (;;) {
121 		ret = smp_call_function_single(task_cpu(p), remote_function,
122 					       &data, 1);
123 		if (!ret)
124 			ret = data.ret;
125 
126 		if (ret != -EAGAIN)
127 			break;
128 
129 		cond_resched();
130 	}
131 
132 	return ret;
133 }
134 
135 /**
136  * cpu_function_call - call a function on the cpu
137  * @cpu:	target cpu to queue this function
138  * @func:	the function to be called
139  * @info:	the function call argument
140  *
141  * Calls the function @func on the remote cpu.
142  *
143  * returns: @func return value or -ENXIO when the cpu is offline
144  */
cpu_function_call(int cpu,remote_function_f func,void * info)145 static int cpu_function_call(int cpu, remote_function_f func, void *info)
146 {
147 	struct remote_function_call data = {
148 		.p	= NULL,
149 		.func	= func,
150 		.info	= info,
151 		.ret	= -ENXIO, /* No such CPU */
152 	};
153 
154 	smp_call_function_single(cpu, remote_function, &data, 1);
155 
156 	return data.ret;
157 }
158 
159 enum event_type_t {
160 	EVENT_FLEXIBLE	= 0x01,
161 	EVENT_PINNED	= 0x02,
162 	EVENT_TIME	= 0x04,
163 	EVENT_FROZEN	= 0x08,
164 	/* see ctx_resched() for details */
165 	EVENT_CPU	= 0x10,
166 	EVENT_CGROUP	= 0x20,
167 
168 	/* compound helpers */
169 	EVENT_ALL         = EVENT_FLEXIBLE | EVENT_PINNED,
170 	EVENT_TIME_FROZEN = EVENT_TIME | EVENT_FROZEN,
171 };
172 
__perf_ctx_lock(struct perf_event_context * ctx)173 static inline void __perf_ctx_lock(struct perf_event_context *ctx)
174 {
175 	raw_spin_lock(&ctx->lock);
176 	WARN_ON_ONCE(ctx->is_active & EVENT_FROZEN);
177 }
178 
perf_ctx_lock(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)179 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
180 			  struct perf_event_context *ctx)
181 {
182 	__perf_ctx_lock(&cpuctx->ctx);
183 	if (ctx)
184 		__perf_ctx_lock(ctx);
185 }
186 
__perf_ctx_unlock(struct perf_event_context * ctx)187 static inline void __perf_ctx_unlock(struct perf_event_context *ctx)
188 {
189 	/*
190 	 * If ctx_sched_in() didn't again set any ALL flags, clean up
191 	 * after ctx_sched_out() by clearing is_active.
192 	 */
193 	if (ctx->is_active & EVENT_FROZEN) {
194 		if (!(ctx->is_active & EVENT_ALL))
195 			ctx->is_active = 0;
196 		else
197 			ctx->is_active &= ~EVENT_FROZEN;
198 	}
199 	raw_spin_unlock(&ctx->lock);
200 }
201 
perf_ctx_unlock(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)202 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
203 			    struct perf_event_context *ctx)
204 {
205 	if (ctx)
206 		__perf_ctx_unlock(ctx);
207 	__perf_ctx_unlock(&cpuctx->ctx);
208 }
209 
210 typedef struct {
211 	struct perf_cpu_context *cpuctx;
212 	struct perf_event_context *ctx;
213 } class_perf_ctx_lock_t;
214 
class_perf_ctx_lock_destructor(class_perf_ctx_lock_t * _T)215 static inline void class_perf_ctx_lock_destructor(class_perf_ctx_lock_t *_T)
216 { perf_ctx_unlock(_T->cpuctx, _T->ctx); }
217 
218 static inline class_perf_ctx_lock_t
class_perf_ctx_lock_constructor(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)219 class_perf_ctx_lock_constructor(struct perf_cpu_context *cpuctx,
220 				struct perf_event_context *ctx)
221 { perf_ctx_lock(cpuctx, ctx); return (class_perf_ctx_lock_t){ cpuctx, ctx }; }
222 
223 #define TASK_TOMBSTONE ((void *)-1L)
224 
is_kernel_event(struct perf_event * event)225 static bool is_kernel_event(struct perf_event *event)
226 {
227 	return READ_ONCE(event->owner) == TASK_TOMBSTONE;
228 }
229 
230 static DEFINE_PER_CPU(struct perf_cpu_context, perf_cpu_context);
231 
perf_cpu_task_ctx(void)232 struct perf_event_context *perf_cpu_task_ctx(void)
233 {
234 	lockdep_assert_irqs_disabled();
235 	return this_cpu_ptr(&perf_cpu_context)->task_ctx;
236 }
237 
238 /*
239  * On task ctx scheduling...
240  *
241  * When !ctx->nr_events a task context will not be scheduled. This means
242  * we can disable the scheduler hooks (for performance) without leaving
243  * pending task ctx state.
244  *
245  * This however results in two special cases:
246  *
247  *  - removing the last event from a task ctx; this is relatively straight
248  *    forward and is done in __perf_remove_from_context.
249  *
250  *  - adding the first event to a task ctx; this is tricky because we cannot
251  *    rely on ctx->is_active and therefore cannot use event_function_call().
252  *    See perf_install_in_context().
253  *
254  * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
255  */
256 
257 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
258 			struct perf_event_context *, void *);
259 
260 struct event_function_struct {
261 	struct perf_event *event;
262 	event_f func;
263 	void *data;
264 };
265 
event_function(void * info)266 static int event_function(void *info)
267 {
268 	struct event_function_struct *efs = info;
269 	struct perf_event *event = efs->event;
270 	struct perf_event_context *ctx = event->ctx;
271 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
272 	struct perf_event_context *task_ctx = cpuctx->task_ctx;
273 	int ret = 0;
274 
275 	lockdep_assert_irqs_disabled();
276 
277 	perf_ctx_lock(cpuctx, task_ctx);
278 	/*
279 	 * Since we do the IPI call without holding ctx->lock things can have
280 	 * changed, double check we hit the task we set out to hit.
281 	 */
282 	if (ctx->task) {
283 		if (ctx->task != current) {
284 			ret = -ESRCH;
285 			goto unlock;
286 		}
287 
288 		/*
289 		 * We only use event_function_call() on established contexts,
290 		 * and event_function() is only ever called when active (or
291 		 * rather, we'll have bailed in task_function_call() or the
292 		 * above ctx->task != current test), therefore we must have
293 		 * ctx->is_active here.
294 		 */
295 		WARN_ON_ONCE(!ctx->is_active);
296 		/*
297 		 * And since we have ctx->is_active, cpuctx->task_ctx must
298 		 * match.
299 		 */
300 		WARN_ON_ONCE(task_ctx != ctx);
301 	} else {
302 		WARN_ON_ONCE(&cpuctx->ctx != ctx);
303 	}
304 
305 	efs->func(event, cpuctx, ctx, efs->data);
306 unlock:
307 	perf_ctx_unlock(cpuctx, task_ctx);
308 
309 	return ret;
310 }
311 
event_function_call(struct perf_event * event,event_f func,void * data)312 static void event_function_call(struct perf_event *event, event_f func, void *data)
313 {
314 	struct perf_event_context *ctx = event->ctx;
315 	struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
316 	struct perf_cpu_context *cpuctx;
317 	struct event_function_struct efs = {
318 		.event = event,
319 		.func = func,
320 		.data = data,
321 	};
322 
323 	if (!event->parent) {
324 		/*
325 		 * If this is a !child event, we must hold ctx::mutex to
326 		 * stabilize the event->ctx relation. See
327 		 * perf_event_ctx_lock().
328 		 */
329 		lockdep_assert_held(&ctx->mutex);
330 	}
331 
332 	if (!task) {
333 		cpu_function_call(event->cpu, event_function, &efs);
334 		return;
335 	}
336 
337 	if (task == TASK_TOMBSTONE)
338 		return;
339 
340 again:
341 	if (!task_function_call(task, event_function, &efs))
342 		return;
343 
344 	local_irq_disable();
345 	cpuctx = this_cpu_ptr(&perf_cpu_context);
346 	perf_ctx_lock(cpuctx, ctx);
347 	/*
348 	 * Reload the task pointer, it might have been changed by
349 	 * a concurrent perf_event_context_sched_out().
350 	 */
351 	task = ctx->task;
352 	if (task == TASK_TOMBSTONE)
353 		goto unlock;
354 	if (ctx->is_active) {
355 		perf_ctx_unlock(cpuctx, ctx);
356 		local_irq_enable();
357 		goto again;
358 	}
359 	func(event, NULL, ctx, data);
360 unlock:
361 	perf_ctx_unlock(cpuctx, ctx);
362 	local_irq_enable();
363 }
364 
365 /*
366  * Similar to event_function_call() + event_function(), but hard assumes IRQs
367  * are already disabled and we're on the right CPU.
368  */
event_function_local(struct perf_event * event,event_f func,void * data)369 static void event_function_local(struct perf_event *event, event_f func, void *data)
370 {
371 	struct perf_event_context *ctx = event->ctx;
372 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
373 	struct task_struct *task = READ_ONCE(ctx->task);
374 	struct perf_event_context *task_ctx = NULL;
375 
376 	lockdep_assert_irqs_disabled();
377 
378 	if (task) {
379 		if (task == TASK_TOMBSTONE)
380 			return;
381 
382 		task_ctx = ctx;
383 	}
384 
385 	perf_ctx_lock(cpuctx, task_ctx);
386 
387 	task = ctx->task;
388 	if (task == TASK_TOMBSTONE)
389 		goto unlock;
390 
391 	if (task) {
392 		/*
393 		 * We must be either inactive or active and the right task,
394 		 * otherwise we're screwed, since we cannot IPI to somewhere
395 		 * else.
396 		 */
397 		if (ctx->is_active) {
398 			if (WARN_ON_ONCE(task != current))
399 				goto unlock;
400 
401 			if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
402 				goto unlock;
403 		}
404 	} else {
405 		WARN_ON_ONCE(&cpuctx->ctx != ctx);
406 	}
407 
408 	func(event, cpuctx, ctx, data);
409 unlock:
410 	perf_ctx_unlock(cpuctx, task_ctx);
411 }
412 
413 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
414 		       PERF_FLAG_FD_OUTPUT  |\
415 		       PERF_FLAG_PID_CGROUP |\
416 		       PERF_FLAG_FD_CLOEXEC)
417 
418 /*
419  * branch priv levels that need permission checks
420  */
421 #define PERF_SAMPLE_BRANCH_PERM_PLM \
422 	(PERF_SAMPLE_BRANCH_KERNEL |\
423 	 PERF_SAMPLE_BRANCH_HV)
424 
425 /*
426  * perf_sched_events : >0 events exist
427  */
428 
429 static void perf_sched_delayed(struct work_struct *work);
430 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
431 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
432 static DEFINE_MUTEX(perf_sched_mutex);
433 static atomic_t perf_sched_count;
434 
435 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
436 
437 static atomic_t nr_mmap_events __read_mostly;
438 static atomic_t nr_comm_events __read_mostly;
439 static atomic_t nr_namespaces_events __read_mostly;
440 static atomic_t nr_task_events __read_mostly;
441 static atomic_t nr_freq_events __read_mostly;
442 static atomic_t nr_switch_events __read_mostly;
443 static atomic_t nr_ksymbol_events __read_mostly;
444 static atomic_t nr_bpf_events __read_mostly;
445 static atomic_t nr_cgroup_events __read_mostly;
446 static atomic_t nr_text_poke_events __read_mostly;
447 static atomic_t nr_build_id_events __read_mostly;
448 
449 static LIST_HEAD(pmus);
450 static DEFINE_MUTEX(pmus_lock);
451 static struct srcu_struct pmus_srcu;
452 static cpumask_var_t perf_online_mask;
453 static cpumask_var_t perf_online_core_mask;
454 static cpumask_var_t perf_online_die_mask;
455 static cpumask_var_t perf_online_cluster_mask;
456 static cpumask_var_t perf_online_pkg_mask;
457 static cpumask_var_t perf_online_sys_mask;
458 static struct kmem_cache *perf_event_cache;
459 
460 /*
461  * perf event paranoia level:
462  *  -1 - not paranoid at all
463  *   0 - disallow raw tracepoint access for unpriv
464  *   1 - disallow cpu events for unpriv
465  *   2 - disallow kernel profiling for unpriv
466  */
467 int sysctl_perf_event_paranoid __read_mostly = 2;
468 
469 /* Minimum for 512 kiB + 1 user control page. 'free' kiB per user. */
470 static int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024);
471 
472 /*
473  * max perf event sample rate
474  */
475 #define DEFAULT_MAX_SAMPLE_RATE		100000
476 #define DEFAULT_SAMPLE_PERIOD_NS	(NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
477 #define DEFAULT_CPU_TIME_MAX_PERCENT	25
478 
479 int sysctl_perf_event_sample_rate __read_mostly	= DEFAULT_MAX_SAMPLE_RATE;
480 static int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
481 
482 static int max_samples_per_tick __read_mostly	= DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
483 static int perf_sample_period_ns __read_mostly	= DEFAULT_SAMPLE_PERIOD_NS;
484 
485 static int perf_sample_allowed_ns __read_mostly =
486 	DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
487 
update_perf_cpu_limits(void)488 static void update_perf_cpu_limits(void)
489 {
490 	u64 tmp = perf_sample_period_ns;
491 
492 	tmp *= sysctl_perf_cpu_time_max_percent;
493 	tmp = div_u64(tmp, 100);
494 	if (!tmp)
495 		tmp = 1;
496 
497 	WRITE_ONCE(perf_sample_allowed_ns, tmp);
498 }
499 
500 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc);
501 
perf_event_max_sample_rate_handler(const struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)502 static int perf_event_max_sample_rate_handler(const struct ctl_table *table, int write,
503 				       void *buffer, size_t *lenp, loff_t *ppos)
504 {
505 	int ret;
506 	int perf_cpu = sysctl_perf_cpu_time_max_percent;
507 	/*
508 	 * If throttling is disabled don't allow the write:
509 	 */
510 	if (write && (perf_cpu == 100 || perf_cpu == 0))
511 		return -EINVAL;
512 
513 	ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
514 	if (ret || !write)
515 		return ret;
516 
517 	max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
518 	perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
519 	update_perf_cpu_limits();
520 
521 	return 0;
522 }
523 
perf_cpu_time_max_percent_handler(const struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)524 static int perf_cpu_time_max_percent_handler(const struct ctl_table *table, int write,
525 		void *buffer, size_t *lenp, loff_t *ppos)
526 {
527 	int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
528 
529 	if (ret || !write)
530 		return ret;
531 
532 	if (sysctl_perf_cpu_time_max_percent == 100 ||
533 	    sysctl_perf_cpu_time_max_percent == 0) {
534 		printk(KERN_WARNING
535 		       "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
536 		WRITE_ONCE(perf_sample_allowed_ns, 0);
537 	} else {
538 		update_perf_cpu_limits();
539 	}
540 
541 	return 0;
542 }
543 
544 static const struct ctl_table events_core_sysctl_table[] = {
545 	/*
546 	 * User-space relies on this file as a feature check for
547 	 * perf_events being enabled. It's an ABI, do not remove!
548 	 */
549 	{
550 		.procname	= "perf_event_paranoid",
551 		.data		= &sysctl_perf_event_paranoid,
552 		.maxlen		= sizeof(sysctl_perf_event_paranoid),
553 		.mode		= 0644,
554 		.proc_handler	= proc_dointvec,
555 	},
556 	{
557 		.procname	= "perf_event_mlock_kb",
558 		.data		= &sysctl_perf_event_mlock,
559 		.maxlen		= sizeof(sysctl_perf_event_mlock),
560 		.mode		= 0644,
561 		.proc_handler	= proc_dointvec,
562 	},
563 	{
564 		.procname	= "perf_event_max_sample_rate",
565 		.data		= &sysctl_perf_event_sample_rate,
566 		.maxlen		= sizeof(sysctl_perf_event_sample_rate),
567 		.mode		= 0644,
568 		.proc_handler	= perf_event_max_sample_rate_handler,
569 		.extra1		= SYSCTL_ONE,
570 	},
571 	{
572 		.procname	= "perf_cpu_time_max_percent",
573 		.data		= &sysctl_perf_cpu_time_max_percent,
574 		.maxlen		= sizeof(sysctl_perf_cpu_time_max_percent),
575 		.mode		= 0644,
576 		.proc_handler	= perf_cpu_time_max_percent_handler,
577 		.extra1		= SYSCTL_ZERO,
578 		.extra2		= SYSCTL_ONE_HUNDRED,
579 	},
580 };
581 
init_events_core_sysctls(void)582 static int __init init_events_core_sysctls(void)
583 {
584 	register_sysctl_init("kernel", events_core_sysctl_table);
585 	return 0;
586 }
587 core_initcall(init_events_core_sysctls);
588 
589 
590 /*
591  * perf samples are done in some very critical code paths (NMIs).
592  * If they take too much CPU time, the system can lock up and not
593  * get any real work done.  This will drop the sample rate when
594  * we detect that events are taking too long.
595  */
596 #define NR_ACCUMULATED_SAMPLES 128
597 static DEFINE_PER_CPU(u64, running_sample_length);
598 
599 static u64 __report_avg;
600 static u64 __report_allowed;
601 
perf_duration_warn(struct irq_work * w)602 static void perf_duration_warn(struct irq_work *w)
603 {
604 	printk_ratelimited(KERN_INFO
605 		"perf: interrupt took too long (%lld > %lld), lowering "
606 		"kernel.perf_event_max_sample_rate to %d\n",
607 		__report_avg, __report_allowed,
608 		sysctl_perf_event_sample_rate);
609 }
610 
611 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
612 
perf_sample_event_took(u64 sample_len_ns)613 void perf_sample_event_took(u64 sample_len_ns)
614 {
615 	u64 max_len = READ_ONCE(perf_sample_allowed_ns);
616 	u64 running_len;
617 	u64 avg_len;
618 	u32 max;
619 
620 	if (max_len == 0)
621 		return;
622 
623 	/* Decay the counter by 1 average sample. */
624 	running_len = __this_cpu_read(running_sample_length);
625 	running_len -= running_len/NR_ACCUMULATED_SAMPLES;
626 	running_len += sample_len_ns;
627 	__this_cpu_write(running_sample_length, running_len);
628 
629 	/*
630 	 * Note: this will be biased artificially low until we have
631 	 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
632 	 * from having to maintain a count.
633 	 */
634 	avg_len = running_len/NR_ACCUMULATED_SAMPLES;
635 	if (avg_len <= max_len)
636 		return;
637 
638 	__report_avg = avg_len;
639 	__report_allowed = max_len;
640 
641 	/*
642 	 * Compute a throttle threshold 25% below the current duration.
643 	 */
644 	avg_len += avg_len / 4;
645 	max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
646 	if (avg_len < max)
647 		max /= (u32)avg_len;
648 	else
649 		max = 1;
650 
651 	WRITE_ONCE(perf_sample_allowed_ns, avg_len);
652 	WRITE_ONCE(max_samples_per_tick, max);
653 
654 	sysctl_perf_event_sample_rate = max * HZ;
655 	perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
656 
657 	if (!irq_work_queue(&perf_duration_work)) {
658 		early_printk("perf: interrupt took too long (%lld > %lld), lowering "
659 			     "kernel.perf_event_max_sample_rate to %d\n",
660 			     __report_avg, __report_allowed,
661 			     sysctl_perf_event_sample_rate);
662 	}
663 }
664 
665 static atomic64_t perf_event_id;
666 
667 static void update_context_time(struct perf_event_context *ctx);
668 static u64 perf_event_time(struct perf_event *event);
669 
perf_event_print_debug(void)670 void __weak perf_event_print_debug(void)	{ }
671 
perf_clock(void)672 static inline u64 perf_clock(void)
673 {
674 	return local_clock();
675 }
676 
perf_event_clock(struct perf_event * event)677 static inline u64 perf_event_clock(struct perf_event *event)
678 {
679 	return event->clock();
680 }
681 
682 /*
683  * State based event timekeeping...
684  *
685  * The basic idea is to use event->state to determine which (if any) time
686  * fields to increment with the current delta. This means we only need to
687  * update timestamps when we change state or when they are explicitly requested
688  * (read).
689  *
690  * Event groups make things a little more complicated, but not terribly so. The
691  * rules for a group are that if the group leader is OFF the entire group is
692  * OFF, irrespective of what the group member states are. This results in
693  * __perf_effective_state().
694  *
695  * A further ramification is that when a group leader flips between OFF and
696  * !OFF, we need to update all group member times.
697  *
698  *
699  * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
700  * need to make sure the relevant context time is updated before we try and
701  * update our timestamps.
702  */
703 
704 static __always_inline enum perf_event_state
__perf_effective_state(struct perf_event * event)705 __perf_effective_state(struct perf_event *event)
706 {
707 	struct perf_event *leader = event->group_leader;
708 
709 	if (leader->state <= PERF_EVENT_STATE_OFF)
710 		return leader->state;
711 
712 	return event->state;
713 }
714 
715 static __always_inline void
__perf_update_times(struct perf_event * event,u64 now,u64 * enabled,u64 * running)716 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
717 {
718 	enum perf_event_state state = __perf_effective_state(event);
719 	u64 delta = now - event->tstamp;
720 
721 	*enabled = event->total_time_enabled;
722 	if (state >= PERF_EVENT_STATE_INACTIVE)
723 		*enabled += delta;
724 
725 	*running = event->total_time_running;
726 	if (state >= PERF_EVENT_STATE_ACTIVE)
727 		*running += delta;
728 }
729 
perf_event_update_time(struct perf_event * event)730 static void perf_event_update_time(struct perf_event *event)
731 {
732 	u64 now = perf_event_time(event);
733 
734 	__perf_update_times(event, now, &event->total_time_enabled,
735 					&event->total_time_running);
736 	event->tstamp = now;
737 }
738 
perf_event_update_sibling_time(struct perf_event * leader)739 static void perf_event_update_sibling_time(struct perf_event *leader)
740 {
741 	struct perf_event *sibling;
742 
743 	for_each_sibling_event(sibling, leader)
744 		perf_event_update_time(sibling);
745 }
746 
747 static void
perf_event_set_state(struct perf_event * event,enum perf_event_state state)748 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
749 {
750 	if (event->state == state)
751 		return;
752 
753 	perf_event_update_time(event);
754 	/*
755 	 * If a group leader gets enabled/disabled all its siblings
756 	 * are affected too.
757 	 */
758 	if ((event->state < 0) ^ (state < 0))
759 		perf_event_update_sibling_time(event);
760 
761 	WRITE_ONCE(event->state, state);
762 }
763 
764 /*
765  * UP store-release, load-acquire
766  */
767 
768 #define __store_release(ptr, val)					\
769 do {									\
770 	barrier();							\
771 	WRITE_ONCE(*(ptr), (val));					\
772 } while (0)
773 
774 #define __load_acquire(ptr)						\
775 ({									\
776 	__unqual_scalar_typeof(*(ptr)) ___p = READ_ONCE(*(ptr));	\
777 	barrier();							\
778 	___p;								\
779 })
780 
781 #define for_each_epc(_epc, _ctx, _pmu, _cgroup)				\
782 	list_for_each_entry(_epc, &((_ctx)->pmu_ctx_list), pmu_ctx_entry) \
783 		if (_cgroup && !_epc->nr_cgroups)			\
784 			continue;					\
785 		else if (_pmu && _epc->pmu != _pmu)			\
786 			continue;					\
787 		else
788 
perf_ctx_disable(struct perf_event_context * ctx,bool cgroup)789 static void perf_ctx_disable(struct perf_event_context *ctx, bool cgroup)
790 {
791 	struct perf_event_pmu_context *pmu_ctx;
792 
793 	for_each_epc(pmu_ctx, ctx, NULL, cgroup)
794 		perf_pmu_disable(pmu_ctx->pmu);
795 }
796 
perf_ctx_enable(struct perf_event_context * ctx,bool cgroup)797 static void perf_ctx_enable(struct perf_event_context *ctx, bool cgroup)
798 {
799 	struct perf_event_pmu_context *pmu_ctx;
800 
801 	for_each_epc(pmu_ctx, ctx, NULL, cgroup)
802 		perf_pmu_enable(pmu_ctx->pmu);
803 }
804 
805 static void ctx_sched_out(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type);
806 static void ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type);
807 
808 #ifdef CONFIG_CGROUP_PERF
809 
810 static inline bool
perf_cgroup_match(struct perf_event * event)811 perf_cgroup_match(struct perf_event *event)
812 {
813 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
814 
815 	/* @event doesn't care about cgroup */
816 	if (!event->cgrp)
817 		return true;
818 
819 	/* wants specific cgroup scope but @cpuctx isn't associated with any */
820 	if (!cpuctx->cgrp)
821 		return false;
822 
823 	/*
824 	 * Cgroup scoping is recursive.  An event enabled for a cgroup is
825 	 * also enabled for all its descendant cgroups.  If @cpuctx's
826 	 * cgroup is a descendant of @event's (the test covers identity
827 	 * case), it's a match.
828 	 */
829 	return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
830 				    event->cgrp->css.cgroup);
831 }
832 
perf_detach_cgroup(struct perf_event * event)833 static inline void perf_detach_cgroup(struct perf_event *event)
834 {
835 	css_put(&event->cgrp->css);
836 	event->cgrp = NULL;
837 }
838 
is_cgroup_event(struct perf_event * event)839 static inline int is_cgroup_event(struct perf_event *event)
840 {
841 	return event->cgrp != NULL;
842 }
843 
perf_cgroup_event_time(struct perf_event * event)844 static inline u64 perf_cgroup_event_time(struct perf_event *event)
845 {
846 	struct perf_cgroup_info *t;
847 
848 	t = per_cpu_ptr(event->cgrp->info, event->cpu);
849 	return t->time;
850 }
851 
perf_cgroup_event_time_now(struct perf_event * event,u64 now)852 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
853 {
854 	struct perf_cgroup_info *t;
855 
856 	t = per_cpu_ptr(event->cgrp->info, event->cpu);
857 	if (!__load_acquire(&t->active))
858 		return t->time;
859 	now += READ_ONCE(t->timeoffset);
860 	return now;
861 }
862 
__update_cgrp_time(struct perf_cgroup_info * info,u64 now,bool adv)863 static inline void __update_cgrp_time(struct perf_cgroup_info *info, u64 now, bool adv)
864 {
865 	if (adv)
866 		info->time += now - info->timestamp;
867 	info->timestamp = now;
868 	/*
869 	 * see update_context_time()
870 	 */
871 	WRITE_ONCE(info->timeoffset, info->time - info->timestamp);
872 }
873 
update_cgrp_time_from_cpuctx(struct perf_cpu_context * cpuctx,bool final)874 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx, bool final)
875 {
876 	struct perf_cgroup *cgrp = cpuctx->cgrp;
877 	struct cgroup_subsys_state *css;
878 	struct perf_cgroup_info *info;
879 
880 	if (cgrp) {
881 		u64 now = perf_clock();
882 
883 		for (css = &cgrp->css; css; css = css->parent) {
884 			cgrp = container_of(css, struct perf_cgroup, css);
885 			info = this_cpu_ptr(cgrp->info);
886 
887 			__update_cgrp_time(info, now, true);
888 			if (final)
889 				__store_release(&info->active, 0);
890 		}
891 	}
892 }
893 
update_cgrp_time_from_event(struct perf_event * event)894 static inline void update_cgrp_time_from_event(struct perf_event *event)
895 {
896 	struct perf_cgroup_info *info;
897 
898 	/*
899 	 * ensure we access cgroup data only when needed and
900 	 * when we know the cgroup is pinned (css_get)
901 	 */
902 	if (!is_cgroup_event(event))
903 		return;
904 
905 	info = this_cpu_ptr(event->cgrp->info);
906 	/*
907 	 * Do not update time when cgroup is not active
908 	 */
909 	if (info->active)
910 		__update_cgrp_time(info, perf_clock(), true);
911 }
912 
913 static inline void
perf_cgroup_set_timestamp(struct perf_cpu_context * cpuctx)914 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx)
915 {
916 	struct perf_event_context *ctx = &cpuctx->ctx;
917 	struct perf_cgroup *cgrp = cpuctx->cgrp;
918 	struct perf_cgroup_info *info;
919 	struct cgroup_subsys_state *css;
920 
921 	/*
922 	 * ctx->lock held by caller
923 	 * ensure we do not access cgroup data
924 	 * unless we have the cgroup pinned (css_get)
925 	 */
926 	if (!cgrp)
927 		return;
928 
929 	WARN_ON_ONCE(!ctx->nr_cgroups);
930 
931 	for (css = &cgrp->css; css; css = css->parent) {
932 		cgrp = container_of(css, struct perf_cgroup, css);
933 		info = this_cpu_ptr(cgrp->info);
934 		__update_cgrp_time(info, ctx->timestamp, false);
935 		__store_release(&info->active, 1);
936 	}
937 }
938 
939 /*
940  * reschedule events based on the cgroup constraint of task.
941  */
perf_cgroup_switch(struct task_struct * task)942 static void perf_cgroup_switch(struct task_struct *task)
943 {
944 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
945 	struct perf_cgroup *cgrp;
946 
947 	/*
948 	 * cpuctx->cgrp is set when the first cgroup event enabled,
949 	 * and is cleared when the last cgroup event disabled.
950 	 */
951 	if (READ_ONCE(cpuctx->cgrp) == NULL)
952 		return;
953 
954 	WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
955 
956 	cgrp = perf_cgroup_from_task(task, NULL);
957 	if (READ_ONCE(cpuctx->cgrp) == cgrp)
958 		return;
959 
960 	guard(perf_ctx_lock)(cpuctx, cpuctx->task_ctx);
961 	/*
962 	 * Re-check, could've raced vs perf_remove_from_context().
963 	 */
964 	if (READ_ONCE(cpuctx->cgrp) == NULL)
965 		return;
966 
967 	perf_ctx_disable(&cpuctx->ctx, true);
968 
969 	ctx_sched_out(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP);
970 	/*
971 	 * must not be done before ctxswout due
972 	 * to update_cgrp_time_from_cpuctx() in
973 	 * ctx_sched_out()
974 	 */
975 	cpuctx->cgrp = cgrp;
976 	/*
977 	 * set cgrp before ctxsw in to allow
978 	 * perf_cgroup_set_timestamp() in ctx_sched_in()
979 	 * to not have to pass task around
980 	 */
981 	ctx_sched_in(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP);
982 
983 	perf_ctx_enable(&cpuctx->ctx, true);
984 }
985 
perf_cgroup_ensure_storage(struct perf_event * event,struct cgroup_subsys_state * css)986 static int perf_cgroup_ensure_storage(struct perf_event *event,
987 				struct cgroup_subsys_state *css)
988 {
989 	struct perf_cpu_context *cpuctx;
990 	struct perf_event **storage;
991 	int cpu, heap_size, ret = 0;
992 
993 	/*
994 	 * Allow storage to have sufficient space for an iterator for each
995 	 * possibly nested cgroup plus an iterator for events with no cgroup.
996 	 */
997 	for (heap_size = 1; css; css = css->parent)
998 		heap_size++;
999 
1000 	for_each_possible_cpu(cpu) {
1001 		cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
1002 		if (heap_size <= cpuctx->heap_size)
1003 			continue;
1004 
1005 		storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
1006 				       GFP_KERNEL, cpu_to_node(cpu));
1007 		if (!storage) {
1008 			ret = -ENOMEM;
1009 			break;
1010 		}
1011 
1012 		raw_spin_lock_irq(&cpuctx->ctx.lock);
1013 		if (cpuctx->heap_size < heap_size) {
1014 			swap(cpuctx->heap, storage);
1015 			if (storage == cpuctx->heap_default)
1016 				storage = NULL;
1017 			cpuctx->heap_size = heap_size;
1018 		}
1019 		raw_spin_unlock_irq(&cpuctx->ctx.lock);
1020 
1021 		kfree(storage);
1022 	}
1023 
1024 	return ret;
1025 }
1026 
perf_cgroup_connect(int fd,struct perf_event * event,struct perf_event_attr * attr,struct perf_event * group_leader)1027 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
1028 				      struct perf_event_attr *attr,
1029 				      struct perf_event *group_leader)
1030 {
1031 	struct perf_cgroup *cgrp;
1032 	struct cgroup_subsys_state *css;
1033 	CLASS(fd, f)(fd);
1034 	int ret = 0;
1035 
1036 	if (fd_empty(f))
1037 		return -EBADF;
1038 
1039 	css = css_tryget_online_from_dir(fd_file(f)->f_path.dentry,
1040 					 &perf_event_cgrp_subsys);
1041 	if (IS_ERR(css))
1042 		return PTR_ERR(css);
1043 
1044 	ret = perf_cgroup_ensure_storage(event, css);
1045 	if (ret)
1046 		return ret;
1047 
1048 	cgrp = container_of(css, struct perf_cgroup, css);
1049 	event->cgrp = cgrp;
1050 
1051 	/*
1052 	 * all events in a group must monitor
1053 	 * the same cgroup because a task belongs
1054 	 * to only one perf cgroup at a time
1055 	 */
1056 	if (group_leader && group_leader->cgrp != cgrp) {
1057 		perf_detach_cgroup(event);
1058 		ret = -EINVAL;
1059 	}
1060 	return ret;
1061 }
1062 
1063 static inline void
perf_cgroup_event_enable(struct perf_event * event,struct perf_event_context * ctx)1064 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1065 {
1066 	struct perf_cpu_context *cpuctx;
1067 
1068 	if (!is_cgroup_event(event))
1069 		return;
1070 
1071 	event->pmu_ctx->nr_cgroups++;
1072 
1073 	/*
1074 	 * Because cgroup events are always per-cpu events,
1075 	 * @ctx == &cpuctx->ctx.
1076 	 */
1077 	cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1078 
1079 	if (ctx->nr_cgroups++)
1080 		return;
1081 
1082 	cpuctx->cgrp = perf_cgroup_from_task(current, ctx);
1083 }
1084 
1085 static inline void
perf_cgroup_event_disable(struct perf_event * event,struct perf_event_context * ctx)1086 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1087 {
1088 	struct perf_cpu_context *cpuctx;
1089 
1090 	if (!is_cgroup_event(event))
1091 		return;
1092 
1093 	event->pmu_ctx->nr_cgroups--;
1094 
1095 	/*
1096 	 * Because cgroup events are always per-cpu events,
1097 	 * @ctx == &cpuctx->ctx.
1098 	 */
1099 	cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1100 
1101 	if (--ctx->nr_cgroups)
1102 		return;
1103 
1104 	cpuctx->cgrp = NULL;
1105 }
1106 
1107 #else /* !CONFIG_CGROUP_PERF */
1108 
1109 static inline bool
perf_cgroup_match(struct perf_event * event)1110 perf_cgroup_match(struct perf_event *event)
1111 {
1112 	return true;
1113 }
1114 
perf_detach_cgroup(struct perf_event * event)1115 static inline void perf_detach_cgroup(struct perf_event *event)
1116 {}
1117 
is_cgroup_event(struct perf_event * event)1118 static inline int is_cgroup_event(struct perf_event *event)
1119 {
1120 	return 0;
1121 }
1122 
update_cgrp_time_from_event(struct perf_event * event)1123 static inline void update_cgrp_time_from_event(struct perf_event *event)
1124 {
1125 }
1126 
update_cgrp_time_from_cpuctx(struct perf_cpu_context * cpuctx,bool final)1127 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx,
1128 						bool final)
1129 {
1130 }
1131 
perf_cgroup_connect(pid_t pid,struct perf_event * event,struct perf_event_attr * attr,struct perf_event * group_leader)1132 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1133 				      struct perf_event_attr *attr,
1134 				      struct perf_event *group_leader)
1135 {
1136 	return -EINVAL;
1137 }
1138 
1139 static inline void
perf_cgroup_set_timestamp(struct perf_cpu_context * cpuctx)1140 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx)
1141 {
1142 }
1143 
perf_cgroup_event_time(struct perf_event * event)1144 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1145 {
1146 	return 0;
1147 }
1148 
perf_cgroup_event_time_now(struct perf_event * event,u64 now)1149 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
1150 {
1151 	return 0;
1152 }
1153 
1154 static inline void
perf_cgroup_event_enable(struct perf_event * event,struct perf_event_context * ctx)1155 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1156 {
1157 }
1158 
1159 static inline void
perf_cgroup_event_disable(struct perf_event * event,struct perf_event_context * ctx)1160 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1161 {
1162 }
1163 
perf_cgroup_switch(struct task_struct * task)1164 static void perf_cgroup_switch(struct task_struct *task)
1165 {
1166 }
1167 #endif
1168 
1169 /*
1170  * set default to be dependent on timer tick just
1171  * like original code
1172  */
1173 #define PERF_CPU_HRTIMER (1000 / HZ)
1174 /*
1175  * function must be called with interrupts disabled
1176  */
perf_mux_hrtimer_handler(struct hrtimer * hr)1177 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1178 {
1179 	struct perf_cpu_pmu_context *cpc;
1180 	bool rotations;
1181 
1182 	lockdep_assert_irqs_disabled();
1183 
1184 	cpc = container_of(hr, struct perf_cpu_pmu_context, hrtimer);
1185 	rotations = perf_rotate_context(cpc);
1186 
1187 	raw_spin_lock(&cpc->hrtimer_lock);
1188 	if (rotations)
1189 		hrtimer_forward_now(hr, cpc->hrtimer_interval);
1190 	else
1191 		cpc->hrtimer_active = 0;
1192 	raw_spin_unlock(&cpc->hrtimer_lock);
1193 
1194 	return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1195 }
1196 
__perf_mux_hrtimer_init(struct perf_cpu_pmu_context * cpc,int cpu)1197 static void __perf_mux_hrtimer_init(struct perf_cpu_pmu_context *cpc, int cpu)
1198 {
1199 	struct hrtimer *timer = &cpc->hrtimer;
1200 	struct pmu *pmu = cpc->epc.pmu;
1201 	u64 interval;
1202 
1203 	/*
1204 	 * check default is sane, if not set then force to
1205 	 * default interval (1/tick)
1206 	 */
1207 	interval = pmu->hrtimer_interval_ms;
1208 	if (interval < 1)
1209 		interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1210 
1211 	cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1212 
1213 	raw_spin_lock_init(&cpc->hrtimer_lock);
1214 	hrtimer_setup(timer, perf_mux_hrtimer_handler, CLOCK_MONOTONIC,
1215 		      HRTIMER_MODE_ABS_PINNED_HARD);
1216 }
1217 
perf_mux_hrtimer_restart(struct perf_cpu_pmu_context * cpc)1218 static int perf_mux_hrtimer_restart(struct perf_cpu_pmu_context *cpc)
1219 {
1220 	struct hrtimer *timer = &cpc->hrtimer;
1221 	unsigned long flags;
1222 
1223 	raw_spin_lock_irqsave(&cpc->hrtimer_lock, flags);
1224 	if (!cpc->hrtimer_active) {
1225 		cpc->hrtimer_active = 1;
1226 		hrtimer_forward_now(timer, cpc->hrtimer_interval);
1227 		hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1228 	}
1229 	raw_spin_unlock_irqrestore(&cpc->hrtimer_lock, flags);
1230 
1231 	return 0;
1232 }
1233 
perf_mux_hrtimer_restart_ipi(void * arg)1234 static int perf_mux_hrtimer_restart_ipi(void *arg)
1235 {
1236 	return perf_mux_hrtimer_restart(arg);
1237 }
1238 
this_cpc(struct pmu * pmu)1239 static __always_inline struct perf_cpu_pmu_context *this_cpc(struct pmu *pmu)
1240 {
1241 	return *this_cpu_ptr(pmu->cpu_pmu_context);
1242 }
1243 
perf_pmu_disable(struct pmu * pmu)1244 void perf_pmu_disable(struct pmu *pmu)
1245 {
1246 	int *count = &this_cpc(pmu)->pmu_disable_count;
1247 	if (!(*count)++)
1248 		pmu->pmu_disable(pmu);
1249 }
1250 
perf_pmu_enable(struct pmu * pmu)1251 void perf_pmu_enable(struct pmu *pmu)
1252 {
1253 	int *count = &this_cpc(pmu)->pmu_disable_count;
1254 	if (!--(*count))
1255 		pmu->pmu_enable(pmu);
1256 }
1257 
perf_assert_pmu_disabled(struct pmu * pmu)1258 static void perf_assert_pmu_disabled(struct pmu *pmu)
1259 {
1260 	int *count = &this_cpc(pmu)->pmu_disable_count;
1261 	WARN_ON_ONCE(*count == 0);
1262 }
1263 
perf_pmu_read(struct perf_event * event)1264 static inline void perf_pmu_read(struct perf_event *event)
1265 {
1266 	if (event->state == PERF_EVENT_STATE_ACTIVE)
1267 		event->pmu->read(event);
1268 }
1269 
get_ctx(struct perf_event_context * ctx)1270 static void get_ctx(struct perf_event_context *ctx)
1271 {
1272 	refcount_inc(&ctx->refcount);
1273 }
1274 
free_ctx(struct rcu_head * head)1275 static void free_ctx(struct rcu_head *head)
1276 {
1277 	struct perf_event_context *ctx;
1278 
1279 	ctx = container_of(head, struct perf_event_context, rcu_head);
1280 	kfree(ctx);
1281 }
1282 
put_ctx(struct perf_event_context * ctx)1283 static void put_ctx(struct perf_event_context *ctx)
1284 {
1285 	if (refcount_dec_and_test(&ctx->refcount)) {
1286 		if (ctx->parent_ctx)
1287 			put_ctx(ctx->parent_ctx);
1288 		if (ctx->task && ctx->task != TASK_TOMBSTONE)
1289 			put_task_struct(ctx->task);
1290 		call_rcu(&ctx->rcu_head, free_ctx);
1291 	} else {
1292 		smp_mb__after_atomic(); /* pairs with wait_var_event() */
1293 		if (ctx->task == TASK_TOMBSTONE)
1294 			wake_up_var(&ctx->refcount);
1295 	}
1296 }
1297 
1298 /*
1299  * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1300  * perf_pmu_migrate_context() we need some magic.
1301  *
1302  * Those places that change perf_event::ctx will hold both
1303  * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1304  *
1305  * Lock ordering is by mutex address. There are two other sites where
1306  * perf_event_context::mutex nests and those are:
1307  *
1308  *  - perf_event_exit_task_context()	[ child , 0 ]
1309  *      perf_event_exit_event()
1310  *        put_event()			[ parent, 1 ]
1311  *
1312  *  - perf_event_init_context()		[ parent, 0 ]
1313  *      inherit_task_group()
1314  *        inherit_group()
1315  *          inherit_event()
1316  *            perf_event_alloc()
1317  *              perf_init_event()
1318  *                perf_try_init_event()	[ child , 1 ]
1319  *
1320  * While it appears there is an obvious deadlock here -- the parent and child
1321  * nesting levels are inverted between the two. This is in fact safe because
1322  * life-time rules separate them. That is an exiting task cannot fork, and a
1323  * spawning task cannot (yet) exit.
1324  *
1325  * But remember that these are parent<->child context relations, and
1326  * migration does not affect children, therefore these two orderings should not
1327  * interact.
1328  *
1329  * The change in perf_event::ctx does not affect children (as claimed above)
1330  * because the sys_perf_event_open() case will install a new event and break
1331  * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1332  * concerned with cpuctx and that doesn't have children.
1333  *
1334  * The places that change perf_event::ctx will issue:
1335  *
1336  *   perf_remove_from_context();
1337  *   synchronize_rcu();
1338  *   perf_install_in_context();
1339  *
1340  * to affect the change. The remove_from_context() + synchronize_rcu() should
1341  * quiesce the event, after which we can install it in the new location. This
1342  * means that only external vectors (perf_fops, prctl) can perturb the event
1343  * while in transit. Therefore all such accessors should also acquire
1344  * perf_event_context::mutex to serialize against this.
1345  *
1346  * However; because event->ctx can change while we're waiting to acquire
1347  * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1348  * function.
1349  *
1350  * Lock order:
1351  *    exec_update_lock
1352  *	task_struct::perf_event_mutex
1353  *	  perf_event_context::mutex
1354  *	    perf_event::child_mutex;
1355  *	      perf_event_context::lock
1356  *	    mmap_lock
1357  *	      perf_event::mmap_mutex
1358  *	        perf_buffer::aux_mutex
1359  *	      perf_addr_filters_head::lock
1360  *
1361  *    cpu_hotplug_lock
1362  *      pmus_lock
1363  *	  cpuctx->mutex / perf_event_context::mutex
1364  */
1365 static struct perf_event_context *
perf_event_ctx_lock_nested(struct perf_event * event,int nesting)1366 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1367 {
1368 	struct perf_event_context *ctx;
1369 
1370 again:
1371 	rcu_read_lock();
1372 	ctx = READ_ONCE(event->ctx);
1373 	if (!refcount_inc_not_zero(&ctx->refcount)) {
1374 		rcu_read_unlock();
1375 		goto again;
1376 	}
1377 	rcu_read_unlock();
1378 
1379 	mutex_lock_nested(&ctx->mutex, nesting);
1380 	if (event->ctx != ctx) {
1381 		mutex_unlock(&ctx->mutex);
1382 		put_ctx(ctx);
1383 		goto again;
1384 	}
1385 
1386 	return ctx;
1387 }
1388 
1389 static inline struct perf_event_context *
perf_event_ctx_lock(struct perf_event * event)1390 perf_event_ctx_lock(struct perf_event *event)
1391 {
1392 	return perf_event_ctx_lock_nested(event, 0);
1393 }
1394 
perf_event_ctx_unlock(struct perf_event * event,struct perf_event_context * ctx)1395 static void perf_event_ctx_unlock(struct perf_event *event,
1396 				  struct perf_event_context *ctx)
1397 {
1398 	mutex_unlock(&ctx->mutex);
1399 	put_ctx(ctx);
1400 }
1401 
1402 /*
1403  * This must be done under the ctx->lock, such as to serialize against
1404  * context_equiv(), therefore we cannot call put_ctx() since that might end up
1405  * calling scheduler related locks and ctx->lock nests inside those.
1406  */
1407 static __must_check struct perf_event_context *
unclone_ctx(struct perf_event_context * ctx)1408 unclone_ctx(struct perf_event_context *ctx)
1409 {
1410 	struct perf_event_context *parent_ctx = ctx->parent_ctx;
1411 
1412 	lockdep_assert_held(&ctx->lock);
1413 
1414 	if (parent_ctx)
1415 		ctx->parent_ctx = NULL;
1416 	ctx->generation++;
1417 
1418 	return parent_ctx;
1419 }
1420 
perf_event_pid_type(struct perf_event * event,struct task_struct * p,enum pid_type type)1421 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1422 				enum pid_type type)
1423 {
1424 	u32 nr;
1425 	/*
1426 	 * only top level events have the pid namespace they were created in
1427 	 */
1428 	if (event->parent)
1429 		event = event->parent;
1430 
1431 	nr = __task_pid_nr_ns(p, type, event->ns);
1432 	/* avoid -1 if it is idle thread or runs in another ns */
1433 	if (!nr && !pid_alive(p))
1434 		nr = -1;
1435 	return nr;
1436 }
1437 
perf_event_pid(struct perf_event * event,struct task_struct * p)1438 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1439 {
1440 	return perf_event_pid_type(event, p, PIDTYPE_TGID);
1441 }
1442 
perf_event_tid(struct perf_event * event,struct task_struct * p)1443 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1444 {
1445 	return perf_event_pid_type(event, p, PIDTYPE_PID);
1446 }
1447 
1448 /*
1449  * If we inherit events we want to return the parent event id
1450  * to userspace.
1451  */
primary_event_id(struct perf_event * event)1452 static u64 primary_event_id(struct perf_event *event)
1453 {
1454 	u64 id = event->id;
1455 
1456 	if (event->parent)
1457 		id = event->parent->id;
1458 
1459 	return id;
1460 }
1461 
1462 /*
1463  * Get the perf_event_context for a task and lock it.
1464  *
1465  * This has to cope with the fact that until it is locked,
1466  * the context could get moved to another task.
1467  */
1468 static struct perf_event_context *
perf_lock_task_context(struct task_struct * task,unsigned long * flags)1469 perf_lock_task_context(struct task_struct *task, unsigned long *flags)
1470 {
1471 	struct perf_event_context *ctx;
1472 
1473 retry:
1474 	/*
1475 	 * One of the few rules of preemptible RCU is that one cannot do
1476 	 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1477 	 * part of the read side critical section was irqs-enabled -- see
1478 	 * rcu_read_unlock_special().
1479 	 *
1480 	 * Since ctx->lock nests under rq->lock we must ensure the entire read
1481 	 * side critical section has interrupts disabled.
1482 	 */
1483 	local_irq_save(*flags);
1484 	rcu_read_lock();
1485 	ctx = rcu_dereference(task->perf_event_ctxp);
1486 	if (ctx) {
1487 		/*
1488 		 * If this context is a clone of another, it might
1489 		 * get swapped for another underneath us by
1490 		 * perf_event_task_sched_out, though the
1491 		 * rcu_read_lock() protects us from any context
1492 		 * getting freed.  Lock the context and check if it
1493 		 * got swapped before we could get the lock, and retry
1494 		 * if so.  If we locked the right context, then it
1495 		 * can't get swapped on us any more.
1496 		 */
1497 		raw_spin_lock(&ctx->lock);
1498 		if (ctx != rcu_dereference(task->perf_event_ctxp)) {
1499 			raw_spin_unlock(&ctx->lock);
1500 			rcu_read_unlock();
1501 			local_irq_restore(*flags);
1502 			goto retry;
1503 		}
1504 
1505 		if (ctx->task == TASK_TOMBSTONE ||
1506 		    !refcount_inc_not_zero(&ctx->refcount)) {
1507 			raw_spin_unlock(&ctx->lock);
1508 			ctx = NULL;
1509 		} else {
1510 			WARN_ON_ONCE(ctx->task != task);
1511 		}
1512 	}
1513 	rcu_read_unlock();
1514 	if (!ctx)
1515 		local_irq_restore(*flags);
1516 	return ctx;
1517 }
1518 
1519 /*
1520  * Get the context for a task and increment its pin_count so it
1521  * can't get swapped to another task.  This also increments its
1522  * reference count so that the context can't get freed.
1523  */
1524 static struct perf_event_context *
perf_pin_task_context(struct task_struct * task)1525 perf_pin_task_context(struct task_struct *task)
1526 {
1527 	struct perf_event_context *ctx;
1528 	unsigned long flags;
1529 
1530 	ctx = perf_lock_task_context(task, &flags);
1531 	if (ctx) {
1532 		++ctx->pin_count;
1533 		raw_spin_unlock_irqrestore(&ctx->lock, flags);
1534 	}
1535 	return ctx;
1536 }
1537 
perf_unpin_context(struct perf_event_context * ctx)1538 static void perf_unpin_context(struct perf_event_context *ctx)
1539 {
1540 	unsigned long flags;
1541 
1542 	raw_spin_lock_irqsave(&ctx->lock, flags);
1543 	--ctx->pin_count;
1544 	raw_spin_unlock_irqrestore(&ctx->lock, flags);
1545 }
1546 
1547 /*
1548  * Update the record of the current time in a context.
1549  */
__update_context_time(struct perf_event_context * ctx,bool adv)1550 static void __update_context_time(struct perf_event_context *ctx, bool adv)
1551 {
1552 	u64 now = perf_clock();
1553 
1554 	lockdep_assert_held(&ctx->lock);
1555 
1556 	if (adv)
1557 		ctx->time += now - ctx->timestamp;
1558 	ctx->timestamp = now;
1559 
1560 	/*
1561 	 * The above: time' = time + (now - timestamp), can be re-arranged
1562 	 * into: time` = now + (time - timestamp), which gives a single value
1563 	 * offset to compute future time without locks on.
1564 	 *
1565 	 * See perf_event_time_now(), which can be used from NMI context where
1566 	 * it's (obviously) not possible to acquire ctx->lock in order to read
1567 	 * both the above values in a consistent manner.
1568 	 */
1569 	WRITE_ONCE(ctx->timeoffset, ctx->time - ctx->timestamp);
1570 }
1571 
update_context_time(struct perf_event_context * ctx)1572 static void update_context_time(struct perf_event_context *ctx)
1573 {
1574 	__update_context_time(ctx, true);
1575 }
1576 
perf_event_time(struct perf_event * event)1577 static u64 perf_event_time(struct perf_event *event)
1578 {
1579 	struct perf_event_context *ctx = event->ctx;
1580 
1581 	if (unlikely(!ctx))
1582 		return 0;
1583 
1584 	if (is_cgroup_event(event))
1585 		return perf_cgroup_event_time(event);
1586 
1587 	return ctx->time;
1588 }
1589 
perf_event_time_now(struct perf_event * event,u64 now)1590 static u64 perf_event_time_now(struct perf_event *event, u64 now)
1591 {
1592 	struct perf_event_context *ctx = event->ctx;
1593 
1594 	if (unlikely(!ctx))
1595 		return 0;
1596 
1597 	if (is_cgroup_event(event))
1598 		return perf_cgroup_event_time_now(event, now);
1599 
1600 	if (!(__load_acquire(&ctx->is_active) & EVENT_TIME))
1601 		return ctx->time;
1602 
1603 	now += READ_ONCE(ctx->timeoffset);
1604 	return now;
1605 }
1606 
get_event_type(struct perf_event * event)1607 static enum event_type_t get_event_type(struct perf_event *event)
1608 {
1609 	struct perf_event_context *ctx = event->ctx;
1610 	enum event_type_t event_type;
1611 
1612 	lockdep_assert_held(&ctx->lock);
1613 
1614 	/*
1615 	 * It's 'group type', really, because if our group leader is
1616 	 * pinned, so are we.
1617 	 */
1618 	if (event->group_leader != event)
1619 		event = event->group_leader;
1620 
1621 	event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1622 	if (!ctx->task)
1623 		event_type |= EVENT_CPU;
1624 
1625 	return event_type;
1626 }
1627 
1628 /*
1629  * Helper function to initialize event group nodes.
1630  */
init_event_group(struct perf_event * event)1631 static void init_event_group(struct perf_event *event)
1632 {
1633 	RB_CLEAR_NODE(&event->group_node);
1634 	event->group_index = 0;
1635 }
1636 
1637 /*
1638  * Extract pinned or flexible groups from the context
1639  * based on event attrs bits.
1640  */
1641 static struct perf_event_groups *
get_event_groups(struct perf_event * event,struct perf_event_context * ctx)1642 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1643 {
1644 	if (event->attr.pinned)
1645 		return &ctx->pinned_groups;
1646 	else
1647 		return &ctx->flexible_groups;
1648 }
1649 
1650 /*
1651  * Helper function to initializes perf_event_group trees.
1652  */
perf_event_groups_init(struct perf_event_groups * groups)1653 static void perf_event_groups_init(struct perf_event_groups *groups)
1654 {
1655 	groups->tree = RB_ROOT;
1656 	groups->index = 0;
1657 }
1658 
event_cgroup(const struct perf_event * event)1659 static inline struct cgroup *event_cgroup(const struct perf_event *event)
1660 {
1661 	struct cgroup *cgroup = NULL;
1662 
1663 #ifdef CONFIG_CGROUP_PERF
1664 	if (event->cgrp)
1665 		cgroup = event->cgrp->css.cgroup;
1666 #endif
1667 
1668 	return cgroup;
1669 }
1670 
1671 /*
1672  * Compare function for event groups;
1673  *
1674  * Implements complex key that first sorts by CPU and then by virtual index
1675  * which provides ordering when rotating groups for the same CPU.
1676  */
1677 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)1678 perf_event_groups_cmp(const int left_cpu, const struct pmu *left_pmu,
1679 		      const struct cgroup *left_cgroup, const u64 left_group_index,
1680 		      const struct perf_event *right)
1681 {
1682 	if (left_cpu < right->cpu)
1683 		return -1;
1684 	if (left_cpu > right->cpu)
1685 		return 1;
1686 
1687 	if (left_pmu) {
1688 		if (left_pmu < right->pmu_ctx->pmu)
1689 			return -1;
1690 		if (left_pmu > right->pmu_ctx->pmu)
1691 			return 1;
1692 	}
1693 
1694 #ifdef CONFIG_CGROUP_PERF
1695 	{
1696 		const struct cgroup *right_cgroup = event_cgroup(right);
1697 
1698 		if (left_cgroup != right_cgroup) {
1699 			if (!left_cgroup) {
1700 				/*
1701 				 * Left has no cgroup but right does, no
1702 				 * cgroups come first.
1703 				 */
1704 				return -1;
1705 			}
1706 			if (!right_cgroup) {
1707 				/*
1708 				 * Right has no cgroup but left does, no
1709 				 * cgroups come first.
1710 				 */
1711 				return 1;
1712 			}
1713 			/* Two dissimilar cgroups, order by id. */
1714 			if (cgroup_id(left_cgroup) < cgroup_id(right_cgroup))
1715 				return -1;
1716 
1717 			return 1;
1718 		}
1719 	}
1720 #endif
1721 
1722 	if (left_group_index < right->group_index)
1723 		return -1;
1724 	if (left_group_index > right->group_index)
1725 		return 1;
1726 
1727 	return 0;
1728 }
1729 
1730 #define __node_2_pe(node) \
1731 	rb_entry((node), struct perf_event, group_node)
1732 
__group_less(struct rb_node * a,const struct rb_node * b)1733 static inline bool __group_less(struct rb_node *a, const struct rb_node *b)
1734 {
1735 	struct perf_event *e = __node_2_pe(a);
1736 	return perf_event_groups_cmp(e->cpu, e->pmu_ctx->pmu, event_cgroup(e),
1737 				     e->group_index, __node_2_pe(b)) < 0;
1738 }
1739 
1740 struct __group_key {
1741 	int cpu;
1742 	struct pmu *pmu;
1743 	struct cgroup *cgroup;
1744 };
1745 
__group_cmp(const void * key,const struct rb_node * node)1746 static inline int __group_cmp(const void *key, const struct rb_node *node)
1747 {
1748 	const struct __group_key *a = key;
1749 	const struct perf_event *b = __node_2_pe(node);
1750 
1751 	/* partial/subtree match: @cpu, @pmu, @cgroup; ignore: @group_index */
1752 	return perf_event_groups_cmp(a->cpu, a->pmu, a->cgroup, b->group_index, b);
1753 }
1754 
1755 static inline int
__group_cmp_ignore_cgroup(const void * key,const struct rb_node * node)1756 __group_cmp_ignore_cgroup(const void *key, const struct rb_node *node)
1757 {
1758 	const struct __group_key *a = key;
1759 	const struct perf_event *b = __node_2_pe(node);
1760 
1761 	/* partial/subtree match: @cpu, @pmu, ignore: @cgroup, @group_index */
1762 	return perf_event_groups_cmp(a->cpu, a->pmu, event_cgroup(b),
1763 				     b->group_index, b);
1764 }
1765 
1766 /*
1767  * Insert @event into @groups' tree; using
1768  *   {@event->cpu, @event->pmu_ctx->pmu, event_cgroup(@event), ++@groups->index}
1769  * as key. This places it last inside the {cpu,pmu,cgroup} subtree.
1770  */
1771 static void
perf_event_groups_insert(struct perf_event_groups * groups,struct perf_event * event)1772 perf_event_groups_insert(struct perf_event_groups *groups,
1773 			 struct perf_event *event)
1774 {
1775 	event->group_index = ++groups->index;
1776 
1777 	rb_add(&event->group_node, &groups->tree, __group_less);
1778 }
1779 
1780 /*
1781  * Helper function to insert event into the pinned or flexible groups.
1782  */
1783 static void
add_event_to_groups(struct perf_event * event,struct perf_event_context * ctx)1784 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1785 {
1786 	struct perf_event_groups *groups;
1787 
1788 	groups = get_event_groups(event, ctx);
1789 	perf_event_groups_insert(groups, event);
1790 }
1791 
1792 /*
1793  * Delete a group from a tree.
1794  */
1795 static void
perf_event_groups_delete(struct perf_event_groups * groups,struct perf_event * event)1796 perf_event_groups_delete(struct perf_event_groups *groups,
1797 			 struct perf_event *event)
1798 {
1799 	WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1800 		     RB_EMPTY_ROOT(&groups->tree));
1801 
1802 	rb_erase(&event->group_node, &groups->tree);
1803 	init_event_group(event);
1804 }
1805 
1806 /*
1807  * Helper function to delete event from its groups.
1808  */
1809 static void
del_event_from_groups(struct perf_event * event,struct perf_event_context * ctx)1810 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1811 {
1812 	struct perf_event_groups *groups;
1813 
1814 	groups = get_event_groups(event, ctx);
1815 	perf_event_groups_delete(groups, event);
1816 }
1817 
1818 /*
1819  * Get the leftmost event in the {cpu,pmu,cgroup} subtree.
1820  */
1821 static struct perf_event *
perf_event_groups_first(struct perf_event_groups * groups,int cpu,struct pmu * pmu,struct cgroup * cgrp)1822 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1823 			struct pmu *pmu, struct cgroup *cgrp)
1824 {
1825 	struct __group_key key = {
1826 		.cpu = cpu,
1827 		.pmu = pmu,
1828 		.cgroup = cgrp,
1829 	};
1830 	struct rb_node *node;
1831 
1832 	node = rb_find_first(&key, &groups->tree, __group_cmp);
1833 	if (node)
1834 		return __node_2_pe(node);
1835 
1836 	return NULL;
1837 }
1838 
1839 static struct perf_event *
perf_event_groups_next(struct perf_event * event,struct pmu * pmu)1840 perf_event_groups_next(struct perf_event *event, struct pmu *pmu)
1841 {
1842 	struct __group_key key = {
1843 		.cpu = event->cpu,
1844 		.pmu = pmu,
1845 		.cgroup = event_cgroup(event),
1846 	};
1847 	struct rb_node *next;
1848 
1849 	next = rb_next_match(&key, &event->group_node, __group_cmp);
1850 	if (next)
1851 		return __node_2_pe(next);
1852 
1853 	return NULL;
1854 }
1855 
1856 #define perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu)		\
1857 	for (event = perf_event_groups_first(groups, cpu, pmu, NULL);	\
1858 	     event; event = perf_event_groups_next(event, pmu))
1859 
1860 /*
1861  * Iterate through the whole groups tree.
1862  */
1863 #define perf_event_groups_for_each(event, groups)			\
1864 	for (event = rb_entry_safe(rb_first(&((groups)->tree)),		\
1865 				typeof(*event), group_node); event;	\
1866 		event = rb_entry_safe(rb_next(&event->group_node),	\
1867 				typeof(*event), group_node))
1868 
1869 /*
1870  * Does the event attribute request inherit with PERF_SAMPLE_READ
1871  */
has_inherit_and_sample_read(struct perf_event_attr * attr)1872 static inline bool has_inherit_and_sample_read(struct perf_event_attr *attr)
1873 {
1874 	return attr->inherit && (attr->sample_type & PERF_SAMPLE_READ);
1875 }
1876 
1877 /*
1878  * Add an event from the lists for its context.
1879  * Must be called with ctx->mutex and ctx->lock held.
1880  */
1881 static void
list_add_event(struct perf_event * event,struct perf_event_context * ctx)1882 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1883 {
1884 	lockdep_assert_held(&ctx->lock);
1885 
1886 	WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1887 	event->attach_state |= PERF_ATTACH_CONTEXT;
1888 
1889 	event->tstamp = perf_event_time(event);
1890 
1891 	/*
1892 	 * If we're a stand alone event or group leader, we go to the context
1893 	 * list, group events are kept attached to the group so that
1894 	 * perf_group_detach can, at all times, locate all siblings.
1895 	 */
1896 	if (event->group_leader == event) {
1897 		event->group_caps = event->event_caps;
1898 		add_event_to_groups(event, ctx);
1899 	}
1900 
1901 	list_add_rcu(&event->event_entry, &ctx->event_list);
1902 	ctx->nr_events++;
1903 	if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
1904 		ctx->nr_user++;
1905 	if (event->attr.inherit_stat)
1906 		ctx->nr_stat++;
1907 	if (has_inherit_and_sample_read(&event->attr))
1908 		local_inc(&ctx->nr_no_switch_fast);
1909 
1910 	if (event->state > PERF_EVENT_STATE_OFF)
1911 		perf_cgroup_event_enable(event, ctx);
1912 
1913 	ctx->generation++;
1914 	event->pmu_ctx->nr_events++;
1915 }
1916 
1917 /*
1918  * Initialize event state based on the perf_event_attr::disabled.
1919  */
perf_event__state_init(struct perf_event * event)1920 static inline void perf_event__state_init(struct perf_event *event)
1921 {
1922 	event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1923 					      PERF_EVENT_STATE_INACTIVE;
1924 }
1925 
__perf_event_read_size(u64 read_format,int nr_siblings)1926 static int __perf_event_read_size(u64 read_format, int nr_siblings)
1927 {
1928 	int entry = sizeof(u64); /* value */
1929 	int size = 0;
1930 	int nr = 1;
1931 
1932 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1933 		size += sizeof(u64);
1934 
1935 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1936 		size += sizeof(u64);
1937 
1938 	if (read_format & PERF_FORMAT_ID)
1939 		entry += sizeof(u64);
1940 
1941 	if (read_format & PERF_FORMAT_LOST)
1942 		entry += sizeof(u64);
1943 
1944 	if (read_format & PERF_FORMAT_GROUP) {
1945 		nr += nr_siblings;
1946 		size += sizeof(u64);
1947 	}
1948 
1949 	/*
1950 	 * Since perf_event_validate_size() limits this to 16k and inhibits
1951 	 * adding more siblings, this will never overflow.
1952 	 */
1953 	return size + nr * entry;
1954 }
1955 
__perf_event_header_size(struct perf_event * event,u64 sample_type)1956 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1957 {
1958 	struct perf_sample_data *data;
1959 	u16 size = 0;
1960 
1961 	if (sample_type & PERF_SAMPLE_IP)
1962 		size += sizeof(data->ip);
1963 
1964 	if (sample_type & PERF_SAMPLE_ADDR)
1965 		size += sizeof(data->addr);
1966 
1967 	if (sample_type & PERF_SAMPLE_PERIOD)
1968 		size += sizeof(data->period);
1969 
1970 	if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
1971 		size += sizeof(data->weight.full);
1972 
1973 	if (sample_type & PERF_SAMPLE_READ)
1974 		size += event->read_size;
1975 
1976 	if (sample_type & PERF_SAMPLE_DATA_SRC)
1977 		size += sizeof(data->data_src.val);
1978 
1979 	if (sample_type & PERF_SAMPLE_TRANSACTION)
1980 		size += sizeof(data->txn);
1981 
1982 	if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1983 		size += sizeof(data->phys_addr);
1984 
1985 	if (sample_type & PERF_SAMPLE_CGROUP)
1986 		size += sizeof(data->cgroup);
1987 
1988 	if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
1989 		size += sizeof(data->data_page_size);
1990 
1991 	if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
1992 		size += sizeof(data->code_page_size);
1993 
1994 	event->header_size = size;
1995 }
1996 
1997 /*
1998  * Called at perf_event creation and when events are attached/detached from a
1999  * group.
2000  */
perf_event__header_size(struct perf_event * event)2001 static void perf_event__header_size(struct perf_event *event)
2002 {
2003 	event->read_size =
2004 		__perf_event_read_size(event->attr.read_format,
2005 				       event->group_leader->nr_siblings);
2006 	__perf_event_header_size(event, event->attr.sample_type);
2007 }
2008 
perf_event__id_header_size(struct perf_event * event)2009 static void perf_event__id_header_size(struct perf_event *event)
2010 {
2011 	struct perf_sample_data *data;
2012 	u64 sample_type = event->attr.sample_type;
2013 	u16 size = 0;
2014 
2015 	if (sample_type & PERF_SAMPLE_TID)
2016 		size += sizeof(data->tid_entry);
2017 
2018 	if (sample_type & PERF_SAMPLE_TIME)
2019 		size += sizeof(data->time);
2020 
2021 	if (sample_type & PERF_SAMPLE_IDENTIFIER)
2022 		size += sizeof(data->id);
2023 
2024 	if (sample_type & PERF_SAMPLE_ID)
2025 		size += sizeof(data->id);
2026 
2027 	if (sample_type & PERF_SAMPLE_STREAM_ID)
2028 		size += sizeof(data->stream_id);
2029 
2030 	if (sample_type & PERF_SAMPLE_CPU)
2031 		size += sizeof(data->cpu_entry);
2032 
2033 	event->id_header_size = size;
2034 }
2035 
2036 /*
2037  * Check that adding an event to the group does not result in anybody
2038  * overflowing the 64k event limit imposed by the output buffer.
2039  *
2040  * Specifically, check that the read_size for the event does not exceed 16k,
2041  * read_size being the one term that grows with groups size. Since read_size
2042  * depends on per-event read_format, also (re)check the existing events.
2043  *
2044  * This leaves 48k for the constant size fields and things like callchains,
2045  * branch stacks and register sets.
2046  */
perf_event_validate_size(struct perf_event * event)2047 static bool perf_event_validate_size(struct perf_event *event)
2048 {
2049 	struct perf_event *sibling, *group_leader = event->group_leader;
2050 
2051 	if (__perf_event_read_size(event->attr.read_format,
2052 				   group_leader->nr_siblings + 1) > 16*1024)
2053 		return false;
2054 
2055 	if (__perf_event_read_size(group_leader->attr.read_format,
2056 				   group_leader->nr_siblings + 1) > 16*1024)
2057 		return false;
2058 
2059 	/*
2060 	 * When creating a new group leader, group_leader->ctx is initialized
2061 	 * after the size has been validated, but we cannot safely use
2062 	 * for_each_sibling_event() until group_leader->ctx is set. A new group
2063 	 * leader cannot have any siblings yet, so we can safely skip checking
2064 	 * the non-existent siblings.
2065 	 */
2066 	if (event == group_leader)
2067 		return true;
2068 
2069 	for_each_sibling_event(sibling, group_leader) {
2070 		if (__perf_event_read_size(sibling->attr.read_format,
2071 					   group_leader->nr_siblings + 1) > 16*1024)
2072 			return false;
2073 	}
2074 
2075 	return true;
2076 }
2077 
perf_group_attach(struct perf_event * event)2078 static void perf_group_attach(struct perf_event *event)
2079 {
2080 	struct perf_event *group_leader = event->group_leader, *pos;
2081 
2082 	lockdep_assert_held(&event->ctx->lock);
2083 
2084 	/*
2085 	 * We can have double attach due to group movement (move_group) in
2086 	 * perf_event_open().
2087 	 */
2088 	if (event->attach_state & PERF_ATTACH_GROUP)
2089 		return;
2090 
2091 	event->attach_state |= PERF_ATTACH_GROUP;
2092 
2093 	if (group_leader == event)
2094 		return;
2095 
2096 	WARN_ON_ONCE(group_leader->ctx != event->ctx);
2097 
2098 	group_leader->group_caps &= event->event_caps;
2099 
2100 	list_add_tail(&event->sibling_list, &group_leader->sibling_list);
2101 	group_leader->nr_siblings++;
2102 	group_leader->group_generation++;
2103 
2104 	perf_event__header_size(group_leader);
2105 
2106 	for_each_sibling_event(pos, group_leader)
2107 		perf_event__header_size(pos);
2108 }
2109 
2110 /*
2111  * Remove an event from the lists for its context.
2112  * Must be called with ctx->mutex and ctx->lock held.
2113  */
2114 static void
list_del_event(struct perf_event * event,struct perf_event_context * ctx)2115 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
2116 {
2117 	WARN_ON_ONCE(event->ctx != ctx);
2118 	lockdep_assert_held(&ctx->lock);
2119 
2120 	/*
2121 	 * We can have double detach due to exit/hot-unplug + close.
2122 	 */
2123 	if (!(event->attach_state & PERF_ATTACH_CONTEXT))
2124 		return;
2125 
2126 	event->attach_state &= ~PERF_ATTACH_CONTEXT;
2127 
2128 	ctx->nr_events--;
2129 	if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
2130 		ctx->nr_user--;
2131 	if (event->attr.inherit_stat)
2132 		ctx->nr_stat--;
2133 	if (has_inherit_and_sample_read(&event->attr))
2134 		local_dec(&ctx->nr_no_switch_fast);
2135 
2136 	list_del_rcu(&event->event_entry);
2137 
2138 	if (event->group_leader == event)
2139 		del_event_from_groups(event, ctx);
2140 
2141 	ctx->generation++;
2142 	event->pmu_ctx->nr_events--;
2143 }
2144 
2145 static int
perf_aux_output_match(struct perf_event * event,struct perf_event * aux_event)2146 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2147 {
2148 	if (!has_aux(aux_event))
2149 		return 0;
2150 
2151 	if (!event->pmu->aux_output_match)
2152 		return 0;
2153 
2154 	return event->pmu->aux_output_match(aux_event);
2155 }
2156 
2157 static void put_event(struct perf_event *event);
2158 static void __event_disable(struct perf_event *event,
2159 			    struct perf_event_context *ctx,
2160 			    enum perf_event_state state);
2161 
perf_put_aux_event(struct perf_event * event)2162 static void perf_put_aux_event(struct perf_event *event)
2163 {
2164 	struct perf_event_context *ctx = event->ctx;
2165 	struct perf_event *iter;
2166 
2167 	/*
2168 	 * If event uses aux_event tear down the link
2169 	 */
2170 	if (event->aux_event) {
2171 		iter = event->aux_event;
2172 		event->aux_event = NULL;
2173 		put_event(iter);
2174 		return;
2175 	}
2176 
2177 	/*
2178 	 * If the event is an aux_event, tear down all links to
2179 	 * it from other events.
2180 	 */
2181 	for_each_sibling_event(iter, event) {
2182 		if (iter->aux_event != event)
2183 			continue;
2184 
2185 		iter->aux_event = NULL;
2186 		put_event(event);
2187 
2188 		/*
2189 		 * If it's ACTIVE, schedule it out and put it into ERROR
2190 		 * state so that we don't try to schedule it again. Note
2191 		 * that perf_event_enable() will clear the ERROR status.
2192 		 */
2193 		__event_disable(iter, ctx, PERF_EVENT_STATE_ERROR);
2194 	}
2195 }
2196 
perf_need_aux_event(struct perf_event * event)2197 static bool perf_need_aux_event(struct perf_event *event)
2198 {
2199 	return event->attr.aux_output || has_aux_action(event);
2200 }
2201 
perf_get_aux_event(struct perf_event * event,struct perf_event * group_leader)2202 static int perf_get_aux_event(struct perf_event *event,
2203 			      struct perf_event *group_leader)
2204 {
2205 	/*
2206 	 * Our group leader must be an aux event if we want to be
2207 	 * an aux_output. This way, the aux event will precede its
2208 	 * aux_output events in the group, and therefore will always
2209 	 * schedule first.
2210 	 */
2211 	if (!group_leader)
2212 		return 0;
2213 
2214 	/*
2215 	 * aux_output and aux_sample_size are mutually exclusive.
2216 	 */
2217 	if (event->attr.aux_output && event->attr.aux_sample_size)
2218 		return 0;
2219 
2220 	if (event->attr.aux_output &&
2221 	    !perf_aux_output_match(event, group_leader))
2222 		return 0;
2223 
2224 	if ((event->attr.aux_pause || event->attr.aux_resume) &&
2225 	    !(group_leader->pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE))
2226 		return 0;
2227 
2228 	if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2229 		return 0;
2230 
2231 	if (!atomic_long_inc_not_zero(&group_leader->refcount))
2232 		return 0;
2233 
2234 	/*
2235 	 * Link aux_outputs to their aux event; this is undone in
2236 	 * perf_group_detach() by perf_put_aux_event(). When the
2237 	 * group in torn down, the aux_output events loose their
2238 	 * link to the aux_event and can't schedule any more.
2239 	 */
2240 	event->aux_event = group_leader;
2241 
2242 	return 1;
2243 }
2244 
get_event_list(struct perf_event * event)2245 static inline struct list_head *get_event_list(struct perf_event *event)
2246 {
2247 	return event->attr.pinned ? &event->pmu_ctx->pinned_active :
2248 				    &event->pmu_ctx->flexible_active;
2249 }
2250 
perf_group_detach(struct perf_event * event)2251 static void perf_group_detach(struct perf_event *event)
2252 {
2253 	struct perf_event *leader = event->group_leader;
2254 	struct perf_event *sibling, *tmp;
2255 	struct perf_event_context *ctx = event->ctx;
2256 
2257 	lockdep_assert_held(&ctx->lock);
2258 
2259 	/*
2260 	 * We can have double detach due to exit/hot-unplug + close.
2261 	 */
2262 	if (!(event->attach_state & PERF_ATTACH_GROUP))
2263 		return;
2264 
2265 	event->attach_state &= ~PERF_ATTACH_GROUP;
2266 
2267 	perf_put_aux_event(event);
2268 
2269 	/*
2270 	 * If this is a sibling, remove it from its group.
2271 	 */
2272 	if (leader != event) {
2273 		list_del_init(&event->sibling_list);
2274 		event->group_leader->nr_siblings--;
2275 		event->group_leader->group_generation++;
2276 		goto out;
2277 	}
2278 
2279 	/*
2280 	 * If this was a group event with sibling events then
2281 	 * upgrade the siblings to singleton events by adding them
2282 	 * to whatever list we are on.
2283 	 */
2284 	list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2285 
2286 		/*
2287 		 * Events that have PERF_EV_CAP_SIBLING require being part of
2288 		 * a group and cannot exist on their own, schedule them out
2289 		 * and move them into the ERROR state. Also see
2290 		 * _perf_event_enable(), it will not be able to recover this
2291 		 * ERROR state.
2292 		 */
2293 		if (sibling->event_caps & PERF_EV_CAP_SIBLING)
2294 			__event_disable(sibling, ctx, PERF_EVENT_STATE_ERROR);
2295 
2296 		sibling->group_leader = sibling;
2297 		list_del_init(&sibling->sibling_list);
2298 
2299 		/* Inherit group flags from the previous leader */
2300 		sibling->group_caps = event->group_caps;
2301 
2302 		if (sibling->attach_state & PERF_ATTACH_CONTEXT) {
2303 			add_event_to_groups(sibling, event->ctx);
2304 
2305 			if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2306 				list_add_tail(&sibling->active_list, get_event_list(sibling));
2307 		}
2308 
2309 		WARN_ON_ONCE(sibling->ctx != event->ctx);
2310 	}
2311 
2312 out:
2313 	for_each_sibling_event(tmp, leader)
2314 		perf_event__header_size(tmp);
2315 
2316 	perf_event__header_size(leader);
2317 }
2318 
2319 static void sync_child_event(struct perf_event *child_event);
2320 
perf_child_detach(struct perf_event * event)2321 static void perf_child_detach(struct perf_event *event)
2322 {
2323 	struct perf_event *parent_event = event->parent;
2324 
2325 	if (!(event->attach_state & PERF_ATTACH_CHILD))
2326 		return;
2327 
2328 	event->attach_state &= ~PERF_ATTACH_CHILD;
2329 
2330 	if (WARN_ON_ONCE(!parent_event))
2331 		return;
2332 
2333 	/*
2334 	 * Can't check this from an IPI, the holder is likey another CPU.
2335 	 *
2336 	lockdep_assert_held(&parent_event->child_mutex);
2337 	 */
2338 
2339 	sync_child_event(event);
2340 	list_del_init(&event->child_list);
2341 }
2342 
is_orphaned_event(struct perf_event * event)2343 static bool is_orphaned_event(struct perf_event *event)
2344 {
2345 	return event->state == PERF_EVENT_STATE_DEAD;
2346 }
2347 
2348 static inline int
event_filter_match(struct perf_event * event)2349 event_filter_match(struct perf_event *event)
2350 {
2351 	return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2352 	       perf_cgroup_match(event);
2353 }
2354 
is_event_in_freq_mode(struct perf_event * event)2355 static inline bool is_event_in_freq_mode(struct perf_event *event)
2356 {
2357 	return event->attr.freq && event->attr.sample_freq;
2358 }
2359 
2360 static void
event_sched_out(struct perf_event * event,struct perf_event_context * ctx)2361 event_sched_out(struct perf_event *event, struct perf_event_context *ctx)
2362 {
2363 	struct perf_event_pmu_context *epc = event->pmu_ctx;
2364 	struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu);
2365 	enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2366 
2367 	// XXX cpc serialization, probably per-cpu IRQ disabled
2368 
2369 	WARN_ON_ONCE(event->ctx != ctx);
2370 	lockdep_assert_held(&ctx->lock);
2371 
2372 	if (event->state != PERF_EVENT_STATE_ACTIVE)
2373 		return;
2374 
2375 	/*
2376 	 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2377 	 * we can schedule events _OUT_ individually through things like
2378 	 * __perf_remove_from_context().
2379 	 */
2380 	list_del_init(&event->active_list);
2381 
2382 	perf_pmu_disable(event->pmu);
2383 
2384 	event->pmu->del(event, 0);
2385 	event->oncpu = -1;
2386 
2387 	if (event->pending_disable) {
2388 		event->pending_disable = 0;
2389 		perf_cgroup_event_disable(event, ctx);
2390 		state = PERF_EVENT_STATE_OFF;
2391 	}
2392 
2393 	perf_event_set_state(event, state);
2394 
2395 	if (!is_software_event(event))
2396 		cpc->active_oncpu--;
2397 	if (is_event_in_freq_mode(event)) {
2398 		ctx->nr_freq--;
2399 		epc->nr_freq--;
2400 	}
2401 	if (event->attr.exclusive || !cpc->active_oncpu)
2402 		cpc->exclusive = 0;
2403 
2404 	perf_pmu_enable(event->pmu);
2405 }
2406 
2407 static void
group_sched_out(struct perf_event * group_event,struct perf_event_context * ctx)2408 group_sched_out(struct perf_event *group_event, struct perf_event_context *ctx)
2409 {
2410 	struct perf_event *event;
2411 
2412 	if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2413 		return;
2414 
2415 	perf_assert_pmu_disabled(group_event->pmu_ctx->pmu);
2416 
2417 	event_sched_out(group_event, ctx);
2418 
2419 	/*
2420 	 * Schedule out siblings (if any):
2421 	 */
2422 	for_each_sibling_event(event, group_event)
2423 		event_sched_out(event, ctx);
2424 }
2425 
2426 static inline void
__ctx_time_update(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,bool final)2427 __ctx_time_update(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx, bool final)
2428 {
2429 	if (ctx->is_active & EVENT_TIME) {
2430 		if (ctx->is_active & EVENT_FROZEN)
2431 			return;
2432 		update_context_time(ctx);
2433 		update_cgrp_time_from_cpuctx(cpuctx, final);
2434 	}
2435 }
2436 
2437 static inline void
ctx_time_update(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)2438 ctx_time_update(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx)
2439 {
2440 	__ctx_time_update(cpuctx, ctx, false);
2441 }
2442 
2443 /*
2444  * To be used inside perf_ctx_lock() / perf_ctx_unlock(). Lasts until perf_ctx_unlock().
2445  */
2446 static inline void
ctx_time_freeze(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)2447 ctx_time_freeze(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx)
2448 {
2449 	ctx_time_update(cpuctx, ctx);
2450 	if (ctx->is_active & EVENT_TIME)
2451 		ctx->is_active |= EVENT_FROZEN;
2452 }
2453 
2454 static inline void
ctx_time_update_event(struct perf_event_context * ctx,struct perf_event * event)2455 ctx_time_update_event(struct perf_event_context *ctx, struct perf_event *event)
2456 {
2457 	if (ctx->is_active & EVENT_TIME) {
2458 		if (ctx->is_active & EVENT_FROZEN)
2459 			return;
2460 		update_context_time(ctx);
2461 		update_cgrp_time_from_event(event);
2462 	}
2463 }
2464 
2465 #define DETACH_GROUP	0x01UL
2466 #define DETACH_CHILD	0x02UL
2467 #define DETACH_EXIT	0x04UL
2468 #define DETACH_REVOKE	0x08UL
2469 #define DETACH_DEAD	0x10UL
2470 
2471 /*
2472  * Cross CPU call to remove a performance event
2473  *
2474  * We disable the event on the hardware level first. After that we
2475  * remove it from the context list.
2476  */
2477 static void
__perf_remove_from_context(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)2478 __perf_remove_from_context(struct perf_event *event,
2479 			   struct perf_cpu_context *cpuctx,
2480 			   struct perf_event_context *ctx,
2481 			   void *info)
2482 {
2483 	struct perf_event_pmu_context *pmu_ctx = event->pmu_ctx;
2484 	enum perf_event_state state = PERF_EVENT_STATE_OFF;
2485 	unsigned long flags = (unsigned long)info;
2486 
2487 	ctx_time_update(cpuctx, ctx);
2488 
2489 	/*
2490 	 * Ensure event_sched_out() switches to OFF, at the very least
2491 	 * this avoids raising perf_pending_task() at this time.
2492 	 */
2493 	if (flags & DETACH_EXIT)
2494 		state = PERF_EVENT_STATE_EXIT;
2495 	if (flags & DETACH_REVOKE)
2496 		state = PERF_EVENT_STATE_REVOKED;
2497 	if (flags & DETACH_DEAD)
2498 		state = PERF_EVENT_STATE_DEAD;
2499 
2500 	event_sched_out(event, ctx);
2501 
2502 	if (event->state > PERF_EVENT_STATE_OFF)
2503 		perf_cgroup_event_disable(event, ctx);
2504 
2505 	perf_event_set_state(event, min(event->state, state));
2506 
2507 	if (flags & DETACH_GROUP)
2508 		perf_group_detach(event);
2509 	if (flags & DETACH_CHILD)
2510 		perf_child_detach(event);
2511 	list_del_event(event, ctx);
2512 
2513 	if (!pmu_ctx->nr_events) {
2514 		pmu_ctx->rotate_necessary = 0;
2515 
2516 		if (ctx->task && ctx->is_active) {
2517 			struct perf_cpu_pmu_context *cpc = this_cpc(pmu_ctx->pmu);
2518 
2519 			WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
2520 			cpc->task_epc = NULL;
2521 		}
2522 	}
2523 
2524 	if (!ctx->nr_events && ctx->is_active) {
2525 		if (ctx == &cpuctx->ctx)
2526 			update_cgrp_time_from_cpuctx(cpuctx, true);
2527 
2528 		ctx->is_active = 0;
2529 		if (ctx->task) {
2530 			WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2531 			cpuctx->task_ctx = NULL;
2532 		}
2533 	}
2534 }
2535 
2536 /*
2537  * Remove the event from a task's (or a CPU's) list of events.
2538  *
2539  * If event->ctx is a cloned context, callers must make sure that
2540  * every task struct that event->ctx->task could possibly point to
2541  * remains valid.  This is OK when called from perf_release since
2542  * that only calls us on the top-level context, which can't be a clone.
2543  * When called from perf_event_exit_task, it's OK because the
2544  * context has been detached from its task.
2545  */
perf_remove_from_context(struct perf_event * event,unsigned long flags)2546 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2547 {
2548 	struct perf_event_context *ctx = event->ctx;
2549 
2550 	lockdep_assert_held(&ctx->mutex);
2551 
2552 	/*
2553 	 * Because of perf_event_exit_task(), perf_remove_from_context() ought
2554 	 * to work in the face of TASK_TOMBSTONE, unlike every other
2555 	 * event_function_call() user.
2556 	 */
2557 	raw_spin_lock_irq(&ctx->lock);
2558 	if (!ctx->is_active) {
2559 		__perf_remove_from_context(event, this_cpu_ptr(&perf_cpu_context),
2560 					   ctx, (void *)flags);
2561 		raw_spin_unlock_irq(&ctx->lock);
2562 		return;
2563 	}
2564 	raw_spin_unlock_irq(&ctx->lock);
2565 
2566 	event_function_call(event, __perf_remove_from_context, (void *)flags);
2567 }
2568 
__event_disable(struct perf_event * event,struct perf_event_context * ctx,enum perf_event_state state)2569 static void __event_disable(struct perf_event *event,
2570 			    struct perf_event_context *ctx,
2571 			    enum perf_event_state state)
2572 {
2573 	event_sched_out(event, ctx);
2574 	perf_cgroup_event_disable(event, ctx);
2575 	perf_event_set_state(event, state);
2576 }
2577 
2578 /*
2579  * Cross CPU call to disable a performance event
2580  */
__perf_event_disable(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)2581 static void __perf_event_disable(struct perf_event *event,
2582 				 struct perf_cpu_context *cpuctx,
2583 				 struct perf_event_context *ctx,
2584 				 void *info)
2585 {
2586 	if (event->state < PERF_EVENT_STATE_INACTIVE)
2587 		return;
2588 
2589 	perf_pmu_disable(event->pmu_ctx->pmu);
2590 	ctx_time_update_event(ctx, event);
2591 
2592 	/*
2593 	 * When disabling a group leader, the whole group becomes ineligible
2594 	 * to run, so schedule out the full group.
2595 	 */
2596 	if (event == event->group_leader)
2597 		group_sched_out(event, ctx);
2598 
2599 	/*
2600 	 * But only mark the leader OFF; the siblings will remain
2601 	 * INACTIVE.
2602 	 */
2603 	__event_disable(event, ctx, PERF_EVENT_STATE_OFF);
2604 
2605 	perf_pmu_enable(event->pmu_ctx->pmu);
2606 }
2607 
2608 /*
2609  * Disable an event.
2610  *
2611  * If event->ctx is a cloned context, callers must make sure that
2612  * every task struct that event->ctx->task could possibly point to
2613  * remains valid.  This condition is satisfied when called through
2614  * perf_event_for_each_child or perf_event_for_each because they
2615  * hold the top-level event's child_mutex, so any descendant that
2616  * goes to exit will block in perf_event_exit_event().
2617  *
2618  * When called from perf_pending_disable it's OK because event->ctx
2619  * is the current context on this CPU and preemption is disabled,
2620  * hence we can't get into perf_event_task_sched_out for this context.
2621  */
_perf_event_disable(struct perf_event * event)2622 static void _perf_event_disable(struct perf_event *event)
2623 {
2624 	struct perf_event_context *ctx = event->ctx;
2625 
2626 	raw_spin_lock_irq(&ctx->lock);
2627 	if (event->state <= PERF_EVENT_STATE_OFF) {
2628 		raw_spin_unlock_irq(&ctx->lock);
2629 		return;
2630 	}
2631 	raw_spin_unlock_irq(&ctx->lock);
2632 
2633 	event_function_call(event, __perf_event_disable, NULL);
2634 }
2635 
perf_event_disable_local(struct perf_event * event)2636 void perf_event_disable_local(struct perf_event *event)
2637 {
2638 	event_function_local(event, __perf_event_disable, NULL);
2639 }
2640 
2641 /*
2642  * Strictly speaking kernel users cannot create groups and therefore this
2643  * interface does not need the perf_event_ctx_lock() magic.
2644  */
perf_event_disable(struct perf_event * event)2645 void perf_event_disable(struct perf_event *event)
2646 {
2647 	struct perf_event_context *ctx;
2648 
2649 	ctx = perf_event_ctx_lock(event);
2650 	_perf_event_disable(event);
2651 	perf_event_ctx_unlock(event, ctx);
2652 }
2653 EXPORT_SYMBOL_GPL(perf_event_disable);
2654 
perf_event_disable_inatomic(struct perf_event * event)2655 void perf_event_disable_inatomic(struct perf_event *event)
2656 {
2657 	event->pending_disable = 1;
2658 	irq_work_queue(&event->pending_disable_irq);
2659 }
2660 
2661 #define MAX_INTERRUPTS (~0ULL)
2662 
2663 static void perf_log_throttle(struct perf_event *event, int enable);
2664 static void perf_log_itrace_start(struct perf_event *event);
2665 
perf_event_unthrottle(struct perf_event * event,bool start)2666 static void perf_event_unthrottle(struct perf_event *event, bool start)
2667 {
2668 	event->hw.interrupts = 0;
2669 	if (start)
2670 		event->pmu->start(event, 0);
2671 	if (event == event->group_leader)
2672 		perf_log_throttle(event, 1);
2673 }
2674 
perf_event_throttle(struct perf_event * event)2675 static void perf_event_throttle(struct perf_event *event)
2676 {
2677 	event->hw.interrupts = MAX_INTERRUPTS;
2678 	event->pmu->stop(event, 0);
2679 	if (event == event->group_leader)
2680 		perf_log_throttle(event, 0);
2681 }
2682 
perf_event_unthrottle_group(struct perf_event * event,bool skip_start_event)2683 static void perf_event_unthrottle_group(struct perf_event *event, bool skip_start_event)
2684 {
2685 	struct perf_event *sibling, *leader = event->group_leader;
2686 
2687 	perf_event_unthrottle(leader, skip_start_event ? leader != event : true);
2688 	for_each_sibling_event(sibling, leader)
2689 		perf_event_unthrottle(sibling, skip_start_event ? sibling != event : true);
2690 }
2691 
perf_event_throttle_group(struct perf_event * event)2692 static void perf_event_throttle_group(struct perf_event *event)
2693 {
2694 	struct perf_event *sibling, *leader = event->group_leader;
2695 
2696 	perf_event_throttle(leader);
2697 	for_each_sibling_event(sibling, leader)
2698 		perf_event_throttle(sibling);
2699 }
2700 
2701 static int
event_sched_in(struct perf_event * event,struct perf_event_context * ctx)2702 event_sched_in(struct perf_event *event, struct perf_event_context *ctx)
2703 {
2704 	struct perf_event_pmu_context *epc = event->pmu_ctx;
2705 	struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu);
2706 	int ret = 0;
2707 
2708 	WARN_ON_ONCE(event->ctx != ctx);
2709 
2710 	lockdep_assert_held(&ctx->lock);
2711 
2712 	if (event->state <= PERF_EVENT_STATE_OFF)
2713 		return 0;
2714 
2715 	WRITE_ONCE(event->oncpu, smp_processor_id());
2716 	/*
2717 	 * Order event::oncpu write to happen before the ACTIVE state is
2718 	 * visible. This allows perf_event_{stop,read}() to observe the correct
2719 	 * ->oncpu if it sees ACTIVE.
2720 	 */
2721 	smp_wmb();
2722 	perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2723 
2724 	/*
2725 	 * Unthrottle events, since we scheduled we might have missed several
2726 	 * ticks already, also for a heavily scheduling task there is little
2727 	 * guarantee it'll get a tick in a timely manner.
2728 	 */
2729 	if (unlikely(event->hw.interrupts == MAX_INTERRUPTS))
2730 		perf_event_unthrottle(event, false);
2731 
2732 	perf_pmu_disable(event->pmu);
2733 
2734 	perf_log_itrace_start(event);
2735 
2736 	if (event->pmu->add(event, PERF_EF_START)) {
2737 		perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2738 		event->oncpu = -1;
2739 		ret = -EAGAIN;
2740 		goto out;
2741 	}
2742 
2743 	if (!is_software_event(event))
2744 		cpc->active_oncpu++;
2745 	if (is_event_in_freq_mode(event)) {
2746 		ctx->nr_freq++;
2747 		epc->nr_freq++;
2748 	}
2749 	if (event->attr.exclusive)
2750 		cpc->exclusive = 1;
2751 
2752 out:
2753 	perf_pmu_enable(event->pmu);
2754 
2755 	return ret;
2756 }
2757 
2758 static int
group_sched_in(struct perf_event * group_event,struct perf_event_context * ctx)2759 group_sched_in(struct perf_event *group_event, struct perf_event_context *ctx)
2760 {
2761 	struct perf_event *event, *partial_group = NULL;
2762 	struct pmu *pmu = group_event->pmu_ctx->pmu;
2763 
2764 	if (group_event->state == PERF_EVENT_STATE_OFF)
2765 		return 0;
2766 
2767 	pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2768 
2769 	if (event_sched_in(group_event, ctx))
2770 		goto error;
2771 
2772 	/*
2773 	 * Schedule in siblings as one group (if any):
2774 	 */
2775 	for_each_sibling_event(event, group_event) {
2776 		if (event_sched_in(event, ctx)) {
2777 			partial_group = event;
2778 			goto group_error;
2779 		}
2780 	}
2781 
2782 	if (!pmu->commit_txn(pmu))
2783 		return 0;
2784 
2785 group_error:
2786 	/*
2787 	 * Groups can be scheduled in as one unit only, so undo any
2788 	 * partial group before returning:
2789 	 * The events up to the failed event are scheduled out normally.
2790 	 */
2791 	for_each_sibling_event(event, group_event) {
2792 		if (event == partial_group)
2793 			break;
2794 
2795 		event_sched_out(event, ctx);
2796 	}
2797 	event_sched_out(group_event, ctx);
2798 
2799 error:
2800 	pmu->cancel_txn(pmu);
2801 	return -EAGAIN;
2802 }
2803 
2804 /*
2805  * Work out whether we can put this event group on the CPU now.
2806  */
group_can_go_on(struct perf_event * event,int can_add_hw)2807 static int group_can_go_on(struct perf_event *event, int can_add_hw)
2808 {
2809 	struct perf_event_pmu_context *epc = event->pmu_ctx;
2810 	struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu);
2811 
2812 	/*
2813 	 * Groups consisting entirely of software events can always go on.
2814 	 */
2815 	if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2816 		return 1;
2817 	/*
2818 	 * If an exclusive group is already on, no other hardware
2819 	 * events can go on.
2820 	 */
2821 	if (cpc->exclusive)
2822 		return 0;
2823 	/*
2824 	 * If this group is exclusive and there are already
2825 	 * events on the CPU, it can't go on.
2826 	 */
2827 	if (event->attr.exclusive && !list_empty(get_event_list(event)))
2828 		return 0;
2829 	/*
2830 	 * Otherwise, try to add it if all previous groups were able
2831 	 * to go on.
2832 	 */
2833 	return can_add_hw;
2834 }
2835 
add_event_to_ctx(struct perf_event * event,struct perf_event_context * ctx)2836 static void add_event_to_ctx(struct perf_event *event,
2837 			       struct perf_event_context *ctx)
2838 {
2839 	list_add_event(event, ctx);
2840 	perf_group_attach(event);
2841 }
2842 
task_ctx_sched_out(struct perf_event_context * ctx,struct pmu * pmu,enum event_type_t event_type)2843 static void task_ctx_sched_out(struct perf_event_context *ctx,
2844 			       struct pmu *pmu,
2845 			       enum event_type_t event_type)
2846 {
2847 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2848 
2849 	if (!cpuctx->task_ctx)
2850 		return;
2851 
2852 	if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2853 		return;
2854 
2855 	ctx_sched_out(ctx, pmu, event_type);
2856 }
2857 
perf_event_sched_in(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,struct pmu * pmu)2858 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2859 				struct perf_event_context *ctx,
2860 				struct pmu *pmu)
2861 {
2862 	ctx_sched_in(&cpuctx->ctx, pmu, EVENT_PINNED);
2863 	if (ctx)
2864 		 ctx_sched_in(ctx, pmu, EVENT_PINNED);
2865 	ctx_sched_in(&cpuctx->ctx, pmu, EVENT_FLEXIBLE);
2866 	if (ctx)
2867 		 ctx_sched_in(ctx, pmu, EVENT_FLEXIBLE);
2868 }
2869 
2870 /*
2871  * We want to maintain the following priority of scheduling:
2872  *  - CPU pinned (EVENT_CPU | EVENT_PINNED)
2873  *  - task pinned (EVENT_PINNED)
2874  *  - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2875  *  - task flexible (EVENT_FLEXIBLE).
2876  *
2877  * In order to avoid unscheduling and scheduling back in everything every
2878  * time an event is added, only do it for the groups of equal priority and
2879  * below.
2880  *
2881  * This can be called after a batch operation on task events, in which case
2882  * event_type is a bit mask of the types of events involved. For CPU events,
2883  * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2884  */
ctx_resched(struct perf_cpu_context * cpuctx,struct perf_event_context * task_ctx,struct pmu * pmu,enum event_type_t event_type)2885 static void ctx_resched(struct perf_cpu_context *cpuctx,
2886 			struct perf_event_context *task_ctx,
2887 			struct pmu *pmu, enum event_type_t event_type)
2888 {
2889 	bool cpu_event = !!(event_type & EVENT_CPU);
2890 	struct perf_event_pmu_context *epc;
2891 
2892 	/*
2893 	 * If pinned groups are involved, flexible groups also need to be
2894 	 * scheduled out.
2895 	 */
2896 	if (event_type & EVENT_PINNED)
2897 		event_type |= EVENT_FLEXIBLE;
2898 
2899 	event_type &= EVENT_ALL;
2900 
2901 	for_each_epc(epc, &cpuctx->ctx, pmu, false)
2902 		perf_pmu_disable(epc->pmu);
2903 
2904 	if (task_ctx) {
2905 		for_each_epc(epc, task_ctx, pmu, false)
2906 			perf_pmu_disable(epc->pmu);
2907 
2908 		task_ctx_sched_out(task_ctx, pmu, event_type);
2909 	}
2910 
2911 	/*
2912 	 * Decide which cpu ctx groups to schedule out based on the types
2913 	 * of events that caused rescheduling:
2914 	 *  - EVENT_CPU: schedule out corresponding groups;
2915 	 *  - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2916 	 *  - otherwise, do nothing more.
2917 	 */
2918 	if (cpu_event)
2919 		ctx_sched_out(&cpuctx->ctx, pmu, event_type);
2920 	else if (event_type & EVENT_PINNED)
2921 		ctx_sched_out(&cpuctx->ctx, pmu, EVENT_FLEXIBLE);
2922 
2923 	perf_event_sched_in(cpuctx, task_ctx, pmu);
2924 
2925 	for_each_epc(epc, &cpuctx->ctx, pmu, false)
2926 		perf_pmu_enable(epc->pmu);
2927 
2928 	if (task_ctx) {
2929 		for_each_epc(epc, task_ctx, pmu, false)
2930 			perf_pmu_enable(epc->pmu);
2931 	}
2932 }
2933 
perf_pmu_resched(struct pmu * pmu)2934 void perf_pmu_resched(struct pmu *pmu)
2935 {
2936 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2937 	struct perf_event_context *task_ctx = cpuctx->task_ctx;
2938 
2939 	perf_ctx_lock(cpuctx, task_ctx);
2940 	ctx_resched(cpuctx, task_ctx, pmu, EVENT_ALL|EVENT_CPU);
2941 	perf_ctx_unlock(cpuctx, task_ctx);
2942 }
2943 
2944 /*
2945  * Cross CPU call to install and enable a performance event
2946  *
2947  * Very similar to remote_function() + event_function() but cannot assume that
2948  * things like ctx->is_active and cpuctx->task_ctx are set.
2949  */
__perf_install_in_context(void * info)2950 static int  __perf_install_in_context(void *info)
2951 {
2952 	struct perf_event *event = info;
2953 	struct perf_event_context *ctx = event->ctx;
2954 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2955 	struct perf_event_context *task_ctx = cpuctx->task_ctx;
2956 	bool reprogram = true;
2957 	int ret = 0;
2958 
2959 	raw_spin_lock(&cpuctx->ctx.lock);
2960 	if (ctx->task) {
2961 		raw_spin_lock(&ctx->lock);
2962 		task_ctx = ctx;
2963 
2964 		reprogram = (ctx->task == current);
2965 
2966 		/*
2967 		 * If the task is running, it must be running on this CPU,
2968 		 * otherwise we cannot reprogram things.
2969 		 *
2970 		 * If its not running, we don't care, ctx->lock will
2971 		 * serialize against it becoming runnable.
2972 		 */
2973 		if (task_curr(ctx->task) && !reprogram) {
2974 			ret = -ESRCH;
2975 			goto unlock;
2976 		}
2977 
2978 		WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2979 	} else if (task_ctx) {
2980 		raw_spin_lock(&task_ctx->lock);
2981 	}
2982 
2983 #ifdef CONFIG_CGROUP_PERF
2984 	if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
2985 		/*
2986 		 * If the current cgroup doesn't match the event's
2987 		 * cgroup, we should not try to schedule it.
2988 		 */
2989 		struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2990 		reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2991 					event->cgrp->css.cgroup);
2992 	}
2993 #endif
2994 
2995 	if (reprogram) {
2996 		ctx_time_freeze(cpuctx, ctx);
2997 		add_event_to_ctx(event, ctx);
2998 		ctx_resched(cpuctx, task_ctx, event->pmu_ctx->pmu,
2999 			    get_event_type(event));
3000 	} else {
3001 		add_event_to_ctx(event, ctx);
3002 	}
3003 
3004 unlock:
3005 	perf_ctx_unlock(cpuctx, task_ctx);
3006 
3007 	return ret;
3008 }
3009 
3010 static bool exclusive_event_installable(struct perf_event *event,
3011 					struct perf_event_context *ctx);
3012 
3013 /*
3014  * Attach a performance event to a context.
3015  *
3016  * Very similar to event_function_call, see comment there.
3017  */
3018 static void
perf_install_in_context(struct perf_event_context * ctx,struct perf_event * event,int cpu)3019 perf_install_in_context(struct perf_event_context *ctx,
3020 			struct perf_event *event,
3021 			int cpu)
3022 {
3023 	struct task_struct *task = READ_ONCE(ctx->task);
3024 
3025 	lockdep_assert_held(&ctx->mutex);
3026 
3027 	WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
3028 
3029 	if (event->cpu != -1)
3030 		WARN_ON_ONCE(event->cpu != cpu);
3031 
3032 	/*
3033 	 * Ensures that if we can observe event->ctx, both the event and ctx
3034 	 * will be 'complete'. See perf_iterate_sb_cpu().
3035 	 */
3036 	smp_store_release(&event->ctx, ctx);
3037 
3038 	/*
3039 	 * perf_event_attr::disabled events will not run and can be initialized
3040 	 * without IPI. Except when this is the first event for the context, in
3041 	 * that case we need the magic of the IPI to set ctx->is_active.
3042 	 *
3043 	 * The IOC_ENABLE that is sure to follow the creation of a disabled
3044 	 * event will issue the IPI and reprogram the hardware.
3045 	 */
3046 	if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF &&
3047 	    ctx->nr_events && !is_cgroup_event(event)) {
3048 		raw_spin_lock_irq(&ctx->lock);
3049 		if (ctx->task == TASK_TOMBSTONE) {
3050 			raw_spin_unlock_irq(&ctx->lock);
3051 			return;
3052 		}
3053 		add_event_to_ctx(event, ctx);
3054 		raw_spin_unlock_irq(&ctx->lock);
3055 		return;
3056 	}
3057 
3058 	if (!task) {
3059 		cpu_function_call(cpu, __perf_install_in_context, event);
3060 		return;
3061 	}
3062 
3063 	/*
3064 	 * Should not happen, we validate the ctx is still alive before calling.
3065 	 */
3066 	if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
3067 		return;
3068 
3069 	/*
3070 	 * Installing events is tricky because we cannot rely on ctx->is_active
3071 	 * to be set in case this is the nr_events 0 -> 1 transition.
3072 	 *
3073 	 * Instead we use task_curr(), which tells us if the task is running.
3074 	 * However, since we use task_curr() outside of rq::lock, we can race
3075 	 * against the actual state. This means the result can be wrong.
3076 	 *
3077 	 * If we get a false positive, we retry, this is harmless.
3078 	 *
3079 	 * If we get a false negative, things are complicated. If we are after
3080 	 * perf_event_context_sched_in() ctx::lock will serialize us, and the
3081 	 * value must be correct. If we're before, it doesn't matter since
3082 	 * perf_event_context_sched_in() will program the counter.
3083 	 *
3084 	 * However, this hinges on the remote context switch having observed
3085 	 * our task->perf_event_ctxp[] store, such that it will in fact take
3086 	 * ctx::lock in perf_event_context_sched_in().
3087 	 *
3088 	 * We do this by task_function_call(), if the IPI fails to hit the task
3089 	 * we know any future context switch of task must see the
3090 	 * perf_event_ctpx[] store.
3091 	 */
3092 
3093 	/*
3094 	 * This smp_mb() orders the task->perf_event_ctxp[] store with the
3095 	 * task_cpu() load, such that if the IPI then does not find the task
3096 	 * running, a future context switch of that task must observe the
3097 	 * store.
3098 	 */
3099 	smp_mb();
3100 again:
3101 	if (!task_function_call(task, __perf_install_in_context, event))
3102 		return;
3103 
3104 	raw_spin_lock_irq(&ctx->lock);
3105 	task = ctx->task;
3106 	if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
3107 		/*
3108 		 * Cannot happen because we already checked above (which also
3109 		 * cannot happen), and we hold ctx->mutex, which serializes us
3110 		 * against perf_event_exit_task_context().
3111 		 */
3112 		raw_spin_unlock_irq(&ctx->lock);
3113 		return;
3114 	}
3115 	/*
3116 	 * If the task is not running, ctx->lock will avoid it becoming so,
3117 	 * thus we can safely install the event.
3118 	 */
3119 	if (task_curr(task)) {
3120 		raw_spin_unlock_irq(&ctx->lock);
3121 		goto again;
3122 	}
3123 	add_event_to_ctx(event, ctx);
3124 	raw_spin_unlock_irq(&ctx->lock);
3125 }
3126 
3127 /*
3128  * Cross CPU call to enable a performance event
3129  */
__perf_event_enable(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)3130 static void __perf_event_enable(struct perf_event *event,
3131 				struct perf_cpu_context *cpuctx,
3132 				struct perf_event_context *ctx,
3133 				void *info)
3134 {
3135 	struct perf_event *leader = event->group_leader;
3136 	struct perf_event_context *task_ctx;
3137 
3138 	if (event->state >= PERF_EVENT_STATE_INACTIVE ||
3139 	    event->state <= PERF_EVENT_STATE_ERROR)
3140 		return;
3141 
3142 	ctx_time_freeze(cpuctx, ctx);
3143 
3144 	perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
3145 	perf_cgroup_event_enable(event, ctx);
3146 
3147 	if (!ctx->is_active)
3148 		return;
3149 
3150 	if (!event_filter_match(event))
3151 		return;
3152 
3153 	/*
3154 	 * If the event is in a group and isn't the group leader,
3155 	 * then don't put it on unless the group is on.
3156 	 */
3157 	if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
3158 		return;
3159 
3160 	task_ctx = cpuctx->task_ctx;
3161 	if (ctx->task)
3162 		WARN_ON_ONCE(task_ctx != ctx);
3163 
3164 	ctx_resched(cpuctx, task_ctx, event->pmu_ctx->pmu, get_event_type(event));
3165 }
3166 
3167 /*
3168  * Enable an event.
3169  *
3170  * If event->ctx is a cloned context, callers must make sure that
3171  * every task struct that event->ctx->task could possibly point to
3172  * remains valid.  This condition is satisfied when called through
3173  * perf_event_for_each_child or perf_event_for_each as described
3174  * for perf_event_disable.
3175  */
_perf_event_enable(struct perf_event * event)3176 static void _perf_event_enable(struct perf_event *event)
3177 {
3178 	struct perf_event_context *ctx = event->ctx;
3179 
3180 	raw_spin_lock_irq(&ctx->lock);
3181 	if (event->state >= PERF_EVENT_STATE_INACTIVE ||
3182 	    event->state <  PERF_EVENT_STATE_ERROR) {
3183 out:
3184 		raw_spin_unlock_irq(&ctx->lock);
3185 		return;
3186 	}
3187 
3188 	/*
3189 	 * If the event is in error state, clear that first.
3190 	 *
3191 	 * That way, if we see the event in error state below, we know that it
3192 	 * has gone back into error state, as distinct from the task having
3193 	 * been scheduled away before the cross-call arrived.
3194 	 */
3195 	if (event->state == PERF_EVENT_STATE_ERROR) {
3196 		/*
3197 		 * Detached SIBLING events cannot leave ERROR state.
3198 		 */
3199 		if (event->event_caps & PERF_EV_CAP_SIBLING &&
3200 		    event->group_leader == event)
3201 			goto out;
3202 
3203 		event->state = PERF_EVENT_STATE_OFF;
3204 	}
3205 	raw_spin_unlock_irq(&ctx->lock);
3206 
3207 	event_function_call(event, __perf_event_enable, NULL);
3208 }
3209 
3210 /*
3211  * See perf_event_disable();
3212  */
perf_event_enable(struct perf_event * event)3213 void perf_event_enable(struct perf_event *event)
3214 {
3215 	struct perf_event_context *ctx;
3216 
3217 	ctx = perf_event_ctx_lock(event);
3218 	_perf_event_enable(event);
3219 	perf_event_ctx_unlock(event, ctx);
3220 }
3221 EXPORT_SYMBOL_GPL(perf_event_enable);
3222 
3223 struct stop_event_data {
3224 	struct perf_event	*event;
3225 	unsigned int		restart;
3226 };
3227 
__perf_event_stop(void * info)3228 static int __perf_event_stop(void *info)
3229 {
3230 	struct stop_event_data *sd = info;
3231 	struct perf_event *event = sd->event;
3232 
3233 	/* if it's already INACTIVE, do nothing */
3234 	if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3235 		return 0;
3236 
3237 	/* matches smp_wmb() in event_sched_in() */
3238 	smp_rmb();
3239 
3240 	/*
3241 	 * There is a window with interrupts enabled before we get here,
3242 	 * so we need to check again lest we try to stop another CPU's event.
3243 	 */
3244 	if (READ_ONCE(event->oncpu) != smp_processor_id())
3245 		return -EAGAIN;
3246 
3247 	event->pmu->stop(event, PERF_EF_UPDATE);
3248 
3249 	/*
3250 	 * May race with the actual stop (through perf_pmu_output_stop()),
3251 	 * but it is only used for events with AUX ring buffer, and such
3252 	 * events will refuse to restart because of rb::aux_mmap_count==0,
3253 	 * see comments in perf_aux_output_begin().
3254 	 *
3255 	 * Since this is happening on an event-local CPU, no trace is lost
3256 	 * while restarting.
3257 	 */
3258 	if (sd->restart)
3259 		event->pmu->start(event, 0);
3260 
3261 	return 0;
3262 }
3263 
perf_event_stop(struct perf_event * event,int restart)3264 static int perf_event_stop(struct perf_event *event, int restart)
3265 {
3266 	struct stop_event_data sd = {
3267 		.event		= event,
3268 		.restart	= restart,
3269 	};
3270 	int ret = 0;
3271 
3272 	do {
3273 		if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3274 			return 0;
3275 
3276 		/* matches smp_wmb() in event_sched_in() */
3277 		smp_rmb();
3278 
3279 		/*
3280 		 * We only want to restart ACTIVE events, so if the event goes
3281 		 * inactive here (event->oncpu==-1), there's nothing more to do;
3282 		 * fall through with ret==-ENXIO.
3283 		 */
3284 		ret = cpu_function_call(READ_ONCE(event->oncpu),
3285 					__perf_event_stop, &sd);
3286 	} while (ret == -EAGAIN);
3287 
3288 	return ret;
3289 }
3290 
3291 /*
3292  * In order to contain the amount of racy and tricky in the address filter
3293  * configuration management, it is a two part process:
3294  *
3295  * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3296  *      we update the addresses of corresponding vmas in
3297  *	event::addr_filter_ranges array and bump the event::addr_filters_gen;
3298  * (p2) when an event is scheduled in (pmu::add), it calls
3299  *      perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3300  *      if the generation has changed since the previous call.
3301  *
3302  * If (p1) happens while the event is active, we restart it to force (p2).
3303  *
3304  * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3305  *     pre-existing mappings, called once when new filters arrive via SET_FILTER
3306  *     ioctl;
3307  * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3308  *     registered mapping, called for every new mmap(), with mm::mmap_lock down
3309  *     for reading;
3310  * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3311  *     of exec.
3312  */
perf_event_addr_filters_sync(struct perf_event * event)3313 void perf_event_addr_filters_sync(struct perf_event *event)
3314 {
3315 	struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3316 
3317 	if (!has_addr_filter(event))
3318 		return;
3319 
3320 	raw_spin_lock(&ifh->lock);
3321 	if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3322 		event->pmu->addr_filters_sync(event);
3323 		event->hw.addr_filters_gen = event->addr_filters_gen;
3324 	}
3325 	raw_spin_unlock(&ifh->lock);
3326 }
3327 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3328 
_perf_event_refresh(struct perf_event * event,int refresh)3329 static int _perf_event_refresh(struct perf_event *event, int refresh)
3330 {
3331 	/*
3332 	 * not supported on inherited events
3333 	 */
3334 	if (event->attr.inherit || !is_sampling_event(event))
3335 		return -EINVAL;
3336 
3337 	atomic_add(refresh, &event->event_limit);
3338 	_perf_event_enable(event);
3339 
3340 	return 0;
3341 }
3342 
3343 /*
3344  * See perf_event_disable()
3345  */
perf_event_refresh(struct perf_event * event,int refresh)3346 int perf_event_refresh(struct perf_event *event, int refresh)
3347 {
3348 	struct perf_event_context *ctx;
3349 	int ret;
3350 
3351 	ctx = perf_event_ctx_lock(event);
3352 	ret = _perf_event_refresh(event, refresh);
3353 	perf_event_ctx_unlock(event, ctx);
3354 
3355 	return ret;
3356 }
3357 EXPORT_SYMBOL_GPL(perf_event_refresh);
3358 
perf_event_modify_breakpoint(struct perf_event * bp,struct perf_event_attr * attr)3359 static int perf_event_modify_breakpoint(struct perf_event *bp,
3360 					 struct perf_event_attr *attr)
3361 {
3362 	int err;
3363 
3364 	_perf_event_disable(bp);
3365 
3366 	err = modify_user_hw_breakpoint_check(bp, attr, true);
3367 
3368 	if (!bp->attr.disabled)
3369 		_perf_event_enable(bp);
3370 
3371 	return err;
3372 }
3373 
3374 /*
3375  * Copy event-type-independent attributes that may be modified.
3376  */
perf_event_modify_copy_attr(struct perf_event_attr * to,const struct perf_event_attr * from)3377 static void perf_event_modify_copy_attr(struct perf_event_attr *to,
3378 					const struct perf_event_attr *from)
3379 {
3380 	to->sig_data = from->sig_data;
3381 }
3382 
perf_event_modify_attr(struct perf_event * event,struct perf_event_attr * attr)3383 static int perf_event_modify_attr(struct perf_event *event,
3384 				  struct perf_event_attr *attr)
3385 {
3386 	int (*func)(struct perf_event *, struct perf_event_attr *);
3387 	struct perf_event *child;
3388 	int err;
3389 
3390 	if (event->attr.type != attr->type)
3391 		return -EINVAL;
3392 
3393 	switch (event->attr.type) {
3394 	case PERF_TYPE_BREAKPOINT:
3395 		func = perf_event_modify_breakpoint;
3396 		break;
3397 	default:
3398 		/* Place holder for future additions. */
3399 		return -EOPNOTSUPP;
3400 	}
3401 
3402 	WARN_ON_ONCE(event->ctx->parent_ctx);
3403 
3404 	mutex_lock(&event->child_mutex);
3405 	/*
3406 	 * Event-type-independent attributes must be copied before event-type
3407 	 * modification, which will validate that final attributes match the
3408 	 * source attributes after all relevant attributes have been copied.
3409 	 */
3410 	perf_event_modify_copy_attr(&event->attr, attr);
3411 	err = func(event, attr);
3412 	if (err)
3413 		goto out;
3414 	list_for_each_entry(child, &event->child_list, child_list) {
3415 		perf_event_modify_copy_attr(&child->attr, attr);
3416 		err = func(child, attr);
3417 		if (err)
3418 			goto out;
3419 	}
3420 out:
3421 	mutex_unlock(&event->child_mutex);
3422 	return err;
3423 }
3424 
__pmu_ctx_sched_out(struct perf_event_pmu_context * pmu_ctx,enum event_type_t event_type)3425 static void __pmu_ctx_sched_out(struct perf_event_pmu_context *pmu_ctx,
3426 				enum event_type_t event_type)
3427 {
3428 	struct perf_event_context *ctx = pmu_ctx->ctx;
3429 	struct perf_event *event, *tmp;
3430 	struct pmu *pmu = pmu_ctx->pmu;
3431 
3432 	if (ctx->task && !(ctx->is_active & EVENT_ALL)) {
3433 		struct perf_cpu_pmu_context *cpc = this_cpc(pmu);
3434 
3435 		WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
3436 		cpc->task_epc = NULL;
3437 	}
3438 
3439 	if (!(event_type & EVENT_ALL))
3440 		return;
3441 
3442 	perf_pmu_disable(pmu);
3443 	if (event_type & EVENT_PINNED) {
3444 		list_for_each_entry_safe(event, tmp,
3445 					 &pmu_ctx->pinned_active,
3446 					 active_list)
3447 			group_sched_out(event, ctx);
3448 	}
3449 
3450 	if (event_type & EVENT_FLEXIBLE) {
3451 		list_for_each_entry_safe(event, tmp,
3452 					 &pmu_ctx->flexible_active,
3453 					 active_list)
3454 			group_sched_out(event, ctx);
3455 		/*
3456 		 * Since we cleared EVENT_FLEXIBLE, also clear
3457 		 * rotate_necessary, is will be reset by
3458 		 * ctx_flexible_sched_in() when needed.
3459 		 */
3460 		pmu_ctx->rotate_necessary = 0;
3461 	}
3462 	perf_pmu_enable(pmu);
3463 }
3464 
3465 /*
3466  * Be very careful with the @pmu argument since this will change ctx state.
3467  * The @pmu argument works for ctx_resched(), because that is symmetric in
3468  * ctx_sched_out() / ctx_sched_in() usage and the ctx state ends up invariant.
3469  *
3470  * However, if you were to be asymmetrical, you could end up with messed up
3471  * state, eg. ctx->is_active cleared even though most EPCs would still actually
3472  * be active.
3473  */
3474 static void
ctx_sched_out(struct perf_event_context * ctx,struct pmu * pmu,enum event_type_t event_type)3475 ctx_sched_out(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type)
3476 {
3477 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3478 	struct perf_event_pmu_context *pmu_ctx;
3479 	int is_active = ctx->is_active;
3480 	bool cgroup = event_type & EVENT_CGROUP;
3481 
3482 	event_type &= ~EVENT_CGROUP;
3483 
3484 	lockdep_assert_held(&ctx->lock);
3485 
3486 	if (likely(!ctx->nr_events)) {
3487 		/*
3488 		 * See __perf_remove_from_context().
3489 		 */
3490 		WARN_ON_ONCE(ctx->is_active);
3491 		if (ctx->task)
3492 			WARN_ON_ONCE(cpuctx->task_ctx);
3493 		return;
3494 	}
3495 
3496 	/*
3497 	 * Always update time if it was set; not only when it changes.
3498 	 * Otherwise we can 'forget' to update time for any but the last
3499 	 * context we sched out. For example:
3500 	 *
3501 	 *   ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3502 	 *   ctx_sched_out(.event_type = EVENT_PINNED)
3503 	 *
3504 	 * would only update time for the pinned events.
3505 	 */
3506 	__ctx_time_update(cpuctx, ctx, ctx == &cpuctx->ctx);
3507 
3508 	/*
3509 	 * CPU-release for the below ->is_active store,
3510 	 * see __load_acquire() in perf_event_time_now()
3511 	 */
3512 	barrier();
3513 	ctx->is_active &= ~event_type;
3514 
3515 	if (!(ctx->is_active & EVENT_ALL)) {
3516 		/*
3517 		 * For FROZEN, preserve TIME|FROZEN such that perf_event_time_now()
3518 		 * does not observe a hole. perf_ctx_unlock() will clean up.
3519 		 */
3520 		if (ctx->is_active & EVENT_FROZEN)
3521 			ctx->is_active &= EVENT_TIME_FROZEN;
3522 		else
3523 			ctx->is_active = 0;
3524 	}
3525 
3526 	if (ctx->task) {
3527 		WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3528 		if (!(ctx->is_active & EVENT_ALL))
3529 			cpuctx->task_ctx = NULL;
3530 	}
3531 
3532 	is_active ^= ctx->is_active; /* changed bits */
3533 
3534 	for_each_epc(pmu_ctx, ctx, pmu, cgroup)
3535 		__pmu_ctx_sched_out(pmu_ctx, is_active);
3536 }
3537 
3538 /*
3539  * Test whether two contexts are equivalent, i.e. whether they have both been
3540  * cloned from the same version of the same context.
3541  *
3542  * Equivalence is measured using a generation number in the context that is
3543  * incremented on each modification to it; see unclone_ctx(), list_add_event()
3544  * and list_del_event().
3545  */
context_equiv(struct perf_event_context * ctx1,struct perf_event_context * ctx2)3546 static int context_equiv(struct perf_event_context *ctx1,
3547 			 struct perf_event_context *ctx2)
3548 {
3549 	lockdep_assert_held(&ctx1->lock);
3550 	lockdep_assert_held(&ctx2->lock);
3551 
3552 	/* Pinning disables the swap optimization */
3553 	if (ctx1->pin_count || ctx2->pin_count)
3554 		return 0;
3555 
3556 	/* If ctx1 is the parent of ctx2 */
3557 	if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3558 		return 1;
3559 
3560 	/* If ctx2 is the parent of ctx1 */
3561 	if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3562 		return 1;
3563 
3564 	/*
3565 	 * If ctx1 and ctx2 have the same parent; we flatten the parent
3566 	 * hierarchy, see perf_event_init_context().
3567 	 */
3568 	if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3569 			ctx1->parent_gen == ctx2->parent_gen)
3570 		return 1;
3571 
3572 	/* Unmatched */
3573 	return 0;
3574 }
3575 
__perf_event_sync_stat(struct perf_event * event,struct perf_event * next_event)3576 static void __perf_event_sync_stat(struct perf_event *event,
3577 				     struct perf_event *next_event)
3578 {
3579 	u64 value;
3580 
3581 	if (!event->attr.inherit_stat)
3582 		return;
3583 
3584 	/*
3585 	 * Update the event value, we cannot use perf_event_read()
3586 	 * because we're in the middle of a context switch and have IRQs
3587 	 * disabled, which upsets smp_call_function_single(), however
3588 	 * we know the event must be on the current CPU, therefore we
3589 	 * don't need to use it.
3590 	 */
3591 	perf_pmu_read(event);
3592 
3593 	perf_event_update_time(event);
3594 
3595 	/*
3596 	 * In order to keep per-task stats reliable we need to flip the event
3597 	 * values when we flip the contexts.
3598 	 */
3599 	value = local64_read(&next_event->count);
3600 	value = local64_xchg(&event->count, value);
3601 	local64_set(&next_event->count, value);
3602 
3603 	swap(event->total_time_enabled, next_event->total_time_enabled);
3604 	swap(event->total_time_running, next_event->total_time_running);
3605 
3606 	/*
3607 	 * Since we swizzled the values, update the user visible data too.
3608 	 */
3609 	perf_event_update_userpage(event);
3610 	perf_event_update_userpage(next_event);
3611 }
3612 
perf_event_sync_stat(struct perf_event_context * ctx,struct perf_event_context * next_ctx)3613 static void perf_event_sync_stat(struct perf_event_context *ctx,
3614 				   struct perf_event_context *next_ctx)
3615 {
3616 	struct perf_event *event, *next_event;
3617 
3618 	if (!ctx->nr_stat)
3619 		return;
3620 
3621 	update_context_time(ctx);
3622 
3623 	event = list_first_entry(&ctx->event_list,
3624 				   struct perf_event, event_entry);
3625 
3626 	next_event = list_first_entry(&next_ctx->event_list,
3627 					struct perf_event, event_entry);
3628 
3629 	while (&event->event_entry != &ctx->event_list &&
3630 	       &next_event->event_entry != &next_ctx->event_list) {
3631 
3632 		__perf_event_sync_stat(event, next_event);
3633 
3634 		event = list_next_entry(event, event_entry);
3635 		next_event = list_next_entry(next_event, event_entry);
3636 	}
3637 }
3638 
perf_ctx_sched_task_cb(struct perf_event_context * ctx,struct task_struct * task,bool sched_in)3639 static void perf_ctx_sched_task_cb(struct perf_event_context *ctx,
3640 				   struct task_struct *task, bool sched_in)
3641 {
3642 	struct perf_event_pmu_context *pmu_ctx;
3643 	struct perf_cpu_pmu_context *cpc;
3644 
3645 	list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
3646 		cpc = this_cpc(pmu_ctx->pmu);
3647 
3648 		if (cpc->sched_cb_usage && pmu_ctx->pmu->sched_task)
3649 			pmu_ctx->pmu->sched_task(pmu_ctx, task, sched_in);
3650 	}
3651 }
3652 
3653 static void
perf_event_context_sched_out(struct task_struct * task,struct task_struct * next)3654 perf_event_context_sched_out(struct task_struct *task, struct task_struct *next)
3655 {
3656 	struct perf_event_context *ctx = task->perf_event_ctxp;
3657 	struct perf_event_context *next_ctx;
3658 	struct perf_event_context *parent, *next_parent;
3659 	int do_switch = 1;
3660 
3661 	if (likely(!ctx))
3662 		return;
3663 
3664 	rcu_read_lock();
3665 	next_ctx = rcu_dereference(next->perf_event_ctxp);
3666 	if (!next_ctx)
3667 		goto unlock;
3668 
3669 	parent = rcu_dereference(ctx->parent_ctx);
3670 	next_parent = rcu_dereference(next_ctx->parent_ctx);
3671 
3672 	/* If neither context have a parent context; they cannot be clones. */
3673 	if (!parent && !next_parent)
3674 		goto unlock;
3675 
3676 	if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3677 		/*
3678 		 * Looks like the two contexts are clones, so we might be
3679 		 * able to optimize the context switch.  We lock both
3680 		 * contexts and check that they are clones under the
3681 		 * lock (including re-checking that neither has been
3682 		 * uncloned in the meantime).  It doesn't matter which
3683 		 * order we take the locks because no other cpu could
3684 		 * be trying to lock both of these tasks.
3685 		 */
3686 		raw_spin_lock(&ctx->lock);
3687 		raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3688 		if (context_equiv(ctx, next_ctx)) {
3689 
3690 			perf_ctx_disable(ctx, false);
3691 
3692 			/* PMIs are disabled; ctx->nr_no_switch_fast is stable. */
3693 			if (local_read(&ctx->nr_no_switch_fast) ||
3694 			    local_read(&next_ctx->nr_no_switch_fast)) {
3695 				/*
3696 				 * Must not swap out ctx when there's pending
3697 				 * events that rely on the ctx->task relation.
3698 				 *
3699 				 * Likewise, when a context contains inherit +
3700 				 * SAMPLE_READ events they should be switched
3701 				 * out using the slow path so that they are
3702 				 * treated as if they were distinct contexts.
3703 				 */
3704 				raw_spin_unlock(&next_ctx->lock);
3705 				rcu_read_unlock();
3706 				goto inside_switch;
3707 			}
3708 
3709 			WRITE_ONCE(ctx->task, next);
3710 			WRITE_ONCE(next_ctx->task, task);
3711 
3712 			perf_ctx_sched_task_cb(ctx, task, false);
3713 
3714 			perf_ctx_enable(ctx, false);
3715 
3716 			/*
3717 			 * RCU_INIT_POINTER here is safe because we've not
3718 			 * modified the ctx and the above modification of
3719 			 * ctx->task is immaterial since this value is
3720 			 * always verified under ctx->lock which we're now
3721 			 * holding.
3722 			 */
3723 			RCU_INIT_POINTER(task->perf_event_ctxp, next_ctx);
3724 			RCU_INIT_POINTER(next->perf_event_ctxp, ctx);
3725 
3726 			do_switch = 0;
3727 
3728 			perf_event_sync_stat(ctx, next_ctx);
3729 		}
3730 		raw_spin_unlock(&next_ctx->lock);
3731 		raw_spin_unlock(&ctx->lock);
3732 	}
3733 unlock:
3734 	rcu_read_unlock();
3735 
3736 	if (do_switch) {
3737 		raw_spin_lock(&ctx->lock);
3738 		perf_ctx_disable(ctx, false);
3739 
3740 inside_switch:
3741 		perf_ctx_sched_task_cb(ctx, task, false);
3742 		task_ctx_sched_out(ctx, NULL, EVENT_ALL);
3743 
3744 		perf_ctx_enable(ctx, false);
3745 		raw_spin_unlock(&ctx->lock);
3746 	}
3747 }
3748 
3749 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3750 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
3751 
perf_sched_cb_dec(struct pmu * pmu)3752 void perf_sched_cb_dec(struct pmu *pmu)
3753 {
3754 	struct perf_cpu_pmu_context *cpc = this_cpc(pmu);
3755 
3756 	this_cpu_dec(perf_sched_cb_usages);
3757 	barrier();
3758 
3759 	if (!--cpc->sched_cb_usage)
3760 		list_del(&cpc->sched_cb_entry);
3761 }
3762 
3763 
perf_sched_cb_inc(struct pmu * pmu)3764 void perf_sched_cb_inc(struct pmu *pmu)
3765 {
3766 	struct perf_cpu_pmu_context *cpc = this_cpc(pmu);
3767 
3768 	if (!cpc->sched_cb_usage++)
3769 		list_add(&cpc->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3770 
3771 	barrier();
3772 	this_cpu_inc(perf_sched_cb_usages);
3773 }
3774 
3775 /*
3776  * This function provides the context switch callback to the lower code
3777  * layer. It is invoked ONLY when the context switch callback is enabled.
3778  *
3779  * This callback is relevant even to per-cpu events; for example multi event
3780  * PEBS requires this to provide PID/TID information. This requires we flush
3781  * all queued PEBS records before we context switch to a new task.
3782  */
__perf_pmu_sched_task(struct perf_cpu_pmu_context * cpc,struct task_struct * task,bool sched_in)3783 static void __perf_pmu_sched_task(struct perf_cpu_pmu_context *cpc,
3784 				  struct task_struct *task, bool sched_in)
3785 {
3786 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3787 	struct pmu *pmu;
3788 
3789 	pmu = cpc->epc.pmu;
3790 
3791 	/* software PMUs will not have sched_task */
3792 	if (WARN_ON_ONCE(!pmu->sched_task))
3793 		return;
3794 
3795 	perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3796 	perf_pmu_disable(pmu);
3797 
3798 	pmu->sched_task(cpc->task_epc, task, sched_in);
3799 
3800 	perf_pmu_enable(pmu);
3801 	perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3802 }
3803 
perf_pmu_sched_task(struct task_struct * prev,struct task_struct * next,bool sched_in)3804 static void perf_pmu_sched_task(struct task_struct *prev,
3805 				struct task_struct *next,
3806 				bool sched_in)
3807 {
3808 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3809 	struct perf_cpu_pmu_context *cpc;
3810 
3811 	/* cpuctx->task_ctx will be handled in perf_event_context_sched_in/out */
3812 	if (prev == next || cpuctx->task_ctx)
3813 		return;
3814 
3815 	list_for_each_entry(cpc, this_cpu_ptr(&sched_cb_list), sched_cb_entry)
3816 		__perf_pmu_sched_task(cpc, sched_in ? next : prev, sched_in);
3817 }
3818 
3819 static void perf_event_switch(struct task_struct *task,
3820 			      struct task_struct *next_prev, bool sched_in);
3821 
3822 /*
3823  * Called from scheduler to remove the events of the current task,
3824  * with interrupts disabled.
3825  *
3826  * We stop each event and update the event value in event->count.
3827  *
3828  * This does not protect us against NMI, but disable()
3829  * sets the disabled bit in the control field of event _before_
3830  * accessing the event control register. If a NMI hits, then it will
3831  * not restart the event.
3832  */
__perf_event_task_sched_out(struct task_struct * task,struct task_struct * next)3833 void __perf_event_task_sched_out(struct task_struct *task,
3834 				 struct task_struct *next)
3835 {
3836 	if (__this_cpu_read(perf_sched_cb_usages))
3837 		perf_pmu_sched_task(task, next, false);
3838 
3839 	if (atomic_read(&nr_switch_events))
3840 		perf_event_switch(task, next, false);
3841 
3842 	perf_event_context_sched_out(task, next);
3843 
3844 	/*
3845 	 * if cgroup events exist on this CPU, then we need
3846 	 * to check if we have to switch out PMU state.
3847 	 * cgroup event are system-wide mode only
3848 	 */
3849 	perf_cgroup_switch(next);
3850 }
3851 
perf_less_group_idx(const void * l,const void * r,void __always_unused * args)3852 static bool perf_less_group_idx(const void *l, const void *r, void __always_unused *args)
3853 {
3854 	const struct perf_event *le = *(const struct perf_event **)l;
3855 	const struct perf_event *re = *(const struct perf_event **)r;
3856 
3857 	return le->group_index < re->group_index;
3858 }
3859 
3860 DEFINE_MIN_HEAP(struct perf_event *, perf_event_min_heap);
3861 
3862 static const struct min_heap_callbacks perf_min_heap = {
3863 	.less = perf_less_group_idx,
3864 	.swp = NULL,
3865 };
3866 
__heap_add(struct perf_event_min_heap * heap,struct perf_event * event)3867 static void __heap_add(struct perf_event_min_heap *heap, struct perf_event *event)
3868 {
3869 	struct perf_event **itrs = heap->data;
3870 
3871 	if (event) {
3872 		itrs[heap->nr] = event;
3873 		heap->nr++;
3874 	}
3875 }
3876 
__link_epc(struct perf_event_pmu_context * pmu_ctx)3877 static void __link_epc(struct perf_event_pmu_context *pmu_ctx)
3878 {
3879 	struct perf_cpu_pmu_context *cpc;
3880 
3881 	if (!pmu_ctx->ctx->task)
3882 		return;
3883 
3884 	cpc = this_cpc(pmu_ctx->pmu);
3885 	WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
3886 	cpc->task_epc = pmu_ctx;
3887 }
3888 
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)3889 static noinline int visit_groups_merge(struct perf_event_context *ctx,
3890 				struct perf_event_groups *groups, int cpu,
3891 				struct pmu *pmu,
3892 				int (*func)(struct perf_event *, void *),
3893 				void *data)
3894 {
3895 #ifdef CONFIG_CGROUP_PERF
3896 	struct cgroup_subsys_state *css = NULL;
3897 #endif
3898 	struct perf_cpu_context *cpuctx = NULL;
3899 	/* Space for per CPU and/or any CPU event iterators. */
3900 	struct perf_event *itrs[2];
3901 	struct perf_event_min_heap event_heap;
3902 	struct perf_event **evt;
3903 	int ret;
3904 
3905 	if (pmu->filter && pmu->filter(pmu, cpu))
3906 		return 0;
3907 
3908 	if (!ctx->task) {
3909 		cpuctx = this_cpu_ptr(&perf_cpu_context);
3910 		event_heap = (struct perf_event_min_heap){
3911 			.data = cpuctx->heap,
3912 			.nr = 0,
3913 			.size = cpuctx->heap_size,
3914 		};
3915 
3916 		lockdep_assert_held(&cpuctx->ctx.lock);
3917 
3918 #ifdef CONFIG_CGROUP_PERF
3919 		if (cpuctx->cgrp)
3920 			css = &cpuctx->cgrp->css;
3921 #endif
3922 	} else {
3923 		event_heap = (struct perf_event_min_heap){
3924 			.data = itrs,
3925 			.nr = 0,
3926 			.size = ARRAY_SIZE(itrs),
3927 		};
3928 		/* Events not within a CPU context may be on any CPU. */
3929 		__heap_add(&event_heap, perf_event_groups_first(groups, -1, pmu, NULL));
3930 	}
3931 	evt = event_heap.data;
3932 
3933 	__heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, NULL));
3934 
3935 #ifdef CONFIG_CGROUP_PERF
3936 	for (; css; css = css->parent)
3937 		__heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, css->cgroup));
3938 #endif
3939 
3940 	if (event_heap.nr) {
3941 		__link_epc((*evt)->pmu_ctx);
3942 		perf_assert_pmu_disabled((*evt)->pmu_ctx->pmu);
3943 	}
3944 
3945 	min_heapify_all_inline(&event_heap, &perf_min_heap, NULL);
3946 
3947 	while (event_heap.nr) {
3948 		ret = func(*evt, data);
3949 		if (ret)
3950 			return ret;
3951 
3952 		*evt = perf_event_groups_next(*evt, pmu);
3953 		if (*evt)
3954 			min_heap_sift_down_inline(&event_heap, 0, &perf_min_heap, NULL);
3955 		else
3956 			min_heap_pop_inline(&event_heap, &perf_min_heap, NULL);
3957 	}
3958 
3959 	return 0;
3960 }
3961 
3962 /*
3963  * Because the userpage is strictly per-event (there is no concept of context,
3964  * so there cannot be a context indirection), every userpage must be updated
3965  * when context time starts :-(
3966  *
3967  * IOW, we must not miss EVENT_TIME edges.
3968  */
event_update_userpage(struct perf_event * event)3969 static inline bool event_update_userpage(struct perf_event *event)
3970 {
3971 	if (likely(!atomic_read(&event->mmap_count)))
3972 		return false;
3973 
3974 	perf_event_update_time(event);
3975 	perf_event_update_userpage(event);
3976 
3977 	return true;
3978 }
3979 
group_update_userpage(struct perf_event * group_event)3980 static inline void group_update_userpage(struct perf_event *group_event)
3981 {
3982 	struct perf_event *event;
3983 
3984 	if (!event_update_userpage(group_event))
3985 		return;
3986 
3987 	for_each_sibling_event(event, group_event)
3988 		event_update_userpage(event);
3989 }
3990 
merge_sched_in(struct perf_event * event,void * data)3991 static int merge_sched_in(struct perf_event *event, void *data)
3992 {
3993 	struct perf_event_context *ctx = event->ctx;
3994 	int *can_add_hw = data;
3995 
3996 	if (event->state <= PERF_EVENT_STATE_OFF)
3997 		return 0;
3998 
3999 	if (!event_filter_match(event))
4000 		return 0;
4001 
4002 	if (group_can_go_on(event, *can_add_hw)) {
4003 		if (!group_sched_in(event, ctx))
4004 			list_add_tail(&event->active_list, get_event_list(event));
4005 	}
4006 
4007 	if (event->state == PERF_EVENT_STATE_INACTIVE) {
4008 		*can_add_hw = 0;
4009 		if (event->attr.pinned) {
4010 			perf_cgroup_event_disable(event, ctx);
4011 			perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
4012 
4013 			if (*perf_event_fasync(event))
4014 				event->pending_kill = POLL_ERR;
4015 
4016 			perf_event_wakeup(event);
4017 		} else {
4018 			struct perf_cpu_pmu_context *cpc = this_cpc(event->pmu_ctx->pmu);
4019 
4020 			event->pmu_ctx->rotate_necessary = 1;
4021 			perf_mux_hrtimer_restart(cpc);
4022 			group_update_userpage(event);
4023 		}
4024 	}
4025 
4026 	return 0;
4027 }
4028 
pmu_groups_sched_in(struct perf_event_context * ctx,struct perf_event_groups * groups,struct pmu * pmu)4029 static void pmu_groups_sched_in(struct perf_event_context *ctx,
4030 				struct perf_event_groups *groups,
4031 				struct pmu *pmu)
4032 {
4033 	int can_add_hw = 1;
4034 	visit_groups_merge(ctx, groups, smp_processor_id(), pmu,
4035 			   merge_sched_in, &can_add_hw);
4036 }
4037 
__pmu_ctx_sched_in(struct perf_event_pmu_context * pmu_ctx,enum event_type_t event_type)4038 static void __pmu_ctx_sched_in(struct perf_event_pmu_context *pmu_ctx,
4039 			       enum event_type_t event_type)
4040 {
4041 	struct perf_event_context *ctx = pmu_ctx->ctx;
4042 
4043 	if (event_type & EVENT_PINNED)
4044 		pmu_groups_sched_in(ctx, &ctx->pinned_groups, pmu_ctx->pmu);
4045 	if (event_type & EVENT_FLEXIBLE)
4046 		pmu_groups_sched_in(ctx, &ctx->flexible_groups, pmu_ctx->pmu);
4047 }
4048 
4049 static void
ctx_sched_in(struct perf_event_context * ctx,struct pmu * pmu,enum event_type_t event_type)4050 ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type)
4051 {
4052 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4053 	struct perf_event_pmu_context *pmu_ctx;
4054 	int is_active = ctx->is_active;
4055 	bool cgroup = event_type & EVENT_CGROUP;
4056 
4057 	event_type &= ~EVENT_CGROUP;
4058 
4059 	lockdep_assert_held(&ctx->lock);
4060 
4061 	if (likely(!ctx->nr_events))
4062 		return;
4063 
4064 	if (!(is_active & EVENT_TIME)) {
4065 		/* start ctx time */
4066 		__update_context_time(ctx, false);
4067 		perf_cgroup_set_timestamp(cpuctx);
4068 		/*
4069 		 * CPU-release for the below ->is_active store,
4070 		 * see __load_acquire() in perf_event_time_now()
4071 		 */
4072 		barrier();
4073 	}
4074 
4075 	ctx->is_active |= (event_type | EVENT_TIME);
4076 	if (ctx->task) {
4077 		if (!(is_active & EVENT_ALL))
4078 			cpuctx->task_ctx = ctx;
4079 		else
4080 			WARN_ON_ONCE(cpuctx->task_ctx != ctx);
4081 	}
4082 
4083 	is_active ^= ctx->is_active; /* changed bits */
4084 
4085 	/*
4086 	 * First go through the list and put on any pinned groups
4087 	 * in order to give them the best chance of going on.
4088 	 */
4089 	if (is_active & EVENT_PINNED) {
4090 		for_each_epc(pmu_ctx, ctx, pmu, cgroup)
4091 			__pmu_ctx_sched_in(pmu_ctx, EVENT_PINNED);
4092 	}
4093 
4094 	/* Then walk through the lower prio flexible groups */
4095 	if (is_active & EVENT_FLEXIBLE) {
4096 		for_each_epc(pmu_ctx, ctx, pmu, cgroup)
4097 			__pmu_ctx_sched_in(pmu_ctx, EVENT_FLEXIBLE);
4098 	}
4099 }
4100 
perf_event_context_sched_in(struct task_struct * task)4101 static void perf_event_context_sched_in(struct task_struct *task)
4102 {
4103 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4104 	struct perf_event_context *ctx;
4105 
4106 	rcu_read_lock();
4107 	ctx = rcu_dereference(task->perf_event_ctxp);
4108 	if (!ctx)
4109 		goto rcu_unlock;
4110 
4111 	if (cpuctx->task_ctx == ctx) {
4112 		perf_ctx_lock(cpuctx, ctx);
4113 		perf_ctx_disable(ctx, false);
4114 
4115 		perf_ctx_sched_task_cb(ctx, task, true);
4116 
4117 		perf_ctx_enable(ctx, false);
4118 		perf_ctx_unlock(cpuctx, ctx);
4119 		goto rcu_unlock;
4120 	}
4121 
4122 	perf_ctx_lock(cpuctx, ctx);
4123 	/*
4124 	 * We must check ctx->nr_events while holding ctx->lock, such
4125 	 * that we serialize against perf_install_in_context().
4126 	 */
4127 	if (!ctx->nr_events)
4128 		goto unlock;
4129 
4130 	perf_ctx_disable(ctx, false);
4131 	/*
4132 	 * We want to keep the following priority order:
4133 	 * cpu pinned (that don't need to move), task pinned,
4134 	 * cpu flexible, task flexible.
4135 	 *
4136 	 * However, if task's ctx is not carrying any pinned
4137 	 * events, no need to flip the cpuctx's events around.
4138 	 */
4139 	if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree)) {
4140 		perf_ctx_disable(&cpuctx->ctx, false);
4141 		ctx_sched_out(&cpuctx->ctx, NULL, EVENT_FLEXIBLE);
4142 	}
4143 
4144 	perf_event_sched_in(cpuctx, ctx, NULL);
4145 
4146 	perf_ctx_sched_task_cb(cpuctx->task_ctx, task, true);
4147 
4148 	if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
4149 		perf_ctx_enable(&cpuctx->ctx, false);
4150 
4151 	perf_ctx_enable(ctx, false);
4152 
4153 unlock:
4154 	perf_ctx_unlock(cpuctx, ctx);
4155 rcu_unlock:
4156 	rcu_read_unlock();
4157 }
4158 
4159 /*
4160  * Called from scheduler to add the events of the current task
4161  * with interrupts disabled.
4162  *
4163  * We restore the event value and then enable it.
4164  *
4165  * This does not protect us against NMI, but enable()
4166  * sets the enabled bit in the control field of event _before_
4167  * accessing the event control register. If a NMI hits, then it will
4168  * keep the event running.
4169  */
__perf_event_task_sched_in(struct task_struct * prev,struct task_struct * task)4170 void __perf_event_task_sched_in(struct task_struct *prev,
4171 				struct task_struct *task)
4172 {
4173 	perf_event_context_sched_in(task);
4174 
4175 	if (atomic_read(&nr_switch_events))
4176 		perf_event_switch(task, prev, true);
4177 
4178 	if (__this_cpu_read(perf_sched_cb_usages))
4179 		perf_pmu_sched_task(prev, task, true);
4180 }
4181 
perf_calculate_period(struct perf_event * event,u64 nsec,u64 count)4182 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
4183 {
4184 	u64 frequency = event->attr.sample_freq;
4185 	u64 sec = NSEC_PER_SEC;
4186 	u64 divisor, dividend;
4187 
4188 	int count_fls, nsec_fls, frequency_fls, sec_fls;
4189 
4190 	count_fls = fls64(count);
4191 	nsec_fls = fls64(nsec);
4192 	frequency_fls = fls64(frequency);
4193 	sec_fls = 30;
4194 
4195 	/*
4196 	 * We got @count in @nsec, with a target of sample_freq HZ
4197 	 * the target period becomes:
4198 	 *
4199 	 *             @count * 10^9
4200 	 * period = -------------------
4201 	 *          @nsec * sample_freq
4202 	 *
4203 	 */
4204 
4205 	/*
4206 	 * Reduce accuracy by one bit such that @a and @b converge
4207 	 * to a similar magnitude.
4208 	 */
4209 #define REDUCE_FLS(a, b)		\
4210 do {					\
4211 	if (a##_fls > b##_fls) {	\
4212 		a >>= 1;		\
4213 		a##_fls--;		\
4214 	} else {			\
4215 		b >>= 1;		\
4216 		b##_fls--;		\
4217 	}				\
4218 } while (0)
4219 
4220 	/*
4221 	 * Reduce accuracy until either term fits in a u64, then proceed with
4222 	 * the other, so that finally we can do a u64/u64 division.
4223 	 */
4224 	while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
4225 		REDUCE_FLS(nsec, frequency);
4226 		REDUCE_FLS(sec, count);
4227 	}
4228 
4229 	if (count_fls + sec_fls > 64) {
4230 		divisor = nsec * frequency;
4231 
4232 		while (count_fls + sec_fls > 64) {
4233 			REDUCE_FLS(count, sec);
4234 			divisor >>= 1;
4235 		}
4236 
4237 		dividend = count * sec;
4238 	} else {
4239 		dividend = count * sec;
4240 
4241 		while (nsec_fls + frequency_fls > 64) {
4242 			REDUCE_FLS(nsec, frequency);
4243 			dividend >>= 1;
4244 		}
4245 
4246 		divisor = nsec * frequency;
4247 	}
4248 
4249 	if (!divisor)
4250 		return dividend;
4251 
4252 	return div64_u64(dividend, divisor);
4253 }
4254 
4255 static DEFINE_PER_CPU(int, perf_throttled_count);
4256 static DEFINE_PER_CPU(u64, perf_throttled_seq);
4257 
perf_adjust_period(struct perf_event * event,u64 nsec,u64 count,bool disable)4258 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
4259 {
4260 	struct hw_perf_event *hwc = &event->hw;
4261 	s64 period, sample_period;
4262 	s64 delta;
4263 
4264 	period = perf_calculate_period(event, nsec, count);
4265 
4266 	delta = (s64)(period - hwc->sample_period);
4267 	if (delta >= 0)
4268 		delta += 7;
4269 	else
4270 		delta -= 7;
4271 	delta /= 8; /* low pass filter */
4272 
4273 	sample_period = hwc->sample_period + delta;
4274 
4275 	if (!sample_period)
4276 		sample_period = 1;
4277 
4278 	hwc->sample_period = sample_period;
4279 
4280 	if (local64_read(&hwc->period_left) > 8*sample_period) {
4281 		if (disable)
4282 			event->pmu->stop(event, PERF_EF_UPDATE);
4283 
4284 		local64_set(&hwc->period_left, 0);
4285 
4286 		if (disable)
4287 			event->pmu->start(event, PERF_EF_RELOAD);
4288 	}
4289 }
4290 
perf_adjust_freq_unthr_events(struct list_head * event_list)4291 static void perf_adjust_freq_unthr_events(struct list_head *event_list)
4292 {
4293 	struct perf_event *event;
4294 	struct hw_perf_event *hwc;
4295 	u64 now, period = TICK_NSEC;
4296 	s64 delta;
4297 
4298 	list_for_each_entry(event, event_list, active_list) {
4299 		if (event->state != PERF_EVENT_STATE_ACTIVE)
4300 			continue;
4301 
4302 		// XXX use visit thingy to avoid the -1,cpu match
4303 		if (!event_filter_match(event))
4304 			continue;
4305 
4306 		hwc = &event->hw;
4307 
4308 		if (hwc->interrupts == MAX_INTERRUPTS)
4309 			perf_event_unthrottle_group(event, is_event_in_freq_mode(event));
4310 
4311 		if (!is_event_in_freq_mode(event))
4312 			continue;
4313 
4314 		/*
4315 		 * stop the event and update event->count
4316 		 */
4317 		event->pmu->stop(event, PERF_EF_UPDATE);
4318 
4319 		now = local64_read(&event->count);
4320 		delta = now - hwc->freq_count_stamp;
4321 		hwc->freq_count_stamp = now;
4322 
4323 		/*
4324 		 * restart the event
4325 		 * reload only if value has changed
4326 		 * we have stopped the event so tell that
4327 		 * to perf_adjust_period() to avoid stopping it
4328 		 * twice.
4329 		 */
4330 		if (delta > 0)
4331 			perf_adjust_period(event, period, delta, false);
4332 
4333 		event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
4334 	}
4335 }
4336 
4337 /*
4338  * combine freq adjustment with unthrottling to avoid two passes over the
4339  * events. At the same time, make sure, having freq events does not change
4340  * the rate of unthrottling as that would introduce bias.
4341  */
4342 static void
perf_adjust_freq_unthr_context(struct perf_event_context * ctx,bool unthrottle)4343 perf_adjust_freq_unthr_context(struct perf_event_context *ctx, bool unthrottle)
4344 {
4345 	struct perf_event_pmu_context *pmu_ctx;
4346 
4347 	/*
4348 	 * only need to iterate over all events iff:
4349 	 * - context have events in frequency mode (needs freq adjust)
4350 	 * - there are events to unthrottle on this cpu
4351 	 */
4352 	if (!(ctx->nr_freq || unthrottle))
4353 		return;
4354 
4355 	raw_spin_lock(&ctx->lock);
4356 
4357 	list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
4358 		if (!(pmu_ctx->nr_freq || unthrottle))
4359 			continue;
4360 		if (!perf_pmu_ctx_is_active(pmu_ctx))
4361 			continue;
4362 		if (pmu_ctx->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT)
4363 			continue;
4364 
4365 		perf_pmu_disable(pmu_ctx->pmu);
4366 		perf_adjust_freq_unthr_events(&pmu_ctx->pinned_active);
4367 		perf_adjust_freq_unthr_events(&pmu_ctx->flexible_active);
4368 		perf_pmu_enable(pmu_ctx->pmu);
4369 	}
4370 
4371 	raw_spin_unlock(&ctx->lock);
4372 }
4373 
4374 /*
4375  * Move @event to the tail of the @ctx's elegible events.
4376  */
rotate_ctx(struct perf_event_context * ctx,struct perf_event * event)4377 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4378 {
4379 	/*
4380 	 * Rotate the first entry last of non-pinned groups. Rotation might be
4381 	 * disabled by the inheritance code.
4382 	 */
4383 	if (ctx->rotate_disable)
4384 		return;
4385 
4386 	perf_event_groups_delete(&ctx->flexible_groups, event);
4387 	perf_event_groups_insert(&ctx->flexible_groups, event);
4388 }
4389 
4390 /* pick an event from the flexible_groups to rotate */
4391 static inline struct perf_event *
ctx_event_to_rotate(struct perf_event_pmu_context * pmu_ctx)4392 ctx_event_to_rotate(struct perf_event_pmu_context *pmu_ctx)
4393 {
4394 	struct perf_event *event;
4395 	struct rb_node *node;
4396 	struct rb_root *tree;
4397 	struct __group_key key = {
4398 		.pmu = pmu_ctx->pmu,
4399 	};
4400 
4401 	/* pick the first active flexible event */
4402 	event = list_first_entry_or_null(&pmu_ctx->flexible_active,
4403 					 struct perf_event, active_list);
4404 	if (event)
4405 		goto out;
4406 
4407 	/* if no active flexible event, pick the first event */
4408 	tree = &pmu_ctx->ctx->flexible_groups.tree;
4409 
4410 	if (!pmu_ctx->ctx->task) {
4411 		key.cpu = smp_processor_id();
4412 
4413 		node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4414 		if (node)
4415 			event = __node_2_pe(node);
4416 		goto out;
4417 	}
4418 
4419 	key.cpu = -1;
4420 	node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4421 	if (node) {
4422 		event = __node_2_pe(node);
4423 		goto out;
4424 	}
4425 
4426 	key.cpu = smp_processor_id();
4427 	node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4428 	if (node)
4429 		event = __node_2_pe(node);
4430 
4431 out:
4432 	/*
4433 	 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4434 	 * finds there are unschedulable events, it will set it again.
4435 	 */
4436 	pmu_ctx->rotate_necessary = 0;
4437 
4438 	return event;
4439 }
4440 
perf_rotate_context(struct perf_cpu_pmu_context * cpc)4441 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc)
4442 {
4443 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4444 	struct perf_event_pmu_context *cpu_epc, *task_epc = NULL;
4445 	struct perf_event *cpu_event = NULL, *task_event = NULL;
4446 	int cpu_rotate, task_rotate;
4447 	struct pmu *pmu;
4448 
4449 	/*
4450 	 * Since we run this from IRQ context, nobody can install new
4451 	 * events, thus the event count values are stable.
4452 	 */
4453 
4454 	cpu_epc = &cpc->epc;
4455 	pmu = cpu_epc->pmu;
4456 	task_epc = cpc->task_epc;
4457 
4458 	cpu_rotate = cpu_epc->rotate_necessary;
4459 	task_rotate = task_epc ? task_epc->rotate_necessary : 0;
4460 
4461 	if (!(cpu_rotate || task_rotate))
4462 		return false;
4463 
4464 	perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4465 	perf_pmu_disable(pmu);
4466 
4467 	if (task_rotate)
4468 		task_event = ctx_event_to_rotate(task_epc);
4469 	if (cpu_rotate)
4470 		cpu_event = ctx_event_to_rotate(cpu_epc);
4471 
4472 	/*
4473 	 * As per the order given at ctx_resched() first 'pop' task flexible
4474 	 * and then, if needed CPU flexible.
4475 	 */
4476 	if (task_event || (task_epc && cpu_event)) {
4477 		update_context_time(task_epc->ctx);
4478 		__pmu_ctx_sched_out(task_epc, EVENT_FLEXIBLE);
4479 	}
4480 
4481 	if (cpu_event) {
4482 		update_context_time(&cpuctx->ctx);
4483 		__pmu_ctx_sched_out(cpu_epc, EVENT_FLEXIBLE);
4484 		rotate_ctx(&cpuctx->ctx, cpu_event);
4485 		__pmu_ctx_sched_in(cpu_epc, EVENT_FLEXIBLE);
4486 	}
4487 
4488 	if (task_event)
4489 		rotate_ctx(task_epc->ctx, task_event);
4490 
4491 	if (task_event || (task_epc && cpu_event))
4492 		__pmu_ctx_sched_in(task_epc, EVENT_FLEXIBLE);
4493 
4494 	perf_pmu_enable(pmu);
4495 	perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4496 
4497 	return true;
4498 }
4499 
perf_event_task_tick(void)4500 void perf_event_task_tick(void)
4501 {
4502 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4503 	struct perf_event_context *ctx;
4504 	int throttled;
4505 
4506 	lockdep_assert_irqs_disabled();
4507 
4508 	__this_cpu_inc(perf_throttled_seq);
4509 	throttled = __this_cpu_xchg(perf_throttled_count, 0);
4510 	tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4511 
4512 	perf_adjust_freq_unthr_context(&cpuctx->ctx, !!throttled);
4513 
4514 	rcu_read_lock();
4515 	ctx = rcu_dereference(current->perf_event_ctxp);
4516 	if (ctx)
4517 		perf_adjust_freq_unthr_context(ctx, !!throttled);
4518 	rcu_read_unlock();
4519 }
4520 
event_enable_on_exec(struct perf_event * event,struct perf_event_context * ctx)4521 static int event_enable_on_exec(struct perf_event *event,
4522 				struct perf_event_context *ctx)
4523 {
4524 	if (!event->attr.enable_on_exec)
4525 		return 0;
4526 
4527 	event->attr.enable_on_exec = 0;
4528 	if (event->state >= PERF_EVENT_STATE_INACTIVE)
4529 		return 0;
4530 
4531 	perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4532 
4533 	return 1;
4534 }
4535 
4536 /*
4537  * Enable all of a task's events that have been marked enable-on-exec.
4538  * This expects task == current.
4539  */
perf_event_enable_on_exec(struct perf_event_context * ctx)4540 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
4541 {
4542 	struct perf_event_context *clone_ctx = NULL;
4543 	enum event_type_t event_type = 0;
4544 	struct perf_cpu_context *cpuctx;
4545 	struct perf_event *event;
4546 	unsigned long flags;
4547 	int enabled = 0;
4548 
4549 	local_irq_save(flags);
4550 	if (WARN_ON_ONCE(current->perf_event_ctxp != ctx))
4551 		goto out;
4552 
4553 	if (!ctx->nr_events)
4554 		goto out;
4555 
4556 	cpuctx = this_cpu_ptr(&perf_cpu_context);
4557 	perf_ctx_lock(cpuctx, ctx);
4558 	ctx_time_freeze(cpuctx, ctx);
4559 
4560 	list_for_each_entry(event, &ctx->event_list, event_entry) {
4561 		enabled |= event_enable_on_exec(event, ctx);
4562 		event_type |= get_event_type(event);
4563 	}
4564 
4565 	/*
4566 	 * Unclone and reschedule this context if we enabled any event.
4567 	 */
4568 	if (enabled) {
4569 		clone_ctx = unclone_ctx(ctx);
4570 		ctx_resched(cpuctx, ctx, NULL, event_type);
4571 	}
4572 	perf_ctx_unlock(cpuctx, ctx);
4573 
4574 out:
4575 	local_irq_restore(flags);
4576 
4577 	if (clone_ctx)
4578 		put_ctx(clone_ctx);
4579 }
4580 
4581 static void perf_remove_from_owner(struct perf_event *event);
4582 static void perf_event_exit_event(struct perf_event *event,
4583 				  struct perf_event_context *ctx,
4584 				  bool revoke);
4585 
4586 /*
4587  * Removes all events from the current task that have been marked
4588  * remove-on-exec, and feeds their values back to parent events.
4589  */
perf_event_remove_on_exec(struct perf_event_context * ctx)4590 static void perf_event_remove_on_exec(struct perf_event_context *ctx)
4591 {
4592 	struct perf_event_context *clone_ctx = NULL;
4593 	struct perf_event *event, *next;
4594 	unsigned long flags;
4595 	bool modified = false;
4596 
4597 	mutex_lock(&ctx->mutex);
4598 
4599 	if (WARN_ON_ONCE(ctx->task != current))
4600 		goto unlock;
4601 
4602 	list_for_each_entry_safe(event, next, &ctx->event_list, event_entry) {
4603 		if (!event->attr.remove_on_exec)
4604 			continue;
4605 
4606 		if (!is_kernel_event(event))
4607 			perf_remove_from_owner(event);
4608 
4609 		modified = true;
4610 
4611 		perf_event_exit_event(event, ctx, false);
4612 	}
4613 
4614 	raw_spin_lock_irqsave(&ctx->lock, flags);
4615 	if (modified)
4616 		clone_ctx = unclone_ctx(ctx);
4617 	raw_spin_unlock_irqrestore(&ctx->lock, flags);
4618 
4619 unlock:
4620 	mutex_unlock(&ctx->mutex);
4621 
4622 	if (clone_ctx)
4623 		put_ctx(clone_ctx);
4624 }
4625 
4626 struct perf_read_data {
4627 	struct perf_event *event;
4628 	bool group;
4629 	int ret;
4630 };
4631 
4632 static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu);
4633 
__perf_event_read_cpu(struct perf_event * event,int event_cpu)4634 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4635 {
4636 	int local_cpu = smp_processor_id();
4637 	u16 local_pkg, event_pkg;
4638 
4639 	if ((unsigned)event_cpu >= nr_cpu_ids)
4640 		return event_cpu;
4641 
4642 	if (event->group_caps & PERF_EV_CAP_READ_SCOPE) {
4643 		const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(event->pmu->scope, event_cpu);
4644 
4645 		if (cpumask && cpumask_test_cpu(local_cpu, cpumask))
4646 			return local_cpu;
4647 	}
4648 
4649 	if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4650 		event_pkg = topology_physical_package_id(event_cpu);
4651 		local_pkg = topology_physical_package_id(local_cpu);
4652 
4653 		if (event_pkg == local_pkg)
4654 			return local_cpu;
4655 	}
4656 
4657 	return event_cpu;
4658 }
4659 
4660 /*
4661  * Cross CPU call to read the hardware event
4662  */
__perf_event_read(void * info)4663 static void __perf_event_read(void *info)
4664 {
4665 	struct perf_read_data *data = info;
4666 	struct perf_event *sub, *event = data->event;
4667 	struct perf_event_context *ctx = event->ctx;
4668 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4669 	struct pmu *pmu = event->pmu;
4670 
4671 	/*
4672 	 * If this is a task context, we need to check whether it is
4673 	 * the current task context of this cpu.  If not it has been
4674 	 * scheduled out before the smp call arrived.  In that case
4675 	 * event->count would have been updated to a recent sample
4676 	 * when the event was scheduled out.
4677 	 */
4678 	if (ctx->task && cpuctx->task_ctx != ctx)
4679 		return;
4680 
4681 	raw_spin_lock(&ctx->lock);
4682 	ctx_time_update_event(ctx, event);
4683 
4684 	perf_event_update_time(event);
4685 	if (data->group)
4686 		perf_event_update_sibling_time(event);
4687 
4688 	if (event->state != PERF_EVENT_STATE_ACTIVE)
4689 		goto unlock;
4690 
4691 	if (!data->group) {
4692 		pmu->read(event);
4693 		data->ret = 0;
4694 		goto unlock;
4695 	}
4696 
4697 	pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4698 
4699 	pmu->read(event);
4700 
4701 	for_each_sibling_event(sub, event)
4702 		perf_pmu_read(sub);
4703 
4704 	data->ret = pmu->commit_txn(pmu);
4705 
4706 unlock:
4707 	raw_spin_unlock(&ctx->lock);
4708 }
4709 
perf_event_count(struct perf_event * event,bool self)4710 static inline u64 perf_event_count(struct perf_event *event, bool self)
4711 {
4712 	if (self)
4713 		return local64_read(&event->count);
4714 
4715 	return local64_read(&event->count) + atomic64_read(&event->child_count);
4716 }
4717 
calc_timer_values(struct perf_event * event,u64 * now,u64 * enabled,u64 * running)4718 static void calc_timer_values(struct perf_event *event,
4719 				u64 *now,
4720 				u64 *enabled,
4721 				u64 *running)
4722 {
4723 	u64 ctx_time;
4724 
4725 	*now = perf_clock();
4726 	ctx_time = perf_event_time_now(event, *now);
4727 	__perf_update_times(event, ctx_time, enabled, running);
4728 }
4729 
4730 /*
4731  * NMI-safe method to read a local event, that is an event that
4732  * is:
4733  *   - either for the current task, or for this CPU
4734  *   - does not have inherit set, for inherited task events
4735  *     will not be local and we cannot read them atomically
4736  *   - must not have a pmu::count method
4737  */
perf_event_read_local(struct perf_event * event,u64 * value,u64 * enabled,u64 * running)4738 int perf_event_read_local(struct perf_event *event, u64 *value,
4739 			  u64 *enabled, u64 *running)
4740 {
4741 	unsigned long flags;
4742 	int event_oncpu;
4743 	int event_cpu;
4744 	int ret = 0;
4745 
4746 	/*
4747 	 * Disabling interrupts avoids all counter scheduling (context
4748 	 * switches, timer based rotation and IPIs).
4749 	 */
4750 	local_irq_save(flags);
4751 
4752 	/*
4753 	 * It must not be an event with inherit set, we cannot read
4754 	 * all child counters from atomic context.
4755 	 */
4756 	if (event->attr.inherit) {
4757 		ret = -EOPNOTSUPP;
4758 		goto out;
4759 	}
4760 
4761 	/* If this is a per-task event, it must be for current */
4762 	if ((event->attach_state & PERF_ATTACH_TASK) &&
4763 	    event->hw.target != current) {
4764 		ret = -EINVAL;
4765 		goto out;
4766 	}
4767 
4768 	/*
4769 	 * Get the event CPU numbers, and adjust them to local if the event is
4770 	 * a per-package event that can be read locally
4771 	 */
4772 	event_oncpu = __perf_event_read_cpu(event, event->oncpu);
4773 	event_cpu = __perf_event_read_cpu(event, event->cpu);
4774 
4775 	/* If this is a per-CPU event, it must be for this CPU */
4776 	if (!(event->attach_state & PERF_ATTACH_TASK) &&
4777 	    event_cpu != smp_processor_id()) {
4778 		ret = -EINVAL;
4779 		goto out;
4780 	}
4781 
4782 	/* If this is a pinned event it must be running on this CPU */
4783 	if (event->attr.pinned && event_oncpu != smp_processor_id()) {
4784 		ret = -EBUSY;
4785 		goto out;
4786 	}
4787 
4788 	/*
4789 	 * If the event is currently on this CPU, its either a per-task event,
4790 	 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4791 	 * oncpu == -1).
4792 	 */
4793 	if (event_oncpu == smp_processor_id())
4794 		event->pmu->read(event);
4795 
4796 	*value = local64_read(&event->count);
4797 	if (enabled || running) {
4798 		u64 __enabled, __running, __now;
4799 
4800 		calc_timer_values(event, &__now, &__enabled, &__running);
4801 		if (enabled)
4802 			*enabled = __enabled;
4803 		if (running)
4804 			*running = __running;
4805 	}
4806 out:
4807 	local_irq_restore(flags);
4808 
4809 	return ret;
4810 }
4811 
perf_event_read(struct perf_event * event,bool group)4812 static int perf_event_read(struct perf_event *event, bool group)
4813 {
4814 	enum perf_event_state state = READ_ONCE(event->state);
4815 	int event_cpu, ret = 0;
4816 
4817 	/*
4818 	 * If event is enabled and currently active on a CPU, update the
4819 	 * value in the event structure:
4820 	 */
4821 again:
4822 	if (state == PERF_EVENT_STATE_ACTIVE) {
4823 		struct perf_read_data data;
4824 
4825 		/*
4826 		 * Orders the ->state and ->oncpu loads such that if we see
4827 		 * ACTIVE we must also see the right ->oncpu.
4828 		 *
4829 		 * Matches the smp_wmb() from event_sched_in().
4830 		 */
4831 		smp_rmb();
4832 
4833 		event_cpu = READ_ONCE(event->oncpu);
4834 		if ((unsigned)event_cpu >= nr_cpu_ids)
4835 			return 0;
4836 
4837 		data = (struct perf_read_data){
4838 			.event = event,
4839 			.group = group,
4840 			.ret = 0,
4841 		};
4842 
4843 		preempt_disable();
4844 		event_cpu = __perf_event_read_cpu(event, event_cpu);
4845 
4846 		/*
4847 		 * Purposely ignore the smp_call_function_single() return
4848 		 * value.
4849 		 *
4850 		 * If event_cpu isn't a valid CPU it means the event got
4851 		 * scheduled out and that will have updated the event count.
4852 		 *
4853 		 * Therefore, either way, we'll have an up-to-date event count
4854 		 * after this.
4855 		 */
4856 		(void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4857 		preempt_enable();
4858 		ret = data.ret;
4859 
4860 	} else if (state == PERF_EVENT_STATE_INACTIVE) {
4861 		struct perf_event_context *ctx = event->ctx;
4862 		unsigned long flags;
4863 
4864 		raw_spin_lock_irqsave(&ctx->lock, flags);
4865 		state = event->state;
4866 		if (state != PERF_EVENT_STATE_INACTIVE) {
4867 			raw_spin_unlock_irqrestore(&ctx->lock, flags);
4868 			goto again;
4869 		}
4870 
4871 		/*
4872 		 * May read while context is not active (e.g., thread is
4873 		 * blocked), in that case we cannot update context time
4874 		 */
4875 		ctx_time_update_event(ctx, event);
4876 
4877 		perf_event_update_time(event);
4878 		if (group)
4879 			perf_event_update_sibling_time(event);
4880 		raw_spin_unlock_irqrestore(&ctx->lock, flags);
4881 	}
4882 
4883 	return ret;
4884 }
4885 
4886 /*
4887  * Initialize the perf_event context in a task_struct:
4888  */
__perf_event_init_context(struct perf_event_context * ctx)4889 static void __perf_event_init_context(struct perf_event_context *ctx)
4890 {
4891 	raw_spin_lock_init(&ctx->lock);
4892 	mutex_init(&ctx->mutex);
4893 	INIT_LIST_HEAD(&ctx->pmu_ctx_list);
4894 	perf_event_groups_init(&ctx->pinned_groups);
4895 	perf_event_groups_init(&ctx->flexible_groups);
4896 	INIT_LIST_HEAD(&ctx->event_list);
4897 	refcount_set(&ctx->refcount, 1);
4898 }
4899 
4900 static void
__perf_init_event_pmu_context(struct perf_event_pmu_context * epc,struct pmu * pmu)4901 __perf_init_event_pmu_context(struct perf_event_pmu_context *epc, struct pmu *pmu)
4902 {
4903 	epc->pmu = pmu;
4904 	INIT_LIST_HEAD(&epc->pmu_ctx_entry);
4905 	INIT_LIST_HEAD(&epc->pinned_active);
4906 	INIT_LIST_HEAD(&epc->flexible_active);
4907 	atomic_set(&epc->refcount, 1);
4908 }
4909 
4910 static struct perf_event_context *
alloc_perf_context(struct task_struct * task)4911 alloc_perf_context(struct task_struct *task)
4912 {
4913 	struct perf_event_context *ctx;
4914 
4915 	ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4916 	if (!ctx)
4917 		return NULL;
4918 
4919 	__perf_event_init_context(ctx);
4920 	if (task)
4921 		ctx->task = get_task_struct(task);
4922 
4923 	return ctx;
4924 }
4925 
4926 static struct task_struct *
find_lively_task_by_vpid(pid_t vpid)4927 find_lively_task_by_vpid(pid_t vpid)
4928 {
4929 	struct task_struct *task;
4930 
4931 	rcu_read_lock();
4932 	if (!vpid)
4933 		task = current;
4934 	else
4935 		task = find_task_by_vpid(vpid);
4936 	if (task)
4937 		get_task_struct(task);
4938 	rcu_read_unlock();
4939 
4940 	if (!task)
4941 		return ERR_PTR(-ESRCH);
4942 
4943 	return task;
4944 }
4945 
4946 /*
4947  * Returns a matching context with refcount and pincount.
4948  */
4949 static struct perf_event_context *
find_get_context(struct task_struct * task,struct perf_event * event)4950 find_get_context(struct task_struct *task, struct perf_event *event)
4951 {
4952 	struct perf_event_context *ctx, *clone_ctx = NULL;
4953 	struct perf_cpu_context *cpuctx;
4954 	unsigned long flags;
4955 	int err;
4956 
4957 	if (!task) {
4958 		/* Must be root to operate on a CPU event: */
4959 		err = perf_allow_cpu();
4960 		if (err)
4961 			return ERR_PTR(err);
4962 
4963 		cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
4964 		ctx = &cpuctx->ctx;
4965 		get_ctx(ctx);
4966 		raw_spin_lock_irqsave(&ctx->lock, flags);
4967 		++ctx->pin_count;
4968 		raw_spin_unlock_irqrestore(&ctx->lock, flags);
4969 
4970 		return ctx;
4971 	}
4972 
4973 	err = -EINVAL;
4974 retry:
4975 	ctx = perf_lock_task_context(task, &flags);
4976 	if (ctx) {
4977 		clone_ctx = unclone_ctx(ctx);
4978 		++ctx->pin_count;
4979 
4980 		raw_spin_unlock_irqrestore(&ctx->lock, flags);
4981 
4982 		if (clone_ctx)
4983 			put_ctx(clone_ctx);
4984 	} else {
4985 		ctx = alloc_perf_context(task);
4986 		err = -ENOMEM;
4987 		if (!ctx)
4988 			goto errout;
4989 
4990 		err = 0;
4991 		mutex_lock(&task->perf_event_mutex);
4992 		/*
4993 		 * If it has already passed perf_event_exit_task().
4994 		 * we must see PF_EXITING, it takes this mutex too.
4995 		 */
4996 		if (task->flags & PF_EXITING)
4997 			err = -ESRCH;
4998 		else if (task->perf_event_ctxp)
4999 			err = -EAGAIN;
5000 		else {
5001 			get_ctx(ctx);
5002 			++ctx->pin_count;
5003 			rcu_assign_pointer(task->perf_event_ctxp, ctx);
5004 		}
5005 		mutex_unlock(&task->perf_event_mutex);
5006 
5007 		if (unlikely(err)) {
5008 			put_ctx(ctx);
5009 
5010 			if (err == -EAGAIN)
5011 				goto retry;
5012 			goto errout;
5013 		}
5014 	}
5015 
5016 	return ctx;
5017 
5018 errout:
5019 	return ERR_PTR(err);
5020 }
5021 
5022 static struct perf_event_pmu_context *
find_get_pmu_context(struct pmu * pmu,struct perf_event_context * ctx,struct perf_event * event)5023 find_get_pmu_context(struct pmu *pmu, struct perf_event_context *ctx,
5024 		     struct perf_event *event)
5025 {
5026 	struct perf_event_pmu_context *new = NULL, *pos = NULL, *epc;
5027 
5028 	if (!ctx->task) {
5029 		/*
5030 		 * perf_pmu_migrate_context() / __perf_pmu_install_event()
5031 		 * relies on the fact that find_get_pmu_context() cannot fail
5032 		 * for CPU contexts.
5033 		 */
5034 		struct perf_cpu_pmu_context *cpc;
5035 
5036 		cpc = *per_cpu_ptr(pmu->cpu_pmu_context, event->cpu);
5037 		epc = &cpc->epc;
5038 		raw_spin_lock_irq(&ctx->lock);
5039 		if (!epc->ctx) {
5040 			/*
5041 			 * One extra reference for the pmu; see perf_pmu_free().
5042 			 */
5043 			atomic_set(&epc->refcount, 2);
5044 			epc->embedded = 1;
5045 			list_add(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
5046 			epc->ctx = ctx;
5047 		} else {
5048 			WARN_ON_ONCE(epc->ctx != ctx);
5049 			atomic_inc(&epc->refcount);
5050 		}
5051 		raw_spin_unlock_irq(&ctx->lock);
5052 		return epc;
5053 	}
5054 
5055 	new = kzalloc(sizeof(*epc), GFP_KERNEL);
5056 	if (!new)
5057 		return ERR_PTR(-ENOMEM);
5058 
5059 	__perf_init_event_pmu_context(new, pmu);
5060 
5061 	/*
5062 	 * XXX
5063 	 *
5064 	 * lockdep_assert_held(&ctx->mutex);
5065 	 *
5066 	 * can't because perf_event_init_task() doesn't actually hold the
5067 	 * child_ctx->mutex.
5068 	 */
5069 
5070 	raw_spin_lock_irq(&ctx->lock);
5071 	list_for_each_entry(epc, &ctx->pmu_ctx_list, pmu_ctx_entry) {
5072 		if (epc->pmu == pmu) {
5073 			WARN_ON_ONCE(epc->ctx != ctx);
5074 			atomic_inc(&epc->refcount);
5075 			goto found_epc;
5076 		}
5077 		/* Make sure the pmu_ctx_list is sorted by PMU type: */
5078 		if (!pos && epc->pmu->type > pmu->type)
5079 			pos = epc;
5080 	}
5081 
5082 	epc = new;
5083 	new = NULL;
5084 
5085 	if (!pos)
5086 		list_add_tail(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
5087 	else
5088 		list_add(&epc->pmu_ctx_entry, pos->pmu_ctx_entry.prev);
5089 
5090 	epc->ctx = ctx;
5091 
5092 found_epc:
5093 	raw_spin_unlock_irq(&ctx->lock);
5094 	kfree(new);
5095 
5096 	return epc;
5097 }
5098 
get_pmu_ctx(struct perf_event_pmu_context * epc)5099 static void get_pmu_ctx(struct perf_event_pmu_context *epc)
5100 {
5101 	WARN_ON_ONCE(!atomic_inc_not_zero(&epc->refcount));
5102 }
5103 
free_cpc_rcu(struct rcu_head * head)5104 static void free_cpc_rcu(struct rcu_head *head)
5105 {
5106 	struct perf_cpu_pmu_context *cpc =
5107 		container_of(head, typeof(*cpc), epc.rcu_head);
5108 
5109 	kfree(cpc);
5110 }
5111 
free_epc_rcu(struct rcu_head * head)5112 static void free_epc_rcu(struct rcu_head *head)
5113 {
5114 	struct perf_event_pmu_context *epc = container_of(head, typeof(*epc), rcu_head);
5115 
5116 	kfree(epc);
5117 }
5118 
put_pmu_ctx(struct perf_event_pmu_context * epc)5119 static void put_pmu_ctx(struct perf_event_pmu_context *epc)
5120 {
5121 	struct perf_event_context *ctx = epc->ctx;
5122 	unsigned long flags;
5123 
5124 	/*
5125 	 * XXX
5126 	 *
5127 	 * lockdep_assert_held(&ctx->mutex);
5128 	 *
5129 	 * can't because of the call-site in _free_event()/put_event()
5130 	 * which isn't always called under ctx->mutex.
5131 	 */
5132 	if (!atomic_dec_and_raw_lock_irqsave(&epc->refcount, &ctx->lock, flags))
5133 		return;
5134 
5135 	WARN_ON_ONCE(list_empty(&epc->pmu_ctx_entry));
5136 
5137 	list_del_init(&epc->pmu_ctx_entry);
5138 	epc->ctx = NULL;
5139 
5140 	WARN_ON_ONCE(!list_empty(&epc->pinned_active));
5141 	WARN_ON_ONCE(!list_empty(&epc->flexible_active));
5142 
5143 	raw_spin_unlock_irqrestore(&ctx->lock, flags);
5144 
5145 	if (epc->embedded) {
5146 		call_rcu(&epc->rcu_head, free_cpc_rcu);
5147 		return;
5148 	}
5149 
5150 	call_rcu(&epc->rcu_head, free_epc_rcu);
5151 }
5152 
5153 static void perf_event_free_filter(struct perf_event *event);
5154 
free_event_rcu(struct rcu_head * head)5155 static void free_event_rcu(struct rcu_head *head)
5156 {
5157 	struct perf_event *event = container_of(head, typeof(*event), rcu_head);
5158 
5159 	if (event->ns)
5160 		put_pid_ns(event->ns);
5161 	perf_event_free_filter(event);
5162 	kmem_cache_free(perf_event_cache, event);
5163 }
5164 
5165 static void ring_buffer_attach(struct perf_event *event,
5166 			       struct perf_buffer *rb);
5167 
detach_sb_event(struct perf_event * event)5168 static void detach_sb_event(struct perf_event *event)
5169 {
5170 	struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
5171 
5172 	raw_spin_lock(&pel->lock);
5173 	list_del_rcu(&event->sb_list);
5174 	raw_spin_unlock(&pel->lock);
5175 }
5176 
is_sb_event(struct perf_event * event)5177 static bool is_sb_event(struct perf_event *event)
5178 {
5179 	struct perf_event_attr *attr = &event->attr;
5180 
5181 	if (event->parent)
5182 		return false;
5183 
5184 	if (event->attach_state & PERF_ATTACH_TASK)
5185 		return false;
5186 
5187 	if (attr->mmap || attr->mmap_data || attr->mmap2 ||
5188 	    attr->comm || attr->comm_exec ||
5189 	    attr->task || attr->ksymbol ||
5190 	    attr->context_switch || attr->text_poke ||
5191 	    attr->bpf_event)
5192 		return true;
5193 
5194 	return false;
5195 }
5196 
unaccount_pmu_sb_event(struct perf_event * event)5197 static void unaccount_pmu_sb_event(struct perf_event *event)
5198 {
5199 	if (is_sb_event(event))
5200 		detach_sb_event(event);
5201 }
5202 
5203 #ifdef CONFIG_NO_HZ_FULL
5204 static DEFINE_SPINLOCK(nr_freq_lock);
5205 #endif
5206 
unaccount_freq_event_nohz(void)5207 static void unaccount_freq_event_nohz(void)
5208 {
5209 #ifdef CONFIG_NO_HZ_FULL
5210 	spin_lock(&nr_freq_lock);
5211 	if (atomic_dec_and_test(&nr_freq_events))
5212 		tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
5213 	spin_unlock(&nr_freq_lock);
5214 #endif
5215 }
5216 
unaccount_freq_event(void)5217 static void unaccount_freq_event(void)
5218 {
5219 	if (tick_nohz_full_enabled())
5220 		unaccount_freq_event_nohz();
5221 	else
5222 		atomic_dec(&nr_freq_events);
5223 }
5224 
5225 
5226 static struct perf_ctx_data *
alloc_perf_ctx_data(struct kmem_cache * ctx_cache,bool global)5227 alloc_perf_ctx_data(struct kmem_cache *ctx_cache, bool global)
5228 {
5229 	struct perf_ctx_data *cd;
5230 
5231 	cd = kzalloc(sizeof(*cd), GFP_KERNEL);
5232 	if (!cd)
5233 		return NULL;
5234 
5235 	cd->data = kmem_cache_zalloc(ctx_cache, GFP_KERNEL);
5236 	if (!cd->data) {
5237 		kfree(cd);
5238 		return NULL;
5239 	}
5240 
5241 	cd->global = global;
5242 	cd->ctx_cache = ctx_cache;
5243 	refcount_set(&cd->refcount, 1);
5244 
5245 	return cd;
5246 }
5247 
free_perf_ctx_data(struct perf_ctx_data * cd)5248 static void free_perf_ctx_data(struct perf_ctx_data *cd)
5249 {
5250 	kmem_cache_free(cd->ctx_cache, cd->data);
5251 	kfree(cd);
5252 }
5253 
__free_perf_ctx_data_rcu(struct rcu_head * rcu_head)5254 static void __free_perf_ctx_data_rcu(struct rcu_head *rcu_head)
5255 {
5256 	struct perf_ctx_data *cd;
5257 
5258 	cd = container_of(rcu_head, struct perf_ctx_data, rcu_head);
5259 	free_perf_ctx_data(cd);
5260 }
5261 
perf_free_ctx_data_rcu(struct perf_ctx_data * cd)5262 static inline void perf_free_ctx_data_rcu(struct perf_ctx_data *cd)
5263 {
5264 	call_rcu(&cd->rcu_head, __free_perf_ctx_data_rcu);
5265 }
5266 
5267 static int
attach_task_ctx_data(struct task_struct * task,struct kmem_cache * ctx_cache,bool global)5268 attach_task_ctx_data(struct task_struct *task, struct kmem_cache *ctx_cache,
5269 		     bool global)
5270 {
5271 	struct perf_ctx_data *cd, *old = NULL;
5272 
5273 	cd = alloc_perf_ctx_data(ctx_cache, global);
5274 	if (!cd)
5275 		return -ENOMEM;
5276 
5277 	for (;;) {
5278 		if (try_cmpxchg((struct perf_ctx_data **)&task->perf_ctx_data, &old, cd)) {
5279 			if (old)
5280 				perf_free_ctx_data_rcu(old);
5281 			return 0;
5282 		}
5283 
5284 		if (!old) {
5285 			/*
5286 			 * After seeing a dead @old, we raced with
5287 			 * removal and lost, try again to install @cd.
5288 			 */
5289 			continue;
5290 		}
5291 
5292 		if (refcount_inc_not_zero(&old->refcount)) {
5293 			free_perf_ctx_data(cd); /* unused */
5294 			return 0;
5295 		}
5296 
5297 		/*
5298 		 * @old is a dead object, refcount==0 is stable, try and
5299 		 * replace it with @cd.
5300 		 */
5301 	}
5302 	return 0;
5303 }
5304 
5305 static void __detach_global_ctx_data(void);
5306 DEFINE_STATIC_PERCPU_RWSEM(global_ctx_data_rwsem);
5307 static refcount_t global_ctx_data_ref;
5308 
5309 static int
attach_global_ctx_data(struct kmem_cache * ctx_cache)5310 attach_global_ctx_data(struct kmem_cache *ctx_cache)
5311 {
5312 	struct task_struct *g, *p;
5313 	struct perf_ctx_data *cd;
5314 	int ret;
5315 
5316 	if (refcount_inc_not_zero(&global_ctx_data_ref))
5317 		return 0;
5318 
5319 	guard(percpu_write)(&global_ctx_data_rwsem);
5320 	if (refcount_inc_not_zero(&global_ctx_data_ref))
5321 		return 0;
5322 again:
5323 	/* Allocate everything */
5324 	scoped_guard (rcu) {
5325 		for_each_process_thread(g, p) {
5326 			cd = rcu_dereference(p->perf_ctx_data);
5327 			if (cd && !cd->global) {
5328 				cd->global = 1;
5329 				if (!refcount_inc_not_zero(&cd->refcount))
5330 					cd = NULL;
5331 			}
5332 			if (!cd) {
5333 				get_task_struct(p);
5334 				goto alloc;
5335 			}
5336 		}
5337 	}
5338 
5339 	refcount_set(&global_ctx_data_ref, 1);
5340 
5341 	return 0;
5342 alloc:
5343 	ret = attach_task_ctx_data(p, ctx_cache, true);
5344 	put_task_struct(p);
5345 	if (ret) {
5346 		__detach_global_ctx_data();
5347 		return ret;
5348 	}
5349 	goto again;
5350 }
5351 
5352 static int
attach_perf_ctx_data(struct perf_event * event)5353 attach_perf_ctx_data(struct perf_event *event)
5354 {
5355 	struct task_struct *task = event->hw.target;
5356 	struct kmem_cache *ctx_cache = event->pmu->task_ctx_cache;
5357 	int ret;
5358 
5359 	if (!ctx_cache)
5360 		return -ENOMEM;
5361 
5362 	if (task)
5363 		return attach_task_ctx_data(task, ctx_cache, false);
5364 
5365 	ret = attach_global_ctx_data(ctx_cache);
5366 	if (ret)
5367 		return ret;
5368 
5369 	event->attach_state |= PERF_ATTACH_GLOBAL_DATA;
5370 	return 0;
5371 }
5372 
5373 static void
detach_task_ctx_data(struct task_struct * p)5374 detach_task_ctx_data(struct task_struct *p)
5375 {
5376 	struct perf_ctx_data *cd;
5377 
5378 	scoped_guard (rcu) {
5379 		cd = rcu_dereference(p->perf_ctx_data);
5380 		if (!cd || !refcount_dec_and_test(&cd->refcount))
5381 			return;
5382 	}
5383 
5384 	/*
5385 	 * The old ctx_data may be lost because of the race.
5386 	 * Nothing is required to do for the case.
5387 	 * See attach_task_ctx_data().
5388 	 */
5389 	if (try_cmpxchg((struct perf_ctx_data **)&p->perf_ctx_data, &cd, NULL))
5390 		perf_free_ctx_data_rcu(cd);
5391 }
5392 
__detach_global_ctx_data(void)5393 static void __detach_global_ctx_data(void)
5394 {
5395 	struct task_struct *g, *p;
5396 	struct perf_ctx_data *cd;
5397 
5398 again:
5399 	scoped_guard (rcu) {
5400 		for_each_process_thread(g, p) {
5401 			cd = rcu_dereference(p->perf_ctx_data);
5402 			if (!cd || !cd->global)
5403 				continue;
5404 			cd->global = 0;
5405 			get_task_struct(p);
5406 			goto detach;
5407 		}
5408 	}
5409 	return;
5410 detach:
5411 	detach_task_ctx_data(p);
5412 	put_task_struct(p);
5413 	goto again;
5414 }
5415 
detach_global_ctx_data(void)5416 static void detach_global_ctx_data(void)
5417 {
5418 	if (refcount_dec_not_one(&global_ctx_data_ref))
5419 		return;
5420 
5421 	guard(percpu_write)(&global_ctx_data_rwsem);
5422 	if (!refcount_dec_and_test(&global_ctx_data_ref))
5423 		return;
5424 
5425 	/* remove everything */
5426 	__detach_global_ctx_data();
5427 }
5428 
detach_perf_ctx_data(struct perf_event * event)5429 static void detach_perf_ctx_data(struct perf_event *event)
5430 {
5431 	struct task_struct *task = event->hw.target;
5432 
5433 	event->attach_state &= ~PERF_ATTACH_TASK_DATA;
5434 
5435 	if (task)
5436 		return detach_task_ctx_data(task);
5437 
5438 	if (event->attach_state & PERF_ATTACH_GLOBAL_DATA) {
5439 		detach_global_ctx_data();
5440 		event->attach_state &= ~PERF_ATTACH_GLOBAL_DATA;
5441 	}
5442 }
5443 
unaccount_event(struct perf_event * event)5444 static void unaccount_event(struct perf_event *event)
5445 {
5446 	bool dec = false;
5447 
5448 	if (event->parent)
5449 		return;
5450 
5451 	if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
5452 		dec = true;
5453 	if (event->attr.mmap || event->attr.mmap_data)
5454 		atomic_dec(&nr_mmap_events);
5455 	if (event->attr.build_id)
5456 		atomic_dec(&nr_build_id_events);
5457 	if (event->attr.comm)
5458 		atomic_dec(&nr_comm_events);
5459 	if (event->attr.namespaces)
5460 		atomic_dec(&nr_namespaces_events);
5461 	if (event->attr.cgroup)
5462 		atomic_dec(&nr_cgroup_events);
5463 	if (event->attr.task)
5464 		atomic_dec(&nr_task_events);
5465 	if (event->attr.freq)
5466 		unaccount_freq_event();
5467 	if (event->attr.context_switch) {
5468 		dec = true;
5469 		atomic_dec(&nr_switch_events);
5470 	}
5471 	if (is_cgroup_event(event))
5472 		dec = true;
5473 	if (has_branch_stack(event))
5474 		dec = true;
5475 	if (event->attr.ksymbol)
5476 		atomic_dec(&nr_ksymbol_events);
5477 	if (event->attr.bpf_event)
5478 		atomic_dec(&nr_bpf_events);
5479 	if (event->attr.text_poke)
5480 		atomic_dec(&nr_text_poke_events);
5481 
5482 	if (dec) {
5483 		if (!atomic_add_unless(&perf_sched_count, -1, 1))
5484 			schedule_delayed_work(&perf_sched_work, HZ);
5485 	}
5486 
5487 	unaccount_pmu_sb_event(event);
5488 }
5489 
perf_sched_delayed(struct work_struct * work)5490 static void perf_sched_delayed(struct work_struct *work)
5491 {
5492 	mutex_lock(&perf_sched_mutex);
5493 	if (atomic_dec_and_test(&perf_sched_count))
5494 		static_branch_disable(&perf_sched_events);
5495 	mutex_unlock(&perf_sched_mutex);
5496 }
5497 
5498 /*
5499  * The following implement mutual exclusion of events on "exclusive" pmus
5500  * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
5501  * at a time, so we disallow creating events that might conflict, namely:
5502  *
5503  *  1) cpu-wide events in the presence of per-task events,
5504  *  2) per-task events in the presence of cpu-wide events,
5505  *  3) two matching events on the same perf_event_context.
5506  *
5507  * The former two cases are handled in the allocation path (perf_event_alloc(),
5508  * _free_event()), the latter -- before the first perf_install_in_context().
5509  */
exclusive_event_init(struct perf_event * event)5510 static int exclusive_event_init(struct perf_event *event)
5511 {
5512 	struct pmu *pmu = event->pmu;
5513 
5514 	if (!is_exclusive_pmu(pmu))
5515 		return 0;
5516 
5517 	/*
5518 	 * Prevent co-existence of per-task and cpu-wide events on the
5519 	 * same exclusive pmu.
5520 	 *
5521 	 * Negative pmu::exclusive_cnt means there are cpu-wide
5522 	 * events on this "exclusive" pmu, positive means there are
5523 	 * per-task events.
5524 	 *
5525 	 * Since this is called in perf_event_alloc() path, event::ctx
5526 	 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
5527 	 * to mean "per-task event", because unlike other attach states it
5528 	 * never gets cleared.
5529 	 */
5530 	if (event->attach_state & PERF_ATTACH_TASK) {
5531 		if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
5532 			return -EBUSY;
5533 	} else {
5534 		if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
5535 			return -EBUSY;
5536 	}
5537 
5538 	event->attach_state |= PERF_ATTACH_EXCLUSIVE;
5539 
5540 	return 0;
5541 }
5542 
exclusive_event_destroy(struct perf_event * event)5543 static void exclusive_event_destroy(struct perf_event *event)
5544 {
5545 	struct pmu *pmu = event->pmu;
5546 
5547 	/* see comment in exclusive_event_init() */
5548 	if (event->attach_state & PERF_ATTACH_TASK)
5549 		atomic_dec(&pmu->exclusive_cnt);
5550 	else
5551 		atomic_inc(&pmu->exclusive_cnt);
5552 
5553 	event->attach_state &= ~PERF_ATTACH_EXCLUSIVE;
5554 }
5555 
exclusive_event_match(struct perf_event * e1,struct perf_event * e2)5556 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
5557 {
5558 	if ((e1->pmu == e2->pmu) &&
5559 	    (e1->cpu == e2->cpu ||
5560 	     e1->cpu == -1 ||
5561 	     e2->cpu == -1))
5562 		return true;
5563 	return false;
5564 }
5565 
exclusive_event_installable(struct perf_event * event,struct perf_event_context * ctx)5566 static bool exclusive_event_installable(struct perf_event *event,
5567 					struct perf_event_context *ctx)
5568 {
5569 	struct perf_event *iter_event;
5570 	struct pmu *pmu = event->pmu;
5571 
5572 	lockdep_assert_held(&ctx->mutex);
5573 
5574 	if (!is_exclusive_pmu(pmu))
5575 		return true;
5576 
5577 	list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
5578 		if (exclusive_event_match(iter_event, event))
5579 			return false;
5580 	}
5581 
5582 	return true;
5583 }
5584 
5585 static void perf_free_addr_filters(struct perf_event *event);
5586 
5587 /* vs perf_event_alloc() error */
__free_event(struct perf_event * event)5588 static void __free_event(struct perf_event *event)
5589 {
5590 	struct pmu *pmu = event->pmu;
5591 
5592 	if (event->attach_state & PERF_ATTACH_CALLCHAIN)
5593 		put_callchain_buffers();
5594 
5595 	kfree(event->addr_filter_ranges);
5596 
5597 	if (event->attach_state & PERF_ATTACH_EXCLUSIVE)
5598 		exclusive_event_destroy(event);
5599 
5600 	if (is_cgroup_event(event))
5601 		perf_detach_cgroup(event);
5602 
5603 	if (event->attach_state & PERF_ATTACH_TASK_DATA)
5604 		detach_perf_ctx_data(event);
5605 
5606 	if (event->destroy)
5607 		event->destroy(event);
5608 
5609 	/*
5610 	 * Must be after ->destroy(), due to uprobe_perf_close() using
5611 	 * hw.target.
5612 	 */
5613 	if (event->hw.target)
5614 		put_task_struct(event->hw.target);
5615 
5616 	if (event->pmu_ctx) {
5617 		/*
5618 		 * put_pmu_ctx() needs an event->ctx reference, because of
5619 		 * epc->ctx.
5620 		 */
5621 		WARN_ON_ONCE(!pmu);
5622 		WARN_ON_ONCE(!event->ctx);
5623 		WARN_ON_ONCE(event->pmu_ctx->ctx != event->ctx);
5624 		put_pmu_ctx(event->pmu_ctx);
5625 	}
5626 
5627 	/*
5628 	 * perf_event_free_task() relies on put_ctx() being 'last', in
5629 	 * particular all task references must be cleaned up.
5630 	 */
5631 	if (event->ctx)
5632 		put_ctx(event->ctx);
5633 
5634 	if (pmu) {
5635 		module_put(pmu->module);
5636 		scoped_guard (spinlock, &pmu->events_lock) {
5637 			list_del(&event->pmu_list);
5638 			wake_up_var(pmu);
5639 		}
5640 	}
5641 
5642 	call_rcu(&event->rcu_head, free_event_rcu);
5643 }
5644 
DEFINE_FREE(__free_event,struct perf_event *,if (_T)__free_event (_T))5645 DEFINE_FREE(__free_event, struct perf_event *, if (_T) __free_event(_T))
5646 
5647 /* vs perf_event_alloc() success */
5648 static void _free_event(struct perf_event *event)
5649 {
5650 	irq_work_sync(&event->pending_irq);
5651 	irq_work_sync(&event->pending_disable_irq);
5652 
5653 	unaccount_event(event);
5654 
5655 	security_perf_event_free(event);
5656 
5657 	if (event->rb) {
5658 		/*
5659 		 * Can happen when we close an event with re-directed output.
5660 		 *
5661 		 * Since we have a 0 refcount, perf_mmap_close() will skip
5662 		 * over us; possibly making our ring_buffer_put() the last.
5663 		 */
5664 		mutex_lock(&event->mmap_mutex);
5665 		ring_buffer_attach(event, NULL);
5666 		mutex_unlock(&event->mmap_mutex);
5667 	}
5668 
5669 	perf_event_free_bpf_prog(event);
5670 	perf_free_addr_filters(event);
5671 
5672 	__free_event(event);
5673 }
5674 
5675 /*
5676  * Used to free events which have a known refcount of 1, such as in error paths
5677  * of inherited events.
5678  */
free_event(struct perf_event * event)5679 static void free_event(struct perf_event *event)
5680 {
5681 	if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
5682 				     "unexpected event refcount: %ld; ptr=%p\n",
5683 				     atomic_long_read(&event->refcount), event)) {
5684 		/* leak to avoid use-after-free */
5685 		return;
5686 	}
5687 
5688 	_free_event(event);
5689 }
5690 
5691 /*
5692  * Remove user event from the owner task.
5693  */
perf_remove_from_owner(struct perf_event * event)5694 static void perf_remove_from_owner(struct perf_event *event)
5695 {
5696 	struct task_struct *owner;
5697 
5698 	rcu_read_lock();
5699 	/*
5700 	 * Matches the smp_store_release() in perf_event_exit_task(). If we
5701 	 * observe !owner it means the list deletion is complete and we can
5702 	 * indeed free this event, otherwise we need to serialize on
5703 	 * owner->perf_event_mutex.
5704 	 */
5705 	owner = READ_ONCE(event->owner);
5706 	if (owner) {
5707 		/*
5708 		 * Since delayed_put_task_struct() also drops the last
5709 		 * task reference we can safely take a new reference
5710 		 * while holding the rcu_read_lock().
5711 		 */
5712 		get_task_struct(owner);
5713 	}
5714 	rcu_read_unlock();
5715 
5716 	if (owner) {
5717 		/*
5718 		 * If we're here through perf_event_exit_task() we're already
5719 		 * holding ctx->mutex which would be an inversion wrt. the
5720 		 * normal lock order.
5721 		 *
5722 		 * However we can safely take this lock because its the child
5723 		 * ctx->mutex.
5724 		 */
5725 		mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
5726 
5727 		/*
5728 		 * We have to re-check the event->owner field, if it is cleared
5729 		 * we raced with perf_event_exit_task(), acquiring the mutex
5730 		 * ensured they're done, and we can proceed with freeing the
5731 		 * event.
5732 		 */
5733 		if (event->owner) {
5734 			list_del_init(&event->owner_entry);
5735 			smp_store_release(&event->owner, NULL);
5736 		}
5737 		mutex_unlock(&owner->perf_event_mutex);
5738 		put_task_struct(owner);
5739 	}
5740 }
5741 
put_event(struct perf_event * event)5742 static void put_event(struct perf_event *event)
5743 {
5744 	struct perf_event *parent;
5745 
5746 	if (!atomic_long_dec_and_test(&event->refcount))
5747 		return;
5748 
5749 	parent = event->parent;
5750 	_free_event(event);
5751 
5752 	/* Matches the refcount bump in inherit_event() */
5753 	if (parent)
5754 		put_event(parent);
5755 }
5756 
5757 /*
5758  * Kill an event dead; while event:refcount will preserve the event
5759  * object, it will not preserve its functionality. Once the last 'user'
5760  * gives up the object, we'll destroy the thing.
5761  */
perf_event_release_kernel(struct perf_event * event)5762 int perf_event_release_kernel(struct perf_event *event)
5763 {
5764 	struct perf_event_context *ctx = event->ctx;
5765 	struct perf_event *child, *tmp;
5766 
5767 	/*
5768 	 * If we got here through err_alloc: free_event(event); we will not
5769 	 * have attached to a context yet.
5770 	 */
5771 	if (!ctx) {
5772 		WARN_ON_ONCE(event->attach_state &
5773 				(PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
5774 		goto no_ctx;
5775 	}
5776 
5777 	if (!is_kernel_event(event))
5778 		perf_remove_from_owner(event);
5779 
5780 	ctx = perf_event_ctx_lock(event);
5781 	WARN_ON_ONCE(ctx->parent_ctx);
5782 
5783 	/*
5784 	 * Mark this event as STATE_DEAD, there is no external reference to it
5785 	 * anymore.
5786 	 *
5787 	 * Anybody acquiring event->child_mutex after the below loop _must_
5788 	 * also see this, most importantly inherit_event() which will avoid
5789 	 * placing more children on the list.
5790 	 *
5791 	 * Thus this guarantees that we will in fact observe and kill _ALL_
5792 	 * child events.
5793 	 */
5794 	if (event->state > PERF_EVENT_STATE_REVOKED) {
5795 		perf_remove_from_context(event, DETACH_GROUP|DETACH_DEAD);
5796 	} else {
5797 		event->state = PERF_EVENT_STATE_DEAD;
5798 	}
5799 
5800 	perf_event_ctx_unlock(event, ctx);
5801 
5802 again:
5803 	mutex_lock(&event->child_mutex);
5804 	list_for_each_entry(child, &event->child_list, child_list) {
5805 		/*
5806 		 * Cannot change, child events are not migrated, see the
5807 		 * comment with perf_event_ctx_lock_nested().
5808 		 */
5809 		ctx = READ_ONCE(child->ctx);
5810 		/*
5811 		 * Since child_mutex nests inside ctx::mutex, we must jump
5812 		 * through hoops. We start by grabbing a reference on the ctx.
5813 		 *
5814 		 * Since the event cannot get freed while we hold the
5815 		 * child_mutex, the context must also exist and have a !0
5816 		 * reference count.
5817 		 */
5818 		get_ctx(ctx);
5819 
5820 		/*
5821 		 * Now that we have a ctx ref, we can drop child_mutex, and
5822 		 * acquire ctx::mutex without fear of it going away. Then we
5823 		 * can re-acquire child_mutex.
5824 		 */
5825 		mutex_unlock(&event->child_mutex);
5826 		mutex_lock(&ctx->mutex);
5827 		mutex_lock(&event->child_mutex);
5828 
5829 		/*
5830 		 * Now that we hold ctx::mutex and child_mutex, revalidate our
5831 		 * state, if child is still the first entry, it didn't get freed
5832 		 * and we can continue doing so.
5833 		 */
5834 		tmp = list_first_entry_or_null(&event->child_list,
5835 					       struct perf_event, child_list);
5836 		if (tmp == child) {
5837 			perf_remove_from_context(child, DETACH_GROUP | DETACH_CHILD);
5838 		} else {
5839 			child = NULL;
5840 		}
5841 
5842 		mutex_unlock(&event->child_mutex);
5843 		mutex_unlock(&ctx->mutex);
5844 
5845 		if (child) {
5846 			/* Last reference unless ->pending_task work is pending */
5847 			put_event(child);
5848 		}
5849 		put_ctx(ctx);
5850 
5851 		goto again;
5852 	}
5853 	mutex_unlock(&event->child_mutex);
5854 
5855 no_ctx:
5856 	/*
5857 	 * Last reference unless ->pending_task work is pending on this event
5858 	 * or any of its children.
5859 	 */
5860 	put_event(event);
5861 	return 0;
5862 }
5863 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5864 
5865 /*
5866  * Called when the last reference to the file is gone.
5867  */
perf_release(struct inode * inode,struct file * file)5868 static int perf_release(struct inode *inode, struct file *file)
5869 {
5870 	perf_event_release_kernel(file->private_data);
5871 	return 0;
5872 }
5873 
__perf_event_read_value(struct perf_event * event,u64 * enabled,u64 * running)5874 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5875 {
5876 	struct perf_event *child;
5877 	u64 total = 0;
5878 
5879 	*enabled = 0;
5880 	*running = 0;
5881 
5882 	mutex_lock(&event->child_mutex);
5883 
5884 	(void)perf_event_read(event, false);
5885 	total += perf_event_count(event, false);
5886 
5887 	*enabled += event->total_time_enabled +
5888 			atomic64_read(&event->child_total_time_enabled);
5889 	*running += event->total_time_running +
5890 			atomic64_read(&event->child_total_time_running);
5891 
5892 	list_for_each_entry(child, &event->child_list, child_list) {
5893 		(void)perf_event_read(child, false);
5894 		total += perf_event_count(child, false);
5895 		*enabled += child->total_time_enabled;
5896 		*running += child->total_time_running;
5897 	}
5898 	mutex_unlock(&event->child_mutex);
5899 
5900 	return total;
5901 }
5902 
perf_event_read_value(struct perf_event * event,u64 * enabled,u64 * running)5903 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5904 {
5905 	struct perf_event_context *ctx;
5906 	u64 count;
5907 
5908 	ctx = perf_event_ctx_lock(event);
5909 	count = __perf_event_read_value(event, enabled, running);
5910 	perf_event_ctx_unlock(event, ctx);
5911 
5912 	return count;
5913 }
5914 EXPORT_SYMBOL_GPL(perf_event_read_value);
5915 
__perf_read_group_add(struct perf_event * leader,u64 read_format,u64 * values)5916 static int __perf_read_group_add(struct perf_event *leader,
5917 					u64 read_format, u64 *values)
5918 {
5919 	struct perf_event_context *ctx = leader->ctx;
5920 	struct perf_event *sub, *parent;
5921 	unsigned long flags;
5922 	int n = 1; /* skip @nr */
5923 	int ret;
5924 
5925 	ret = perf_event_read(leader, true);
5926 	if (ret)
5927 		return ret;
5928 
5929 	raw_spin_lock_irqsave(&ctx->lock, flags);
5930 	/*
5931 	 * Verify the grouping between the parent and child (inherited)
5932 	 * events is still in tact.
5933 	 *
5934 	 * Specifically:
5935 	 *  - leader->ctx->lock pins leader->sibling_list
5936 	 *  - parent->child_mutex pins parent->child_list
5937 	 *  - parent->ctx->mutex pins parent->sibling_list
5938 	 *
5939 	 * Because parent->ctx != leader->ctx (and child_list nests inside
5940 	 * ctx->mutex), group destruction is not atomic between children, also
5941 	 * see perf_event_release_kernel(). Additionally, parent can grow the
5942 	 * group.
5943 	 *
5944 	 * Therefore it is possible to have parent and child groups in a
5945 	 * different configuration and summing over such a beast makes no sense
5946 	 * what so ever.
5947 	 *
5948 	 * Reject this.
5949 	 */
5950 	parent = leader->parent;
5951 	if (parent &&
5952 	    (parent->group_generation != leader->group_generation ||
5953 	     parent->nr_siblings != leader->nr_siblings)) {
5954 		ret = -ECHILD;
5955 		goto unlock;
5956 	}
5957 
5958 	/*
5959 	 * Since we co-schedule groups, {enabled,running} times of siblings
5960 	 * will be identical to those of the leader, so we only publish one
5961 	 * set.
5962 	 */
5963 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5964 		values[n++] += leader->total_time_enabled +
5965 			atomic64_read(&leader->child_total_time_enabled);
5966 	}
5967 
5968 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5969 		values[n++] += leader->total_time_running +
5970 			atomic64_read(&leader->child_total_time_running);
5971 	}
5972 
5973 	/*
5974 	 * Write {count,id} tuples for every sibling.
5975 	 */
5976 	values[n++] += perf_event_count(leader, false);
5977 	if (read_format & PERF_FORMAT_ID)
5978 		values[n++] = primary_event_id(leader);
5979 	if (read_format & PERF_FORMAT_LOST)
5980 		values[n++] = atomic64_read(&leader->lost_samples);
5981 
5982 	for_each_sibling_event(sub, leader) {
5983 		values[n++] += perf_event_count(sub, false);
5984 		if (read_format & PERF_FORMAT_ID)
5985 			values[n++] = primary_event_id(sub);
5986 		if (read_format & PERF_FORMAT_LOST)
5987 			values[n++] = atomic64_read(&sub->lost_samples);
5988 	}
5989 
5990 unlock:
5991 	raw_spin_unlock_irqrestore(&ctx->lock, flags);
5992 	return ret;
5993 }
5994 
perf_read_group(struct perf_event * event,u64 read_format,char __user * buf)5995 static int perf_read_group(struct perf_event *event,
5996 				   u64 read_format, char __user *buf)
5997 {
5998 	struct perf_event *leader = event->group_leader, *child;
5999 	struct perf_event_context *ctx = leader->ctx;
6000 	int ret;
6001 	u64 *values;
6002 
6003 	lockdep_assert_held(&ctx->mutex);
6004 
6005 	values = kzalloc(event->read_size, GFP_KERNEL);
6006 	if (!values)
6007 		return -ENOMEM;
6008 
6009 	values[0] = 1 + leader->nr_siblings;
6010 
6011 	mutex_lock(&leader->child_mutex);
6012 
6013 	ret = __perf_read_group_add(leader, read_format, values);
6014 	if (ret)
6015 		goto unlock;
6016 
6017 	list_for_each_entry(child, &leader->child_list, child_list) {
6018 		ret = __perf_read_group_add(child, read_format, values);
6019 		if (ret)
6020 			goto unlock;
6021 	}
6022 
6023 	mutex_unlock(&leader->child_mutex);
6024 
6025 	ret = event->read_size;
6026 	if (copy_to_user(buf, values, event->read_size))
6027 		ret = -EFAULT;
6028 	goto out;
6029 
6030 unlock:
6031 	mutex_unlock(&leader->child_mutex);
6032 out:
6033 	kfree(values);
6034 	return ret;
6035 }
6036 
perf_read_one(struct perf_event * event,u64 read_format,char __user * buf)6037 static int perf_read_one(struct perf_event *event,
6038 				 u64 read_format, char __user *buf)
6039 {
6040 	u64 enabled, running;
6041 	u64 values[5];
6042 	int n = 0;
6043 
6044 	values[n++] = __perf_event_read_value(event, &enabled, &running);
6045 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6046 		values[n++] = enabled;
6047 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6048 		values[n++] = running;
6049 	if (read_format & PERF_FORMAT_ID)
6050 		values[n++] = primary_event_id(event);
6051 	if (read_format & PERF_FORMAT_LOST)
6052 		values[n++] = atomic64_read(&event->lost_samples);
6053 
6054 	if (copy_to_user(buf, values, n * sizeof(u64)))
6055 		return -EFAULT;
6056 
6057 	return n * sizeof(u64);
6058 }
6059 
is_event_hup(struct perf_event * event)6060 static bool is_event_hup(struct perf_event *event)
6061 {
6062 	bool no_children;
6063 
6064 	if (event->state > PERF_EVENT_STATE_EXIT)
6065 		return false;
6066 
6067 	mutex_lock(&event->child_mutex);
6068 	no_children = list_empty(&event->child_list);
6069 	mutex_unlock(&event->child_mutex);
6070 	return no_children;
6071 }
6072 
6073 /*
6074  * Read the performance event - simple non blocking version for now
6075  */
6076 static ssize_t
__perf_read(struct perf_event * event,char __user * buf,size_t count)6077 __perf_read(struct perf_event *event, char __user *buf, size_t count)
6078 {
6079 	u64 read_format = event->attr.read_format;
6080 	int ret;
6081 
6082 	/*
6083 	 * Return end-of-file for a read on an event that is in
6084 	 * error state (i.e. because it was pinned but it couldn't be
6085 	 * scheduled on to the CPU at some point).
6086 	 */
6087 	if (event->state == PERF_EVENT_STATE_ERROR)
6088 		return 0;
6089 
6090 	if (count < event->read_size)
6091 		return -ENOSPC;
6092 
6093 	WARN_ON_ONCE(event->ctx->parent_ctx);
6094 	if (read_format & PERF_FORMAT_GROUP)
6095 		ret = perf_read_group(event, read_format, buf);
6096 	else
6097 		ret = perf_read_one(event, read_format, buf);
6098 
6099 	return ret;
6100 }
6101 
6102 static ssize_t
perf_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)6103 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
6104 {
6105 	struct perf_event *event = file->private_data;
6106 	struct perf_event_context *ctx;
6107 	int ret;
6108 
6109 	ret = security_perf_event_read(event);
6110 	if (ret)
6111 		return ret;
6112 
6113 	ctx = perf_event_ctx_lock(event);
6114 	ret = __perf_read(event, buf, count);
6115 	perf_event_ctx_unlock(event, ctx);
6116 
6117 	return ret;
6118 }
6119 
perf_poll(struct file * file,poll_table * wait)6120 static __poll_t perf_poll(struct file *file, poll_table *wait)
6121 {
6122 	struct perf_event *event = file->private_data;
6123 	struct perf_buffer *rb;
6124 	__poll_t events = EPOLLHUP;
6125 
6126 	if (event->state <= PERF_EVENT_STATE_REVOKED)
6127 		return EPOLLERR;
6128 
6129 	poll_wait(file, &event->waitq, wait);
6130 
6131 	if (event->state <= PERF_EVENT_STATE_REVOKED)
6132 		return EPOLLERR;
6133 
6134 	if (is_event_hup(event))
6135 		return events;
6136 
6137 	if (unlikely(READ_ONCE(event->state) == PERF_EVENT_STATE_ERROR &&
6138 		     event->attr.pinned))
6139 		return EPOLLERR;
6140 
6141 	/*
6142 	 * Pin the event->rb by taking event->mmap_mutex; otherwise
6143 	 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
6144 	 */
6145 	mutex_lock(&event->mmap_mutex);
6146 	rb = event->rb;
6147 	if (rb)
6148 		events = atomic_xchg(&rb->poll, 0);
6149 	mutex_unlock(&event->mmap_mutex);
6150 	return events;
6151 }
6152 
_perf_event_reset(struct perf_event * event)6153 static void _perf_event_reset(struct perf_event *event)
6154 {
6155 	(void)perf_event_read(event, false);
6156 	local64_set(&event->count, 0);
6157 	perf_event_update_userpage(event);
6158 }
6159 
6160 /* Assume it's not an event with inherit set. */
perf_event_pause(struct perf_event * event,bool reset)6161 u64 perf_event_pause(struct perf_event *event, bool reset)
6162 {
6163 	struct perf_event_context *ctx;
6164 	u64 count;
6165 
6166 	ctx = perf_event_ctx_lock(event);
6167 	WARN_ON_ONCE(event->attr.inherit);
6168 	_perf_event_disable(event);
6169 	count = local64_read(&event->count);
6170 	if (reset)
6171 		local64_set(&event->count, 0);
6172 	perf_event_ctx_unlock(event, ctx);
6173 
6174 	return count;
6175 }
6176 EXPORT_SYMBOL_GPL(perf_event_pause);
6177 
6178 /*
6179  * Holding the top-level event's child_mutex means that any
6180  * descendant process that has inherited this event will block
6181  * in perf_event_exit_event() if it goes to exit, thus satisfying the
6182  * task existence requirements of perf_event_enable/disable.
6183  */
perf_event_for_each_child(struct perf_event * event,void (* func)(struct perf_event *))6184 static void perf_event_for_each_child(struct perf_event *event,
6185 					void (*func)(struct perf_event *))
6186 {
6187 	struct perf_event *child;
6188 
6189 	WARN_ON_ONCE(event->ctx->parent_ctx);
6190 
6191 	mutex_lock(&event->child_mutex);
6192 	func(event);
6193 	list_for_each_entry(child, &event->child_list, child_list)
6194 		func(child);
6195 	mutex_unlock(&event->child_mutex);
6196 }
6197 
perf_event_for_each(struct perf_event * event,void (* func)(struct perf_event *))6198 static void perf_event_for_each(struct perf_event *event,
6199 				  void (*func)(struct perf_event *))
6200 {
6201 	struct perf_event_context *ctx = event->ctx;
6202 	struct perf_event *sibling;
6203 
6204 	lockdep_assert_held(&ctx->mutex);
6205 
6206 	event = event->group_leader;
6207 
6208 	perf_event_for_each_child(event, func);
6209 	for_each_sibling_event(sibling, event)
6210 		perf_event_for_each_child(sibling, func);
6211 }
6212 
__perf_event_period(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)6213 static void __perf_event_period(struct perf_event *event,
6214 				struct perf_cpu_context *cpuctx,
6215 				struct perf_event_context *ctx,
6216 				void *info)
6217 {
6218 	u64 value = *((u64 *)info);
6219 	bool active;
6220 
6221 	if (event->attr.freq) {
6222 		event->attr.sample_freq = value;
6223 	} else {
6224 		event->attr.sample_period = value;
6225 		event->hw.sample_period = value;
6226 	}
6227 
6228 	active = (event->state == PERF_EVENT_STATE_ACTIVE);
6229 	if (active) {
6230 		perf_pmu_disable(event->pmu);
6231 		event->pmu->stop(event, PERF_EF_UPDATE);
6232 	}
6233 
6234 	local64_set(&event->hw.period_left, 0);
6235 
6236 	if (active) {
6237 		event->pmu->start(event, PERF_EF_RELOAD);
6238 		/*
6239 		 * Once the period is force-reset, the event starts immediately.
6240 		 * But the event/group could be throttled. Unthrottle the
6241 		 * event/group now to avoid the next tick trying to unthrottle
6242 		 * while we already re-started the event/group.
6243 		 */
6244 		if (event->hw.interrupts == MAX_INTERRUPTS)
6245 			perf_event_unthrottle_group(event, true);
6246 		perf_pmu_enable(event->pmu);
6247 	}
6248 }
6249 
perf_event_check_period(struct perf_event * event,u64 value)6250 static int perf_event_check_period(struct perf_event *event, u64 value)
6251 {
6252 	return event->pmu->check_period(event, value);
6253 }
6254 
_perf_event_period(struct perf_event * event,u64 value)6255 static int _perf_event_period(struct perf_event *event, u64 value)
6256 {
6257 	if (!is_sampling_event(event))
6258 		return -EINVAL;
6259 
6260 	if (!value)
6261 		return -EINVAL;
6262 
6263 	if (event->attr.freq) {
6264 		if (value > sysctl_perf_event_sample_rate)
6265 			return -EINVAL;
6266 	} else {
6267 		if (perf_event_check_period(event, value))
6268 			return -EINVAL;
6269 		if (value & (1ULL << 63))
6270 			return -EINVAL;
6271 	}
6272 
6273 	event_function_call(event, __perf_event_period, &value);
6274 
6275 	return 0;
6276 }
6277 
perf_event_period(struct perf_event * event,u64 value)6278 int perf_event_period(struct perf_event *event, u64 value)
6279 {
6280 	struct perf_event_context *ctx;
6281 	int ret;
6282 
6283 	ctx = perf_event_ctx_lock(event);
6284 	ret = _perf_event_period(event, value);
6285 	perf_event_ctx_unlock(event, ctx);
6286 
6287 	return ret;
6288 }
6289 EXPORT_SYMBOL_GPL(perf_event_period);
6290 
6291 static const struct file_operations perf_fops;
6292 
is_perf_file(struct fd f)6293 static inline bool is_perf_file(struct fd f)
6294 {
6295 	return !fd_empty(f) && fd_file(f)->f_op == &perf_fops;
6296 }
6297 
6298 static int perf_event_set_output(struct perf_event *event,
6299 				 struct perf_event *output_event);
6300 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
6301 static int perf_copy_attr(struct perf_event_attr __user *uattr,
6302 			  struct perf_event_attr *attr);
6303 static int __perf_event_set_bpf_prog(struct perf_event *event,
6304 				     struct bpf_prog *prog,
6305 				     u64 bpf_cookie);
6306 
_perf_ioctl(struct perf_event * event,unsigned int cmd,unsigned long arg)6307 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
6308 {
6309 	void (*func)(struct perf_event *);
6310 	u32 flags = arg;
6311 
6312 	if (event->state <= PERF_EVENT_STATE_REVOKED)
6313 		return -ENODEV;
6314 
6315 	switch (cmd) {
6316 	case PERF_EVENT_IOC_ENABLE:
6317 		func = _perf_event_enable;
6318 		break;
6319 	case PERF_EVENT_IOC_DISABLE:
6320 		func = _perf_event_disable;
6321 		break;
6322 	case PERF_EVENT_IOC_RESET:
6323 		func = _perf_event_reset;
6324 		break;
6325 
6326 	case PERF_EVENT_IOC_REFRESH:
6327 		return _perf_event_refresh(event, arg);
6328 
6329 	case PERF_EVENT_IOC_PERIOD:
6330 	{
6331 		u64 value;
6332 
6333 		if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
6334 			return -EFAULT;
6335 
6336 		return _perf_event_period(event, value);
6337 	}
6338 	case PERF_EVENT_IOC_ID:
6339 	{
6340 		u64 id = primary_event_id(event);
6341 
6342 		if (copy_to_user((void __user *)arg, &id, sizeof(id)))
6343 			return -EFAULT;
6344 		return 0;
6345 	}
6346 
6347 	case PERF_EVENT_IOC_SET_OUTPUT:
6348 	{
6349 		CLASS(fd, output)(arg);	     // arg == -1 => empty
6350 		struct perf_event *output_event = NULL;
6351 		if (arg != -1) {
6352 			if (!is_perf_file(output))
6353 				return -EBADF;
6354 			output_event = fd_file(output)->private_data;
6355 		}
6356 		return perf_event_set_output(event, output_event);
6357 	}
6358 
6359 	case PERF_EVENT_IOC_SET_FILTER:
6360 		return perf_event_set_filter(event, (void __user *)arg);
6361 
6362 	case PERF_EVENT_IOC_SET_BPF:
6363 	{
6364 		struct bpf_prog *prog;
6365 		int err;
6366 
6367 		prog = bpf_prog_get(arg);
6368 		if (IS_ERR(prog))
6369 			return PTR_ERR(prog);
6370 
6371 		err = __perf_event_set_bpf_prog(event, prog, 0);
6372 		if (err) {
6373 			bpf_prog_put(prog);
6374 			return err;
6375 		}
6376 
6377 		return 0;
6378 	}
6379 
6380 	case PERF_EVENT_IOC_PAUSE_OUTPUT: {
6381 		struct perf_buffer *rb;
6382 
6383 		rcu_read_lock();
6384 		rb = rcu_dereference(event->rb);
6385 		if (!rb || !rb->nr_pages) {
6386 			rcu_read_unlock();
6387 			return -EINVAL;
6388 		}
6389 		rb_toggle_paused(rb, !!arg);
6390 		rcu_read_unlock();
6391 		return 0;
6392 	}
6393 
6394 	case PERF_EVENT_IOC_QUERY_BPF:
6395 		return perf_event_query_prog_array(event, (void __user *)arg);
6396 
6397 	case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
6398 		struct perf_event_attr new_attr;
6399 		int err = perf_copy_attr((struct perf_event_attr __user *)arg,
6400 					 &new_attr);
6401 
6402 		if (err)
6403 			return err;
6404 
6405 		return perf_event_modify_attr(event,  &new_attr);
6406 	}
6407 	default:
6408 		return -ENOTTY;
6409 	}
6410 
6411 	if (flags & PERF_IOC_FLAG_GROUP)
6412 		perf_event_for_each(event, func);
6413 	else
6414 		perf_event_for_each_child(event, func);
6415 
6416 	return 0;
6417 }
6418 
perf_ioctl(struct file * file,unsigned int cmd,unsigned long arg)6419 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
6420 {
6421 	struct perf_event *event = file->private_data;
6422 	struct perf_event_context *ctx;
6423 	long ret;
6424 
6425 	/* Treat ioctl like writes as it is likely a mutating operation. */
6426 	ret = security_perf_event_write(event);
6427 	if (ret)
6428 		return ret;
6429 
6430 	ctx = perf_event_ctx_lock(event);
6431 	ret = _perf_ioctl(event, cmd, arg);
6432 	perf_event_ctx_unlock(event, ctx);
6433 
6434 	return ret;
6435 }
6436 
6437 #ifdef CONFIG_COMPAT
perf_compat_ioctl(struct file * file,unsigned int cmd,unsigned long arg)6438 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
6439 				unsigned long arg)
6440 {
6441 	switch (_IOC_NR(cmd)) {
6442 	case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
6443 	case _IOC_NR(PERF_EVENT_IOC_ID):
6444 	case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
6445 	case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
6446 		/* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
6447 		if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
6448 			cmd &= ~IOCSIZE_MASK;
6449 			cmd |= sizeof(void *) << IOCSIZE_SHIFT;
6450 		}
6451 		break;
6452 	}
6453 	return perf_ioctl(file, cmd, arg);
6454 }
6455 #else
6456 # define perf_compat_ioctl NULL
6457 #endif
6458 
perf_event_task_enable(void)6459 int perf_event_task_enable(void)
6460 {
6461 	struct perf_event_context *ctx;
6462 	struct perf_event *event;
6463 
6464 	mutex_lock(&current->perf_event_mutex);
6465 	list_for_each_entry(event, &current->perf_event_list, owner_entry) {
6466 		ctx = perf_event_ctx_lock(event);
6467 		perf_event_for_each_child(event, _perf_event_enable);
6468 		perf_event_ctx_unlock(event, ctx);
6469 	}
6470 	mutex_unlock(&current->perf_event_mutex);
6471 
6472 	return 0;
6473 }
6474 
perf_event_task_disable(void)6475 int perf_event_task_disable(void)
6476 {
6477 	struct perf_event_context *ctx;
6478 	struct perf_event *event;
6479 
6480 	mutex_lock(&current->perf_event_mutex);
6481 	list_for_each_entry(event, &current->perf_event_list, owner_entry) {
6482 		ctx = perf_event_ctx_lock(event);
6483 		perf_event_for_each_child(event, _perf_event_disable);
6484 		perf_event_ctx_unlock(event, ctx);
6485 	}
6486 	mutex_unlock(&current->perf_event_mutex);
6487 
6488 	return 0;
6489 }
6490 
perf_event_index(struct perf_event * event)6491 static int perf_event_index(struct perf_event *event)
6492 {
6493 	if (event->hw.state & PERF_HES_STOPPED)
6494 		return 0;
6495 
6496 	if (event->state != PERF_EVENT_STATE_ACTIVE)
6497 		return 0;
6498 
6499 	return event->pmu->event_idx(event);
6500 }
6501 
perf_event_init_userpage(struct perf_event * event)6502 static void perf_event_init_userpage(struct perf_event *event)
6503 {
6504 	struct perf_event_mmap_page *userpg;
6505 	struct perf_buffer *rb;
6506 
6507 	rcu_read_lock();
6508 	rb = rcu_dereference(event->rb);
6509 	if (!rb)
6510 		goto unlock;
6511 
6512 	userpg = rb->user_page;
6513 
6514 	/* Allow new userspace to detect that bit 0 is deprecated */
6515 	userpg->cap_bit0_is_deprecated = 1;
6516 	userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
6517 	userpg->data_offset = PAGE_SIZE;
6518 	userpg->data_size = perf_data_size(rb);
6519 
6520 unlock:
6521 	rcu_read_unlock();
6522 }
6523 
arch_perf_update_userpage(struct perf_event * event,struct perf_event_mmap_page * userpg,u64 now)6524 void __weak arch_perf_update_userpage(
6525 	struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
6526 {
6527 }
6528 
6529 /*
6530  * Callers need to ensure there can be no nesting of this function, otherwise
6531  * the seqlock logic goes bad. We can not serialize this because the arch
6532  * code calls this from NMI context.
6533  */
perf_event_update_userpage(struct perf_event * event)6534 void perf_event_update_userpage(struct perf_event *event)
6535 {
6536 	struct perf_event_mmap_page *userpg;
6537 	struct perf_buffer *rb;
6538 	u64 enabled, running, now;
6539 
6540 	rcu_read_lock();
6541 	rb = rcu_dereference(event->rb);
6542 	if (!rb)
6543 		goto unlock;
6544 
6545 	/*
6546 	 * compute total_time_enabled, total_time_running
6547 	 * based on snapshot values taken when the event
6548 	 * was last scheduled in.
6549 	 *
6550 	 * we cannot simply called update_context_time()
6551 	 * because of locking issue as we can be called in
6552 	 * NMI context
6553 	 */
6554 	calc_timer_values(event, &now, &enabled, &running);
6555 
6556 	userpg = rb->user_page;
6557 	/*
6558 	 * Disable preemption to guarantee consistent time stamps are stored to
6559 	 * the user page.
6560 	 */
6561 	preempt_disable();
6562 	++userpg->lock;
6563 	barrier();
6564 	userpg->index = perf_event_index(event);
6565 	userpg->offset = perf_event_count(event, false);
6566 	if (userpg->index)
6567 		userpg->offset -= local64_read(&event->hw.prev_count);
6568 
6569 	userpg->time_enabled = enabled +
6570 			atomic64_read(&event->child_total_time_enabled);
6571 
6572 	userpg->time_running = running +
6573 			atomic64_read(&event->child_total_time_running);
6574 
6575 	arch_perf_update_userpage(event, userpg, now);
6576 
6577 	barrier();
6578 	++userpg->lock;
6579 	preempt_enable();
6580 unlock:
6581 	rcu_read_unlock();
6582 }
6583 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
6584 
ring_buffer_attach(struct perf_event * event,struct perf_buffer * rb)6585 static void ring_buffer_attach(struct perf_event *event,
6586 			       struct perf_buffer *rb)
6587 {
6588 	struct perf_buffer *old_rb = NULL;
6589 	unsigned long flags;
6590 
6591 	WARN_ON_ONCE(event->parent);
6592 
6593 	if (event->rb) {
6594 		/*
6595 		 * Should be impossible, we set this when removing
6596 		 * event->rb_entry and wait/clear when adding event->rb_entry.
6597 		 */
6598 		WARN_ON_ONCE(event->rcu_pending);
6599 
6600 		old_rb = event->rb;
6601 		spin_lock_irqsave(&old_rb->event_lock, flags);
6602 		list_del_rcu(&event->rb_entry);
6603 		spin_unlock_irqrestore(&old_rb->event_lock, flags);
6604 
6605 		event->rcu_batches = get_state_synchronize_rcu();
6606 		event->rcu_pending = 1;
6607 	}
6608 
6609 	if (rb) {
6610 		if (event->rcu_pending) {
6611 			cond_synchronize_rcu(event->rcu_batches);
6612 			event->rcu_pending = 0;
6613 		}
6614 
6615 		spin_lock_irqsave(&rb->event_lock, flags);
6616 		list_add_rcu(&event->rb_entry, &rb->event_list);
6617 		spin_unlock_irqrestore(&rb->event_lock, flags);
6618 	}
6619 
6620 	/*
6621 	 * Avoid racing with perf_mmap_close(AUX): stop the event
6622 	 * before swizzling the event::rb pointer; if it's getting
6623 	 * unmapped, its aux_mmap_count will be 0 and it won't
6624 	 * restart. See the comment in __perf_pmu_output_stop().
6625 	 *
6626 	 * Data will inevitably be lost when set_output is done in
6627 	 * mid-air, but then again, whoever does it like this is
6628 	 * not in for the data anyway.
6629 	 */
6630 	if (has_aux(event))
6631 		perf_event_stop(event, 0);
6632 
6633 	rcu_assign_pointer(event->rb, rb);
6634 
6635 	if (old_rb) {
6636 		ring_buffer_put(old_rb);
6637 		/*
6638 		 * Since we detached before setting the new rb, so that we
6639 		 * could attach the new rb, we could have missed a wakeup.
6640 		 * Provide it now.
6641 		 */
6642 		wake_up_all(&event->waitq);
6643 	}
6644 }
6645 
ring_buffer_wakeup(struct perf_event * event)6646 static void ring_buffer_wakeup(struct perf_event *event)
6647 {
6648 	struct perf_buffer *rb;
6649 
6650 	if (event->parent)
6651 		event = event->parent;
6652 
6653 	rcu_read_lock();
6654 	rb = rcu_dereference(event->rb);
6655 	if (rb) {
6656 		list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
6657 			wake_up_all(&event->waitq);
6658 	}
6659 	rcu_read_unlock();
6660 }
6661 
ring_buffer_get(struct perf_event * event)6662 struct perf_buffer *ring_buffer_get(struct perf_event *event)
6663 {
6664 	struct perf_buffer *rb;
6665 
6666 	if (event->parent)
6667 		event = event->parent;
6668 
6669 	rcu_read_lock();
6670 	rb = rcu_dereference(event->rb);
6671 	if (rb) {
6672 		if (!refcount_inc_not_zero(&rb->refcount))
6673 			rb = NULL;
6674 	}
6675 	rcu_read_unlock();
6676 
6677 	return rb;
6678 }
6679 
ring_buffer_put(struct perf_buffer * rb)6680 void ring_buffer_put(struct perf_buffer *rb)
6681 {
6682 	if (!refcount_dec_and_test(&rb->refcount))
6683 		return;
6684 
6685 	WARN_ON_ONCE(!list_empty(&rb->event_list));
6686 
6687 	call_rcu(&rb->rcu_head, rb_free_rcu);
6688 }
6689 
6690 typedef void (*mapped_f)(struct perf_event *event, struct mm_struct *mm);
6691 
6692 #define get_mapped(event, func)			\
6693 ({	struct pmu *pmu;			\
6694 	mapped_f f = NULL;			\
6695 	guard(rcu)();				\
6696 	pmu = READ_ONCE(event->pmu);		\
6697 	if (pmu)				\
6698 		f = pmu->func;			\
6699 	f;					\
6700 })
6701 
perf_mmap_open(struct vm_area_struct * vma)6702 static void perf_mmap_open(struct vm_area_struct *vma)
6703 {
6704 	struct perf_event *event = vma->vm_file->private_data;
6705 	mapped_f mapped = get_mapped(event, event_mapped);
6706 
6707 	atomic_inc(&event->mmap_count);
6708 	atomic_inc(&event->rb->mmap_count);
6709 
6710 	if (vma->vm_pgoff)
6711 		atomic_inc(&event->rb->aux_mmap_count);
6712 
6713 	if (mapped)
6714 		mapped(event, vma->vm_mm);
6715 }
6716 
6717 static void perf_pmu_output_stop(struct perf_event *event);
6718 
6719 /*
6720  * A buffer can be mmap()ed multiple times; either directly through the same
6721  * event, or through other events by use of perf_event_set_output().
6722  *
6723  * In order to undo the VM accounting done by perf_mmap() we need to destroy
6724  * the buffer here, where we still have a VM context. This means we need
6725  * to detach all events redirecting to us.
6726  */
perf_mmap_close(struct vm_area_struct * vma)6727 static void perf_mmap_close(struct vm_area_struct *vma)
6728 {
6729 	struct perf_event *event = vma->vm_file->private_data;
6730 	mapped_f unmapped = get_mapped(event, event_unmapped);
6731 	struct perf_buffer *rb = ring_buffer_get(event);
6732 	struct user_struct *mmap_user = rb->mmap_user;
6733 	int mmap_locked = rb->mmap_locked;
6734 	unsigned long size = perf_data_size(rb);
6735 	bool detach_rest = false;
6736 
6737 	/* FIXIES vs perf_pmu_unregister() */
6738 	if (unmapped)
6739 		unmapped(event, vma->vm_mm);
6740 
6741 	/*
6742 	 * The AUX buffer is strictly a sub-buffer, serialize using aux_mutex
6743 	 * to avoid complications.
6744 	 */
6745 	if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
6746 	    atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &rb->aux_mutex)) {
6747 		/*
6748 		 * Stop all AUX events that are writing to this buffer,
6749 		 * so that we can free its AUX pages and corresponding PMU
6750 		 * data. Note that after rb::aux_mmap_count dropped to zero,
6751 		 * they won't start any more (see perf_aux_output_begin()).
6752 		 */
6753 		perf_pmu_output_stop(event);
6754 
6755 		/* now it's safe to free the pages */
6756 		atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
6757 		atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
6758 
6759 		/* this has to be the last one */
6760 		rb_free_aux(rb);
6761 		WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
6762 
6763 		mutex_unlock(&rb->aux_mutex);
6764 	}
6765 
6766 	if (atomic_dec_and_test(&rb->mmap_count))
6767 		detach_rest = true;
6768 
6769 	if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
6770 		goto out_put;
6771 
6772 	ring_buffer_attach(event, NULL);
6773 	mutex_unlock(&event->mmap_mutex);
6774 
6775 	/* If there's still other mmap()s of this buffer, we're done. */
6776 	if (!detach_rest)
6777 		goto out_put;
6778 
6779 	/*
6780 	 * No other mmap()s, detach from all other events that might redirect
6781 	 * into the now unreachable buffer. Somewhat complicated by the
6782 	 * fact that rb::event_lock otherwise nests inside mmap_mutex.
6783 	 */
6784 again:
6785 	rcu_read_lock();
6786 	list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
6787 		if (!atomic_long_inc_not_zero(&event->refcount)) {
6788 			/*
6789 			 * This event is en-route to free_event() which will
6790 			 * detach it and remove it from the list.
6791 			 */
6792 			continue;
6793 		}
6794 		rcu_read_unlock();
6795 
6796 		mutex_lock(&event->mmap_mutex);
6797 		/*
6798 		 * Check we didn't race with perf_event_set_output() which can
6799 		 * swizzle the rb from under us while we were waiting to
6800 		 * acquire mmap_mutex.
6801 		 *
6802 		 * If we find a different rb; ignore this event, a next
6803 		 * iteration will no longer find it on the list. We have to
6804 		 * still restart the iteration to make sure we're not now
6805 		 * iterating the wrong list.
6806 		 */
6807 		if (event->rb == rb)
6808 			ring_buffer_attach(event, NULL);
6809 
6810 		mutex_unlock(&event->mmap_mutex);
6811 		put_event(event);
6812 
6813 		/*
6814 		 * Restart the iteration; either we're on the wrong list or
6815 		 * destroyed its integrity by doing a deletion.
6816 		 */
6817 		goto again;
6818 	}
6819 	rcu_read_unlock();
6820 
6821 	/*
6822 	 * It could be there's still a few 0-ref events on the list; they'll
6823 	 * get cleaned up by free_event() -- they'll also still have their
6824 	 * ref on the rb and will free it whenever they are done with it.
6825 	 *
6826 	 * Aside from that, this buffer is 'fully' detached and unmapped,
6827 	 * undo the VM accounting.
6828 	 */
6829 
6830 	atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
6831 			&mmap_user->locked_vm);
6832 	atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
6833 	free_uid(mmap_user);
6834 
6835 out_put:
6836 	ring_buffer_put(rb); /* could be last */
6837 }
6838 
perf_mmap_pfn_mkwrite(struct vm_fault * vmf)6839 static vm_fault_t perf_mmap_pfn_mkwrite(struct vm_fault *vmf)
6840 {
6841 	/* The first page is the user control page, others are read-only. */
6842 	return vmf->pgoff == 0 ? 0 : VM_FAULT_SIGBUS;
6843 }
6844 
6845 static const struct vm_operations_struct perf_mmap_vmops = {
6846 	.open		= perf_mmap_open,
6847 	.close		= perf_mmap_close, /* non mergeable */
6848 	.pfn_mkwrite	= perf_mmap_pfn_mkwrite,
6849 };
6850 
map_range(struct perf_buffer * rb,struct vm_area_struct * vma)6851 static int map_range(struct perf_buffer *rb, struct vm_area_struct *vma)
6852 {
6853 	unsigned long nr_pages = vma_pages(vma);
6854 	int err = 0;
6855 	unsigned long pagenum;
6856 
6857 	/*
6858 	 * We map this as a VM_PFNMAP VMA.
6859 	 *
6860 	 * This is not ideal as this is designed broadly for mappings of PFNs
6861 	 * referencing memory-mapped I/O ranges or non-system RAM i.e. for which
6862 	 * !pfn_valid(pfn).
6863 	 *
6864 	 * We are mapping kernel-allocated memory (memory we manage ourselves)
6865 	 * which would more ideally be mapped using vm_insert_page() or a
6866 	 * similar mechanism, that is as a VM_MIXEDMAP mapping.
6867 	 *
6868 	 * However this won't work here, because:
6869 	 *
6870 	 * 1. It uses vma->vm_page_prot, but this field has not been completely
6871 	 *    setup at the point of the f_op->mmp() hook, so we are unable to
6872 	 *    indicate that this should be mapped CoW in order that the
6873 	 *    mkwrite() hook can be invoked to make the first page R/W and the
6874 	 *    rest R/O as desired.
6875 	 *
6876 	 * 2. Anything other than a VM_PFNMAP of valid PFNs will result in
6877 	 *    vm_normal_page() returning a struct page * pointer, which means
6878 	 *    vm_ops->page_mkwrite() will be invoked rather than
6879 	 *    vm_ops->pfn_mkwrite(), and this means we have to set page->mapping
6880 	 *    to work around retry logic in the fault handler, however this
6881 	 *    field is no longer allowed to be used within struct page.
6882 	 *
6883 	 * 3. Having a struct page * made available in the fault logic also
6884 	 *    means that the page gets put on the rmap and becomes
6885 	 *    inappropriately accessible and subject to map and ref counting.
6886 	 *
6887 	 * Ideally we would have a mechanism that could explicitly express our
6888 	 * desires, but this is not currently the case, so we instead use
6889 	 * VM_PFNMAP.
6890 	 *
6891 	 * We manage the lifetime of these mappings with internal refcounts (see
6892 	 * perf_mmap_open() and perf_mmap_close()) so we ensure the lifetime of
6893 	 * this mapping is maintained correctly.
6894 	 */
6895 	for (pagenum = 0; pagenum < nr_pages; pagenum++) {
6896 		unsigned long va = vma->vm_start + PAGE_SIZE * pagenum;
6897 		struct page *page = perf_mmap_to_page(rb, vma->vm_pgoff + pagenum);
6898 
6899 		if (page == NULL) {
6900 			err = -EINVAL;
6901 			break;
6902 		}
6903 
6904 		/* Map readonly, perf_mmap_pfn_mkwrite() called on write fault. */
6905 		err = remap_pfn_range(vma, va, page_to_pfn(page), PAGE_SIZE,
6906 				      vm_get_page_prot(vma->vm_flags & ~VM_SHARED));
6907 		if (err)
6908 			break;
6909 	}
6910 
6911 #ifdef CONFIG_MMU
6912 	/* Clear any partial mappings on error. */
6913 	if (err)
6914 		zap_page_range_single(vma, vma->vm_start, nr_pages * PAGE_SIZE, NULL);
6915 #endif
6916 
6917 	return err;
6918 }
6919 
perf_mmap(struct file * file,struct vm_area_struct * vma)6920 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
6921 {
6922 	struct perf_event *event = file->private_data;
6923 	unsigned long user_locked, user_lock_limit;
6924 	struct user_struct *user = current_user();
6925 	struct mutex *aux_mutex = NULL;
6926 	struct perf_buffer *rb = NULL;
6927 	unsigned long locked, lock_limit;
6928 	unsigned long vma_size;
6929 	unsigned long nr_pages;
6930 	long user_extra = 0, extra = 0;
6931 	int ret, flags = 0;
6932 	mapped_f mapped;
6933 
6934 	/*
6935 	 * Don't allow mmap() of inherited per-task counters. This would
6936 	 * create a performance issue due to all children writing to the
6937 	 * same rb.
6938 	 */
6939 	if (event->cpu == -1 && event->attr.inherit)
6940 		return -EINVAL;
6941 
6942 	if (!(vma->vm_flags & VM_SHARED))
6943 		return -EINVAL;
6944 
6945 	ret = security_perf_event_read(event);
6946 	if (ret)
6947 		return ret;
6948 
6949 	vma_size = vma->vm_end - vma->vm_start;
6950 	nr_pages = vma_size / PAGE_SIZE;
6951 
6952 	if (nr_pages > INT_MAX)
6953 		return -ENOMEM;
6954 
6955 	if (vma_size != PAGE_SIZE * nr_pages)
6956 		return -EINVAL;
6957 
6958 	user_extra = nr_pages;
6959 
6960 	mutex_lock(&event->mmap_mutex);
6961 	ret = -EINVAL;
6962 
6963 	/*
6964 	 * This relies on __pmu_detach_event() taking mmap_mutex after marking
6965 	 * the event REVOKED. Either we observe the state, or __pmu_detach_event()
6966 	 * will detach the rb created here.
6967 	 */
6968 	if (event->state <= PERF_EVENT_STATE_REVOKED) {
6969 		ret = -ENODEV;
6970 		goto unlock;
6971 	}
6972 
6973 	if (vma->vm_pgoff == 0) {
6974 		nr_pages -= 1;
6975 
6976 		/*
6977 		 * If we have rb pages ensure they're a power-of-two number, so we
6978 		 * can do bitmasks instead of modulo.
6979 		 */
6980 		if (nr_pages != 0 && !is_power_of_2(nr_pages))
6981 			goto unlock;
6982 
6983 		WARN_ON_ONCE(event->ctx->parent_ctx);
6984 
6985 		if (event->rb) {
6986 			if (data_page_nr(event->rb) != nr_pages)
6987 				goto unlock;
6988 
6989 			if (atomic_inc_not_zero(&event->rb->mmap_count)) {
6990 				/*
6991 				 * Success -- managed to mmap() the same buffer
6992 				 * multiple times.
6993 				 */
6994 				ret = 0;
6995 				/* We need the rb to map pages. */
6996 				rb = event->rb;
6997 				goto unlock;
6998 			}
6999 
7000 			/*
7001 			 * Raced against perf_mmap_close()'s
7002 			 * atomic_dec_and_mutex_lock() remove the
7003 			 * event and continue as if !event->rb
7004 			 */
7005 			ring_buffer_attach(event, NULL);
7006 		}
7007 
7008 	} else {
7009 		/*
7010 		 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
7011 		 * mapped, all subsequent mappings should have the same size
7012 		 * and offset. Must be above the normal perf buffer.
7013 		 */
7014 		u64 aux_offset, aux_size;
7015 
7016 		rb = event->rb;
7017 		if (!rb)
7018 			goto aux_unlock;
7019 
7020 		aux_mutex = &rb->aux_mutex;
7021 		mutex_lock(aux_mutex);
7022 
7023 		aux_offset = READ_ONCE(rb->user_page->aux_offset);
7024 		aux_size = READ_ONCE(rb->user_page->aux_size);
7025 
7026 		if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
7027 			goto aux_unlock;
7028 
7029 		if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
7030 			goto aux_unlock;
7031 
7032 		/* already mapped with a different offset */
7033 		if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
7034 			goto aux_unlock;
7035 
7036 		if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
7037 			goto aux_unlock;
7038 
7039 		/* already mapped with a different size */
7040 		if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
7041 			goto aux_unlock;
7042 
7043 		if (!is_power_of_2(nr_pages))
7044 			goto aux_unlock;
7045 
7046 		if (!atomic_inc_not_zero(&rb->mmap_count))
7047 			goto aux_unlock;
7048 
7049 		if (rb_has_aux(rb)) {
7050 			atomic_inc(&rb->aux_mmap_count);
7051 			ret = 0;
7052 			goto unlock;
7053 		}
7054 
7055 		atomic_set(&rb->aux_mmap_count, 1);
7056 	}
7057 
7058 	user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
7059 
7060 	/*
7061 	 * Increase the limit linearly with more CPUs:
7062 	 */
7063 	user_lock_limit *= num_online_cpus();
7064 
7065 	user_locked = atomic_long_read(&user->locked_vm);
7066 
7067 	/*
7068 	 * sysctl_perf_event_mlock may have changed, so that
7069 	 *     user->locked_vm > user_lock_limit
7070 	 */
7071 	if (user_locked > user_lock_limit)
7072 		user_locked = user_lock_limit;
7073 	user_locked += user_extra;
7074 
7075 	if (user_locked > user_lock_limit) {
7076 		/*
7077 		 * charge locked_vm until it hits user_lock_limit;
7078 		 * charge the rest from pinned_vm
7079 		 */
7080 		extra = user_locked - user_lock_limit;
7081 		user_extra -= extra;
7082 	}
7083 
7084 	lock_limit = rlimit(RLIMIT_MEMLOCK);
7085 	lock_limit >>= PAGE_SHIFT;
7086 	locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
7087 
7088 	if ((locked > lock_limit) && perf_is_paranoid() &&
7089 		!capable(CAP_IPC_LOCK)) {
7090 		ret = -EPERM;
7091 		goto unlock;
7092 	}
7093 
7094 	WARN_ON(!rb && event->rb);
7095 
7096 	if (vma->vm_flags & VM_WRITE)
7097 		flags |= RING_BUFFER_WRITABLE;
7098 
7099 	if (!rb) {
7100 		rb = rb_alloc(nr_pages,
7101 			      event->attr.watermark ? event->attr.wakeup_watermark : 0,
7102 			      event->cpu, flags);
7103 
7104 		if (!rb) {
7105 			ret = -ENOMEM;
7106 			goto unlock;
7107 		}
7108 
7109 		atomic_set(&rb->mmap_count, 1);
7110 		rb->mmap_user = get_current_user();
7111 		rb->mmap_locked = extra;
7112 
7113 		ring_buffer_attach(event, rb);
7114 
7115 		perf_event_update_time(event);
7116 		perf_event_init_userpage(event);
7117 		perf_event_update_userpage(event);
7118 	} else {
7119 		ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
7120 				   event->attr.aux_watermark, flags);
7121 		if (!ret)
7122 			rb->aux_mmap_locked = extra;
7123 	}
7124 
7125 	ret = 0;
7126 
7127 unlock:
7128 	if (!ret) {
7129 		atomic_long_add(user_extra, &user->locked_vm);
7130 		atomic64_add(extra, &vma->vm_mm->pinned_vm);
7131 
7132 		atomic_inc(&event->mmap_count);
7133 	} else if (rb) {
7134 		atomic_dec(&rb->mmap_count);
7135 	}
7136 aux_unlock:
7137 	if (aux_mutex)
7138 		mutex_unlock(aux_mutex);
7139 	mutex_unlock(&event->mmap_mutex);
7140 
7141 	/*
7142 	 * Since pinned accounting is per vm we cannot allow fork() to copy our
7143 	 * vma.
7144 	 */
7145 	vm_flags_set(vma, VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP);
7146 	vma->vm_ops = &perf_mmap_vmops;
7147 
7148 	if (!ret)
7149 		ret = map_range(rb, vma);
7150 
7151 	mapped = get_mapped(event, event_mapped);
7152 	if (mapped)
7153 		mapped(event, vma->vm_mm);
7154 
7155 	return ret;
7156 }
7157 
perf_fasync(int fd,struct file * filp,int on)7158 static int perf_fasync(int fd, struct file *filp, int on)
7159 {
7160 	struct inode *inode = file_inode(filp);
7161 	struct perf_event *event = filp->private_data;
7162 	int retval;
7163 
7164 	if (event->state <= PERF_EVENT_STATE_REVOKED)
7165 		return -ENODEV;
7166 
7167 	inode_lock(inode);
7168 	retval = fasync_helper(fd, filp, on, &event->fasync);
7169 	inode_unlock(inode);
7170 
7171 	if (retval < 0)
7172 		return retval;
7173 
7174 	return 0;
7175 }
7176 
7177 static const struct file_operations perf_fops = {
7178 	.release		= perf_release,
7179 	.read			= perf_read,
7180 	.poll			= perf_poll,
7181 	.unlocked_ioctl		= perf_ioctl,
7182 	.compat_ioctl		= perf_compat_ioctl,
7183 	.mmap			= perf_mmap,
7184 	.fasync			= perf_fasync,
7185 };
7186 
7187 /*
7188  * Perf event wakeup
7189  *
7190  * If there's data, ensure we set the poll() state and publish everything
7191  * to user-space before waking everybody up.
7192  */
7193 
perf_event_wakeup(struct perf_event * event)7194 void perf_event_wakeup(struct perf_event *event)
7195 {
7196 	ring_buffer_wakeup(event);
7197 
7198 	if (event->pending_kill) {
7199 		kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
7200 		event->pending_kill = 0;
7201 	}
7202 }
7203 
perf_sigtrap(struct perf_event * event)7204 static void perf_sigtrap(struct perf_event *event)
7205 {
7206 	/*
7207 	 * We'd expect this to only occur if the irq_work is delayed and either
7208 	 * ctx->task or current has changed in the meantime. This can be the
7209 	 * case on architectures that do not implement arch_irq_work_raise().
7210 	 */
7211 	if (WARN_ON_ONCE(event->ctx->task != current))
7212 		return;
7213 
7214 	/*
7215 	 * Both perf_pending_task() and perf_pending_irq() can race with the
7216 	 * task exiting.
7217 	 */
7218 	if (current->flags & PF_EXITING)
7219 		return;
7220 
7221 	send_sig_perf((void __user *)event->pending_addr,
7222 		      event->orig_type, event->attr.sig_data);
7223 }
7224 
7225 /*
7226  * Deliver the pending work in-event-context or follow the context.
7227  */
__perf_pending_disable(struct perf_event * event)7228 static void __perf_pending_disable(struct perf_event *event)
7229 {
7230 	int cpu = READ_ONCE(event->oncpu);
7231 
7232 	/*
7233 	 * If the event isn't running; we done. event_sched_out() will have
7234 	 * taken care of things.
7235 	 */
7236 	if (cpu < 0)
7237 		return;
7238 
7239 	/*
7240 	 * Yay, we hit home and are in the context of the event.
7241 	 */
7242 	if (cpu == smp_processor_id()) {
7243 		if (event->pending_disable) {
7244 			event->pending_disable = 0;
7245 			perf_event_disable_local(event);
7246 		}
7247 		return;
7248 	}
7249 
7250 	/*
7251 	 *  CPU-A			CPU-B
7252 	 *
7253 	 *  perf_event_disable_inatomic()
7254 	 *    @pending_disable = CPU-A;
7255 	 *    irq_work_queue();
7256 	 *
7257 	 *  sched-out
7258 	 *    @pending_disable = -1;
7259 	 *
7260 	 *				sched-in
7261 	 *				perf_event_disable_inatomic()
7262 	 *				  @pending_disable = CPU-B;
7263 	 *				  irq_work_queue(); // FAILS
7264 	 *
7265 	 *  irq_work_run()
7266 	 *    perf_pending_disable()
7267 	 *
7268 	 * But the event runs on CPU-B and wants disabling there.
7269 	 */
7270 	irq_work_queue_on(&event->pending_disable_irq, cpu);
7271 }
7272 
perf_pending_disable(struct irq_work * entry)7273 static void perf_pending_disable(struct irq_work *entry)
7274 {
7275 	struct perf_event *event = container_of(entry, struct perf_event, pending_disable_irq);
7276 	int rctx;
7277 
7278 	/*
7279 	 * If we 'fail' here, that's OK, it means recursion is already disabled
7280 	 * and we won't recurse 'further'.
7281 	 */
7282 	rctx = perf_swevent_get_recursion_context();
7283 	__perf_pending_disable(event);
7284 	if (rctx >= 0)
7285 		perf_swevent_put_recursion_context(rctx);
7286 }
7287 
perf_pending_irq(struct irq_work * entry)7288 static void perf_pending_irq(struct irq_work *entry)
7289 {
7290 	struct perf_event *event = container_of(entry, struct perf_event, pending_irq);
7291 	int rctx;
7292 
7293 	/*
7294 	 * If we 'fail' here, that's OK, it means recursion is already disabled
7295 	 * and we won't recurse 'further'.
7296 	 */
7297 	rctx = perf_swevent_get_recursion_context();
7298 
7299 	/*
7300 	 * The wakeup isn't bound to the context of the event -- it can happen
7301 	 * irrespective of where the event is.
7302 	 */
7303 	if (event->pending_wakeup) {
7304 		event->pending_wakeup = 0;
7305 		perf_event_wakeup(event);
7306 	}
7307 
7308 	if (rctx >= 0)
7309 		perf_swevent_put_recursion_context(rctx);
7310 }
7311 
perf_pending_task(struct callback_head * head)7312 static void perf_pending_task(struct callback_head *head)
7313 {
7314 	struct perf_event *event = container_of(head, struct perf_event, pending_task);
7315 	int rctx;
7316 
7317 	/*
7318 	 * If we 'fail' here, that's OK, it means recursion is already disabled
7319 	 * and we won't recurse 'further'.
7320 	 */
7321 	rctx = perf_swevent_get_recursion_context();
7322 
7323 	if (event->pending_work) {
7324 		event->pending_work = 0;
7325 		perf_sigtrap(event);
7326 		local_dec(&event->ctx->nr_no_switch_fast);
7327 	}
7328 	put_event(event);
7329 
7330 	if (rctx >= 0)
7331 		perf_swevent_put_recursion_context(rctx);
7332 }
7333 
7334 #ifdef CONFIG_GUEST_PERF_EVENTS
7335 struct perf_guest_info_callbacks __rcu *perf_guest_cbs;
7336 
7337 DEFINE_STATIC_CALL_RET0(__perf_guest_state, *perf_guest_cbs->state);
7338 DEFINE_STATIC_CALL_RET0(__perf_guest_get_ip, *perf_guest_cbs->get_ip);
7339 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr);
7340 
perf_register_guest_info_callbacks(struct perf_guest_info_callbacks * cbs)7341 void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
7342 {
7343 	if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs)))
7344 		return;
7345 
7346 	rcu_assign_pointer(perf_guest_cbs, cbs);
7347 	static_call_update(__perf_guest_state, cbs->state);
7348 	static_call_update(__perf_guest_get_ip, cbs->get_ip);
7349 
7350 	/* Implementing ->handle_intel_pt_intr is optional. */
7351 	if (cbs->handle_intel_pt_intr)
7352 		static_call_update(__perf_guest_handle_intel_pt_intr,
7353 				   cbs->handle_intel_pt_intr);
7354 }
7355 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
7356 
perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks * cbs)7357 void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
7358 {
7359 	if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs) != cbs))
7360 		return;
7361 
7362 	rcu_assign_pointer(perf_guest_cbs, NULL);
7363 	static_call_update(__perf_guest_state, (void *)&__static_call_return0);
7364 	static_call_update(__perf_guest_get_ip, (void *)&__static_call_return0);
7365 	static_call_update(__perf_guest_handle_intel_pt_intr,
7366 			   (void *)&__static_call_return0);
7367 	synchronize_rcu();
7368 }
7369 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
7370 #endif
7371 
should_sample_guest(struct perf_event * event)7372 static bool should_sample_guest(struct perf_event *event)
7373 {
7374 	return !event->attr.exclude_guest && perf_guest_state();
7375 }
7376 
perf_misc_flags(struct perf_event * event,struct pt_regs * regs)7377 unsigned long perf_misc_flags(struct perf_event *event,
7378 			      struct pt_regs *regs)
7379 {
7380 	if (should_sample_guest(event))
7381 		return perf_arch_guest_misc_flags(regs);
7382 
7383 	return perf_arch_misc_flags(regs);
7384 }
7385 
perf_instruction_pointer(struct perf_event * event,struct pt_regs * regs)7386 unsigned long perf_instruction_pointer(struct perf_event *event,
7387 				       struct pt_regs *regs)
7388 {
7389 	if (should_sample_guest(event))
7390 		return perf_guest_get_ip();
7391 
7392 	return perf_arch_instruction_pointer(regs);
7393 }
7394 
7395 static void
perf_output_sample_regs(struct perf_output_handle * handle,struct pt_regs * regs,u64 mask)7396 perf_output_sample_regs(struct perf_output_handle *handle,
7397 			struct pt_regs *regs, u64 mask)
7398 {
7399 	int bit;
7400 	DECLARE_BITMAP(_mask, 64);
7401 
7402 	bitmap_from_u64(_mask, mask);
7403 	for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
7404 		u64 val;
7405 
7406 		val = perf_reg_value(regs, bit);
7407 		perf_output_put(handle, val);
7408 	}
7409 }
7410 
perf_sample_regs_user(struct perf_regs * regs_user,struct pt_regs * regs)7411 static void perf_sample_regs_user(struct perf_regs *regs_user,
7412 				  struct pt_regs *regs)
7413 {
7414 	if (user_mode(regs)) {
7415 		regs_user->abi = perf_reg_abi(current);
7416 		regs_user->regs = regs;
7417 	} else if (!(current->flags & PF_KTHREAD)) {
7418 		perf_get_regs_user(regs_user, regs);
7419 	} else {
7420 		regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
7421 		regs_user->regs = NULL;
7422 	}
7423 }
7424 
perf_sample_regs_intr(struct perf_regs * regs_intr,struct pt_regs * regs)7425 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
7426 				  struct pt_regs *regs)
7427 {
7428 	regs_intr->regs = regs;
7429 	regs_intr->abi  = perf_reg_abi(current);
7430 }
7431 
7432 
7433 /*
7434  * Get remaining task size from user stack pointer.
7435  *
7436  * It'd be better to take stack vma map and limit this more
7437  * precisely, but there's no way to get it safely under interrupt,
7438  * so using TASK_SIZE as limit.
7439  */
perf_ustack_task_size(struct pt_regs * regs)7440 static u64 perf_ustack_task_size(struct pt_regs *regs)
7441 {
7442 	unsigned long addr = perf_user_stack_pointer(regs);
7443 
7444 	if (!addr || addr >= TASK_SIZE)
7445 		return 0;
7446 
7447 	return TASK_SIZE - addr;
7448 }
7449 
7450 static u16
perf_sample_ustack_size(u16 stack_size,u16 header_size,struct pt_regs * regs)7451 perf_sample_ustack_size(u16 stack_size, u16 header_size,
7452 			struct pt_regs *regs)
7453 {
7454 	u64 task_size;
7455 
7456 	/* No regs, no stack pointer, no dump. */
7457 	if (!regs)
7458 		return 0;
7459 
7460 	/* No mm, no stack, no dump. */
7461 	if (!current->mm)
7462 		return 0;
7463 
7464 	/*
7465 	 * Check if we fit in with the requested stack size into the:
7466 	 * - TASK_SIZE
7467 	 *   If we don't, we limit the size to the TASK_SIZE.
7468 	 *
7469 	 * - remaining sample size
7470 	 *   If we don't, we customize the stack size to
7471 	 *   fit in to the remaining sample size.
7472 	 */
7473 
7474 	task_size  = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
7475 	stack_size = min(stack_size, (u16) task_size);
7476 
7477 	/* Current header size plus static size and dynamic size. */
7478 	header_size += 2 * sizeof(u64);
7479 
7480 	/* Do we fit in with the current stack dump size? */
7481 	if ((u16) (header_size + stack_size) < header_size) {
7482 		/*
7483 		 * If we overflow the maximum size for the sample,
7484 		 * we customize the stack dump size to fit in.
7485 		 */
7486 		stack_size = USHRT_MAX - header_size - sizeof(u64);
7487 		stack_size = round_up(stack_size, sizeof(u64));
7488 	}
7489 
7490 	return stack_size;
7491 }
7492 
7493 static void
perf_output_sample_ustack(struct perf_output_handle * handle,u64 dump_size,struct pt_regs * regs)7494 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
7495 			  struct pt_regs *regs)
7496 {
7497 	/* Case of a kernel thread, nothing to dump */
7498 	if (!regs) {
7499 		u64 size = 0;
7500 		perf_output_put(handle, size);
7501 	} else {
7502 		unsigned long sp;
7503 		unsigned int rem;
7504 		u64 dyn_size;
7505 
7506 		/*
7507 		 * We dump:
7508 		 * static size
7509 		 *   - the size requested by user or the best one we can fit
7510 		 *     in to the sample max size
7511 		 * data
7512 		 *   - user stack dump data
7513 		 * dynamic size
7514 		 *   - the actual dumped size
7515 		 */
7516 
7517 		/* Static size. */
7518 		perf_output_put(handle, dump_size);
7519 
7520 		/* Data. */
7521 		sp = perf_user_stack_pointer(regs);
7522 		rem = __output_copy_user(handle, (void *) sp, dump_size);
7523 		dyn_size = dump_size - rem;
7524 
7525 		perf_output_skip(handle, rem);
7526 
7527 		/* Dynamic size. */
7528 		perf_output_put(handle, dyn_size);
7529 	}
7530 }
7531 
perf_prepare_sample_aux(struct perf_event * event,struct perf_sample_data * data,size_t size)7532 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
7533 					  struct perf_sample_data *data,
7534 					  size_t size)
7535 {
7536 	struct perf_event *sampler = event->aux_event;
7537 	struct perf_buffer *rb;
7538 
7539 	data->aux_size = 0;
7540 
7541 	if (!sampler)
7542 		goto out;
7543 
7544 	if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
7545 		goto out;
7546 
7547 	if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
7548 		goto out;
7549 
7550 	rb = ring_buffer_get(sampler);
7551 	if (!rb)
7552 		goto out;
7553 
7554 	/*
7555 	 * If this is an NMI hit inside sampling code, don't take
7556 	 * the sample. See also perf_aux_sample_output().
7557 	 */
7558 	if (READ_ONCE(rb->aux_in_sampling)) {
7559 		data->aux_size = 0;
7560 	} else {
7561 		size = min_t(size_t, size, perf_aux_size(rb));
7562 		data->aux_size = ALIGN(size, sizeof(u64));
7563 	}
7564 	ring_buffer_put(rb);
7565 
7566 out:
7567 	return data->aux_size;
7568 }
7569 
perf_pmu_snapshot_aux(struct perf_buffer * rb,struct perf_event * event,struct perf_output_handle * handle,unsigned long size)7570 static long perf_pmu_snapshot_aux(struct perf_buffer *rb,
7571                                  struct perf_event *event,
7572                                  struct perf_output_handle *handle,
7573                                  unsigned long size)
7574 {
7575 	unsigned long flags;
7576 	long ret;
7577 
7578 	/*
7579 	 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
7580 	 * paths. If we start calling them in NMI context, they may race with
7581 	 * the IRQ ones, that is, for example, re-starting an event that's just
7582 	 * been stopped, which is why we're using a separate callback that
7583 	 * doesn't change the event state.
7584 	 *
7585 	 * IRQs need to be disabled to prevent IPIs from racing with us.
7586 	 */
7587 	local_irq_save(flags);
7588 	/*
7589 	 * Guard against NMI hits inside the critical section;
7590 	 * see also perf_prepare_sample_aux().
7591 	 */
7592 	WRITE_ONCE(rb->aux_in_sampling, 1);
7593 	barrier();
7594 
7595 	ret = event->pmu->snapshot_aux(event, handle, size);
7596 
7597 	barrier();
7598 	WRITE_ONCE(rb->aux_in_sampling, 0);
7599 	local_irq_restore(flags);
7600 
7601 	return ret;
7602 }
7603 
perf_aux_sample_output(struct perf_event * event,struct perf_output_handle * handle,struct perf_sample_data * data)7604 static void perf_aux_sample_output(struct perf_event *event,
7605 				   struct perf_output_handle *handle,
7606 				   struct perf_sample_data *data)
7607 {
7608 	struct perf_event *sampler = event->aux_event;
7609 	struct perf_buffer *rb;
7610 	unsigned long pad;
7611 	long size;
7612 
7613 	if (WARN_ON_ONCE(!sampler || !data->aux_size))
7614 		return;
7615 
7616 	rb = ring_buffer_get(sampler);
7617 	if (!rb)
7618 		return;
7619 
7620 	size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
7621 
7622 	/*
7623 	 * An error here means that perf_output_copy() failed (returned a
7624 	 * non-zero surplus that it didn't copy), which in its current
7625 	 * enlightened implementation is not possible. If that changes, we'd
7626 	 * like to know.
7627 	 */
7628 	if (WARN_ON_ONCE(size < 0))
7629 		goto out_put;
7630 
7631 	/*
7632 	 * The pad comes from ALIGN()ing data->aux_size up to u64 in
7633 	 * perf_prepare_sample_aux(), so should not be more than that.
7634 	 */
7635 	pad = data->aux_size - size;
7636 	if (WARN_ON_ONCE(pad >= sizeof(u64)))
7637 		pad = 8;
7638 
7639 	if (pad) {
7640 		u64 zero = 0;
7641 		perf_output_copy(handle, &zero, pad);
7642 	}
7643 
7644 out_put:
7645 	ring_buffer_put(rb);
7646 }
7647 
7648 /*
7649  * A set of common sample data types saved even for non-sample records
7650  * when event->attr.sample_id_all is set.
7651  */
7652 #define PERF_SAMPLE_ID_ALL  (PERF_SAMPLE_TID | PERF_SAMPLE_TIME |	\
7653 			     PERF_SAMPLE_ID | PERF_SAMPLE_STREAM_ID |	\
7654 			     PERF_SAMPLE_CPU | PERF_SAMPLE_IDENTIFIER)
7655 
__perf_event_header__init_id(struct perf_sample_data * data,struct perf_event * event,u64 sample_type)7656 static void __perf_event_header__init_id(struct perf_sample_data *data,
7657 					 struct perf_event *event,
7658 					 u64 sample_type)
7659 {
7660 	data->type = event->attr.sample_type;
7661 	data->sample_flags |= data->type & PERF_SAMPLE_ID_ALL;
7662 
7663 	if (sample_type & PERF_SAMPLE_TID) {
7664 		/* namespace issues */
7665 		data->tid_entry.pid = perf_event_pid(event, current);
7666 		data->tid_entry.tid = perf_event_tid(event, current);
7667 	}
7668 
7669 	if (sample_type & PERF_SAMPLE_TIME)
7670 		data->time = perf_event_clock(event);
7671 
7672 	if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
7673 		data->id = primary_event_id(event);
7674 
7675 	if (sample_type & PERF_SAMPLE_STREAM_ID)
7676 		data->stream_id = event->id;
7677 
7678 	if (sample_type & PERF_SAMPLE_CPU) {
7679 		data->cpu_entry.cpu	 = raw_smp_processor_id();
7680 		data->cpu_entry.reserved = 0;
7681 	}
7682 }
7683 
perf_event_header__init_id(struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event)7684 void perf_event_header__init_id(struct perf_event_header *header,
7685 				struct perf_sample_data *data,
7686 				struct perf_event *event)
7687 {
7688 	if (event->attr.sample_id_all) {
7689 		header->size += event->id_header_size;
7690 		__perf_event_header__init_id(data, event, event->attr.sample_type);
7691 	}
7692 }
7693 
__perf_event__output_id_sample(struct perf_output_handle * handle,struct perf_sample_data * data)7694 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
7695 					   struct perf_sample_data *data)
7696 {
7697 	u64 sample_type = data->type;
7698 
7699 	if (sample_type & PERF_SAMPLE_TID)
7700 		perf_output_put(handle, data->tid_entry);
7701 
7702 	if (sample_type & PERF_SAMPLE_TIME)
7703 		perf_output_put(handle, data->time);
7704 
7705 	if (sample_type & PERF_SAMPLE_ID)
7706 		perf_output_put(handle, data->id);
7707 
7708 	if (sample_type & PERF_SAMPLE_STREAM_ID)
7709 		perf_output_put(handle, data->stream_id);
7710 
7711 	if (sample_type & PERF_SAMPLE_CPU)
7712 		perf_output_put(handle, data->cpu_entry);
7713 
7714 	if (sample_type & PERF_SAMPLE_IDENTIFIER)
7715 		perf_output_put(handle, data->id);
7716 }
7717 
perf_event__output_id_sample(struct perf_event * event,struct perf_output_handle * handle,struct perf_sample_data * sample)7718 void perf_event__output_id_sample(struct perf_event *event,
7719 				  struct perf_output_handle *handle,
7720 				  struct perf_sample_data *sample)
7721 {
7722 	if (event->attr.sample_id_all)
7723 		__perf_event__output_id_sample(handle, sample);
7724 }
7725 
perf_output_read_one(struct perf_output_handle * handle,struct perf_event * event,u64 enabled,u64 running)7726 static void perf_output_read_one(struct perf_output_handle *handle,
7727 				 struct perf_event *event,
7728 				 u64 enabled, u64 running)
7729 {
7730 	u64 read_format = event->attr.read_format;
7731 	u64 values[5];
7732 	int n = 0;
7733 
7734 	values[n++] = perf_event_count(event, has_inherit_and_sample_read(&event->attr));
7735 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
7736 		values[n++] = enabled +
7737 			atomic64_read(&event->child_total_time_enabled);
7738 	}
7739 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
7740 		values[n++] = running +
7741 			atomic64_read(&event->child_total_time_running);
7742 	}
7743 	if (read_format & PERF_FORMAT_ID)
7744 		values[n++] = primary_event_id(event);
7745 	if (read_format & PERF_FORMAT_LOST)
7746 		values[n++] = atomic64_read(&event->lost_samples);
7747 
7748 	__output_copy(handle, values, n * sizeof(u64));
7749 }
7750 
perf_output_read_group(struct perf_output_handle * handle,struct perf_event * event,u64 enabled,u64 running)7751 static void perf_output_read_group(struct perf_output_handle *handle,
7752 				   struct perf_event *event,
7753 				   u64 enabled, u64 running)
7754 {
7755 	struct perf_event *leader = event->group_leader, *sub;
7756 	u64 read_format = event->attr.read_format;
7757 	unsigned long flags;
7758 	u64 values[6];
7759 	int n = 0;
7760 	bool self = has_inherit_and_sample_read(&event->attr);
7761 
7762 	/*
7763 	 * Disabling interrupts avoids all counter scheduling
7764 	 * (context switches, timer based rotation and IPIs).
7765 	 */
7766 	local_irq_save(flags);
7767 
7768 	values[n++] = 1 + leader->nr_siblings;
7769 
7770 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
7771 		values[n++] = enabled;
7772 
7773 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
7774 		values[n++] = running;
7775 
7776 	if ((leader != event) && !handle->skip_read)
7777 		perf_pmu_read(leader);
7778 
7779 	values[n++] = perf_event_count(leader, self);
7780 	if (read_format & PERF_FORMAT_ID)
7781 		values[n++] = primary_event_id(leader);
7782 	if (read_format & PERF_FORMAT_LOST)
7783 		values[n++] = atomic64_read(&leader->lost_samples);
7784 
7785 	__output_copy(handle, values, n * sizeof(u64));
7786 
7787 	for_each_sibling_event(sub, leader) {
7788 		n = 0;
7789 
7790 		if ((sub != event) && !handle->skip_read)
7791 			perf_pmu_read(sub);
7792 
7793 		values[n++] = perf_event_count(sub, self);
7794 		if (read_format & PERF_FORMAT_ID)
7795 			values[n++] = primary_event_id(sub);
7796 		if (read_format & PERF_FORMAT_LOST)
7797 			values[n++] = atomic64_read(&sub->lost_samples);
7798 
7799 		__output_copy(handle, values, n * sizeof(u64));
7800 	}
7801 
7802 	local_irq_restore(flags);
7803 }
7804 
7805 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
7806 				 PERF_FORMAT_TOTAL_TIME_RUNNING)
7807 
7808 /*
7809  * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
7810  *
7811  * The problem is that its both hard and excessively expensive to iterate the
7812  * child list, not to mention that its impossible to IPI the children running
7813  * on another CPU, from interrupt/NMI context.
7814  *
7815  * Instead the combination of PERF_SAMPLE_READ and inherit will track per-thread
7816  * counts rather than attempting to accumulate some value across all children on
7817  * all cores.
7818  */
perf_output_read(struct perf_output_handle * handle,struct perf_event * event)7819 static void perf_output_read(struct perf_output_handle *handle,
7820 			     struct perf_event *event)
7821 {
7822 	u64 enabled = 0, running = 0, now;
7823 	u64 read_format = event->attr.read_format;
7824 
7825 	/*
7826 	 * compute total_time_enabled, total_time_running
7827 	 * based on snapshot values taken when the event
7828 	 * was last scheduled in.
7829 	 *
7830 	 * we cannot simply called update_context_time()
7831 	 * because of locking issue as we are called in
7832 	 * NMI context
7833 	 */
7834 	if (read_format & PERF_FORMAT_TOTAL_TIMES)
7835 		calc_timer_values(event, &now, &enabled, &running);
7836 
7837 	if (event->attr.read_format & PERF_FORMAT_GROUP)
7838 		perf_output_read_group(handle, event, enabled, running);
7839 	else
7840 		perf_output_read_one(handle, event, enabled, running);
7841 }
7842 
perf_output_sample(struct perf_output_handle * handle,struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event)7843 void perf_output_sample(struct perf_output_handle *handle,
7844 			struct perf_event_header *header,
7845 			struct perf_sample_data *data,
7846 			struct perf_event *event)
7847 {
7848 	u64 sample_type = data->type;
7849 
7850 	if (data->sample_flags & PERF_SAMPLE_READ)
7851 		handle->skip_read = 1;
7852 
7853 	perf_output_put(handle, *header);
7854 
7855 	if (sample_type & PERF_SAMPLE_IDENTIFIER)
7856 		perf_output_put(handle, data->id);
7857 
7858 	if (sample_type & PERF_SAMPLE_IP)
7859 		perf_output_put(handle, data->ip);
7860 
7861 	if (sample_type & PERF_SAMPLE_TID)
7862 		perf_output_put(handle, data->tid_entry);
7863 
7864 	if (sample_type & PERF_SAMPLE_TIME)
7865 		perf_output_put(handle, data->time);
7866 
7867 	if (sample_type & PERF_SAMPLE_ADDR)
7868 		perf_output_put(handle, data->addr);
7869 
7870 	if (sample_type & PERF_SAMPLE_ID)
7871 		perf_output_put(handle, data->id);
7872 
7873 	if (sample_type & PERF_SAMPLE_STREAM_ID)
7874 		perf_output_put(handle, data->stream_id);
7875 
7876 	if (sample_type & PERF_SAMPLE_CPU)
7877 		perf_output_put(handle, data->cpu_entry);
7878 
7879 	if (sample_type & PERF_SAMPLE_PERIOD)
7880 		perf_output_put(handle, data->period);
7881 
7882 	if (sample_type & PERF_SAMPLE_READ)
7883 		perf_output_read(handle, event);
7884 
7885 	if (sample_type & PERF_SAMPLE_CALLCHAIN) {
7886 		int size = 1;
7887 
7888 		size += data->callchain->nr;
7889 		size *= sizeof(u64);
7890 		__output_copy(handle, data->callchain, size);
7891 	}
7892 
7893 	if (sample_type & PERF_SAMPLE_RAW) {
7894 		struct perf_raw_record *raw = data->raw;
7895 
7896 		if (raw) {
7897 			struct perf_raw_frag *frag = &raw->frag;
7898 
7899 			perf_output_put(handle, raw->size);
7900 			do {
7901 				if (frag->copy) {
7902 					__output_custom(handle, frag->copy,
7903 							frag->data, frag->size);
7904 				} else {
7905 					__output_copy(handle, frag->data,
7906 						      frag->size);
7907 				}
7908 				if (perf_raw_frag_last(frag))
7909 					break;
7910 				frag = frag->next;
7911 			} while (1);
7912 			if (frag->pad)
7913 				__output_skip(handle, NULL, frag->pad);
7914 		} else {
7915 			struct {
7916 				u32	size;
7917 				u32	data;
7918 			} raw = {
7919 				.size = sizeof(u32),
7920 				.data = 0,
7921 			};
7922 			perf_output_put(handle, raw);
7923 		}
7924 	}
7925 
7926 	if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7927 		if (data->br_stack) {
7928 			size_t size;
7929 
7930 			size = data->br_stack->nr
7931 			     * sizeof(struct perf_branch_entry);
7932 
7933 			perf_output_put(handle, data->br_stack->nr);
7934 			if (branch_sample_hw_index(event))
7935 				perf_output_put(handle, data->br_stack->hw_idx);
7936 			perf_output_copy(handle, data->br_stack->entries, size);
7937 			/*
7938 			 * Add the extension space which is appended
7939 			 * right after the struct perf_branch_stack.
7940 			 */
7941 			if (data->br_stack_cntr) {
7942 				size = data->br_stack->nr * sizeof(u64);
7943 				perf_output_copy(handle, data->br_stack_cntr, size);
7944 			}
7945 		} else {
7946 			/*
7947 			 * we always store at least the value of nr
7948 			 */
7949 			u64 nr = 0;
7950 			perf_output_put(handle, nr);
7951 		}
7952 	}
7953 
7954 	if (sample_type & PERF_SAMPLE_REGS_USER) {
7955 		u64 abi = data->regs_user.abi;
7956 
7957 		/*
7958 		 * If there are no regs to dump, notice it through
7959 		 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7960 		 */
7961 		perf_output_put(handle, abi);
7962 
7963 		if (abi) {
7964 			u64 mask = event->attr.sample_regs_user;
7965 			perf_output_sample_regs(handle,
7966 						data->regs_user.regs,
7967 						mask);
7968 		}
7969 	}
7970 
7971 	if (sample_type & PERF_SAMPLE_STACK_USER) {
7972 		perf_output_sample_ustack(handle,
7973 					  data->stack_user_size,
7974 					  data->regs_user.regs);
7975 	}
7976 
7977 	if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
7978 		perf_output_put(handle, data->weight.full);
7979 
7980 	if (sample_type & PERF_SAMPLE_DATA_SRC)
7981 		perf_output_put(handle, data->data_src.val);
7982 
7983 	if (sample_type & PERF_SAMPLE_TRANSACTION)
7984 		perf_output_put(handle, data->txn);
7985 
7986 	if (sample_type & PERF_SAMPLE_REGS_INTR) {
7987 		u64 abi = data->regs_intr.abi;
7988 		/*
7989 		 * If there are no regs to dump, notice it through
7990 		 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7991 		 */
7992 		perf_output_put(handle, abi);
7993 
7994 		if (abi) {
7995 			u64 mask = event->attr.sample_regs_intr;
7996 
7997 			perf_output_sample_regs(handle,
7998 						data->regs_intr.regs,
7999 						mask);
8000 		}
8001 	}
8002 
8003 	if (sample_type & PERF_SAMPLE_PHYS_ADDR)
8004 		perf_output_put(handle, data->phys_addr);
8005 
8006 	if (sample_type & PERF_SAMPLE_CGROUP)
8007 		perf_output_put(handle, data->cgroup);
8008 
8009 	if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
8010 		perf_output_put(handle, data->data_page_size);
8011 
8012 	if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
8013 		perf_output_put(handle, data->code_page_size);
8014 
8015 	if (sample_type & PERF_SAMPLE_AUX) {
8016 		perf_output_put(handle, data->aux_size);
8017 
8018 		if (data->aux_size)
8019 			perf_aux_sample_output(event, handle, data);
8020 	}
8021 
8022 	if (!event->attr.watermark) {
8023 		int wakeup_events = event->attr.wakeup_events;
8024 
8025 		if (wakeup_events) {
8026 			struct perf_buffer *rb = handle->rb;
8027 			int events = local_inc_return(&rb->events);
8028 
8029 			if (events >= wakeup_events) {
8030 				local_sub(wakeup_events, &rb->events);
8031 				local_inc(&rb->wakeup);
8032 			}
8033 		}
8034 	}
8035 }
8036 
perf_virt_to_phys(u64 virt)8037 static u64 perf_virt_to_phys(u64 virt)
8038 {
8039 	u64 phys_addr = 0;
8040 
8041 	if (!virt)
8042 		return 0;
8043 
8044 	if (virt >= TASK_SIZE) {
8045 		/* If it's vmalloc()d memory, leave phys_addr as 0 */
8046 		if (virt_addr_valid((void *)(uintptr_t)virt) &&
8047 		    !(virt >= VMALLOC_START && virt < VMALLOC_END))
8048 			phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
8049 	} else {
8050 		/*
8051 		 * Walking the pages tables for user address.
8052 		 * Interrupts are disabled, so it prevents any tear down
8053 		 * of the page tables.
8054 		 * Try IRQ-safe get_user_page_fast_only first.
8055 		 * If failed, leave phys_addr as 0.
8056 		 */
8057 		if (current->mm != NULL) {
8058 			struct page *p;
8059 
8060 			pagefault_disable();
8061 			if (get_user_page_fast_only(virt, 0, &p)) {
8062 				phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
8063 				put_page(p);
8064 			}
8065 			pagefault_enable();
8066 		}
8067 	}
8068 
8069 	return phys_addr;
8070 }
8071 
8072 /*
8073  * Return the pagetable size of a given virtual address.
8074  */
perf_get_pgtable_size(struct mm_struct * mm,unsigned long addr)8075 static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
8076 {
8077 	u64 size = 0;
8078 
8079 #ifdef CONFIG_HAVE_GUP_FAST
8080 	pgd_t *pgdp, pgd;
8081 	p4d_t *p4dp, p4d;
8082 	pud_t *pudp, pud;
8083 	pmd_t *pmdp, pmd;
8084 	pte_t *ptep, pte;
8085 
8086 	pgdp = pgd_offset(mm, addr);
8087 	pgd = READ_ONCE(*pgdp);
8088 	if (pgd_none(pgd))
8089 		return 0;
8090 
8091 	if (pgd_leaf(pgd))
8092 		return pgd_leaf_size(pgd);
8093 
8094 	p4dp = p4d_offset_lockless(pgdp, pgd, addr);
8095 	p4d = READ_ONCE(*p4dp);
8096 	if (!p4d_present(p4d))
8097 		return 0;
8098 
8099 	if (p4d_leaf(p4d))
8100 		return p4d_leaf_size(p4d);
8101 
8102 	pudp = pud_offset_lockless(p4dp, p4d, addr);
8103 	pud = READ_ONCE(*pudp);
8104 	if (!pud_present(pud))
8105 		return 0;
8106 
8107 	if (pud_leaf(pud))
8108 		return pud_leaf_size(pud);
8109 
8110 	pmdp = pmd_offset_lockless(pudp, pud, addr);
8111 again:
8112 	pmd = pmdp_get_lockless(pmdp);
8113 	if (!pmd_present(pmd))
8114 		return 0;
8115 
8116 	if (pmd_leaf(pmd))
8117 		return pmd_leaf_size(pmd);
8118 
8119 	ptep = pte_offset_map(&pmd, addr);
8120 	if (!ptep)
8121 		goto again;
8122 
8123 	pte = ptep_get_lockless(ptep);
8124 	if (pte_present(pte))
8125 		size = __pte_leaf_size(pmd, pte);
8126 	pte_unmap(ptep);
8127 #endif /* CONFIG_HAVE_GUP_FAST */
8128 
8129 	return size;
8130 }
8131 
perf_get_page_size(unsigned long addr)8132 static u64 perf_get_page_size(unsigned long addr)
8133 {
8134 	struct mm_struct *mm;
8135 	unsigned long flags;
8136 	u64 size;
8137 
8138 	if (!addr)
8139 		return 0;
8140 
8141 	/*
8142 	 * Software page-table walkers must disable IRQs,
8143 	 * which prevents any tear down of the page tables.
8144 	 */
8145 	local_irq_save(flags);
8146 
8147 	mm = current->mm;
8148 	if (!mm) {
8149 		/*
8150 		 * For kernel threads and the like, use init_mm so that
8151 		 * we can find kernel memory.
8152 		 */
8153 		mm = &init_mm;
8154 	}
8155 
8156 	size = perf_get_pgtable_size(mm, addr);
8157 
8158 	local_irq_restore(flags);
8159 
8160 	return size;
8161 }
8162 
8163 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
8164 
8165 struct perf_callchain_entry *
perf_callchain(struct perf_event * event,struct pt_regs * regs)8166 perf_callchain(struct perf_event *event, struct pt_regs *regs)
8167 {
8168 	bool kernel = !event->attr.exclude_callchain_kernel;
8169 	bool user   = !event->attr.exclude_callchain_user;
8170 	/* Disallow cross-task user callchains. */
8171 	bool crosstask = event->ctx->task && event->ctx->task != current;
8172 	const u32 max_stack = event->attr.sample_max_stack;
8173 	struct perf_callchain_entry *callchain;
8174 
8175 	if (!current->mm)
8176 		user = false;
8177 
8178 	if (!kernel && !user)
8179 		return &__empty_callchain;
8180 
8181 	callchain = get_perf_callchain(regs, 0, kernel, user,
8182 				       max_stack, crosstask, true);
8183 	return callchain ?: &__empty_callchain;
8184 }
8185 
__cond_set(u64 flags,u64 s,u64 d)8186 static __always_inline u64 __cond_set(u64 flags, u64 s, u64 d)
8187 {
8188 	return d * !!(flags & s);
8189 }
8190 
perf_prepare_sample(struct perf_sample_data * data,struct perf_event * event,struct pt_regs * regs)8191 void perf_prepare_sample(struct perf_sample_data *data,
8192 			 struct perf_event *event,
8193 			 struct pt_regs *regs)
8194 {
8195 	u64 sample_type = event->attr.sample_type;
8196 	u64 filtered_sample_type;
8197 
8198 	/*
8199 	 * Add the sample flags that are dependent to others.  And clear the
8200 	 * sample flags that have already been done by the PMU driver.
8201 	 */
8202 	filtered_sample_type = sample_type;
8203 	filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_CODE_PAGE_SIZE,
8204 					   PERF_SAMPLE_IP);
8205 	filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_DATA_PAGE_SIZE |
8206 					   PERF_SAMPLE_PHYS_ADDR, PERF_SAMPLE_ADDR);
8207 	filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_STACK_USER,
8208 					   PERF_SAMPLE_REGS_USER);
8209 	filtered_sample_type &= ~data->sample_flags;
8210 
8211 	if (filtered_sample_type == 0) {
8212 		/* Make sure it has the correct data->type for output */
8213 		data->type = event->attr.sample_type;
8214 		return;
8215 	}
8216 
8217 	__perf_event_header__init_id(data, event, filtered_sample_type);
8218 
8219 	if (filtered_sample_type & PERF_SAMPLE_IP) {
8220 		data->ip = perf_instruction_pointer(event, regs);
8221 		data->sample_flags |= PERF_SAMPLE_IP;
8222 	}
8223 
8224 	if (filtered_sample_type & PERF_SAMPLE_CALLCHAIN)
8225 		perf_sample_save_callchain(data, event, regs);
8226 
8227 	if (filtered_sample_type & PERF_SAMPLE_RAW) {
8228 		data->raw = NULL;
8229 		data->dyn_size += sizeof(u64);
8230 		data->sample_flags |= PERF_SAMPLE_RAW;
8231 	}
8232 
8233 	if (filtered_sample_type & PERF_SAMPLE_BRANCH_STACK) {
8234 		data->br_stack = NULL;
8235 		data->dyn_size += sizeof(u64);
8236 		data->sample_flags |= PERF_SAMPLE_BRANCH_STACK;
8237 	}
8238 
8239 	if (filtered_sample_type & PERF_SAMPLE_REGS_USER)
8240 		perf_sample_regs_user(&data->regs_user, regs);
8241 
8242 	/*
8243 	 * It cannot use the filtered_sample_type here as REGS_USER can be set
8244 	 * by STACK_USER (using __cond_set() above) and we don't want to update
8245 	 * the dyn_size if it's not requested by users.
8246 	 */
8247 	if ((sample_type & ~data->sample_flags) & PERF_SAMPLE_REGS_USER) {
8248 		/* regs dump ABI info */
8249 		int size = sizeof(u64);
8250 
8251 		if (data->regs_user.regs) {
8252 			u64 mask = event->attr.sample_regs_user;
8253 			size += hweight64(mask) * sizeof(u64);
8254 		}
8255 
8256 		data->dyn_size += size;
8257 		data->sample_flags |= PERF_SAMPLE_REGS_USER;
8258 	}
8259 
8260 	if (filtered_sample_type & PERF_SAMPLE_STACK_USER) {
8261 		/*
8262 		 * Either we need PERF_SAMPLE_STACK_USER bit to be always
8263 		 * processed as the last one or have additional check added
8264 		 * in case new sample type is added, because we could eat
8265 		 * up the rest of the sample size.
8266 		 */
8267 		u16 stack_size = event->attr.sample_stack_user;
8268 		u16 header_size = perf_sample_data_size(data, event);
8269 		u16 size = sizeof(u64);
8270 
8271 		stack_size = perf_sample_ustack_size(stack_size, header_size,
8272 						     data->regs_user.regs);
8273 
8274 		/*
8275 		 * If there is something to dump, add space for the dump
8276 		 * itself and for the field that tells the dynamic size,
8277 		 * which is how many have been actually dumped.
8278 		 */
8279 		if (stack_size)
8280 			size += sizeof(u64) + stack_size;
8281 
8282 		data->stack_user_size = stack_size;
8283 		data->dyn_size += size;
8284 		data->sample_flags |= PERF_SAMPLE_STACK_USER;
8285 	}
8286 
8287 	if (filtered_sample_type & PERF_SAMPLE_WEIGHT_TYPE) {
8288 		data->weight.full = 0;
8289 		data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE;
8290 	}
8291 
8292 	if (filtered_sample_type & PERF_SAMPLE_DATA_SRC) {
8293 		data->data_src.val = PERF_MEM_NA;
8294 		data->sample_flags |= PERF_SAMPLE_DATA_SRC;
8295 	}
8296 
8297 	if (filtered_sample_type & PERF_SAMPLE_TRANSACTION) {
8298 		data->txn = 0;
8299 		data->sample_flags |= PERF_SAMPLE_TRANSACTION;
8300 	}
8301 
8302 	if (filtered_sample_type & PERF_SAMPLE_ADDR) {
8303 		data->addr = 0;
8304 		data->sample_flags |= PERF_SAMPLE_ADDR;
8305 	}
8306 
8307 	if (filtered_sample_type & PERF_SAMPLE_REGS_INTR) {
8308 		/* regs dump ABI info */
8309 		int size = sizeof(u64);
8310 
8311 		perf_sample_regs_intr(&data->regs_intr, regs);
8312 
8313 		if (data->regs_intr.regs) {
8314 			u64 mask = event->attr.sample_regs_intr;
8315 
8316 			size += hweight64(mask) * sizeof(u64);
8317 		}
8318 
8319 		data->dyn_size += size;
8320 		data->sample_flags |= PERF_SAMPLE_REGS_INTR;
8321 	}
8322 
8323 	if (filtered_sample_type & PERF_SAMPLE_PHYS_ADDR) {
8324 		data->phys_addr = perf_virt_to_phys(data->addr);
8325 		data->sample_flags |= PERF_SAMPLE_PHYS_ADDR;
8326 	}
8327 
8328 #ifdef CONFIG_CGROUP_PERF
8329 	if (filtered_sample_type & PERF_SAMPLE_CGROUP) {
8330 		struct cgroup *cgrp;
8331 
8332 		/* protected by RCU */
8333 		cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
8334 		data->cgroup = cgroup_id(cgrp);
8335 		data->sample_flags |= PERF_SAMPLE_CGROUP;
8336 	}
8337 #endif
8338 
8339 	/*
8340 	 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't
8341 	 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr,
8342 	 * but the value will not dump to the userspace.
8343 	 */
8344 	if (filtered_sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) {
8345 		data->data_page_size = perf_get_page_size(data->addr);
8346 		data->sample_flags |= PERF_SAMPLE_DATA_PAGE_SIZE;
8347 	}
8348 
8349 	if (filtered_sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) {
8350 		data->code_page_size = perf_get_page_size(data->ip);
8351 		data->sample_flags |= PERF_SAMPLE_CODE_PAGE_SIZE;
8352 	}
8353 
8354 	if (filtered_sample_type & PERF_SAMPLE_AUX) {
8355 		u64 size;
8356 		u16 header_size = perf_sample_data_size(data, event);
8357 
8358 		header_size += sizeof(u64); /* size */
8359 
8360 		/*
8361 		 * Given the 16bit nature of header::size, an AUX sample can
8362 		 * easily overflow it, what with all the preceding sample bits.
8363 		 * Make sure this doesn't happen by using up to U16_MAX bytes
8364 		 * per sample in total (rounded down to 8 byte boundary).
8365 		 */
8366 		size = min_t(size_t, U16_MAX - header_size,
8367 			     event->attr.aux_sample_size);
8368 		size = rounddown(size, 8);
8369 		size = perf_prepare_sample_aux(event, data, size);
8370 
8371 		WARN_ON_ONCE(size + header_size > U16_MAX);
8372 		data->dyn_size += size + sizeof(u64); /* size above */
8373 		data->sample_flags |= PERF_SAMPLE_AUX;
8374 	}
8375 }
8376 
perf_prepare_header(struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event,struct pt_regs * regs)8377 void perf_prepare_header(struct perf_event_header *header,
8378 			 struct perf_sample_data *data,
8379 			 struct perf_event *event,
8380 			 struct pt_regs *regs)
8381 {
8382 	header->type = PERF_RECORD_SAMPLE;
8383 	header->size = perf_sample_data_size(data, event);
8384 	header->misc = perf_misc_flags(event, regs);
8385 
8386 	/*
8387 	 * If you're adding more sample types here, you likely need to do
8388 	 * something about the overflowing header::size, like repurpose the
8389 	 * lowest 3 bits of size, which should be always zero at the moment.
8390 	 * This raises a more important question, do we really need 512k sized
8391 	 * samples and why, so good argumentation is in order for whatever you
8392 	 * do here next.
8393 	 */
8394 	WARN_ON_ONCE(header->size & 7);
8395 }
8396 
__perf_event_aux_pause(struct perf_event * event,bool pause)8397 static void __perf_event_aux_pause(struct perf_event *event, bool pause)
8398 {
8399 	if (pause) {
8400 		if (!event->hw.aux_paused) {
8401 			event->hw.aux_paused = 1;
8402 			event->pmu->stop(event, PERF_EF_PAUSE);
8403 		}
8404 	} else {
8405 		if (event->hw.aux_paused) {
8406 			event->hw.aux_paused = 0;
8407 			event->pmu->start(event, PERF_EF_RESUME);
8408 		}
8409 	}
8410 }
8411 
perf_event_aux_pause(struct perf_event * event,bool pause)8412 static void perf_event_aux_pause(struct perf_event *event, bool pause)
8413 {
8414 	struct perf_buffer *rb;
8415 
8416 	if (WARN_ON_ONCE(!event))
8417 		return;
8418 
8419 	rb = ring_buffer_get(event);
8420 	if (!rb)
8421 		return;
8422 
8423 	scoped_guard (irqsave) {
8424 		/*
8425 		 * Guard against self-recursion here. Another event could trip
8426 		 * this same from NMI context.
8427 		 */
8428 		if (READ_ONCE(rb->aux_in_pause_resume))
8429 			break;
8430 
8431 		WRITE_ONCE(rb->aux_in_pause_resume, 1);
8432 		barrier();
8433 		__perf_event_aux_pause(event, pause);
8434 		barrier();
8435 		WRITE_ONCE(rb->aux_in_pause_resume, 0);
8436 	}
8437 	ring_buffer_put(rb);
8438 }
8439 
8440 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))8441 __perf_event_output(struct perf_event *event,
8442 		    struct perf_sample_data *data,
8443 		    struct pt_regs *regs,
8444 		    int (*output_begin)(struct perf_output_handle *,
8445 					struct perf_sample_data *,
8446 					struct perf_event *,
8447 					unsigned int))
8448 {
8449 	struct perf_output_handle handle;
8450 	struct perf_event_header header;
8451 	int err;
8452 
8453 	/* protect the callchain buffers */
8454 	rcu_read_lock();
8455 
8456 	perf_prepare_sample(data, event, regs);
8457 	perf_prepare_header(&header, data, event, regs);
8458 
8459 	err = output_begin(&handle, data, event, header.size);
8460 	if (err)
8461 		goto exit;
8462 
8463 	perf_output_sample(&handle, &header, data, event);
8464 
8465 	perf_output_end(&handle);
8466 
8467 exit:
8468 	rcu_read_unlock();
8469 	return err;
8470 }
8471 
8472 void
perf_event_output_forward(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)8473 perf_event_output_forward(struct perf_event *event,
8474 			 struct perf_sample_data *data,
8475 			 struct pt_regs *regs)
8476 {
8477 	__perf_event_output(event, data, regs, perf_output_begin_forward);
8478 }
8479 
8480 void
perf_event_output_backward(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)8481 perf_event_output_backward(struct perf_event *event,
8482 			   struct perf_sample_data *data,
8483 			   struct pt_regs *regs)
8484 {
8485 	__perf_event_output(event, data, regs, perf_output_begin_backward);
8486 }
8487 
8488 int
perf_event_output(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)8489 perf_event_output(struct perf_event *event,
8490 		  struct perf_sample_data *data,
8491 		  struct pt_regs *regs)
8492 {
8493 	return __perf_event_output(event, data, regs, perf_output_begin);
8494 }
8495 
8496 /*
8497  * read event_id
8498  */
8499 
8500 struct perf_read_event {
8501 	struct perf_event_header	header;
8502 
8503 	u32				pid;
8504 	u32				tid;
8505 };
8506 
8507 static void
perf_event_read_event(struct perf_event * event,struct task_struct * task)8508 perf_event_read_event(struct perf_event *event,
8509 			struct task_struct *task)
8510 {
8511 	struct perf_output_handle handle;
8512 	struct perf_sample_data sample;
8513 	struct perf_read_event read_event = {
8514 		.header = {
8515 			.type = PERF_RECORD_READ,
8516 			.misc = 0,
8517 			.size = sizeof(read_event) + event->read_size,
8518 		},
8519 		.pid = perf_event_pid(event, task),
8520 		.tid = perf_event_tid(event, task),
8521 	};
8522 	int ret;
8523 
8524 	perf_event_header__init_id(&read_event.header, &sample, event);
8525 	ret = perf_output_begin(&handle, &sample, event, read_event.header.size);
8526 	if (ret)
8527 		return;
8528 
8529 	perf_output_put(&handle, read_event);
8530 	perf_output_read(&handle, event);
8531 	perf_event__output_id_sample(event, &handle, &sample);
8532 
8533 	perf_output_end(&handle);
8534 }
8535 
8536 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
8537 
8538 static void
perf_iterate_ctx(struct perf_event_context * ctx,perf_iterate_f output,void * data,bool all)8539 perf_iterate_ctx(struct perf_event_context *ctx,
8540 		   perf_iterate_f output,
8541 		   void *data, bool all)
8542 {
8543 	struct perf_event *event;
8544 
8545 	list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
8546 		if (!all) {
8547 			if (event->state < PERF_EVENT_STATE_INACTIVE)
8548 				continue;
8549 			if (!event_filter_match(event))
8550 				continue;
8551 		}
8552 
8553 		output(event, data);
8554 	}
8555 }
8556 
perf_iterate_sb_cpu(perf_iterate_f output,void * data)8557 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
8558 {
8559 	struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
8560 	struct perf_event *event;
8561 
8562 	list_for_each_entry_rcu(event, &pel->list, sb_list) {
8563 		/*
8564 		 * Skip events that are not fully formed yet; ensure that
8565 		 * if we observe event->ctx, both event and ctx will be
8566 		 * complete enough. See perf_install_in_context().
8567 		 */
8568 		if (!smp_load_acquire(&event->ctx))
8569 			continue;
8570 
8571 		if (event->state < PERF_EVENT_STATE_INACTIVE)
8572 			continue;
8573 		if (!event_filter_match(event))
8574 			continue;
8575 		output(event, data);
8576 	}
8577 }
8578 
8579 /*
8580  * Iterate all events that need to receive side-band events.
8581  *
8582  * For new callers; ensure that account_pmu_sb_event() includes
8583  * your event, otherwise it might not get delivered.
8584  */
8585 static void
perf_iterate_sb(perf_iterate_f output,void * data,struct perf_event_context * task_ctx)8586 perf_iterate_sb(perf_iterate_f output, void *data,
8587 	       struct perf_event_context *task_ctx)
8588 {
8589 	struct perf_event_context *ctx;
8590 
8591 	rcu_read_lock();
8592 	preempt_disable();
8593 
8594 	/*
8595 	 * If we have task_ctx != NULL we only notify the task context itself.
8596 	 * The task_ctx is set only for EXIT events before releasing task
8597 	 * context.
8598 	 */
8599 	if (task_ctx) {
8600 		perf_iterate_ctx(task_ctx, output, data, false);
8601 		goto done;
8602 	}
8603 
8604 	perf_iterate_sb_cpu(output, data);
8605 
8606 	ctx = rcu_dereference(current->perf_event_ctxp);
8607 	if (ctx)
8608 		perf_iterate_ctx(ctx, output, data, false);
8609 done:
8610 	preempt_enable();
8611 	rcu_read_unlock();
8612 }
8613 
8614 /*
8615  * Clear all file-based filters at exec, they'll have to be
8616  * re-instated when/if these objects are mmapped again.
8617  */
perf_event_addr_filters_exec(struct perf_event * event,void * data)8618 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
8619 {
8620 	struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8621 	struct perf_addr_filter *filter;
8622 	unsigned int restart = 0, count = 0;
8623 	unsigned long flags;
8624 
8625 	if (!has_addr_filter(event))
8626 		return;
8627 
8628 	raw_spin_lock_irqsave(&ifh->lock, flags);
8629 	list_for_each_entry(filter, &ifh->list, entry) {
8630 		if (filter->path.dentry) {
8631 			event->addr_filter_ranges[count].start = 0;
8632 			event->addr_filter_ranges[count].size = 0;
8633 			restart++;
8634 		}
8635 
8636 		count++;
8637 	}
8638 
8639 	if (restart)
8640 		event->addr_filters_gen++;
8641 	raw_spin_unlock_irqrestore(&ifh->lock, flags);
8642 
8643 	if (restart)
8644 		perf_event_stop(event, 1);
8645 }
8646 
perf_event_exec(void)8647 void perf_event_exec(void)
8648 {
8649 	struct perf_event_context *ctx;
8650 
8651 	ctx = perf_pin_task_context(current);
8652 	if (!ctx)
8653 		return;
8654 
8655 	perf_event_enable_on_exec(ctx);
8656 	perf_event_remove_on_exec(ctx);
8657 	scoped_guard(rcu)
8658 		perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL, true);
8659 
8660 	perf_unpin_context(ctx);
8661 	put_ctx(ctx);
8662 }
8663 
8664 struct remote_output {
8665 	struct perf_buffer	*rb;
8666 	int			err;
8667 };
8668 
__perf_event_output_stop(struct perf_event * event,void * data)8669 static void __perf_event_output_stop(struct perf_event *event, void *data)
8670 {
8671 	struct perf_event *parent = event->parent;
8672 	struct remote_output *ro = data;
8673 	struct perf_buffer *rb = ro->rb;
8674 	struct stop_event_data sd = {
8675 		.event	= event,
8676 	};
8677 
8678 	if (!has_aux(event))
8679 		return;
8680 
8681 	if (!parent)
8682 		parent = event;
8683 
8684 	/*
8685 	 * In case of inheritance, it will be the parent that links to the
8686 	 * ring-buffer, but it will be the child that's actually using it.
8687 	 *
8688 	 * We are using event::rb to determine if the event should be stopped,
8689 	 * however this may race with ring_buffer_attach() (through set_output),
8690 	 * which will make us skip the event that actually needs to be stopped.
8691 	 * So ring_buffer_attach() has to stop an aux event before re-assigning
8692 	 * its rb pointer.
8693 	 */
8694 	if (rcu_dereference(parent->rb) == rb)
8695 		ro->err = __perf_event_stop(&sd);
8696 }
8697 
__perf_pmu_output_stop(void * info)8698 static int __perf_pmu_output_stop(void *info)
8699 {
8700 	struct perf_event *event = info;
8701 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
8702 	struct remote_output ro = {
8703 		.rb	= event->rb,
8704 	};
8705 
8706 	rcu_read_lock();
8707 	perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
8708 	if (cpuctx->task_ctx)
8709 		perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
8710 				   &ro, false);
8711 	rcu_read_unlock();
8712 
8713 	return ro.err;
8714 }
8715 
perf_pmu_output_stop(struct perf_event * event)8716 static void perf_pmu_output_stop(struct perf_event *event)
8717 {
8718 	struct perf_event *iter;
8719 	int err, cpu;
8720 
8721 restart:
8722 	rcu_read_lock();
8723 	list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
8724 		/*
8725 		 * For per-CPU events, we need to make sure that neither they
8726 		 * nor their children are running; for cpu==-1 events it's
8727 		 * sufficient to stop the event itself if it's active, since
8728 		 * it can't have children.
8729 		 */
8730 		cpu = iter->cpu;
8731 		if (cpu == -1)
8732 			cpu = READ_ONCE(iter->oncpu);
8733 
8734 		if (cpu == -1)
8735 			continue;
8736 
8737 		err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
8738 		if (err == -EAGAIN) {
8739 			rcu_read_unlock();
8740 			goto restart;
8741 		}
8742 	}
8743 	rcu_read_unlock();
8744 }
8745 
8746 /*
8747  * task tracking -- fork/exit
8748  *
8749  * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
8750  */
8751 
8752 struct perf_task_event {
8753 	struct task_struct		*task;
8754 	struct perf_event_context	*task_ctx;
8755 
8756 	struct {
8757 		struct perf_event_header	header;
8758 
8759 		u32				pid;
8760 		u32				ppid;
8761 		u32				tid;
8762 		u32				ptid;
8763 		u64				time;
8764 	} event_id;
8765 };
8766 
perf_event_task_match(struct perf_event * event)8767 static int perf_event_task_match(struct perf_event *event)
8768 {
8769 	return event->attr.comm  || event->attr.mmap ||
8770 	       event->attr.mmap2 || event->attr.mmap_data ||
8771 	       event->attr.task;
8772 }
8773 
perf_event_task_output(struct perf_event * event,void * data)8774 static void perf_event_task_output(struct perf_event *event,
8775 				   void *data)
8776 {
8777 	struct perf_task_event *task_event = data;
8778 	struct perf_output_handle handle;
8779 	struct perf_sample_data	sample;
8780 	struct task_struct *task = task_event->task;
8781 	int ret, size = task_event->event_id.header.size;
8782 
8783 	if (!perf_event_task_match(event))
8784 		return;
8785 
8786 	perf_event_header__init_id(&task_event->event_id.header, &sample, event);
8787 
8788 	ret = perf_output_begin(&handle, &sample, event,
8789 				task_event->event_id.header.size);
8790 	if (ret)
8791 		goto out;
8792 
8793 	task_event->event_id.pid = perf_event_pid(event, task);
8794 	task_event->event_id.tid = perf_event_tid(event, task);
8795 
8796 	if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
8797 		task_event->event_id.ppid = perf_event_pid(event,
8798 							task->real_parent);
8799 		task_event->event_id.ptid = perf_event_pid(event,
8800 							task->real_parent);
8801 	} else {  /* PERF_RECORD_FORK */
8802 		task_event->event_id.ppid = perf_event_pid(event, current);
8803 		task_event->event_id.ptid = perf_event_tid(event, current);
8804 	}
8805 
8806 	task_event->event_id.time = perf_event_clock(event);
8807 
8808 	perf_output_put(&handle, task_event->event_id);
8809 
8810 	perf_event__output_id_sample(event, &handle, &sample);
8811 
8812 	perf_output_end(&handle);
8813 out:
8814 	task_event->event_id.header.size = size;
8815 }
8816 
perf_event_task(struct task_struct * task,struct perf_event_context * task_ctx,int new)8817 static void perf_event_task(struct task_struct *task,
8818 			      struct perf_event_context *task_ctx,
8819 			      int new)
8820 {
8821 	struct perf_task_event task_event;
8822 
8823 	if (!atomic_read(&nr_comm_events) &&
8824 	    !atomic_read(&nr_mmap_events) &&
8825 	    !atomic_read(&nr_task_events))
8826 		return;
8827 
8828 	task_event = (struct perf_task_event){
8829 		.task	  = task,
8830 		.task_ctx = task_ctx,
8831 		.event_id    = {
8832 			.header = {
8833 				.type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
8834 				.misc = 0,
8835 				.size = sizeof(task_event.event_id),
8836 			},
8837 			/* .pid  */
8838 			/* .ppid */
8839 			/* .tid  */
8840 			/* .ptid */
8841 			/* .time */
8842 		},
8843 	};
8844 
8845 	perf_iterate_sb(perf_event_task_output,
8846 		       &task_event,
8847 		       task_ctx);
8848 }
8849 
8850 /*
8851  * Allocate data for a new task when profiling system-wide
8852  * events which require PMU specific data
8853  */
8854 static void
perf_event_alloc_task_data(struct task_struct * child,struct task_struct * parent)8855 perf_event_alloc_task_data(struct task_struct *child,
8856 			   struct task_struct *parent)
8857 {
8858 	struct kmem_cache *ctx_cache = NULL;
8859 	struct perf_ctx_data *cd;
8860 
8861 	if (!refcount_read(&global_ctx_data_ref))
8862 		return;
8863 
8864 	scoped_guard (rcu) {
8865 		cd = rcu_dereference(parent->perf_ctx_data);
8866 		if (cd)
8867 			ctx_cache = cd->ctx_cache;
8868 	}
8869 
8870 	if (!ctx_cache)
8871 		return;
8872 
8873 	guard(percpu_read)(&global_ctx_data_rwsem);
8874 	scoped_guard (rcu) {
8875 		cd = rcu_dereference(child->perf_ctx_data);
8876 		if (!cd) {
8877 			/*
8878 			 * A system-wide event may be unaccount,
8879 			 * when attaching the perf_ctx_data.
8880 			 */
8881 			if (!refcount_read(&global_ctx_data_ref))
8882 				return;
8883 			goto attach;
8884 		}
8885 
8886 		if (!cd->global) {
8887 			cd->global = 1;
8888 			refcount_inc(&cd->refcount);
8889 		}
8890 	}
8891 
8892 	return;
8893 attach:
8894 	attach_task_ctx_data(child, ctx_cache, true);
8895 }
8896 
perf_event_fork(struct task_struct * task)8897 void perf_event_fork(struct task_struct *task)
8898 {
8899 	perf_event_task(task, NULL, 1);
8900 	perf_event_namespaces(task);
8901 	perf_event_alloc_task_data(task, current);
8902 }
8903 
8904 /*
8905  * comm tracking
8906  */
8907 
8908 struct perf_comm_event {
8909 	struct task_struct	*task;
8910 	char			*comm;
8911 	int			comm_size;
8912 
8913 	struct {
8914 		struct perf_event_header	header;
8915 
8916 		u32				pid;
8917 		u32				tid;
8918 	} event_id;
8919 };
8920 
perf_event_comm_match(struct perf_event * event)8921 static int perf_event_comm_match(struct perf_event *event)
8922 {
8923 	return event->attr.comm;
8924 }
8925 
perf_event_comm_output(struct perf_event * event,void * data)8926 static void perf_event_comm_output(struct perf_event *event,
8927 				   void *data)
8928 {
8929 	struct perf_comm_event *comm_event = data;
8930 	struct perf_output_handle handle;
8931 	struct perf_sample_data sample;
8932 	int size = comm_event->event_id.header.size;
8933 	int ret;
8934 
8935 	if (!perf_event_comm_match(event))
8936 		return;
8937 
8938 	perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
8939 	ret = perf_output_begin(&handle, &sample, event,
8940 				comm_event->event_id.header.size);
8941 
8942 	if (ret)
8943 		goto out;
8944 
8945 	comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
8946 	comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
8947 
8948 	perf_output_put(&handle, comm_event->event_id);
8949 	__output_copy(&handle, comm_event->comm,
8950 				   comm_event->comm_size);
8951 
8952 	perf_event__output_id_sample(event, &handle, &sample);
8953 
8954 	perf_output_end(&handle);
8955 out:
8956 	comm_event->event_id.header.size = size;
8957 }
8958 
perf_event_comm_event(struct perf_comm_event * comm_event)8959 static void perf_event_comm_event(struct perf_comm_event *comm_event)
8960 {
8961 	char comm[TASK_COMM_LEN];
8962 	unsigned int size;
8963 
8964 	memset(comm, 0, sizeof(comm));
8965 	strscpy(comm, comm_event->task->comm);
8966 	size = ALIGN(strlen(comm)+1, sizeof(u64));
8967 
8968 	comm_event->comm = comm;
8969 	comm_event->comm_size = size;
8970 
8971 	comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
8972 
8973 	perf_iterate_sb(perf_event_comm_output,
8974 		       comm_event,
8975 		       NULL);
8976 }
8977 
perf_event_comm(struct task_struct * task,bool exec)8978 void perf_event_comm(struct task_struct *task, bool exec)
8979 {
8980 	struct perf_comm_event comm_event;
8981 
8982 	if (!atomic_read(&nr_comm_events))
8983 		return;
8984 
8985 	comm_event = (struct perf_comm_event){
8986 		.task	= task,
8987 		/* .comm      */
8988 		/* .comm_size */
8989 		.event_id  = {
8990 			.header = {
8991 				.type = PERF_RECORD_COMM,
8992 				.misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
8993 				/* .size */
8994 			},
8995 			/* .pid */
8996 			/* .tid */
8997 		},
8998 	};
8999 
9000 	perf_event_comm_event(&comm_event);
9001 }
9002 
9003 /*
9004  * namespaces tracking
9005  */
9006 
9007 struct perf_namespaces_event {
9008 	struct task_struct		*task;
9009 
9010 	struct {
9011 		struct perf_event_header	header;
9012 
9013 		u32				pid;
9014 		u32				tid;
9015 		u64				nr_namespaces;
9016 		struct perf_ns_link_info	link_info[NR_NAMESPACES];
9017 	} event_id;
9018 };
9019 
perf_event_namespaces_match(struct perf_event * event)9020 static int perf_event_namespaces_match(struct perf_event *event)
9021 {
9022 	return event->attr.namespaces;
9023 }
9024 
perf_event_namespaces_output(struct perf_event * event,void * data)9025 static void perf_event_namespaces_output(struct perf_event *event,
9026 					 void *data)
9027 {
9028 	struct perf_namespaces_event *namespaces_event = data;
9029 	struct perf_output_handle handle;
9030 	struct perf_sample_data sample;
9031 	u16 header_size = namespaces_event->event_id.header.size;
9032 	int ret;
9033 
9034 	if (!perf_event_namespaces_match(event))
9035 		return;
9036 
9037 	perf_event_header__init_id(&namespaces_event->event_id.header,
9038 				   &sample, event);
9039 	ret = perf_output_begin(&handle, &sample, event,
9040 				namespaces_event->event_id.header.size);
9041 	if (ret)
9042 		goto out;
9043 
9044 	namespaces_event->event_id.pid = perf_event_pid(event,
9045 							namespaces_event->task);
9046 	namespaces_event->event_id.tid = perf_event_tid(event,
9047 							namespaces_event->task);
9048 
9049 	perf_output_put(&handle, namespaces_event->event_id);
9050 
9051 	perf_event__output_id_sample(event, &handle, &sample);
9052 
9053 	perf_output_end(&handle);
9054 out:
9055 	namespaces_event->event_id.header.size = header_size;
9056 }
9057 
perf_fill_ns_link_info(struct perf_ns_link_info * ns_link_info,struct task_struct * task,const struct proc_ns_operations * ns_ops)9058 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
9059 				   struct task_struct *task,
9060 				   const struct proc_ns_operations *ns_ops)
9061 {
9062 	struct path ns_path;
9063 	struct inode *ns_inode;
9064 	int error;
9065 
9066 	error = ns_get_path(&ns_path, task, ns_ops);
9067 	if (!error) {
9068 		ns_inode = ns_path.dentry->d_inode;
9069 		ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
9070 		ns_link_info->ino = ns_inode->i_ino;
9071 		path_put(&ns_path);
9072 	}
9073 }
9074 
perf_event_namespaces(struct task_struct * task)9075 void perf_event_namespaces(struct task_struct *task)
9076 {
9077 	struct perf_namespaces_event namespaces_event;
9078 	struct perf_ns_link_info *ns_link_info;
9079 
9080 	if (!atomic_read(&nr_namespaces_events))
9081 		return;
9082 
9083 	namespaces_event = (struct perf_namespaces_event){
9084 		.task	= task,
9085 		.event_id  = {
9086 			.header = {
9087 				.type = PERF_RECORD_NAMESPACES,
9088 				.misc = 0,
9089 				.size = sizeof(namespaces_event.event_id),
9090 			},
9091 			/* .pid */
9092 			/* .tid */
9093 			.nr_namespaces = NR_NAMESPACES,
9094 			/* .link_info[NR_NAMESPACES] */
9095 		},
9096 	};
9097 
9098 	ns_link_info = namespaces_event.event_id.link_info;
9099 
9100 	perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
9101 			       task, &mntns_operations);
9102 
9103 #ifdef CONFIG_USER_NS
9104 	perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
9105 			       task, &userns_operations);
9106 #endif
9107 #ifdef CONFIG_NET_NS
9108 	perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
9109 			       task, &netns_operations);
9110 #endif
9111 #ifdef CONFIG_UTS_NS
9112 	perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
9113 			       task, &utsns_operations);
9114 #endif
9115 #ifdef CONFIG_IPC_NS
9116 	perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
9117 			       task, &ipcns_operations);
9118 #endif
9119 #ifdef CONFIG_PID_NS
9120 	perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
9121 			       task, &pidns_operations);
9122 #endif
9123 #ifdef CONFIG_CGROUPS
9124 	perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
9125 			       task, &cgroupns_operations);
9126 #endif
9127 
9128 	perf_iterate_sb(perf_event_namespaces_output,
9129 			&namespaces_event,
9130 			NULL);
9131 }
9132 
9133 /*
9134  * cgroup tracking
9135  */
9136 #ifdef CONFIG_CGROUP_PERF
9137 
9138 struct perf_cgroup_event {
9139 	char				*path;
9140 	int				path_size;
9141 	struct {
9142 		struct perf_event_header	header;
9143 		u64				id;
9144 		char				path[];
9145 	} event_id;
9146 };
9147 
perf_event_cgroup_match(struct perf_event * event)9148 static int perf_event_cgroup_match(struct perf_event *event)
9149 {
9150 	return event->attr.cgroup;
9151 }
9152 
perf_event_cgroup_output(struct perf_event * event,void * data)9153 static void perf_event_cgroup_output(struct perf_event *event, void *data)
9154 {
9155 	struct perf_cgroup_event *cgroup_event = data;
9156 	struct perf_output_handle handle;
9157 	struct perf_sample_data sample;
9158 	u16 header_size = cgroup_event->event_id.header.size;
9159 	int ret;
9160 
9161 	if (!perf_event_cgroup_match(event))
9162 		return;
9163 
9164 	perf_event_header__init_id(&cgroup_event->event_id.header,
9165 				   &sample, event);
9166 	ret = perf_output_begin(&handle, &sample, event,
9167 				cgroup_event->event_id.header.size);
9168 	if (ret)
9169 		goto out;
9170 
9171 	perf_output_put(&handle, cgroup_event->event_id);
9172 	__output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
9173 
9174 	perf_event__output_id_sample(event, &handle, &sample);
9175 
9176 	perf_output_end(&handle);
9177 out:
9178 	cgroup_event->event_id.header.size = header_size;
9179 }
9180 
perf_event_cgroup(struct cgroup * cgrp)9181 static void perf_event_cgroup(struct cgroup *cgrp)
9182 {
9183 	struct perf_cgroup_event cgroup_event;
9184 	char path_enomem[16] = "//enomem";
9185 	char *pathname;
9186 	size_t size;
9187 
9188 	if (!atomic_read(&nr_cgroup_events))
9189 		return;
9190 
9191 	cgroup_event = (struct perf_cgroup_event){
9192 		.event_id  = {
9193 			.header = {
9194 				.type = PERF_RECORD_CGROUP,
9195 				.misc = 0,
9196 				.size = sizeof(cgroup_event.event_id),
9197 			},
9198 			.id = cgroup_id(cgrp),
9199 		},
9200 	};
9201 
9202 	pathname = kmalloc(PATH_MAX, GFP_KERNEL);
9203 	if (pathname == NULL) {
9204 		cgroup_event.path = path_enomem;
9205 	} else {
9206 		/* just to be sure to have enough space for alignment */
9207 		cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
9208 		cgroup_event.path = pathname;
9209 	}
9210 
9211 	/*
9212 	 * Since our buffer works in 8 byte units we need to align our string
9213 	 * size to a multiple of 8. However, we must guarantee the tail end is
9214 	 * zero'd out to avoid leaking random bits to userspace.
9215 	 */
9216 	size = strlen(cgroup_event.path) + 1;
9217 	while (!IS_ALIGNED(size, sizeof(u64)))
9218 		cgroup_event.path[size++] = '\0';
9219 
9220 	cgroup_event.event_id.header.size += size;
9221 	cgroup_event.path_size = size;
9222 
9223 	perf_iterate_sb(perf_event_cgroup_output,
9224 			&cgroup_event,
9225 			NULL);
9226 
9227 	kfree(pathname);
9228 }
9229 
9230 #endif
9231 
9232 /*
9233  * mmap tracking
9234  */
9235 
9236 struct perf_mmap_event {
9237 	struct vm_area_struct	*vma;
9238 
9239 	const char		*file_name;
9240 	int			file_size;
9241 	int			maj, min;
9242 	u64			ino;
9243 	u64			ino_generation;
9244 	u32			prot, flags;
9245 	u8			build_id[BUILD_ID_SIZE_MAX];
9246 	u32			build_id_size;
9247 
9248 	struct {
9249 		struct perf_event_header	header;
9250 
9251 		u32				pid;
9252 		u32				tid;
9253 		u64				start;
9254 		u64				len;
9255 		u64				pgoff;
9256 	} event_id;
9257 };
9258 
perf_event_mmap_match(struct perf_event * event,void * data)9259 static int perf_event_mmap_match(struct perf_event *event,
9260 				 void *data)
9261 {
9262 	struct perf_mmap_event *mmap_event = data;
9263 	struct vm_area_struct *vma = mmap_event->vma;
9264 	int executable = vma->vm_flags & VM_EXEC;
9265 
9266 	return (!executable && event->attr.mmap_data) ||
9267 	       (executable && (event->attr.mmap || event->attr.mmap2));
9268 }
9269 
perf_event_mmap_output(struct perf_event * event,void * data)9270 static void perf_event_mmap_output(struct perf_event *event,
9271 				   void *data)
9272 {
9273 	struct perf_mmap_event *mmap_event = data;
9274 	struct perf_output_handle handle;
9275 	struct perf_sample_data sample;
9276 	int size = mmap_event->event_id.header.size;
9277 	u32 type = mmap_event->event_id.header.type;
9278 	bool use_build_id;
9279 	int ret;
9280 
9281 	if (!perf_event_mmap_match(event, data))
9282 		return;
9283 
9284 	if (event->attr.mmap2) {
9285 		mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
9286 		mmap_event->event_id.header.size += sizeof(mmap_event->maj);
9287 		mmap_event->event_id.header.size += sizeof(mmap_event->min);
9288 		mmap_event->event_id.header.size += sizeof(mmap_event->ino);
9289 		mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
9290 		mmap_event->event_id.header.size += sizeof(mmap_event->prot);
9291 		mmap_event->event_id.header.size += sizeof(mmap_event->flags);
9292 	}
9293 
9294 	perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
9295 	ret = perf_output_begin(&handle, &sample, event,
9296 				mmap_event->event_id.header.size);
9297 	if (ret)
9298 		goto out;
9299 
9300 	mmap_event->event_id.pid = perf_event_pid(event, current);
9301 	mmap_event->event_id.tid = perf_event_tid(event, current);
9302 
9303 	use_build_id = event->attr.build_id && mmap_event->build_id_size;
9304 
9305 	if (event->attr.mmap2 && use_build_id)
9306 		mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID;
9307 
9308 	perf_output_put(&handle, mmap_event->event_id);
9309 
9310 	if (event->attr.mmap2) {
9311 		if (use_build_id) {
9312 			u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 };
9313 
9314 			__output_copy(&handle, size, 4);
9315 			__output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX);
9316 		} else {
9317 			perf_output_put(&handle, mmap_event->maj);
9318 			perf_output_put(&handle, mmap_event->min);
9319 			perf_output_put(&handle, mmap_event->ino);
9320 			perf_output_put(&handle, mmap_event->ino_generation);
9321 		}
9322 		perf_output_put(&handle, mmap_event->prot);
9323 		perf_output_put(&handle, mmap_event->flags);
9324 	}
9325 
9326 	__output_copy(&handle, mmap_event->file_name,
9327 				   mmap_event->file_size);
9328 
9329 	perf_event__output_id_sample(event, &handle, &sample);
9330 
9331 	perf_output_end(&handle);
9332 out:
9333 	mmap_event->event_id.header.size = size;
9334 	mmap_event->event_id.header.type = type;
9335 }
9336 
perf_event_mmap_event(struct perf_mmap_event * mmap_event)9337 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
9338 {
9339 	struct vm_area_struct *vma = mmap_event->vma;
9340 	struct file *file = vma->vm_file;
9341 	int maj = 0, min = 0;
9342 	u64 ino = 0, gen = 0;
9343 	u32 prot = 0, flags = 0;
9344 	unsigned int size;
9345 	char tmp[16];
9346 	char *buf = NULL;
9347 	char *name = NULL;
9348 
9349 	if (vma->vm_flags & VM_READ)
9350 		prot |= PROT_READ;
9351 	if (vma->vm_flags & VM_WRITE)
9352 		prot |= PROT_WRITE;
9353 	if (vma->vm_flags & VM_EXEC)
9354 		prot |= PROT_EXEC;
9355 
9356 	if (vma->vm_flags & VM_MAYSHARE)
9357 		flags = MAP_SHARED;
9358 	else
9359 		flags = MAP_PRIVATE;
9360 
9361 	if (vma->vm_flags & VM_LOCKED)
9362 		flags |= MAP_LOCKED;
9363 	if (is_vm_hugetlb_page(vma))
9364 		flags |= MAP_HUGETLB;
9365 
9366 	if (file) {
9367 		struct inode *inode;
9368 		dev_t dev;
9369 
9370 		buf = kmalloc(PATH_MAX, GFP_KERNEL);
9371 		if (!buf) {
9372 			name = "//enomem";
9373 			goto cpy_name;
9374 		}
9375 		/*
9376 		 * d_path() works from the end of the rb backwards, so we
9377 		 * need to add enough zero bytes after the string to handle
9378 		 * the 64bit alignment we do later.
9379 		 */
9380 		name = file_path(file, buf, PATH_MAX - sizeof(u64));
9381 		if (IS_ERR(name)) {
9382 			name = "//toolong";
9383 			goto cpy_name;
9384 		}
9385 		inode = file_inode(vma->vm_file);
9386 		dev = inode->i_sb->s_dev;
9387 		ino = inode->i_ino;
9388 		gen = inode->i_generation;
9389 		maj = MAJOR(dev);
9390 		min = MINOR(dev);
9391 
9392 		goto got_name;
9393 	} else {
9394 		if (vma->vm_ops && vma->vm_ops->name)
9395 			name = (char *) vma->vm_ops->name(vma);
9396 		if (!name)
9397 			name = (char *)arch_vma_name(vma);
9398 		if (!name) {
9399 			if (vma_is_initial_heap(vma))
9400 				name = "[heap]";
9401 			else if (vma_is_initial_stack(vma))
9402 				name = "[stack]";
9403 			else
9404 				name = "//anon";
9405 		}
9406 	}
9407 
9408 cpy_name:
9409 	strscpy(tmp, name);
9410 	name = tmp;
9411 got_name:
9412 	/*
9413 	 * Since our buffer works in 8 byte units we need to align our string
9414 	 * size to a multiple of 8. However, we must guarantee the tail end is
9415 	 * zero'd out to avoid leaking random bits to userspace.
9416 	 */
9417 	size = strlen(name)+1;
9418 	while (!IS_ALIGNED(size, sizeof(u64)))
9419 		name[size++] = '\0';
9420 
9421 	mmap_event->file_name = name;
9422 	mmap_event->file_size = size;
9423 	mmap_event->maj = maj;
9424 	mmap_event->min = min;
9425 	mmap_event->ino = ino;
9426 	mmap_event->ino_generation = gen;
9427 	mmap_event->prot = prot;
9428 	mmap_event->flags = flags;
9429 
9430 	if (!(vma->vm_flags & VM_EXEC))
9431 		mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
9432 
9433 	mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
9434 
9435 	if (atomic_read(&nr_build_id_events))
9436 		build_id_parse_nofault(vma, mmap_event->build_id, &mmap_event->build_id_size);
9437 
9438 	perf_iterate_sb(perf_event_mmap_output,
9439 		       mmap_event,
9440 		       NULL);
9441 
9442 	kfree(buf);
9443 }
9444 
9445 /*
9446  * Check whether inode and address range match filter criteria.
9447  */
perf_addr_filter_match(struct perf_addr_filter * filter,struct file * file,unsigned long offset,unsigned long size)9448 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
9449 				     struct file *file, unsigned long offset,
9450 				     unsigned long size)
9451 {
9452 	/* d_inode(NULL) won't be equal to any mapped user-space file */
9453 	if (!filter->path.dentry)
9454 		return false;
9455 
9456 	if (d_inode(filter->path.dentry) != file_inode(file))
9457 		return false;
9458 
9459 	if (filter->offset > offset + size)
9460 		return false;
9461 
9462 	if (filter->offset + filter->size < offset)
9463 		return false;
9464 
9465 	return true;
9466 }
9467 
perf_addr_filter_vma_adjust(struct perf_addr_filter * filter,struct vm_area_struct * vma,struct perf_addr_filter_range * fr)9468 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
9469 					struct vm_area_struct *vma,
9470 					struct perf_addr_filter_range *fr)
9471 {
9472 	unsigned long vma_size = vma->vm_end - vma->vm_start;
9473 	unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
9474 	struct file *file = vma->vm_file;
9475 
9476 	if (!perf_addr_filter_match(filter, file, off, vma_size))
9477 		return false;
9478 
9479 	if (filter->offset < off) {
9480 		fr->start = vma->vm_start;
9481 		fr->size = min(vma_size, filter->size - (off - filter->offset));
9482 	} else {
9483 		fr->start = vma->vm_start + filter->offset - off;
9484 		fr->size = min(vma->vm_end - fr->start, filter->size);
9485 	}
9486 
9487 	return true;
9488 }
9489 
__perf_addr_filters_adjust(struct perf_event * event,void * data)9490 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
9491 {
9492 	struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
9493 	struct vm_area_struct *vma = data;
9494 	struct perf_addr_filter *filter;
9495 	unsigned int restart = 0, count = 0;
9496 	unsigned long flags;
9497 
9498 	if (!has_addr_filter(event))
9499 		return;
9500 
9501 	if (!vma->vm_file)
9502 		return;
9503 
9504 	raw_spin_lock_irqsave(&ifh->lock, flags);
9505 	list_for_each_entry(filter, &ifh->list, entry) {
9506 		if (perf_addr_filter_vma_adjust(filter, vma,
9507 						&event->addr_filter_ranges[count]))
9508 			restart++;
9509 
9510 		count++;
9511 	}
9512 
9513 	if (restart)
9514 		event->addr_filters_gen++;
9515 	raw_spin_unlock_irqrestore(&ifh->lock, flags);
9516 
9517 	if (restart)
9518 		perf_event_stop(event, 1);
9519 }
9520 
9521 /*
9522  * Adjust all task's events' filters to the new vma
9523  */
perf_addr_filters_adjust(struct vm_area_struct * vma)9524 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
9525 {
9526 	struct perf_event_context *ctx;
9527 
9528 	/*
9529 	 * Data tracing isn't supported yet and as such there is no need
9530 	 * to keep track of anything that isn't related to executable code:
9531 	 */
9532 	if (!(vma->vm_flags & VM_EXEC))
9533 		return;
9534 
9535 	rcu_read_lock();
9536 	ctx = rcu_dereference(current->perf_event_ctxp);
9537 	if (ctx)
9538 		perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
9539 	rcu_read_unlock();
9540 }
9541 
perf_event_mmap(struct vm_area_struct * vma)9542 void perf_event_mmap(struct vm_area_struct *vma)
9543 {
9544 	struct perf_mmap_event mmap_event;
9545 
9546 	if (!atomic_read(&nr_mmap_events))
9547 		return;
9548 
9549 	mmap_event = (struct perf_mmap_event){
9550 		.vma	= vma,
9551 		/* .file_name */
9552 		/* .file_size */
9553 		.event_id  = {
9554 			.header = {
9555 				.type = PERF_RECORD_MMAP,
9556 				.misc = PERF_RECORD_MISC_USER,
9557 				/* .size */
9558 			},
9559 			/* .pid */
9560 			/* .tid */
9561 			.start  = vma->vm_start,
9562 			.len    = vma->vm_end - vma->vm_start,
9563 			.pgoff  = (u64)vma->vm_pgoff << PAGE_SHIFT,
9564 		},
9565 		/* .maj (attr_mmap2 only) */
9566 		/* .min (attr_mmap2 only) */
9567 		/* .ino (attr_mmap2 only) */
9568 		/* .ino_generation (attr_mmap2 only) */
9569 		/* .prot (attr_mmap2 only) */
9570 		/* .flags (attr_mmap2 only) */
9571 	};
9572 
9573 	perf_addr_filters_adjust(vma);
9574 	perf_event_mmap_event(&mmap_event);
9575 }
9576 
perf_event_aux_event(struct perf_event * event,unsigned long head,unsigned long size,u64 flags)9577 void perf_event_aux_event(struct perf_event *event, unsigned long head,
9578 			  unsigned long size, u64 flags)
9579 {
9580 	struct perf_output_handle handle;
9581 	struct perf_sample_data sample;
9582 	struct perf_aux_event {
9583 		struct perf_event_header	header;
9584 		u64				offset;
9585 		u64				size;
9586 		u64				flags;
9587 	} rec = {
9588 		.header = {
9589 			.type = PERF_RECORD_AUX,
9590 			.misc = 0,
9591 			.size = sizeof(rec),
9592 		},
9593 		.offset		= head,
9594 		.size		= size,
9595 		.flags		= flags,
9596 	};
9597 	int ret;
9598 
9599 	perf_event_header__init_id(&rec.header, &sample, event);
9600 	ret = perf_output_begin(&handle, &sample, event, rec.header.size);
9601 
9602 	if (ret)
9603 		return;
9604 
9605 	perf_output_put(&handle, rec);
9606 	perf_event__output_id_sample(event, &handle, &sample);
9607 
9608 	perf_output_end(&handle);
9609 }
9610 
9611 /*
9612  * Lost/dropped samples logging
9613  */
perf_log_lost_samples(struct perf_event * event,u64 lost)9614 void perf_log_lost_samples(struct perf_event *event, u64 lost)
9615 {
9616 	struct perf_output_handle handle;
9617 	struct perf_sample_data sample;
9618 	int ret;
9619 
9620 	struct {
9621 		struct perf_event_header	header;
9622 		u64				lost;
9623 	} lost_samples_event = {
9624 		.header = {
9625 			.type = PERF_RECORD_LOST_SAMPLES,
9626 			.misc = 0,
9627 			.size = sizeof(lost_samples_event),
9628 		},
9629 		.lost		= lost,
9630 	};
9631 
9632 	perf_event_header__init_id(&lost_samples_event.header, &sample, event);
9633 
9634 	ret = perf_output_begin(&handle, &sample, event,
9635 				lost_samples_event.header.size);
9636 	if (ret)
9637 		return;
9638 
9639 	perf_output_put(&handle, lost_samples_event);
9640 	perf_event__output_id_sample(event, &handle, &sample);
9641 	perf_output_end(&handle);
9642 }
9643 
9644 /*
9645  * context_switch tracking
9646  */
9647 
9648 struct perf_switch_event {
9649 	struct task_struct	*task;
9650 	struct task_struct	*next_prev;
9651 
9652 	struct {
9653 		struct perf_event_header	header;
9654 		u32				next_prev_pid;
9655 		u32				next_prev_tid;
9656 	} event_id;
9657 };
9658 
perf_event_switch_match(struct perf_event * event)9659 static int perf_event_switch_match(struct perf_event *event)
9660 {
9661 	return event->attr.context_switch;
9662 }
9663 
perf_event_switch_output(struct perf_event * event,void * data)9664 static void perf_event_switch_output(struct perf_event *event, void *data)
9665 {
9666 	struct perf_switch_event *se = data;
9667 	struct perf_output_handle handle;
9668 	struct perf_sample_data sample;
9669 	int ret;
9670 
9671 	if (!perf_event_switch_match(event))
9672 		return;
9673 
9674 	/* Only CPU-wide events are allowed to see next/prev pid/tid */
9675 	if (event->ctx->task) {
9676 		se->event_id.header.type = PERF_RECORD_SWITCH;
9677 		se->event_id.header.size = sizeof(se->event_id.header);
9678 	} else {
9679 		se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
9680 		se->event_id.header.size = sizeof(se->event_id);
9681 		se->event_id.next_prev_pid =
9682 					perf_event_pid(event, se->next_prev);
9683 		se->event_id.next_prev_tid =
9684 					perf_event_tid(event, se->next_prev);
9685 	}
9686 
9687 	perf_event_header__init_id(&se->event_id.header, &sample, event);
9688 
9689 	ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size);
9690 	if (ret)
9691 		return;
9692 
9693 	if (event->ctx->task)
9694 		perf_output_put(&handle, se->event_id.header);
9695 	else
9696 		perf_output_put(&handle, se->event_id);
9697 
9698 	perf_event__output_id_sample(event, &handle, &sample);
9699 
9700 	perf_output_end(&handle);
9701 }
9702 
perf_event_switch(struct task_struct * task,struct task_struct * next_prev,bool sched_in)9703 static void perf_event_switch(struct task_struct *task,
9704 			      struct task_struct *next_prev, bool sched_in)
9705 {
9706 	struct perf_switch_event switch_event;
9707 
9708 	/* N.B. caller checks nr_switch_events != 0 */
9709 
9710 	switch_event = (struct perf_switch_event){
9711 		.task		= task,
9712 		.next_prev	= next_prev,
9713 		.event_id	= {
9714 			.header = {
9715 				/* .type */
9716 				.misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
9717 				/* .size */
9718 			},
9719 			/* .next_prev_pid */
9720 			/* .next_prev_tid */
9721 		},
9722 	};
9723 
9724 	if (!sched_in && task_is_runnable(task)) {
9725 		switch_event.event_id.header.misc |=
9726 				PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
9727 	}
9728 
9729 	perf_iterate_sb(perf_event_switch_output, &switch_event, NULL);
9730 }
9731 
9732 /*
9733  * IRQ throttle logging
9734  */
9735 
perf_log_throttle(struct perf_event * event,int enable)9736 static void perf_log_throttle(struct perf_event *event, int enable)
9737 {
9738 	struct perf_output_handle handle;
9739 	struct perf_sample_data sample;
9740 	int ret;
9741 
9742 	struct {
9743 		struct perf_event_header	header;
9744 		u64				time;
9745 		u64				id;
9746 		u64				stream_id;
9747 	} throttle_event = {
9748 		.header = {
9749 			.type = PERF_RECORD_THROTTLE,
9750 			.misc = 0,
9751 			.size = sizeof(throttle_event),
9752 		},
9753 		.time		= perf_event_clock(event),
9754 		.id		= primary_event_id(event),
9755 		.stream_id	= event->id,
9756 	};
9757 
9758 	if (enable)
9759 		throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
9760 
9761 	perf_event_header__init_id(&throttle_event.header, &sample, event);
9762 
9763 	ret = perf_output_begin(&handle, &sample, event,
9764 				throttle_event.header.size);
9765 	if (ret)
9766 		return;
9767 
9768 	perf_output_put(&handle, throttle_event);
9769 	perf_event__output_id_sample(event, &handle, &sample);
9770 	perf_output_end(&handle);
9771 }
9772 
9773 /*
9774  * ksymbol register/unregister tracking
9775  */
9776 
9777 struct perf_ksymbol_event {
9778 	const char	*name;
9779 	int		name_len;
9780 	struct {
9781 		struct perf_event_header        header;
9782 		u64				addr;
9783 		u32				len;
9784 		u16				ksym_type;
9785 		u16				flags;
9786 	} event_id;
9787 };
9788 
perf_event_ksymbol_match(struct perf_event * event)9789 static int perf_event_ksymbol_match(struct perf_event *event)
9790 {
9791 	return event->attr.ksymbol;
9792 }
9793 
perf_event_ksymbol_output(struct perf_event * event,void * data)9794 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
9795 {
9796 	struct perf_ksymbol_event *ksymbol_event = data;
9797 	struct perf_output_handle handle;
9798 	struct perf_sample_data sample;
9799 	int ret;
9800 
9801 	if (!perf_event_ksymbol_match(event))
9802 		return;
9803 
9804 	perf_event_header__init_id(&ksymbol_event->event_id.header,
9805 				   &sample, event);
9806 	ret = perf_output_begin(&handle, &sample, event,
9807 				ksymbol_event->event_id.header.size);
9808 	if (ret)
9809 		return;
9810 
9811 	perf_output_put(&handle, ksymbol_event->event_id);
9812 	__output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
9813 	perf_event__output_id_sample(event, &handle, &sample);
9814 
9815 	perf_output_end(&handle);
9816 }
9817 
perf_event_ksymbol(u16 ksym_type,u64 addr,u32 len,bool unregister,const char * sym)9818 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
9819 			const char *sym)
9820 {
9821 	struct perf_ksymbol_event ksymbol_event;
9822 	char name[KSYM_NAME_LEN];
9823 	u16 flags = 0;
9824 	int name_len;
9825 
9826 	if (!atomic_read(&nr_ksymbol_events))
9827 		return;
9828 
9829 	if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
9830 	    ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
9831 		goto err;
9832 
9833 	strscpy(name, sym);
9834 	name_len = strlen(name) + 1;
9835 	while (!IS_ALIGNED(name_len, sizeof(u64)))
9836 		name[name_len++] = '\0';
9837 	BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
9838 
9839 	if (unregister)
9840 		flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
9841 
9842 	ksymbol_event = (struct perf_ksymbol_event){
9843 		.name = name,
9844 		.name_len = name_len,
9845 		.event_id = {
9846 			.header = {
9847 				.type = PERF_RECORD_KSYMBOL,
9848 				.size = sizeof(ksymbol_event.event_id) +
9849 					name_len,
9850 			},
9851 			.addr = addr,
9852 			.len = len,
9853 			.ksym_type = ksym_type,
9854 			.flags = flags,
9855 		},
9856 	};
9857 
9858 	perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
9859 	return;
9860 err:
9861 	WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
9862 }
9863 
9864 /*
9865  * bpf program load/unload tracking
9866  */
9867 
9868 struct perf_bpf_event {
9869 	struct bpf_prog	*prog;
9870 	struct {
9871 		struct perf_event_header        header;
9872 		u16				type;
9873 		u16				flags;
9874 		u32				id;
9875 		u8				tag[BPF_TAG_SIZE];
9876 	} event_id;
9877 };
9878 
perf_event_bpf_match(struct perf_event * event)9879 static int perf_event_bpf_match(struct perf_event *event)
9880 {
9881 	return event->attr.bpf_event;
9882 }
9883 
perf_event_bpf_output(struct perf_event * event,void * data)9884 static void perf_event_bpf_output(struct perf_event *event, void *data)
9885 {
9886 	struct perf_bpf_event *bpf_event = data;
9887 	struct perf_output_handle handle;
9888 	struct perf_sample_data sample;
9889 	int ret;
9890 
9891 	if (!perf_event_bpf_match(event))
9892 		return;
9893 
9894 	perf_event_header__init_id(&bpf_event->event_id.header,
9895 				   &sample, event);
9896 	ret = perf_output_begin(&handle, &sample, event,
9897 				bpf_event->event_id.header.size);
9898 	if (ret)
9899 		return;
9900 
9901 	perf_output_put(&handle, bpf_event->event_id);
9902 	perf_event__output_id_sample(event, &handle, &sample);
9903 
9904 	perf_output_end(&handle);
9905 }
9906 
perf_event_bpf_emit_ksymbols(struct bpf_prog * prog,enum perf_bpf_event_type type)9907 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
9908 					 enum perf_bpf_event_type type)
9909 {
9910 	bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
9911 	int i;
9912 
9913 	perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
9914 			   (u64)(unsigned long)prog->bpf_func,
9915 			   prog->jited_len, unregister,
9916 			   prog->aux->ksym.name);
9917 
9918 	for (i = 1; i < prog->aux->func_cnt; i++) {
9919 		struct bpf_prog *subprog = prog->aux->func[i];
9920 
9921 		perf_event_ksymbol(
9922 			PERF_RECORD_KSYMBOL_TYPE_BPF,
9923 			(u64)(unsigned long)subprog->bpf_func,
9924 			subprog->jited_len, unregister,
9925 			subprog->aux->ksym.name);
9926 	}
9927 }
9928 
perf_event_bpf_event(struct bpf_prog * prog,enum perf_bpf_event_type type,u16 flags)9929 void perf_event_bpf_event(struct bpf_prog *prog,
9930 			  enum perf_bpf_event_type type,
9931 			  u16 flags)
9932 {
9933 	struct perf_bpf_event bpf_event;
9934 
9935 	switch (type) {
9936 	case PERF_BPF_EVENT_PROG_LOAD:
9937 	case PERF_BPF_EVENT_PROG_UNLOAD:
9938 		if (atomic_read(&nr_ksymbol_events))
9939 			perf_event_bpf_emit_ksymbols(prog, type);
9940 		break;
9941 	default:
9942 		return;
9943 	}
9944 
9945 	if (!atomic_read(&nr_bpf_events))
9946 		return;
9947 
9948 	bpf_event = (struct perf_bpf_event){
9949 		.prog = prog,
9950 		.event_id = {
9951 			.header = {
9952 				.type = PERF_RECORD_BPF_EVENT,
9953 				.size = sizeof(bpf_event.event_id),
9954 			},
9955 			.type = type,
9956 			.flags = flags,
9957 			.id = prog->aux->id,
9958 		},
9959 	};
9960 
9961 	BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
9962 
9963 	memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
9964 	perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
9965 }
9966 
9967 struct perf_text_poke_event {
9968 	const void		*old_bytes;
9969 	const void		*new_bytes;
9970 	size_t			pad;
9971 	u16			old_len;
9972 	u16			new_len;
9973 
9974 	struct {
9975 		struct perf_event_header	header;
9976 
9977 		u64				addr;
9978 	} event_id;
9979 };
9980 
perf_event_text_poke_match(struct perf_event * event)9981 static int perf_event_text_poke_match(struct perf_event *event)
9982 {
9983 	return event->attr.text_poke;
9984 }
9985 
perf_event_text_poke_output(struct perf_event * event,void * data)9986 static void perf_event_text_poke_output(struct perf_event *event, void *data)
9987 {
9988 	struct perf_text_poke_event *text_poke_event = data;
9989 	struct perf_output_handle handle;
9990 	struct perf_sample_data sample;
9991 	u64 padding = 0;
9992 	int ret;
9993 
9994 	if (!perf_event_text_poke_match(event))
9995 		return;
9996 
9997 	perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
9998 
9999 	ret = perf_output_begin(&handle, &sample, event,
10000 				text_poke_event->event_id.header.size);
10001 	if (ret)
10002 		return;
10003 
10004 	perf_output_put(&handle, text_poke_event->event_id);
10005 	perf_output_put(&handle, text_poke_event->old_len);
10006 	perf_output_put(&handle, text_poke_event->new_len);
10007 
10008 	__output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
10009 	__output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
10010 
10011 	if (text_poke_event->pad)
10012 		__output_copy(&handle, &padding, text_poke_event->pad);
10013 
10014 	perf_event__output_id_sample(event, &handle, &sample);
10015 
10016 	perf_output_end(&handle);
10017 }
10018 
perf_event_text_poke(const void * addr,const void * old_bytes,size_t old_len,const void * new_bytes,size_t new_len)10019 void perf_event_text_poke(const void *addr, const void *old_bytes,
10020 			  size_t old_len, const void *new_bytes, size_t new_len)
10021 {
10022 	struct perf_text_poke_event text_poke_event;
10023 	size_t tot, pad;
10024 
10025 	if (!atomic_read(&nr_text_poke_events))
10026 		return;
10027 
10028 	tot  = sizeof(text_poke_event.old_len) + old_len;
10029 	tot += sizeof(text_poke_event.new_len) + new_len;
10030 	pad  = ALIGN(tot, sizeof(u64)) - tot;
10031 
10032 	text_poke_event = (struct perf_text_poke_event){
10033 		.old_bytes    = old_bytes,
10034 		.new_bytes    = new_bytes,
10035 		.pad          = pad,
10036 		.old_len      = old_len,
10037 		.new_len      = new_len,
10038 		.event_id  = {
10039 			.header = {
10040 				.type = PERF_RECORD_TEXT_POKE,
10041 				.misc = PERF_RECORD_MISC_KERNEL,
10042 				.size = sizeof(text_poke_event.event_id) + tot + pad,
10043 			},
10044 			.addr = (unsigned long)addr,
10045 		},
10046 	};
10047 
10048 	perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
10049 }
10050 
perf_event_itrace_started(struct perf_event * event)10051 void perf_event_itrace_started(struct perf_event *event)
10052 {
10053 	WRITE_ONCE(event->attach_state, event->attach_state | PERF_ATTACH_ITRACE);
10054 }
10055 
perf_log_itrace_start(struct perf_event * event)10056 static void perf_log_itrace_start(struct perf_event *event)
10057 {
10058 	struct perf_output_handle handle;
10059 	struct perf_sample_data sample;
10060 	struct perf_aux_event {
10061 		struct perf_event_header        header;
10062 		u32				pid;
10063 		u32				tid;
10064 	} rec;
10065 	int ret;
10066 
10067 	if (event->parent)
10068 		event = event->parent;
10069 
10070 	if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
10071 	    event->attach_state & PERF_ATTACH_ITRACE)
10072 		return;
10073 
10074 	rec.header.type	= PERF_RECORD_ITRACE_START;
10075 	rec.header.misc	= 0;
10076 	rec.header.size	= sizeof(rec);
10077 	rec.pid	= perf_event_pid(event, current);
10078 	rec.tid	= perf_event_tid(event, current);
10079 
10080 	perf_event_header__init_id(&rec.header, &sample, event);
10081 	ret = perf_output_begin(&handle, &sample, event, rec.header.size);
10082 
10083 	if (ret)
10084 		return;
10085 
10086 	perf_output_put(&handle, rec);
10087 	perf_event__output_id_sample(event, &handle, &sample);
10088 
10089 	perf_output_end(&handle);
10090 }
10091 
perf_report_aux_output_id(struct perf_event * event,u64 hw_id)10092 void perf_report_aux_output_id(struct perf_event *event, u64 hw_id)
10093 {
10094 	struct perf_output_handle handle;
10095 	struct perf_sample_data sample;
10096 	struct perf_aux_event {
10097 		struct perf_event_header        header;
10098 		u64				hw_id;
10099 	} rec;
10100 	int ret;
10101 
10102 	if (event->parent)
10103 		event = event->parent;
10104 
10105 	rec.header.type	= PERF_RECORD_AUX_OUTPUT_HW_ID;
10106 	rec.header.misc	= 0;
10107 	rec.header.size	= sizeof(rec);
10108 	rec.hw_id	= hw_id;
10109 
10110 	perf_event_header__init_id(&rec.header, &sample, event);
10111 	ret = perf_output_begin(&handle, &sample, event, rec.header.size);
10112 
10113 	if (ret)
10114 		return;
10115 
10116 	perf_output_put(&handle, rec);
10117 	perf_event__output_id_sample(event, &handle, &sample);
10118 
10119 	perf_output_end(&handle);
10120 }
10121 EXPORT_SYMBOL_GPL(perf_report_aux_output_id);
10122 
10123 static int
__perf_event_account_interrupt(struct perf_event * event,int throttle)10124 __perf_event_account_interrupt(struct perf_event *event, int throttle)
10125 {
10126 	struct hw_perf_event *hwc = &event->hw;
10127 	int ret = 0;
10128 	u64 seq;
10129 
10130 	seq = __this_cpu_read(perf_throttled_seq);
10131 	if (seq != hwc->interrupts_seq) {
10132 		hwc->interrupts_seq = seq;
10133 		hwc->interrupts = 1;
10134 	} else {
10135 		hwc->interrupts++;
10136 	}
10137 
10138 	if (unlikely(throttle && hwc->interrupts >= max_samples_per_tick)) {
10139 		__this_cpu_inc(perf_throttled_count);
10140 		tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
10141 		perf_event_throttle_group(event);
10142 		ret = 1;
10143 	}
10144 
10145 	if (event->attr.freq) {
10146 		u64 now = perf_clock();
10147 		s64 delta = now - hwc->freq_time_stamp;
10148 
10149 		hwc->freq_time_stamp = now;
10150 
10151 		if (delta > 0 && delta < 2*TICK_NSEC)
10152 			perf_adjust_period(event, delta, hwc->last_period, true);
10153 	}
10154 
10155 	return ret;
10156 }
10157 
perf_event_account_interrupt(struct perf_event * event)10158 int perf_event_account_interrupt(struct perf_event *event)
10159 {
10160 	return __perf_event_account_interrupt(event, 1);
10161 }
10162 
sample_is_allowed(struct perf_event * event,struct pt_regs * regs)10163 static inline bool sample_is_allowed(struct perf_event *event, struct pt_regs *regs)
10164 {
10165 	/*
10166 	 * Due to interrupt latency (AKA "skid"), we may enter the
10167 	 * kernel before taking an overflow, even if the PMU is only
10168 	 * counting user events.
10169 	 */
10170 	if (event->attr.exclude_kernel && !user_mode(regs))
10171 		return false;
10172 
10173 	return true;
10174 }
10175 
10176 #ifdef CONFIG_BPF_SYSCALL
bpf_overflow_handler(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)10177 static int bpf_overflow_handler(struct perf_event *event,
10178 				struct perf_sample_data *data,
10179 				struct pt_regs *regs)
10180 {
10181 	struct bpf_perf_event_data_kern ctx = {
10182 		.data = data,
10183 		.event = event,
10184 	};
10185 	struct bpf_prog *prog;
10186 	int ret = 0;
10187 
10188 	ctx.regs = perf_arch_bpf_user_pt_regs(regs);
10189 	if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
10190 		goto out;
10191 	rcu_read_lock();
10192 	prog = READ_ONCE(event->prog);
10193 	if (prog) {
10194 		perf_prepare_sample(data, event, regs);
10195 		ret = bpf_prog_run(prog, &ctx);
10196 	}
10197 	rcu_read_unlock();
10198 out:
10199 	__this_cpu_dec(bpf_prog_active);
10200 
10201 	return ret;
10202 }
10203 
perf_event_set_bpf_handler(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)10204 static inline int perf_event_set_bpf_handler(struct perf_event *event,
10205 					     struct bpf_prog *prog,
10206 					     u64 bpf_cookie)
10207 {
10208 	if (event->overflow_handler_context)
10209 		/* hw breakpoint or kernel counter */
10210 		return -EINVAL;
10211 
10212 	if (event->prog)
10213 		return -EEXIST;
10214 
10215 	if (prog->type != BPF_PROG_TYPE_PERF_EVENT)
10216 		return -EINVAL;
10217 
10218 	if (event->attr.precise_ip &&
10219 	    prog->call_get_stack &&
10220 	    (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) ||
10221 	     event->attr.exclude_callchain_kernel ||
10222 	     event->attr.exclude_callchain_user)) {
10223 		/*
10224 		 * On perf_event with precise_ip, calling bpf_get_stack()
10225 		 * may trigger unwinder warnings and occasional crashes.
10226 		 * bpf_get_[stack|stackid] works around this issue by using
10227 		 * callchain attached to perf_sample_data. If the
10228 		 * perf_event does not full (kernel and user) callchain
10229 		 * attached to perf_sample_data, do not allow attaching BPF
10230 		 * program that calls bpf_get_[stack|stackid].
10231 		 */
10232 		return -EPROTO;
10233 	}
10234 
10235 	event->prog = prog;
10236 	event->bpf_cookie = bpf_cookie;
10237 	return 0;
10238 }
10239 
perf_event_free_bpf_handler(struct perf_event * event)10240 static inline void perf_event_free_bpf_handler(struct perf_event *event)
10241 {
10242 	struct bpf_prog *prog = event->prog;
10243 
10244 	if (!prog)
10245 		return;
10246 
10247 	event->prog = NULL;
10248 	bpf_prog_put(prog);
10249 }
10250 #else
bpf_overflow_handler(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)10251 static inline int bpf_overflow_handler(struct perf_event *event,
10252 				       struct perf_sample_data *data,
10253 				       struct pt_regs *regs)
10254 {
10255 	return 1;
10256 }
10257 
perf_event_set_bpf_handler(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)10258 static inline int perf_event_set_bpf_handler(struct perf_event *event,
10259 					     struct bpf_prog *prog,
10260 					     u64 bpf_cookie)
10261 {
10262 	return -EOPNOTSUPP;
10263 }
10264 
perf_event_free_bpf_handler(struct perf_event * event)10265 static inline void perf_event_free_bpf_handler(struct perf_event *event)
10266 {
10267 }
10268 #endif
10269 
10270 /*
10271  * Generic event overflow handling, sampling.
10272  */
10273 
__perf_event_overflow(struct perf_event * event,int throttle,struct perf_sample_data * data,struct pt_regs * regs)10274 static int __perf_event_overflow(struct perf_event *event,
10275 				 int throttle, struct perf_sample_data *data,
10276 				 struct pt_regs *regs)
10277 {
10278 	int events = atomic_read(&event->event_limit);
10279 	int ret = 0;
10280 
10281 	/*
10282 	 * Non-sampling counters might still use the PMI to fold short
10283 	 * hardware counters, ignore those.
10284 	 */
10285 	if (unlikely(!is_sampling_event(event)))
10286 		return 0;
10287 
10288 	ret = __perf_event_account_interrupt(event, throttle);
10289 
10290 	if (event->attr.aux_pause)
10291 		perf_event_aux_pause(event->aux_event, true);
10292 
10293 	if (event->prog && event->prog->type == BPF_PROG_TYPE_PERF_EVENT &&
10294 	    !bpf_overflow_handler(event, data, regs))
10295 		goto out;
10296 
10297 	/*
10298 	 * XXX event_limit might not quite work as expected on inherited
10299 	 * events
10300 	 */
10301 
10302 	event->pending_kill = POLL_IN;
10303 	if (events && atomic_dec_and_test(&event->event_limit)) {
10304 		ret = 1;
10305 		event->pending_kill = POLL_HUP;
10306 		perf_event_disable_inatomic(event);
10307 	}
10308 
10309 	if (event->attr.sigtrap) {
10310 		/*
10311 		 * The desired behaviour of sigtrap vs invalid samples is a bit
10312 		 * tricky; on the one hand, one should not loose the SIGTRAP if
10313 		 * it is the first event, on the other hand, we should also not
10314 		 * trigger the WARN or override the data address.
10315 		 */
10316 		bool valid_sample = sample_is_allowed(event, regs);
10317 		unsigned int pending_id = 1;
10318 		enum task_work_notify_mode notify_mode;
10319 
10320 		if (regs)
10321 			pending_id = hash32_ptr((void *)instruction_pointer(regs)) ?: 1;
10322 
10323 		notify_mode = in_nmi() ? TWA_NMI_CURRENT : TWA_RESUME;
10324 
10325 		if (!event->pending_work &&
10326 		    !task_work_add(current, &event->pending_task, notify_mode)) {
10327 			event->pending_work = pending_id;
10328 			local_inc(&event->ctx->nr_no_switch_fast);
10329 			WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount));
10330 
10331 			event->pending_addr = 0;
10332 			if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR))
10333 				event->pending_addr = data->addr;
10334 
10335 		} else if (event->attr.exclude_kernel && valid_sample) {
10336 			/*
10337 			 * Should not be able to return to user space without
10338 			 * consuming pending_work; with exceptions:
10339 			 *
10340 			 *  1. Where !exclude_kernel, events can overflow again
10341 			 *     in the kernel without returning to user space.
10342 			 *
10343 			 *  2. Events that can overflow again before the IRQ-
10344 			 *     work without user space progress (e.g. hrtimer).
10345 			 *     To approximate progress (with false negatives),
10346 			 *     check 32-bit hash of the current IP.
10347 			 */
10348 			WARN_ON_ONCE(event->pending_work != pending_id);
10349 		}
10350 	}
10351 
10352 	READ_ONCE(event->overflow_handler)(event, data, regs);
10353 
10354 	if (*perf_event_fasync(event) && event->pending_kill) {
10355 		event->pending_wakeup = 1;
10356 		irq_work_queue(&event->pending_irq);
10357 	}
10358 out:
10359 	if (event->attr.aux_resume)
10360 		perf_event_aux_pause(event->aux_event, false);
10361 
10362 	return ret;
10363 }
10364 
perf_event_overflow(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)10365 int perf_event_overflow(struct perf_event *event,
10366 			struct perf_sample_data *data,
10367 			struct pt_regs *regs)
10368 {
10369 	return __perf_event_overflow(event, 1, data, regs);
10370 }
10371 
10372 /*
10373  * Generic software event infrastructure
10374  */
10375 
10376 struct swevent_htable {
10377 	struct swevent_hlist		*swevent_hlist;
10378 	struct mutex			hlist_mutex;
10379 	int				hlist_refcount;
10380 };
10381 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
10382 
10383 /*
10384  * We directly increment event->count and keep a second value in
10385  * event->hw.period_left to count intervals. This period event
10386  * is kept in the range [-sample_period, 0] so that we can use the
10387  * sign as trigger.
10388  */
10389 
perf_swevent_set_period(struct perf_event * event)10390 u64 perf_swevent_set_period(struct perf_event *event)
10391 {
10392 	struct hw_perf_event *hwc = &event->hw;
10393 	u64 period = hwc->last_period;
10394 	u64 nr, offset;
10395 	s64 old, val;
10396 
10397 	hwc->last_period = hwc->sample_period;
10398 
10399 	old = local64_read(&hwc->period_left);
10400 	do {
10401 		val = old;
10402 		if (val < 0)
10403 			return 0;
10404 
10405 		nr = div64_u64(period + val, period);
10406 		offset = nr * period;
10407 		val -= offset;
10408 	} while (!local64_try_cmpxchg(&hwc->period_left, &old, val));
10409 
10410 	return nr;
10411 }
10412 
perf_swevent_overflow(struct perf_event * event,u64 overflow,struct perf_sample_data * data,struct pt_regs * regs)10413 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
10414 				    struct perf_sample_data *data,
10415 				    struct pt_regs *regs)
10416 {
10417 	struct hw_perf_event *hwc = &event->hw;
10418 	int throttle = 0;
10419 
10420 	if (!overflow)
10421 		overflow = perf_swevent_set_period(event);
10422 
10423 	if (hwc->interrupts == MAX_INTERRUPTS)
10424 		return;
10425 
10426 	for (; overflow; overflow--) {
10427 		if (__perf_event_overflow(event, throttle,
10428 					    data, regs)) {
10429 			/*
10430 			 * We inhibit the overflow from happening when
10431 			 * hwc->interrupts == MAX_INTERRUPTS.
10432 			 */
10433 			break;
10434 		}
10435 		throttle = 1;
10436 	}
10437 }
10438 
perf_swevent_event(struct perf_event * event,u64 nr,struct perf_sample_data * data,struct pt_regs * regs)10439 static void perf_swevent_event(struct perf_event *event, u64 nr,
10440 			       struct perf_sample_data *data,
10441 			       struct pt_regs *regs)
10442 {
10443 	struct hw_perf_event *hwc = &event->hw;
10444 
10445 	local64_add(nr, &event->count);
10446 
10447 	if (!regs)
10448 		return;
10449 
10450 	if (!is_sampling_event(event))
10451 		return;
10452 
10453 	if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
10454 		data->period = nr;
10455 		return perf_swevent_overflow(event, 1, data, regs);
10456 	} else
10457 		data->period = event->hw.last_period;
10458 
10459 	if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
10460 		return perf_swevent_overflow(event, 1, data, regs);
10461 
10462 	if (local64_add_negative(nr, &hwc->period_left))
10463 		return;
10464 
10465 	perf_swevent_overflow(event, 0, data, regs);
10466 }
10467 
perf_exclude_event(struct perf_event * event,struct pt_regs * regs)10468 int perf_exclude_event(struct perf_event *event, struct pt_regs *regs)
10469 {
10470 	if (event->hw.state & PERF_HES_STOPPED)
10471 		return 1;
10472 
10473 	if (regs) {
10474 		if (event->attr.exclude_user && user_mode(regs))
10475 			return 1;
10476 
10477 		if (event->attr.exclude_kernel && !user_mode(regs))
10478 			return 1;
10479 	}
10480 
10481 	return 0;
10482 }
10483 
perf_swevent_match(struct perf_event * event,enum perf_type_id type,u32 event_id,struct perf_sample_data * data,struct pt_regs * regs)10484 static int perf_swevent_match(struct perf_event *event,
10485 				enum perf_type_id type,
10486 				u32 event_id,
10487 				struct perf_sample_data *data,
10488 				struct pt_regs *regs)
10489 {
10490 	if (event->attr.type != type)
10491 		return 0;
10492 
10493 	if (event->attr.config != event_id)
10494 		return 0;
10495 
10496 	if (perf_exclude_event(event, regs))
10497 		return 0;
10498 
10499 	return 1;
10500 }
10501 
swevent_hash(u64 type,u32 event_id)10502 static inline u64 swevent_hash(u64 type, u32 event_id)
10503 {
10504 	u64 val = event_id | (type << 32);
10505 
10506 	return hash_64(val, SWEVENT_HLIST_BITS);
10507 }
10508 
10509 static inline struct hlist_head *
__find_swevent_head(struct swevent_hlist * hlist,u64 type,u32 event_id)10510 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
10511 {
10512 	u64 hash = swevent_hash(type, event_id);
10513 
10514 	return &hlist->heads[hash];
10515 }
10516 
10517 /* For the read side: events when they trigger */
10518 static inline struct hlist_head *
find_swevent_head_rcu(struct swevent_htable * swhash,u64 type,u32 event_id)10519 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
10520 {
10521 	struct swevent_hlist *hlist;
10522 
10523 	hlist = rcu_dereference(swhash->swevent_hlist);
10524 	if (!hlist)
10525 		return NULL;
10526 
10527 	return __find_swevent_head(hlist, type, event_id);
10528 }
10529 
10530 /* For the event head insertion and removal in the hlist */
10531 static inline struct hlist_head *
find_swevent_head(struct swevent_htable * swhash,struct perf_event * event)10532 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
10533 {
10534 	struct swevent_hlist *hlist;
10535 	u32 event_id = event->attr.config;
10536 	u64 type = event->attr.type;
10537 
10538 	/*
10539 	 * Event scheduling is always serialized against hlist allocation
10540 	 * and release. Which makes the protected version suitable here.
10541 	 * The context lock guarantees that.
10542 	 */
10543 	hlist = rcu_dereference_protected(swhash->swevent_hlist,
10544 					  lockdep_is_held(&event->ctx->lock));
10545 	if (!hlist)
10546 		return NULL;
10547 
10548 	return __find_swevent_head(hlist, type, event_id);
10549 }
10550 
do_perf_sw_event(enum perf_type_id type,u32 event_id,u64 nr,struct perf_sample_data * data,struct pt_regs * regs)10551 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
10552 				    u64 nr,
10553 				    struct perf_sample_data *data,
10554 				    struct pt_regs *regs)
10555 {
10556 	struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
10557 	struct perf_event *event;
10558 	struct hlist_head *head;
10559 
10560 	rcu_read_lock();
10561 	head = find_swevent_head_rcu(swhash, type, event_id);
10562 	if (!head)
10563 		goto end;
10564 
10565 	hlist_for_each_entry_rcu(event, head, hlist_entry) {
10566 		if (perf_swevent_match(event, type, event_id, data, regs))
10567 			perf_swevent_event(event, nr, data, regs);
10568 	}
10569 end:
10570 	rcu_read_unlock();
10571 }
10572 
10573 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
10574 
perf_swevent_get_recursion_context(void)10575 int perf_swevent_get_recursion_context(void)
10576 {
10577 	return get_recursion_context(current->perf_recursion);
10578 }
10579 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
10580 
perf_swevent_put_recursion_context(int rctx)10581 void perf_swevent_put_recursion_context(int rctx)
10582 {
10583 	put_recursion_context(current->perf_recursion, rctx);
10584 }
10585 
___perf_sw_event(u32 event_id,u64 nr,struct pt_regs * regs,u64 addr)10586 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
10587 {
10588 	struct perf_sample_data data;
10589 
10590 	if (WARN_ON_ONCE(!regs))
10591 		return;
10592 
10593 	perf_sample_data_init(&data, addr, 0);
10594 	do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
10595 }
10596 
__perf_sw_event(u32 event_id,u64 nr,struct pt_regs * regs,u64 addr)10597 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
10598 {
10599 	int rctx;
10600 
10601 	preempt_disable_notrace();
10602 	rctx = perf_swevent_get_recursion_context();
10603 	if (unlikely(rctx < 0))
10604 		goto fail;
10605 
10606 	___perf_sw_event(event_id, nr, regs, addr);
10607 
10608 	perf_swevent_put_recursion_context(rctx);
10609 fail:
10610 	preempt_enable_notrace();
10611 }
10612 
perf_swevent_read(struct perf_event * event)10613 static void perf_swevent_read(struct perf_event *event)
10614 {
10615 }
10616 
perf_swevent_add(struct perf_event * event,int flags)10617 static int perf_swevent_add(struct perf_event *event, int flags)
10618 {
10619 	struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
10620 	struct hw_perf_event *hwc = &event->hw;
10621 	struct hlist_head *head;
10622 
10623 	if (is_sampling_event(event)) {
10624 		hwc->last_period = hwc->sample_period;
10625 		perf_swevent_set_period(event);
10626 	}
10627 
10628 	hwc->state = !(flags & PERF_EF_START);
10629 
10630 	head = find_swevent_head(swhash, event);
10631 	if (WARN_ON_ONCE(!head))
10632 		return -EINVAL;
10633 
10634 	hlist_add_head_rcu(&event->hlist_entry, head);
10635 	perf_event_update_userpage(event);
10636 
10637 	return 0;
10638 }
10639 
perf_swevent_del(struct perf_event * event,int flags)10640 static void perf_swevent_del(struct perf_event *event, int flags)
10641 {
10642 	hlist_del_rcu(&event->hlist_entry);
10643 }
10644 
perf_swevent_start(struct perf_event * event,int flags)10645 static void perf_swevent_start(struct perf_event *event, int flags)
10646 {
10647 	event->hw.state = 0;
10648 }
10649 
perf_swevent_stop(struct perf_event * event,int flags)10650 static void perf_swevent_stop(struct perf_event *event, int flags)
10651 {
10652 	event->hw.state = PERF_HES_STOPPED;
10653 }
10654 
10655 /* Deref the hlist from the update side */
10656 static inline struct swevent_hlist *
swevent_hlist_deref(struct swevent_htable * swhash)10657 swevent_hlist_deref(struct swevent_htable *swhash)
10658 {
10659 	return rcu_dereference_protected(swhash->swevent_hlist,
10660 					 lockdep_is_held(&swhash->hlist_mutex));
10661 }
10662 
swevent_hlist_release(struct swevent_htable * swhash)10663 static void swevent_hlist_release(struct swevent_htable *swhash)
10664 {
10665 	struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
10666 
10667 	if (!hlist)
10668 		return;
10669 
10670 	RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
10671 	kfree_rcu(hlist, rcu_head);
10672 }
10673 
swevent_hlist_put_cpu(int cpu)10674 static void swevent_hlist_put_cpu(int cpu)
10675 {
10676 	struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
10677 
10678 	mutex_lock(&swhash->hlist_mutex);
10679 
10680 	if (!--swhash->hlist_refcount)
10681 		swevent_hlist_release(swhash);
10682 
10683 	mutex_unlock(&swhash->hlist_mutex);
10684 }
10685 
swevent_hlist_put(void)10686 static void swevent_hlist_put(void)
10687 {
10688 	int cpu;
10689 
10690 	for_each_possible_cpu(cpu)
10691 		swevent_hlist_put_cpu(cpu);
10692 }
10693 
swevent_hlist_get_cpu(int cpu)10694 static int swevent_hlist_get_cpu(int cpu)
10695 {
10696 	struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
10697 	int err = 0;
10698 
10699 	mutex_lock(&swhash->hlist_mutex);
10700 	if (!swevent_hlist_deref(swhash) &&
10701 	    cpumask_test_cpu(cpu, perf_online_mask)) {
10702 		struct swevent_hlist *hlist;
10703 
10704 		hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
10705 		if (!hlist) {
10706 			err = -ENOMEM;
10707 			goto exit;
10708 		}
10709 		rcu_assign_pointer(swhash->swevent_hlist, hlist);
10710 	}
10711 	swhash->hlist_refcount++;
10712 exit:
10713 	mutex_unlock(&swhash->hlist_mutex);
10714 
10715 	return err;
10716 }
10717 
swevent_hlist_get(void)10718 static int swevent_hlist_get(void)
10719 {
10720 	int err, cpu, failed_cpu;
10721 
10722 	mutex_lock(&pmus_lock);
10723 	for_each_possible_cpu(cpu) {
10724 		err = swevent_hlist_get_cpu(cpu);
10725 		if (err) {
10726 			failed_cpu = cpu;
10727 			goto fail;
10728 		}
10729 	}
10730 	mutex_unlock(&pmus_lock);
10731 	return 0;
10732 fail:
10733 	for_each_possible_cpu(cpu) {
10734 		if (cpu == failed_cpu)
10735 			break;
10736 		swevent_hlist_put_cpu(cpu);
10737 	}
10738 	mutex_unlock(&pmus_lock);
10739 	return err;
10740 }
10741 
10742 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
10743 
sw_perf_event_destroy(struct perf_event * event)10744 static void sw_perf_event_destroy(struct perf_event *event)
10745 {
10746 	u64 event_id = event->attr.config;
10747 
10748 	WARN_ON(event->parent);
10749 
10750 	static_key_slow_dec(&perf_swevent_enabled[event_id]);
10751 	swevent_hlist_put();
10752 }
10753 
10754 static struct pmu perf_cpu_clock; /* fwd declaration */
10755 static struct pmu perf_task_clock;
10756 
perf_swevent_init(struct perf_event * event)10757 static int perf_swevent_init(struct perf_event *event)
10758 {
10759 	u64 event_id = event->attr.config;
10760 
10761 	if (event->attr.type != PERF_TYPE_SOFTWARE)
10762 		return -ENOENT;
10763 
10764 	/*
10765 	 * no branch sampling for software events
10766 	 */
10767 	if (has_branch_stack(event))
10768 		return -EOPNOTSUPP;
10769 
10770 	switch (event_id) {
10771 	case PERF_COUNT_SW_CPU_CLOCK:
10772 		event->attr.type = perf_cpu_clock.type;
10773 		return -ENOENT;
10774 	case PERF_COUNT_SW_TASK_CLOCK:
10775 		event->attr.type = perf_task_clock.type;
10776 		return -ENOENT;
10777 
10778 	default:
10779 		break;
10780 	}
10781 
10782 	if (event_id >= PERF_COUNT_SW_MAX)
10783 		return -ENOENT;
10784 
10785 	if (!event->parent) {
10786 		int err;
10787 
10788 		err = swevent_hlist_get();
10789 		if (err)
10790 			return err;
10791 
10792 		static_key_slow_inc(&perf_swevent_enabled[event_id]);
10793 		event->destroy = sw_perf_event_destroy;
10794 	}
10795 
10796 	return 0;
10797 }
10798 
10799 static struct pmu perf_swevent = {
10800 	.task_ctx_nr	= perf_sw_context,
10801 
10802 	.capabilities	= PERF_PMU_CAP_NO_NMI,
10803 
10804 	.event_init	= perf_swevent_init,
10805 	.add		= perf_swevent_add,
10806 	.del		= perf_swevent_del,
10807 	.start		= perf_swevent_start,
10808 	.stop		= perf_swevent_stop,
10809 	.read		= perf_swevent_read,
10810 };
10811 
10812 #ifdef CONFIG_EVENT_TRACING
10813 
tp_perf_event_destroy(struct perf_event * event)10814 static void tp_perf_event_destroy(struct perf_event *event)
10815 {
10816 	perf_trace_destroy(event);
10817 }
10818 
perf_tp_event_init(struct perf_event * event)10819 static int perf_tp_event_init(struct perf_event *event)
10820 {
10821 	int err;
10822 
10823 	if (event->attr.type != PERF_TYPE_TRACEPOINT)
10824 		return -ENOENT;
10825 
10826 	/*
10827 	 * no branch sampling for tracepoint events
10828 	 */
10829 	if (has_branch_stack(event))
10830 		return -EOPNOTSUPP;
10831 
10832 	err = perf_trace_init(event);
10833 	if (err)
10834 		return err;
10835 
10836 	event->destroy = tp_perf_event_destroy;
10837 
10838 	return 0;
10839 }
10840 
10841 static struct pmu perf_tracepoint = {
10842 	.task_ctx_nr	= perf_sw_context,
10843 
10844 	.event_init	= perf_tp_event_init,
10845 	.add		= perf_trace_add,
10846 	.del		= perf_trace_del,
10847 	.start		= perf_swevent_start,
10848 	.stop		= perf_swevent_stop,
10849 	.read		= perf_swevent_read,
10850 };
10851 
perf_tp_filter_match(struct perf_event * event,struct perf_raw_record * raw)10852 static int perf_tp_filter_match(struct perf_event *event,
10853 				struct perf_raw_record *raw)
10854 {
10855 	void *record = raw->frag.data;
10856 
10857 	/* only top level events have filters set */
10858 	if (event->parent)
10859 		event = event->parent;
10860 
10861 	if (likely(!event->filter) || filter_match_preds(event->filter, record))
10862 		return 1;
10863 	return 0;
10864 }
10865 
perf_tp_event_match(struct perf_event * event,struct perf_raw_record * raw,struct pt_regs * regs)10866 static int perf_tp_event_match(struct perf_event *event,
10867 				struct perf_raw_record *raw,
10868 				struct pt_regs *regs)
10869 {
10870 	if (event->hw.state & PERF_HES_STOPPED)
10871 		return 0;
10872 	/*
10873 	 * If exclude_kernel, only trace user-space tracepoints (uprobes)
10874 	 */
10875 	if (event->attr.exclude_kernel && !user_mode(regs))
10876 		return 0;
10877 
10878 	if (!perf_tp_filter_match(event, raw))
10879 		return 0;
10880 
10881 	return 1;
10882 }
10883 
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)10884 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
10885 			       struct trace_event_call *call, u64 count,
10886 			       struct pt_regs *regs, struct hlist_head *head,
10887 			       struct task_struct *task)
10888 {
10889 	if (bpf_prog_array_valid(call)) {
10890 		*(struct pt_regs **)raw_data = regs;
10891 		if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
10892 			perf_swevent_put_recursion_context(rctx);
10893 			return;
10894 		}
10895 	}
10896 	perf_tp_event(call->event.type, count, raw_data, size, regs, head,
10897 		      rctx, task);
10898 }
10899 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
10900 
__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)10901 static void __perf_tp_event_target_task(u64 count, void *record,
10902 					struct pt_regs *regs,
10903 					struct perf_sample_data *data,
10904 					struct perf_raw_record *raw,
10905 					struct perf_event *event)
10906 {
10907 	struct trace_entry *entry = record;
10908 
10909 	if (event->attr.config != entry->type)
10910 		return;
10911 	/* Cannot deliver synchronous signal to other task. */
10912 	if (event->attr.sigtrap)
10913 		return;
10914 	if (perf_tp_event_match(event, raw, regs)) {
10915 		perf_sample_data_init(data, 0, 0);
10916 		perf_sample_save_raw_data(data, event, raw);
10917 		perf_swevent_event(event, count, data, regs);
10918 	}
10919 }
10920 
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)10921 static void perf_tp_event_target_task(u64 count, void *record,
10922 				      struct pt_regs *regs,
10923 				      struct perf_sample_data *data,
10924 				      struct perf_raw_record *raw,
10925 				      struct perf_event_context *ctx)
10926 {
10927 	unsigned int cpu = smp_processor_id();
10928 	struct pmu *pmu = &perf_tracepoint;
10929 	struct perf_event *event, *sibling;
10930 
10931 	perf_event_groups_for_cpu_pmu(event, &ctx->pinned_groups, cpu, pmu) {
10932 		__perf_tp_event_target_task(count, record, regs, data, raw, event);
10933 		for_each_sibling_event(sibling, event)
10934 			__perf_tp_event_target_task(count, record, regs, data, raw, sibling);
10935 	}
10936 
10937 	perf_event_groups_for_cpu_pmu(event, &ctx->flexible_groups, cpu, pmu) {
10938 		__perf_tp_event_target_task(count, record, regs, data, raw, event);
10939 		for_each_sibling_event(sibling, event)
10940 			__perf_tp_event_target_task(count, record, regs, data, raw, sibling);
10941 	}
10942 }
10943 
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)10944 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
10945 		   struct pt_regs *regs, struct hlist_head *head, int rctx,
10946 		   struct task_struct *task)
10947 {
10948 	struct perf_sample_data data;
10949 	struct perf_event *event;
10950 
10951 	struct perf_raw_record raw = {
10952 		.frag = {
10953 			.size = entry_size,
10954 			.data = record,
10955 		},
10956 	};
10957 
10958 	perf_trace_buf_update(record, event_type);
10959 
10960 	hlist_for_each_entry_rcu(event, head, hlist_entry) {
10961 		if (perf_tp_event_match(event, &raw, regs)) {
10962 			/*
10963 			 * Here use the same on-stack perf_sample_data,
10964 			 * some members in data are event-specific and
10965 			 * need to be re-computed for different sweveents.
10966 			 * Re-initialize data->sample_flags safely to avoid
10967 			 * the problem that next event skips preparing data
10968 			 * because data->sample_flags is set.
10969 			 */
10970 			perf_sample_data_init(&data, 0, 0);
10971 			perf_sample_save_raw_data(&data, event, &raw);
10972 			perf_swevent_event(event, count, &data, regs);
10973 		}
10974 	}
10975 
10976 	/*
10977 	 * If we got specified a target task, also iterate its context and
10978 	 * deliver this event there too.
10979 	 */
10980 	if (task && task != current) {
10981 		struct perf_event_context *ctx;
10982 
10983 		rcu_read_lock();
10984 		ctx = rcu_dereference(task->perf_event_ctxp);
10985 		if (!ctx)
10986 			goto unlock;
10987 
10988 		raw_spin_lock(&ctx->lock);
10989 		perf_tp_event_target_task(count, record, regs, &data, &raw, ctx);
10990 		raw_spin_unlock(&ctx->lock);
10991 unlock:
10992 		rcu_read_unlock();
10993 	}
10994 
10995 	perf_swevent_put_recursion_context(rctx);
10996 }
10997 EXPORT_SYMBOL_GPL(perf_tp_event);
10998 
10999 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
11000 /*
11001  * Flags in config, used by dynamic PMU kprobe and uprobe
11002  * The flags should match following PMU_FORMAT_ATTR().
11003  *
11004  * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
11005  *                               if not set, create kprobe/uprobe
11006  *
11007  * The following values specify a reference counter (or semaphore in the
11008  * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
11009  * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
11010  *
11011  * PERF_UPROBE_REF_CTR_OFFSET_BITS	# of bits in config as th offset
11012  * PERF_UPROBE_REF_CTR_OFFSET_SHIFT	# of bits to shift left
11013  */
11014 enum perf_probe_config {
11015 	PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0,  /* [k,u]retprobe */
11016 	PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
11017 	PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
11018 };
11019 
11020 PMU_FORMAT_ATTR(retprobe, "config:0");
11021 #endif
11022 
11023 #ifdef CONFIG_KPROBE_EVENTS
11024 static struct attribute *kprobe_attrs[] = {
11025 	&format_attr_retprobe.attr,
11026 	NULL,
11027 };
11028 
11029 static struct attribute_group kprobe_format_group = {
11030 	.name = "format",
11031 	.attrs = kprobe_attrs,
11032 };
11033 
11034 static const struct attribute_group *kprobe_attr_groups[] = {
11035 	&kprobe_format_group,
11036 	NULL,
11037 };
11038 
11039 static int perf_kprobe_event_init(struct perf_event *event);
11040 static struct pmu perf_kprobe = {
11041 	.task_ctx_nr	= perf_sw_context,
11042 	.event_init	= perf_kprobe_event_init,
11043 	.add		= perf_trace_add,
11044 	.del		= perf_trace_del,
11045 	.start		= perf_swevent_start,
11046 	.stop		= perf_swevent_stop,
11047 	.read		= perf_swevent_read,
11048 	.attr_groups	= kprobe_attr_groups,
11049 };
11050 
perf_kprobe_event_init(struct perf_event * event)11051 static int perf_kprobe_event_init(struct perf_event *event)
11052 {
11053 	int err;
11054 	bool is_retprobe;
11055 
11056 	if (event->attr.type != perf_kprobe.type)
11057 		return -ENOENT;
11058 
11059 	if (!perfmon_capable())
11060 		return -EACCES;
11061 
11062 	/*
11063 	 * no branch sampling for probe events
11064 	 */
11065 	if (has_branch_stack(event))
11066 		return -EOPNOTSUPP;
11067 
11068 	is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
11069 	err = perf_kprobe_init(event, is_retprobe);
11070 	if (err)
11071 		return err;
11072 
11073 	event->destroy = perf_kprobe_destroy;
11074 
11075 	return 0;
11076 }
11077 #endif /* CONFIG_KPROBE_EVENTS */
11078 
11079 #ifdef CONFIG_UPROBE_EVENTS
11080 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
11081 
11082 static struct attribute *uprobe_attrs[] = {
11083 	&format_attr_retprobe.attr,
11084 	&format_attr_ref_ctr_offset.attr,
11085 	NULL,
11086 };
11087 
11088 static struct attribute_group uprobe_format_group = {
11089 	.name = "format",
11090 	.attrs = uprobe_attrs,
11091 };
11092 
11093 static const struct attribute_group *uprobe_attr_groups[] = {
11094 	&uprobe_format_group,
11095 	NULL,
11096 };
11097 
11098 static int perf_uprobe_event_init(struct perf_event *event);
11099 static struct pmu perf_uprobe = {
11100 	.task_ctx_nr	= perf_sw_context,
11101 	.event_init	= perf_uprobe_event_init,
11102 	.add		= perf_trace_add,
11103 	.del		= perf_trace_del,
11104 	.start		= perf_swevent_start,
11105 	.stop		= perf_swevent_stop,
11106 	.read		= perf_swevent_read,
11107 	.attr_groups	= uprobe_attr_groups,
11108 };
11109 
perf_uprobe_event_init(struct perf_event * event)11110 static int perf_uprobe_event_init(struct perf_event *event)
11111 {
11112 	int err;
11113 	unsigned long ref_ctr_offset;
11114 	bool is_retprobe;
11115 
11116 	if (event->attr.type != perf_uprobe.type)
11117 		return -ENOENT;
11118 
11119 	if (!perfmon_capable())
11120 		return -EACCES;
11121 
11122 	/*
11123 	 * no branch sampling for probe events
11124 	 */
11125 	if (has_branch_stack(event))
11126 		return -EOPNOTSUPP;
11127 
11128 	is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
11129 	ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
11130 	err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
11131 	if (err)
11132 		return err;
11133 
11134 	event->destroy = perf_uprobe_destroy;
11135 
11136 	return 0;
11137 }
11138 #endif /* CONFIG_UPROBE_EVENTS */
11139 
perf_tp_register(void)11140 static inline void perf_tp_register(void)
11141 {
11142 	perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
11143 #ifdef CONFIG_KPROBE_EVENTS
11144 	perf_pmu_register(&perf_kprobe, "kprobe", -1);
11145 #endif
11146 #ifdef CONFIG_UPROBE_EVENTS
11147 	perf_pmu_register(&perf_uprobe, "uprobe", -1);
11148 #endif
11149 }
11150 
perf_event_free_filter(struct perf_event * event)11151 static void perf_event_free_filter(struct perf_event *event)
11152 {
11153 	ftrace_profile_free_filter(event);
11154 }
11155 
11156 /*
11157  * returns true if the event is a tracepoint, or a kprobe/upprobe created
11158  * with perf_event_open()
11159  */
perf_event_is_tracing(struct perf_event * event)11160 static inline bool perf_event_is_tracing(struct perf_event *event)
11161 {
11162 	if (event->pmu == &perf_tracepoint)
11163 		return true;
11164 #ifdef CONFIG_KPROBE_EVENTS
11165 	if (event->pmu == &perf_kprobe)
11166 		return true;
11167 #endif
11168 #ifdef CONFIG_UPROBE_EVENTS
11169 	if (event->pmu == &perf_uprobe)
11170 		return true;
11171 #endif
11172 	return false;
11173 }
11174 
__perf_event_set_bpf_prog(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)11175 static int __perf_event_set_bpf_prog(struct perf_event *event,
11176 				     struct bpf_prog *prog,
11177 				     u64 bpf_cookie)
11178 {
11179 	bool is_kprobe, is_uprobe, is_tracepoint, is_syscall_tp;
11180 
11181 	if (event->state <= PERF_EVENT_STATE_REVOKED)
11182 		return -ENODEV;
11183 
11184 	if (!perf_event_is_tracing(event))
11185 		return perf_event_set_bpf_handler(event, prog, bpf_cookie);
11186 
11187 	is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_KPROBE;
11188 	is_uprobe = event->tp_event->flags & TRACE_EVENT_FL_UPROBE;
11189 	is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
11190 	is_syscall_tp = is_syscall_trace_event(event->tp_event);
11191 	if (!is_kprobe && !is_uprobe && !is_tracepoint && !is_syscall_tp)
11192 		/* bpf programs can only be attached to u/kprobe or tracepoint */
11193 		return -EINVAL;
11194 
11195 	if (((is_kprobe || is_uprobe) && prog->type != BPF_PROG_TYPE_KPROBE) ||
11196 	    (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
11197 	    (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT))
11198 		return -EINVAL;
11199 
11200 	if (prog->type == BPF_PROG_TYPE_KPROBE && prog->sleepable && !is_uprobe)
11201 		/* only uprobe programs are allowed to be sleepable */
11202 		return -EINVAL;
11203 
11204 	/* Kprobe override only works for kprobes, not uprobes. */
11205 	if (prog->kprobe_override && !is_kprobe)
11206 		return -EINVAL;
11207 
11208 	if (is_tracepoint || is_syscall_tp) {
11209 		int off = trace_event_get_offsets(event->tp_event);
11210 
11211 		if (prog->aux->max_ctx_offset > off)
11212 			return -EACCES;
11213 	}
11214 
11215 	return perf_event_attach_bpf_prog(event, prog, bpf_cookie);
11216 }
11217 
perf_event_set_bpf_prog(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)11218 int perf_event_set_bpf_prog(struct perf_event *event,
11219 			    struct bpf_prog *prog,
11220 			    u64 bpf_cookie)
11221 {
11222 	struct perf_event_context *ctx;
11223 	int ret;
11224 
11225 	ctx = perf_event_ctx_lock(event);
11226 	ret = __perf_event_set_bpf_prog(event, prog, bpf_cookie);
11227 	perf_event_ctx_unlock(event, ctx);
11228 
11229 	return ret;
11230 }
11231 
perf_event_free_bpf_prog(struct perf_event * event)11232 void perf_event_free_bpf_prog(struct perf_event *event)
11233 {
11234 	if (!event->prog)
11235 		return;
11236 
11237 	if (!perf_event_is_tracing(event)) {
11238 		perf_event_free_bpf_handler(event);
11239 		return;
11240 	}
11241 	perf_event_detach_bpf_prog(event);
11242 }
11243 
11244 #else
11245 
perf_tp_register(void)11246 static inline void perf_tp_register(void)
11247 {
11248 }
11249 
perf_event_free_filter(struct perf_event * event)11250 static void perf_event_free_filter(struct perf_event *event)
11251 {
11252 }
11253 
__perf_event_set_bpf_prog(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)11254 static int __perf_event_set_bpf_prog(struct perf_event *event,
11255 				     struct bpf_prog *prog,
11256 				     u64 bpf_cookie)
11257 {
11258 	return -ENOENT;
11259 }
11260 
perf_event_set_bpf_prog(struct perf_event * event,struct bpf_prog * prog,u64 bpf_cookie)11261 int perf_event_set_bpf_prog(struct perf_event *event,
11262 			    struct bpf_prog *prog,
11263 			    u64 bpf_cookie)
11264 {
11265 	return -ENOENT;
11266 }
11267 
perf_event_free_bpf_prog(struct perf_event * event)11268 void perf_event_free_bpf_prog(struct perf_event *event)
11269 {
11270 }
11271 #endif /* CONFIG_EVENT_TRACING */
11272 
11273 #ifdef CONFIG_HAVE_HW_BREAKPOINT
perf_bp_event(struct perf_event * bp,void * data)11274 void perf_bp_event(struct perf_event *bp, void *data)
11275 {
11276 	struct perf_sample_data sample;
11277 	struct pt_regs *regs = data;
11278 
11279 	perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
11280 
11281 	if (!bp->hw.state && !perf_exclude_event(bp, regs))
11282 		perf_swevent_event(bp, 1, &sample, regs);
11283 }
11284 #endif
11285 
11286 /*
11287  * Allocate a new address filter
11288  */
11289 static struct perf_addr_filter *
perf_addr_filter_new(struct perf_event * event,struct list_head * filters)11290 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
11291 {
11292 	int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
11293 	struct perf_addr_filter *filter;
11294 
11295 	filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
11296 	if (!filter)
11297 		return NULL;
11298 
11299 	INIT_LIST_HEAD(&filter->entry);
11300 	list_add_tail(&filter->entry, filters);
11301 
11302 	return filter;
11303 }
11304 
free_filters_list(struct list_head * filters)11305 static void free_filters_list(struct list_head *filters)
11306 {
11307 	struct perf_addr_filter *filter, *iter;
11308 
11309 	list_for_each_entry_safe(filter, iter, filters, entry) {
11310 		path_put(&filter->path);
11311 		list_del(&filter->entry);
11312 		kfree(filter);
11313 	}
11314 }
11315 
11316 /*
11317  * Free existing address filters and optionally install new ones
11318  */
perf_addr_filters_splice(struct perf_event * event,struct list_head * head)11319 static void perf_addr_filters_splice(struct perf_event *event,
11320 				     struct list_head *head)
11321 {
11322 	unsigned long flags;
11323 	LIST_HEAD(list);
11324 
11325 	if (!has_addr_filter(event))
11326 		return;
11327 
11328 	/* don't bother with children, they don't have their own filters */
11329 	if (event->parent)
11330 		return;
11331 
11332 	raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
11333 
11334 	list_splice_init(&event->addr_filters.list, &list);
11335 	if (head)
11336 		list_splice(head, &event->addr_filters.list);
11337 
11338 	raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
11339 
11340 	free_filters_list(&list);
11341 }
11342 
perf_free_addr_filters(struct perf_event * event)11343 static void perf_free_addr_filters(struct perf_event *event)
11344 {
11345 	/*
11346 	 * Used during free paths, there is no concurrency.
11347 	 */
11348 	if (list_empty(&event->addr_filters.list))
11349 		return;
11350 
11351 	perf_addr_filters_splice(event, NULL);
11352 }
11353 
11354 /*
11355  * Scan through mm's vmas and see if one of them matches the
11356  * @filter; if so, adjust filter's address range.
11357  * Called with mm::mmap_lock down for reading.
11358  */
perf_addr_filter_apply(struct perf_addr_filter * filter,struct mm_struct * mm,struct perf_addr_filter_range * fr)11359 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
11360 				   struct mm_struct *mm,
11361 				   struct perf_addr_filter_range *fr)
11362 {
11363 	struct vm_area_struct *vma;
11364 	VMA_ITERATOR(vmi, mm, 0);
11365 
11366 	for_each_vma(vmi, vma) {
11367 		if (!vma->vm_file)
11368 			continue;
11369 
11370 		if (perf_addr_filter_vma_adjust(filter, vma, fr))
11371 			return;
11372 	}
11373 }
11374 
11375 /*
11376  * Update event's address range filters based on the
11377  * task's existing mappings, if any.
11378  */
perf_event_addr_filters_apply(struct perf_event * event)11379 static void perf_event_addr_filters_apply(struct perf_event *event)
11380 {
11381 	struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11382 	struct task_struct *task = READ_ONCE(event->ctx->task);
11383 	struct perf_addr_filter *filter;
11384 	struct mm_struct *mm = NULL;
11385 	unsigned int count = 0;
11386 	unsigned long flags;
11387 
11388 	/*
11389 	 * We may observe TASK_TOMBSTONE, which means that the event tear-down
11390 	 * will stop on the parent's child_mutex that our caller is also holding
11391 	 */
11392 	if (task == TASK_TOMBSTONE)
11393 		return;
11394 
11395 	if (ifh->nr_file_filters) {
11396 		mm = get_task_mm(task);
11397 		if (!mm)
11398 			goto restart;
11399 
11400 		mmap_read_lock(mm);
11401 	}
11402 
11403 	raw_spin_lock_irqsave(&ifh->lock, flags);
11404 	list_for_each_entry(filter, &ifh->list, entry) {
11405 		if (filter->path.dentry) {
11406 			/*
11407 			 * Adjust base offset if the filter is associated to a
11408 			 * binary that needs to be mapped:
11409 			 */
11410 			event->addr_filter_ranges[count].start = 0;
11411 			event->addr_filter_ranges[count].size = 0;
11412 
11413 			perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
11414 		} else {
11415 			event->addr_filter_ranges[count].start = filter->offset;
11416 			event->addr_filter_ranges[count].size  = filter->size;
11417 		}
11418 
11419 		count++;
11420 	}
11421 
11422 	event->addr_filters_gen++;
11423 	raw_spin_unlock_irqrestore(&ifh->lock, flags);
11424 
11425 	if (ifh->nr_file_filters) {
11426 		mmap_read_unlock(mm);
11427 
11428 		mmput(mm);
11429 	}
11430 
11431 restart:
11432 	perf_event_stop(event, 1);
11433 }
11434 
11435 /*
11436  * Address range filtering: limiting the data to certain
11437  * instruction address ranges. Filters are ioctl()ed to us from
11438  * userspace as ascii strings.
11439  *
11440  * Filter string format:
11441  *
11442  * ACTION RANGE_SPEC
11443  * where ACTION is one of the
11444  *  * "filter": limit the trace to this region
11445  *  * "start": start tracing from this address
11446  *  * "stop": stop tracing at this address/region;
11447  * RANGE_SPEC is
11448  *  * for kernel addresses: <start address>[/<size>]
11449  *  * for object files:     <start address>[/<size>]@</path/to/object/file>
11450  *
11451  * if <size> is not specified or is zero, the range is treated as a single
11452  * address; not valid for ACTION=="filter".
11453  */
11454 enum {
11455 	IF_ACT_NONE = -1,
11456 	IF_ACT_FILTER,
11457 	IF_ACT_START,
11458 	IF_ACT_STOP,
11459 	IF_SRC_FILE,
11460 	IF_SRC_KERNEL,
11461 	IF_SRC_FILEADDR,
11462 	IF_SRC_KERNELADDR,
11463 };
11464 
11465 enum {
11466 	IF_STATE_ACTION = 0,
11467 	IF_STATE_SOURCE,
11468 	IF_STATE_END,
11469 };
11470 
11471 static const match_table_t if_tokens = {
11472 	{ IF_ACT_FILTER,	"filter" },
11473 	{ IF_ACT_START,		"start" },
11474 	{ IF_ACT_STOP,		"stop" },
11475 	{ IF_SRC_FILE,		"%u/%u@%s" },
11476 	{ IF_SRC_KERNEL,	"%u/%u" },
11477 	{ IF_SRC_FILEADDR,	"%u@%s" },
11478 	{ IF_SRC_KERNELADDR,	"%u" },
11479 	{ IF_ACT_NONE,		NULL },
11480 };
11481 
11482 /*
11483  * Address filter string parser
11484  */
11485 static int
perf_event_parse_addr_filter(struct perf_event * event,char * fstr,struct list_head * filters)11486 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
11487 			     struct list_head *filters)
11488 {
11489 	struct perf_addr_filter *filter = NULL;
11490 	char *start, *orig, *filename = NULL;
11491 	substring_t args[MAX_OPT_ARGS];
11492 	int state = IF_STATE_ACTION, token;
11493 	unsigned int kernel = 0;
11494 	int ret = -EINVAL;
11495 
11496 	orig = fstr = kstrdup(fstr, GFP_KERNEL);
11497 	if (!fstr)
11498 		return -ENOMEM;
11499 
11500 	while ((start = strsep(&fstr, " ,\n")) != NULL) {
11501 		static const enum perf_addr_filter_action_t actions[] = {
11502 			[IF_ACT_FILTER]	= PERF_ADDR_FILTER_ACTION_FILTER,
11503 			[IF_ACT_START]	= PERF_ADDR_FILTER_ACTION_START,
11504 			[IF_ACT_STOP]	= PERF_ADDR_FILTER_ACTION_STOP,
11505 		};
11506 		ret = -EINVAL;
11507 
11508 		if (!*start)
11509 			continue;
11510 
11511 		/* filter definition begins */
11512 		if (state == IF_STATE_ACTION) {
11513 			filter = perf_addr_filter_new(event, filters);
11514 			if (!filter)
11515 				goto fail;
11516 		}
11517 
11518 		token = match_token(start, if_tokens, args);
11519 		switch (token) {
11520 		case IF_ACT_FILTER:
11521 		case IF_ACT_START:
11522 		case IF_ACT_STOP:
11523 			if (state != IF_STATE_ACTION)
11524 				goto fail;
11525 
11526 			filter->action = actions[token];
11527 			state = IF_STATE_SOURCE;
11528 			break;
11529 
11530 		case IF_SRC_KERNELADDR:
11531 		case IF_SRC_KERNEL:
11532 			kernel = 1;
11533 			fallthrough;
11534 
11535 		case IF_SRC_FILEADDR:
11536 		case IF_SRC_FILE:
11537 			if (state != IF_STATE_SOURCE)
11538 				goto fail;
11539 
11540 			*args[0].to = 0;
11541 			ret = kstrtoul(args[0].from, 0, &filter->offset);
11542 			if (ret)
11543 				goto fail;
11544 
11545 			if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
11546 				*args[1].to = 0;
11547 				ret = kstrtoul(args[1].from, 0, &filter->size);
11548 				if (ret)
11549 					goto fail;
11550 			}
11551 
11552 			if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
11553 				int fpos = token == IF_SRC_FILE ? 2 : 1;
11554 
11555 				kfree(filename);
11556 				filename = match_strdup(&args[fpos]);
11557 				if (!filename) {
11558 					ret = -ENOMEM;
11559 					goto fail;
11560 				}
11561 			}
11562 
11563 			state = IF_STATE_END;
11564 			break;
11565 
11566 		default:
11567 			goto fail;
11568 		}
11569 
11570 		/*
11571 		 * Filter definition is fully parsed, validate and install it.
11572 		 * Make sure that it doesn't contradict itself or the event's
11573 		 * attribute.
11574 		 */
11575 		if (state == IF_STATE_END) {
11576 			ret = -EINVAL;
11577 
11578 			/*
11579 			 * ACTION "filter" must have a non-zero length region
11580 			 * specified.
11581 			 */
11582 			if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
11583 			    !filter->size)
11584 				goto fail;
11585 
11586 			if (!kernel) {
11587 				if (!filename)
11588 					goto fail;
11589 
11590 				/*
11591 				 * For now, we only support file-based filters
11592 				 * in per-task events; doing so for CPU-wide
11593 				 * events requires additional context switching
11594 				 * trickery, since same object code will be
11595 				 * mapped at different virtual addresses in
11596 				 * different processes.
11597 				 */
11598 				ret = -EOPNOTSUPP;
11599 				if (!event->ctx->task)
11600 					goto fail;
11601 
11602 				/* look up the path and grab its inode */
11603 				ret = kern_path(filename, LOOKUP_FOLLOW,
11604 						&filter->path);
11605 				if (ret)
11606 					goto fail;
11607 
11608 				ret = -EINVAL;
11609 				if (!filter->path.dentry ||
11610 				    !S_ISREG(d_inode(filter->path.dentry)
11611 					     ->i_mode))
11612 					goto fail;
11613 
11614 				event->addr_filters.nr_file_filters++;
11615 			}
11616 
11617 			/* ready to consume more filters */
11618 			kfree(filename);
11619 			filename = NULL;
11620 			state = IF_STATE_ACTION;
11621 			filter = NULL;
11622 			kernel = 0;
11623 		}
11624 	}
11625 
11626 	if (state != IF_STATE_ACTION)
11627 		goto fail;
11628 
11629 	kfree(filename);
11630 	kfree(orig);
11631 
11632 	return 0;
11633 
11634 fail:
11635 	kfree(filename);
11636 	free_filters_list(filters);
11637 	kfree(orig);
11638 
11639 	return ret;
11640 }
11641 
11642 static int
perf_event_set_addr_filter(struct perf_event * event,char * filter_str)11643 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
11644 {
11645 	LIST_HEAD(filters);
11646 	int ret;
11647 
11648 	/*
11649 	 * Since this is called in perf_ioctl() path, we're already holding
11650 	 * ctx::mutex.
11651 	 */
11652 	lockdep_assert_held(&event->ctx->mutex);
11653 
11654 	if (WARN_ON_ONCE(event->parent))
11655 		return -EINVAL;
11656 
11657 	ret = perf_event_parse_addr_filter(event, filter_str, &filters);
11658 	if (ret)
11659 		goto fail_clear_files;
11660 
11661 	ret = event->pmu->addr_filters_validate(&filters);
11662 	if (ret)
11663 		goto fail_free_filters;
11664 
11665 	/* remove existing filters, if any */
11666 	perf_addr_filters_splice(event, &filters);
11667 
11668 	/* install new filters */
11669 	perf_event_for_each_child(event, perf_event_addr_filters_apply);
11670 
11671 	return ret;
11672 
11673 fail_free_filters:
11674 	free_filters_list(&filters);
11675 
11676 fail_clear_files:
11677 	event->addr_filters.nr_file_filters = 0;
11678 
11679 	return ret;
11680 }
11681 
perf_event_set_filter(struct perf_event * event,void __user * arg)11682 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
11683 {
11684 	int ret = -EINVAL;
11685 	char *filter_str;
11686 
11687 	filter_str = strndup_user(arg, PAGE_SIZE);
11688 	if (IS_ERR(filter_str))
11689 		return PTR_ERR(filter_str);
11690 
11691 #ifdef CONFIG_EVENT_TRACING
11692 	if (perf_event_is_tracing(event)) {
11693 		struct perf_event_context *ctx = event->ctx;
11694 
11695 		/*
11696 		 * Beware, here be dragons!!
11697 		 *
11698 		 * the tracepoint muck will deadlock against ctx->mutex, but
11699 		 * the tracepoint stuff does not actually need it. So
11700 		 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
11701 		 * already have a reference on ctx.
11702 		 *
11703 		 * This can result in event getting moved to a different ctx,
11704 		 * but that does not affect the tracepoint state.
11705 		 */
11706 		mutex_unlock(&ctx->mutex);
11707 		ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
11708 		mutex_lock(&ctx->mutex);
11709 	} else
11710 #endif
11711 	if (has_addr_filter(event))
11712 		ret = perf_event_set_addr_filter(event, filter_str);
11713 
11714 	kfree(filter_str);
11715 	return ret;
11716 }
11717 
11718 /*
11719  * hrtimer based swevent callback
11720  */
11721 
perf_swevent_hrtimer(struct hrtimer * hrtimer)11722 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
11723 {
11724 	enum hrtimer_restart ret = HRTIMER_RESTART;
11725 	struct perf_sample_data data;
11726 	struct pt_regs *regs;
11727 	struct perf_event *event;
11728 	u64 period;
11729 
11730 	event = container_of(hrtimer, struct perf_event, hw.hrtimer);
11731 
11732 	if (event->state != PERF_EVENT_STATE_ACTIVE)
11733 		return HRTIMER_NORESTART;
11734 
11735 	event->pmu->read(event);
11736 
11737 	perf_sample_data_init(&data, 0, event->hw.last_period);
11738 	regs = get_irq_regs();
11739 
11740 	if (regs && !perf_exclude_event(event, regs)) {
11741 		if (!(event->attr.exclude_idle && is_idle_task(current)))
11742 			if (__perf_event_overflow(event, 1, &data, regs))
11743 				ret = HRTIMER_NORESTART;
11744 	}
11745 
11746 	period = max_t(u64, 10000, event->hw.sample_period);
11747 	hrtimer_forward_now(hrtimer, ns_to_ktime(period));
11748 
11749 	return ret;
11750 }
11751 
perf_swevent_start_hrtimer(struct perf_event * event)11752 static void perf_swevent_start_hrtimer(struct perf_event *event)
11753 {
11754 	struct hw_perf_event *hwc = &event->hw;
11755 	s64 period;
11756 
11757 	if (!is_sampling_event(event))
11758 		return;
11759 
11760 	period = local64_read(&hwc->period_left);
11761 	if (period) {
11762 		if (period < 0)
11763 			period = 10000;
11764 
11765 		local64_set(&hwc->period_left, 0);
11766 	} else {
11767 		period = max_t(u64, 10000, hwc->sample_period);
11768 	}
11769 	hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
11770 		      HRTIMER_MODE_REL_PINNED_HARD);
11771 }
11772 
perf_swevent_cancel_hrtimer(struct perf_event * event)11773 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
11774 {
11775 	struct hw_perf_event *hwc = &event->hw;
11776 
11777 	/*
11778 	 * The throttle can be triggered in the hrtimer handler.
11779 	 * The HRTIMER_NORESTART should be used to stop the timer,
11780 	 * rather than hrtimer_cancel(). See perf_swevent_hrtimer()
11781 	 */
11782 	if (is_sampling_event(event) && (hwc->interrupts != MAX_INTERRUPTS)) {
11783 		ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
11784 		local64_set(&hwc->period_left, ktime_to_ns(remaining));
11785 
11786 		hrtimer_cancel(&hwc->hrtimer);
11787 	}
11788 }
11789 
perf_swevent_init_hrtimer(struct perf_event * event)11790 static void perf_swevent_init_hrtimer(struct perf_event *event)
11791 {
11792 	struct hw_perf_event *hwc = &event->hw;
11793 
11794 	if (!is_sampling_event(event))
11795 		return;
11796 
11797 	hrtimer_setup(&hwc->hrtimer, perf_swevent_hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
11798 
11799 	/*
11800 	 * Since hrtimers have a fixed rate, we can do a static freq->period
11801 	 * mapping and avoid the whole period adjust feedback stuff.
11802 	 */
11803 	if (event->attr.freq) {
11804 		long freq = event->attr.sample_freq;
11805 
11806 		event->attr.sample_period = NSEC_PER_SEC / freq;
11807 		hwc->sample_period = event->attr.sample_period;
11808 		local64_set(&hwc->period_left, hwc->sample_period);
11809 		hwc->last_period = hwc->sample_period;
11810 		event->attr.freq = 0;
11811 	}
11812 }
11813 
11814 /*
11815  * Software event: cpu wall time clock
11816  */
11817 
cpu_clock_event_update(struct perf_event * event)11818 static void cpu_clock_event_update(struct perf_event *event)
11819 {
11820 	s64 prev;
11821 	u64 now;
11822 
11823 	now = local_clock();
11824 	prev = local64_xchg(&event->hw.prev_count, now);
11825 	local64_add(now - prev, &event->count);
11826 }
11827 
cpu_clock_event_start(struct perf_event * event,int flags)11828 static void cpu_clock_event_start(struct perf_event *event, int flags)
11829 {
11830 	local64_set(&event->hw.prev_count, local_clock());
11831 	perf_swevent_start_hrtimer(event);
11832 }
11833 
cpu_clock_event_stop(struct perf_event * event,int flags)11834 static void cpu_clock_event_stop(struct perf_event *event, int flags)
11835 {
11836 	perf_swevent_cancel_hrtimer(event);
11837 	if (flags & PERF_EF_UPDATE)
11838 		cpu_clock_event_update(event);
11839 }
11840 
cpu_clock_event_add(struct perf_event * event,int flags)11841 static int cpu_clock_event_add(struct perf_event *event, int flags)
11842 {
11843 	if (flags & PERF_EF_START)
11844 		cpu_clock_event_start(event, flags);
11845 	perf_event_update_userpage(event);
11846 
11847 	return 0;
11848 }
11849 
cpu_clock_event_del(struct perf_event * event,int flags)11850 static void cpu_clock_event_del(struct perf_event *event, int flags)
11851 {
11852 	cpu_clock_event_stop(event, flags);
11853 }
11854 
cpu_clock_event_read(struct perf_event * event)11855 static void cpu_clock_event_read(struct perf_event *event)
11856 {
11857 	cpu_clock_event_update(event);
11858 }
11859 
cpu_clock_event_init(struct perf_event * event)11860 static int cpu_clock_event_init(struct perf_event *event)
11861 {
11862 	if (event->attr.type != perf_cpu_clock.type)
11863 		return -ENOENT;
11864 
11865 	if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
11866 		return -ENOENT;
11867 
11868 	/*
11869 	 * no branch sampling for software events
11870 	 */
11871 	if (has_branch_stack(event))
11872 		return -EOPNOTSUPP;
11873 
11874 	perf_swevent_init_hrtimer(event);
11875 
11876 	return 0;
11877 }
11878 
11879 static struct pmu perf_cpu_clock = {
11880 	.task_ctx_nr	= perf_sw_context,
11881 
11882 	.capabilities	= PERF_PMU_CAP_NO_NMI,
11883 	.dev		= PMU_NULL_DEV,
11884 
11885 	.event_init	= cpu_clock_event_init,
11886 	.add		= cpu_clock_event_add,
11887 	.del		= cpu_clock_event_del,
11888 	.start		= cpu_clock_event_start,
11889 	.stop		= cpu_clock_event_stop,
11890 	.read		= cpu_clock_event_read,
11891 };
11892 
11893 /*
11894  * Software event: task time clock
11895  */
11896 
task_clock_event_update(struct perf_event * event,u64 now)11897 static void task_clock_event_update(struct perf_event *event, u64 now)
11898 {
11899 	u64 prev;
11900 	s64 delta;
11901 
11902 	prev = local64_xchg(&event->hw.prev_count, now);
11903 	delta = now - prev;
11904 	local64_add(delta, &event->count);
11905 }
11906 
task_clock_event_start(struct perf_event * event,int flags)11907 static void task_clock_event_start(struct perf_event *event, int flags)
11908 {
11909 	local64_set(&event->hw.prev_count, event->ctx->time);
11910 	perf_swevent_start_hrtimer(event);
11911 }
11912 
task_clock_event_stop(struct perf_event * event,int flags)11913 static void task_clock_event_stop(struct perf_event *event, int flags)
11914 {
11915 	perf_swevent_cancel_hrtimer(event);
11916 	if (flags & PERF_EF_UPDATE)
11917 		task_clock_event_update(event, event->ctx->time);
11918 }
11919 
task_clock_event_add(struct perf_event * event,int flags)11920 static int task_clock_event_add(struct perf_event *event, int flags)
11921 {
11922 	if (flags & PERF_EF_START)
11923 		task_clock_event_start(event, flags);
11924 	perf_event_update_userpage(event);
11925 
11926 	return 0;
11927 }
11928 
task_clock_event_del(struct perf_event * event,int flags)11929 static void task_clock_event_del(struct perf_event *event, int flags)
11930 {
11931 	task_clock_event_stop(event, PERF_EF_UPDATE);
11932 }
11933 
task_clock_event_read(struct perf_event * event)11934 static void task_clock_event_read(struct perf_event *event)
11935 {
11936 	u64 now = perf_clock();
11937 	u64 delta = now - event->ctx->timestamp;
11938 	u64 time = event->ctx->time + delta;
11939 
11940 	task_clock_event_update(event, time);
11941 }
11942 
task_clock_event_init(struct perf_event * event)11943 static int task_clock_event_init(struct perf_event *event)
11944 {
11945 	if (event->attr.type != perf_task_clock.type)
11946 		return -ENOENT;
11947 
11948 	if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
11949 		return -ENOENT;
11950 
11951 	/*
11952 	 * no branch sampling for software events
11953 	 */
11954 	if (has_branch_stack(event))
11955 		return -EOPNOTSUPP;
11956 
11957 	perf_swevent_init_hrtimer(event);
11958 
11959 	return 0;
11960 }
11961 
11962 static struct pmu perf_task_clock = {
11963 	.task_ctx_nr	= perf_sw_context,
11964 
11965 	.capabilities	= PERF_PMU_CAP_NO_NMI,
11966 	.dev		= PMU_NULL_DEV,
11967 
11968 	.event_init	= task_clock_event_init,
11969 	.add		= task_clock_event_add,
11970 	.del		= task_clock_event_del,
11971 	.start		= task_clock_event_start,
11972 	.stop		= task_clock_event_stop,
11973 	.read		= task_clock_event_read,
11974 };
11975 
perf_pmu_nop_void(struct pmu * pmu)11976 static void perf_pmu_nop_void(struct pmu *pmu)
11977 {
11978 }
11979 
perf_pmu_nop_txn(struct pmu * pmu,unsigned int flags)11980 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
11981 {
11982 }
11983 
perf_pmu_nop_int(struct pmu * pmu)11984 static int perf_pmu_nop_int(struct pmu *pmu)
11985 {
11986 	return 0;
11987 }
11988 
perf_event_nop_int(struct perf_event * event,u64 value)11989 static int perf_event_nop_int(struct perf_event *event, u64 value)
11990 {
11991 	return 0;
11992 }
11993 
11994 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
11995 
perf_pmu_start_txn(struct pmu * pmu,unsigned int flags)11996 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
11997 {
11998 	__this_cpu_write(nop_txn_flags, flags);
11999 
12000 	if (flags & ~PERF_PMU_TXN_ADD)
12001 		return;
12002 
12003 	perf_pmu_disable(pmu);
12004 }
12005 
perf_pmu_commit_txn(struct pmu * pmu)12006 static int perf_pmu_commit_txn(struct pmu *pmu)
12007 {
12008 	unsigned int flags = __this_cpu_read(nop_txn_flags);
12009 
12010 	__this_cpu_write(nop_txn_flags, 0);
12011 
12012 	if (flags & ~PERF_PMU_TXN_ADD)
12013 		return 0;
12014 
12015 	perf_pmu_enable(pmu);
12016 	return 0;
12017 }
12018 
perf_pmu_cancel_txn(struct pmu * pmu)12019 static void perf_pmu_cancel_txn(struct pmu *pmu)
12020 {
12021 	unsigned int flags =  __this_cpu_read(nop_txn_flags);
12022 
12023 	__this_cpu_write(nop_txn_flags, 0);
12024 
12025 	if (flags & ~PERF_PMU_TXN_ADD)
12026 		return;
12027 
12028 	perf_pmu_enable(pmu);
12029 }
12030 
perf_event_idx_default(struct perf_event * event)12031 static int perf_event_idx_default(struct perf_event *event)
12032 {
12033 	return 0;
12034 }
12035 
12036 /*
12037  * Let userspace know that this PMU supports address range filtering:
12038  */
nr_addr_filters_show(struct device * dev,struct device_attribute * attr,char * page)12039 static ssize_t nr_addr_filters_show(struct device *dev,
12040 				    struct device_attribute *attr,
12041 				    char *page)
12042 {
12043 	struct pmu *pmu = dev_get_drvdata(dev);
12044 
12045 	return sysfs_emit(page, "%d\n", pmu->nr_addr_filters);
12046 }
12047 DEVICE_ATTR_RO(nr_addr_filters);
12048 
12049 static struct idr pmu_idr;
12050 
12051 static ssize_t
type_show(struct device * dev,struct device_attribute * attr,char * page)12052 type_show(struct device *dev, struct device_attribute *attr, char *page)
12053 {
12054 	struct pmu *pmu = dev_get_drvdata(dev);
12055 
12056 	return sysfs_emit(page, "%d\n", pmu->type);
12057 }
12058 static DEVICE_ATTR_RO(type);
12059 
12060 static ssize_t
perf_event_mux_interval_ms_show(struct device * dev,struct device_attribute * attr,char * page)12061 perf_event_mux_interval_ms_show(struct device *dev,
12062 				struct device_attribute *attr,
12063 				char *page)
12064 {
12065 	struct pmu *pmu = dev_get_drvdata(dev);
12066 
12067 	return sysfs_emit(page, "%d\n", pmu->hrtimer_interval_ms);
12068 }
12069 
12070 static DEFINE_MUTEX(mux_interval_mutex);
12071 
12072 static ssize_t
perf_event_mux_interval_ms_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)12073 perf_event_mux_interval_ms_store(struct device *dev,
12074 				 struct device_attribute *attr,
12075 				 const char *buf, size_t count)
12076 {
12077 	struct pmu *pmu = dev_get_drvdata(dev);
12078 	int timer, cpu, ret;
12079 
12080 	ret = kstrtoint(buf, 0, &timer);
12081 	if (ret)
12082 		return ret;
12083 
12084 	if (timer < 1)
12085 		return -EINVAL;
12086 
12087 	/* same value, noting to do */
12088 	if (timer == pmu->hrtimer_interval_ms)
12089 		return count;
12090 
12091 	mutex_lock(&mux_interval_mutex);
12092 	pmu->hrtimer_interval_ms = timer;
12093 
12094 	/* update all cpuctx for this PMU */
12095 	cpus_read_lock();
12096 	for_each_online_cpu(cpu) {
12097 		struct perf_cpu_pmu_context *cpc;
12098 		cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu);
12099 		cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
12100 
12101 		cpu_function_call(cpu, perf_mux_hrtimer_restart_ipi, cpc);
12102 	}
12103 	cpus_read_unlock();
12104 	mutex_unlock(&mux_interval_mutex);
12105 
12106 	return count;
12107 }
12108 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
12109 
perf_scope_cpu_topology_cpumask(unsigned int scope,int cpu)12110 static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu)
12111 {
12112 	switch (scope) {
12113 	case PERF_PMU_SCOPE_CORE:
12114 		return topology_sibling_cpumask(cpu);
12115 	case PERF_PMU_SCOPE_DIE:
12116 		return topology_die_cpumask(cpu);
12117 	case PERF_PMU_SCOPE_CLUSTER:
12118 		return topology_cluster_cpumask(cpu);
12119 	case PERF_PMU_SCOPE_PKG:
12120 		return topology_core_cpumask(cpu);
12121 	case PERF_PMU_SCOPE_SYS_WIDE:
12122 		return cpu_online_mask;
12123 	}
12124 
12125 	return NULL;
12126 }
12127 
perf_scope_cpumask(unsigned int scope)12128 static inline struct cpumask *perf_scope_cpumask(unsigned int scope)
12129 {
12130 	switch (scope) {
12131 	case PERF_PMU_SCOPE_CORE:
12132 		return perf_online_core_mask;
12133 	case PERF_PMU_SCOPE_DIE:
12134 		return perf_online_die_mask;
12135 	case PERF_PMU_SCOPE_CLUSTER:
12136 		return perf_online_cluster_mask;
12137 	case PERF_PMU_SCOPE_PKG:
12138 		return perf_online_pkg_mask;
12139 	case PERF_PMU_SCOPE_SYS_WIDE:
12140 		return perf_online_sys_mask;
12141 	}
12142 
12143 	return NULL;
12144 }
12145 
cpumask_show(struct device * dev,struct device_attribute * attr,char * buf)12146 static ssize_t cpumask_show(struct device *dev, struct device_attribute *attr,
12147 			    char *buf)
12148 {
12149 	struct pmu *pmu = dev_get_drvdata(dev);
12150 	struct cpumask *mask = perf_scope_cpumask(pmu->scope);
12151 
12152 	if (mask)
12153 		return cpumap_print_to_pagebuf(true, buf, mask);
12154 	return 0;
12155 }
12156 
12157 static DEVICE_ATTR_RO(cpumask);
12158 
12159 static struct attribute *pmu_dev_attrs[] = {
12160 	&dev_attr_type.attr,
12161 	&dev_attr_perf_event_mux_interval_ms.attr,
12162 	&dev_attr_nr_addr_filters.attr,
12163 	&dev_attr_cpumask.attr,
12164 	NULL,
12165 };
12166 
pmu_dev_is_visible(struct kobject * kobj,struct attribute * a,int n)12167 static umode_t pmu_dev_is_visible(struct kobject *kobj, struct attribute *a, int n)
12168 {
12169 	struct device *dev = kobj_to_dev(kobj);
12170 	struct pmu *pmu = dev_get_drvdata(dev);
12171 
12172 	if (n == 2 && !pmu->nr_addr_filters)
12173 		return 0;
12174 
12175 	/* cpumask */
12176 	if (n == 3 && pmu->scope == PERF_PMU_SCOPE_NONE)
12177 		return 0;
12178 
12179 	return a->mode;
12180 }
12181 
12182 static struct attribute_group pmu_dev_attr_group = {
12183 	.is_visible = pmu_dev_is_visible,
12184 	.attrs = pmu_dev_attrs,
12185 };
12186 
12187 static const struct attribute_group *pmu_dev_groups[] = {
12188 	&pmu_dev_attr_group,
12189 	NULL,
12190 };
12191 
12192 static int pmu_bus_running;
12193 static struct bus_type pmu_bus = {
12194 	.name		= "event_source",
12195 	.dev_groups	= pmu_dev_groups,
12196 };
12197 
pmu_dev_release(struct device * dev)12198 static void pmu_dev_release(struct device *dev)
12199 {
12200 	kfree(dev);
12201 }
12202 
pmu_dev_alloc(struct pmu * pmu)12203 static int pmu_dev_alloc(struct pmu *pmu)
12204 {
12205 	int ret = -ENOMEM;
12206 
12207 	pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
12208 	if (!pmu->dev)
12209 		goto out;
12210 
12211 	pmu->dev->groups = pmu->attr_groups;
12212 	device_initialize(pmu->dev);
12213 
12214 	dev_set_drvdata(pmu->dev, pmu);
12215 	pmu->dev->bus = &pmu_bus;
12216 	pmu->dev->parent = pmu->parent;
12217 	pmu->dev->release = pmu_dev_release;
12218 
12219 	ret = dev_set_name(pmu->dev, "%s", pmu->name);
12220 	if (ret)
12221 		goto free_dev;
12222 
12223 	ret = device_add(pmu->dev);
12224 	if (ret)
12225 		goto free_dev;
12226 
12227 	if (pmu->attr_update) {
12228 		ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
12229 		if (ret)
12230 			goto del_dev;
12231 	}
12232 
12233 out:
12234 	return ret;
12235 
12236 del_dev:
12237 	device_del(pmu->dev);
12238 
12239 free_dev:
12240 	put_device(pmu->dev);
12241 	pmu->dev = NULL;
12242 	goto out;
12243 }
12244 
12245 static struct lock_class_key cpuctx_mutex;
12246 static struct lock_class_key cpuctx_lock;
12247 
idr_cmpxchg(struct idr * idr,unsigned long id,void * old,void * new)12248 static bool idr_cmpxchg(struct idr *idr, unsigned long id, void *old, void *new)
12249 {
12250 	void *tmp, *val = idr_find(idr, id);
12251 
12252 	if (val != old)
12253 		return false;
12254 
12255 	tmp = idr_replace(idr, new, id);
12256 	if (IS_ERR(tmp))
12257 		return false;
12258 
12259 	WARN_ON_ONCE(tmp != val);
12260 	return true;
12261 }
12262 
perf_pmu_free(struct pmu * pmu)12263 static void perf_pmu_free(struct pmu *pmu)
12264 {
12265 	if (pmu_bus_running && pmu->dev && pmu->dev != PMU_NULL_DEV) {
12266 		if (pmu->nr_addr_filters)
12267 			device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
12268 		device_del(pmu->dev);
12269 		put_device(pmu->dev);
12270 	}
12271 
12272 	if (pmu->cpu_pmu_context) {
12273 		int cpu;
12274 
12275 		for_each_possible_cpu(cpu) {
12276 			struct perf_cpu_pmu_context *cpc;
12277 
12278 			cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu);
12279 			if (!cpc)
12280 				continue;
12281 			if (cpc->epc.embedded) {
12282 				/* refcount managed */
12283 				put_pmu_ctx(&cpc->epc);
12284 				continue;
12285 			}
12286 			kfree(cpc);
12287 		}
12288 		free_percpu(pmu->cpu_pmu_context);
12289 	}
12290 }
12291 
DEFINE_FREE(pmu_unregister,struct pmu *,if (_T)perf_pmu_free (_T))12292 DEFINE_FREE(pmu_unregister, struct pmu *, if (_T) perf_pmu_free(_T))
12293 
12294 int perf_pmu_register(struct pmu *_pmu, const char *name, int type)
12295 {
12296 	int cpu, max = PERF_TYPE_MAX;
12297 
12298 	struct pmu *pmu __free(pmu_unregister) = _pmu;
12299 	guard(mutex)(&pmus_lock);
12300 
12301 	if (WARN_ONCE(!name, "Can not register anonymous pmu.\n"))
12302 		return -EINVAL;
12303 
12304 	if (WARN_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE,
12305 		      "Can not register a pmu with an invalid scope.\n"))
12306 		return -EINVAL;
12307 
12308 	pmu->name = name;
12309 
12310 	if (type >= 0)
12311 		max = type;
12312 
12313 	CLASS(idr_alloc, pmu_type)(&pmu_idr, NULL, max, 0, GFP_KERNEL);
12314 	if (pmu_type.id < 0)
12315 		return pmu_type.id;
12316 
12317 	WARN_ON(type >= 0 && pmu_type.id != type);
12318 
12319 	pmu->type = pmu_type.id;
12320 	atomic_set(&pmu->exclusive_cnt, 0);
12321 
12322 	if (pmu_bus_running && !pmu->dev) {
12323 		int ret = pmu_dev_alloc(pmu);
12324 		if (ret)
12325 			return ret;
12326 	}
12327 
12328 	pmu->cpu_pmu_context = alloc_percpu(struct perf_cpu_pmu_context *);
12329 	if (!pmu->cpu_pmu_context)
12330 		return -ENOMEM;
12331 
12332 	for_each_possible_cpu(cpu) {
12333 		struct perf_cpu_pmu_context *cpc =
12334 			kmalloc_node(sizeof(struct perf_cpu_pmu_context),
12335 				     GFP_KERNEL | __GFP_ZERO,
12336 				     cpu_to_node(cpu));
12337 
12338 		if (!cpc)
12339 			return -ENOMEM;
12340 
12341 		*per_cpu_ptr(pmu->cpu_pmu_context, cpu) = cpc;
12342 		__perf_init_event_pmu_context(&cpc->epc, pmu);
12343 		__perf_mux_hrtimer_init(cpc, cpu);
12344 	}
12345 
12346 	if (!pmu->start_txn) {
12347 		if (pmu->pmu_enable) {
12348 			/*
12349 			 * If we have pmu_enable/pmu_disable calls, install
12350 			 * transaction stubs that use that to try and batch
12351 			 * hardware accesses.
12352 			 */
12353 			pmu->start_txn  = perf_pmu_start_txn;
12354 			pmu->commit_txn = perf_pmu_commit_txn;
12355 			pmu->cancel_txn = perf_pmu_cancel_txn;
12356 		} else {
12357 			pmu->start_txn  = perf_pmu_nop_txn;
12358 			pmu->commit_txn = perf_pmu_nop_int;
12359 			pmu->cancel_txn = perf_pmu_nop_void;
12360 		}
12361 	}
12362 
12363 	if (!pmu->pmu_enable) {
12364 		pmu->pmu_enable  = perf_pmu_nop_void;
12365 		pmu->pmu_disable = perf_pmu_nop_void;
12366 	}
12367 
12368 	if (!pmu->check_period)
12369 		pmu->check_period = perf_event_nop_int;
12370 
12371 	if (!pmu->event_idx)
12372 		pmu->event_idx = perf_event_idx_default;
12373 
12374 	INIT_LIST_HEAD(&pmu->events);
12375 	spin_lock_init(&pmu->events_lock);
12376 
12377 	/*
12378 	 * Now that the PMU is complete, make it visible to perf_try_init_event().
12379 	 */
12380 	if (!idr_cmpxchg(&pmu_idr, pmu->type, NULL, pmu))
12381 		return -EINVAL;
12382 	list_add_rcu(&pmu->entry, &pmus);
12383 
12384 	take_idr_id(pmu_type);
12385 	_pmu = no_free_ptr(pmu); // let it rip
12386 	return 0;
12387 }
12388 EXPORT_SYMBOL_GPL(perf_pmu_register);
12389 
__pmu_detach_event(struct pmu * pmu,struct perf_event * event,struct perf_event_context * ctx)12390 static void __pmu_detach_event(struct pmu *pmu, struct perf_event *event,
12391 			       struct perf_event_context *ctx)
12392 {
12393 	/*
12394 	 * De-schedule the event and mark it REVOKED.
12395 	 */
12396 	perf_event_exit_event(event, ctx, true);
12397 
12398 	/*
12399 	 * All _free_event() bits that rely on event->pmu:
12400 	 *
12401 	 * Notably, perf_mmap() relies on the ordering here.
12402 	 */
12403 	scoped_guard (mutex, &event->mmap_mutex) {
12404 		WARN_ON_ONCE(pmu->event_unmapped);
12405 		/*
12406 		 * Mostly an empty lock sequence, such that perf_mmap(), which
12407 		 * relies on mmap_mutex, is sure to observe the state change.
12408 		 */
12409 	}
12410 
12411 	perf_event_free_bpf_prog(event);
12412 	perf_free_addr_filters(event);
12413 
12414 	if (event->destroy) {
12415 		event->destroy(event);
12416 		event->destroy = NULL;
12417 	}
12418 
12419 	if (event->pmu_ctx) {
12420 		put_pmu_ctx(event->pmu_ctx);
12421 		event->pmu_ctx = NULL;
12422 	}
12423 
12424 	exclusive_event_destroy(event);
12425 	module_put(pmu->module);
12426 
12427 	event->pmu = NULL; /* force fault instead of UAF */
12428 }
12429 
pmu_detach_event(struct pmu * pmu,struct perf_event * event)12430 static void pmu_detach_event(struct pmu *pmu, struct perf_event *event)
12431 {
12432 	struct perf_event_context *ctx;
12433 
12434 	ctx = perf_event_ctx_lock(event);
12435 	__pmu_detach_event(pmu, event, ctx);
12436 	perf_event_ctx_unlock(event, ctx);
12437 
12438 	scoped_guard (spinlock, &pmu->events_lock)
12439 		list_del(&event->pmu_list);
12440 }
12441 
pmu_get_event(struct pmu * pmu)12442 static struct perf_event *pmu_get_event(struct pmu *pmu)
12443 {
12444 	struct perf_event *event;
12445 
12446 	guard(spinlock)(&pmu->events_lock);
12447 	list_for_each_entry(event, &pmu->events, pmu_list) {
12448 		if (atomic_long_inc_not_zero(&event->refcount))
12449 			return event;
12450 	}
12451 
12452 	return NULL;
12453 }
12454 
pmu_empty(struct pmu * pmu)12455 static bool pmu_empty(struct pmu *pmu)
12456 {
12457 	guard(spinlock)(&pmu->events_lock);
12458 	return list_empty(&pmu->events);
12459 }
12460 
pmu_detach_events(struct pmu * pmu)12461 static void pmu_detach_events(struct pmu *pmu)
12462 {
12463 	struct perf_event *event;
12464 
12465 	for (;;) {
12466 		event = pmu_get_event(pmu);
12467 		if (!event)
12468 			break;
12469 
12470 		pmu_detach_event(pmu, event);
12471 		put_event(event);
12472 	}
12473 
12474 	/*
12475 	 * wait for pending _free_event()s
12476 	 */
12477 	wait_var_event(pmu, pmu_empty(pmu));
12478 }
12479 
perf_pmu_unregister(struct pmu * pmu)12480 int perf_pmu_unregister(struct pmu *pmu)
12481 {
12482 	scoped_guard (mutex, &pmus_lock) {
12483 		if (!idr_cmpxchg(&pmu_idr, pmu->type, pmu, NULL))
12484 			return -EINVAL;
12485 
12486 		list_del_rcu(&pmu->entry);
12487 	}
12488 
12489 	/*
12490 	 * We dereference the pmu list under both SRCU and regular RCU, so
12491 	 * synchronize against both of those.
12492 	 *
12493 	 * Notably, the entirety of event creation, from perf_init_event()
12494 	 * (which will now fail, because of the above) until
12495 	 * perf_install_in_context() should be under SRCU such that
12496 	 * this synchronizes against event creation. This avoids trying to
12497 	 * detach events that are not fully formed.
12498 	 */
12499 	synchronize_srcu(&pmus_srcu);
12500 	synchronize_rcu();
12501 
12502 	if (pmu->event_unmapped && !pmu_empty(pmu)) {
12503 		/*
12504 		 * Can't force remove events when pmu::event_unmapped()
12505 		 * is used in perf_mmap_close().
12506 		 */
12507 		guard(mutex)(&pmus_lock);
12508 		idr_cmpxchg(&pmu_idr, pmu->type, NULL, pmu);
12509 		list_add_rcu(&pmu->entry, &pmus);
12510 		return -EBUSY;
12511 	}
12512 
12513 	scoped_guard (mutex, &pmus_lock)
12514 		idr_remove(&pmu_idr, pmu->type);
12515 
12516 	/*
12517 	 * PMU is removed from the pmus list, so no new events will
12518 	 * be created, now take care of the existing ones.
12519 	 */
12520 	pmu_detach_events(pmu);
12521 
12522 	/*
12523 	 * PMU is unused, make it go away.
12524 	 */
12525 	perf_pmu_free(pmu);
12526 	return 0;
12527 }
12528 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
12529 
has_extended_regs(struct perf_event * event)12530 static inline bool has_extended_regs(struct perf_event *event)
12531 {
12532 	return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
12533 	       (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
12534 }
12535 
perf_try_init_event(struct pmu * pmu,struct perf_event * event)12536 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
12537 {
12538 	struct perf_event_context *ctx = NULL;
12539 	int ret;
12540 
12541 	if (!try_module_get(pmu->module))
12542 		return -ENODEV;
12543 
12544 	/*
12545 	 * A number of pmu->event_init() methods iterate the sibling_list to,
12546 	 * for example, validate if the group fits on the PMU. Therefore,
12547 	 * if this is a sibling event, acquire the ctx->mutex to protect
12548 	 * the sibling_list.
12549 	 */
12550 	if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
12551 		/*
12552 		 * This ctx->mutex can nest when we're called through
12553 		 * inheritance. See the perf_event_ctx_lock_nested() comment.
12554 		 */
12555 		ctx = perf_event_ctx_lock_nested(event->group_leader,
12556 						 SINGLE_DEPTH_NESTING);
12557 		BUG_ON(!ctx);
12558 	}
12559 
12560 	event->pmu = pmu;
12561 	ret = pmu->event_init(event);
12562 
12563 	if (ctx)
12564 		perf_event_ctx_unlock(event->group_leader, ctx);
12565 
12566 	if (ret)
12567 		goto err_pmu;
12568 
12569 	if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
12570 	    has_extended_regs(event)) {
12571 		ret = -EOPNOTSUPP;
12572 		goto err_destroy;
12573 	}
12574 
12575 	if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
12576 	    event_has_any_exclude_flag(event)) {
12577 		ret = -EINVAL;
12578 		goto err_destroy;
12579 	}
12580 
12581 	if (pmu->scope != PERF_PMU_SCOPE_NONE && event->cpu >= 0) {
12582 		const struct cpumask *cpumask;
12583 		struct cpumask *pmu_cpumask;
12584 		int cpu;
12585 
12586 		cpumask = perf_scope_cpu_topology_cpumask(pmu->scope, event->cpu);
12587 		pmu_cpumask = perf_scope_cpumask(pmu->scope);
12588 
12589 		ret = -ENODEV;
12590 		if (!pmu_cpumask || !cpumask)
12591 			goto err_destroy;
12592 
12593 		cpu = cpumask_any_and(pmu_cpumask, cpumask);
12594 		if (cpu >= nr_cpu_ids)
12595 			goto err_destroy;
12596 
12597 		event->event_caps |= PERF_EV_CAP_READ_SCOPE;
12598 	}
12599 
12600 	return 0;
12601 
12602 err_destroy:
12603 	if (event->destroy) {
12604 		event->destroy(event);
12605 		event->destroy = NULL;
12606 	}
12607 
12608 err_pmu:
12609 	event->pmu = NULL;
12610 	module_put(pmu->module);
12611 	return ret;
12612 }
12613 
perf_init_event(struct perf_event * event)12614 static struct pmu *perf_init_event(struct perf_event *event)
12615 {
12616 	bool extended_type = false;
12617 	struct pmu *pmu;
12618 	int type, ret;
12619 
12620 	guard(srcu)(&pmus_srcu); /* pmu idr/list access */
12621 
12622 	/*
12623 	 * Save original type before calling pmu->event_init() since certain
12624 	 * pmus overwrites event->attr.type to forward event to another pmu.
12625 	 */
12626 	event->orig_type = event->attr.type;
12627 
12628 	/* Try parent's PMU first: */
12629 	if (event->parent && event->parent->pmu) {
12630 		pmu = event->parent->pmu;
12631 		ret = perf_try_init_event(pmu, event);
12632 		if (!ret)
12633 			return pmu;
12634 	}
12635 
12636 	/*
12637 	 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
12638 	 * are often aliases for PERF_TYPE_RAW.
12639 	 */
12640 	type = event->attr.type;
12641 	if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE) {
12642 		type = event->attr.config >> PERF_PMU_TYPE_SHIFT;
12643 		if (!type) {
12644 			type = PERF_TYPE_RAW;
12645 		} else {
12646 			extended_type = true;
12647 			event->attr.config &= PERF_HW_EVENT_MASK;
12648 		}
12649 	}
12650 
12651 again:
12652 	scoped_guard (rcu)
12653 		pmu = idr_find(&pmu_idr, type);
12654 	if (pmu) {
12655 		if (event->attr.type != type && type != PERF_TYPE_RAW &&
12656 		    !(pmu->capabilities & PERF_PMU_CAP_EXTENDED_HW_TYPE))
12657 			return ERR_PTR(-ENOENT);
12658 
12659 		ret = perf_try_init_event(pmu, event);
12660 		if (ret == -ENOENT && event->attr.type != type && !extended_type) {
12661 			type = event->attr.type;
12662 			goto again;
12663 		}
12664 
12665 		if (ret)
12666 			return ERR_PTR(ret);
12667 
12668 		return pmu;
12669 	}
12670 
12671 	list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
12672 		ret = perf_try_init_event(pmu, event);
12673 		if (!ret)
12674 			return pmu;
12675 
12676 		if (ret != -ENOENT)
12677 			return ERR_PTR(ret);
12678 	}
12679 
12680 	return ERR_PTR(-ENOENT);
12681 }
12682 
attach_sb_event(struct perf_event * event)12683 static void attach_sb_event(struct perf_event *event)
12684 {
12685 	struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
12686 
12687 	raw_spin_lock(&pel->lock);
12688 	list_add_rcu(&event->sb_list, &pel->list);
12689 	raw_spin_unlock(&pel->lock);
12690 }
12691 
12692 /*
12693  * We keep a list of all !task (and therefore per-cpu) events
12694  * that need to receive side-band records.
12695  *
12696  * This avoids having to scan all the various PMU per-cpu contexts
12697  * looking for them.
12698  */
account_pmu_sb_event(struct perf_event * event)12699 static void account_pmu_sb_event(struct perf_event *event)
12700 {
12701 	if (is_sb_event(event))
12702 		attach_sb_event(event);
12703 }
12704 
12705 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
account_freq_event_nohz(void)12706 static void account_freq_event_nohz(void)
12707 {
12708 #ifdef CONFIG_NO_HZ_FULL
12709 	/* Lock so we don't race with concurrent unaccount */
12710 	spin_lock(&nr_freq_lock);
12711 	if (atomic_inc_return(&nr_freq_events) == 1)
12712 		tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
12713 	spin_unlock(&nr_freq_lock);
12714 #endif
12715 }
12716 
account_freq_event(void)12717 static void account_freq_event(void)
12718 {
12719 	if (tick_nohz_full_enabled())
12720 		account_freq_event_nohz();
12721 	else
12722 		atomic_inc(&nr_freq_events);
12723 }
12724 
12725 
account_event(struct perf_event * event)12726 static void account_event(struct perf_event *event)
12727 {
12728 	bool inc = false;
12729 
12730 	if (event->parent)
12731 		return;
12732 
12733 	if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
12734 		inc = true;
12735 	if (event->attr.mmap || event->attr.mmap_data)
12736 		atomic_inc(&nr_mmap_events);
12737 	if (event->attr.build_id)
12738 		atomic_inc(&nr_build_id_events);
12739 	if (event->attr.comm)
12740 		atomic_inc(&nr_comm_events);
12741 	if (event->attr.namespaces)
12742 		atomic_inc(&nr_namespaces_events);
12743 	if (event->attr.cgroup)
12744 		atomic_inc(&nr_cgroup_events);
12745 	if (event->attr.task)
12746 		atomic_inc(&nr_task_events);
12747 	if (event->attr.freq)
12748 		account_freq_event();
12749 	if (event->attr.context_switch) {
12750 		atomic_inc(&nr_switch_events);
12751 		inc = true;
12752 	}
12753 	if (has_branch_stack(event))
12754 		inc = true;
12755 	if (is_cgroup_event(event))
12756 		inc = true;
12757 	if (event->attr.ksymbol)
12758 		atomic_inc(&nr_ksymbol_events);
12759 	if (event->attr.bpf_event)
12760 		atomic_inc(&nr_bpf_events);
12761 	if (event->attr.text_poke)
12762 		atomic_inc(&nr_text_poke_events);
12763 
12764 	if (inc) {
12765 		/*
12766 		 * We need the mutex here because static_branch_enable()
12767 		 * must complete *before* the perf_sched_count increment
12768 		 * becomes visible.
12769 		 */
12770 		if (atomic_inc_not_zero(&perf_sched_count))
12771 			goto enabled;
12772 
12773 		mutex_lock(&perf_sched_mutex);
12774 		if (!atomic_read(&perf_sched_count)) {
12775 			static_branch_enable(&perf_sched_events);
12776 			/*
12777 			 * Guarantee that all CPUs observe they key change and
12778 			 * call the perf scheduling hooks before proceeding to
12779 			 * install events that need them.
12780 			 */
12781 			synchronize_rcu();
12782 		}
12783 		/*
12784 		 * Now that we have waited for the sync_sched(), allow further
12785 		 * increments to by-pass the mutex.
12786 		 */
12787 		atomic_inc(&perf_sched_count);
12788 		mutex_unlock(&perf_sched_mutex);
12789 	}
12790 enabled:
12791 
12792 	account_pmu_sb_event(event);
12793 }
12794 
12795 /*
12796  * Allocate and initialize an event structure
12797  */
12798 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)12799 perf_event_alloc(struct perf_event_attr *attr, int cpu,
12800 		 struct task_struct *task,
12801 		 struct perf_event *group_leader,
12802 		 struct perf_event *parent_event,
12803 		 perf_overflow_handler_t overflow_handler,
12804 		 void *context, int cgroup_fd)
12805 {
12806 	struct pmu *pmu;
12807 	struct hw_perf_event *hwc;
12808 	long err = -EINVAL;
12809 	int node;
12810 
12811 	if ((unsigned)cpu >= nr_cpu_ids) {
12812 		if (!task || cpu != -1)
12813 			return ERR_PTR(-EINVAL);
12814 	}
12815 	if (attr->sigtrap && !task) {
12816 		/* Requires a task: avoid signalling random tasks. */
12817 		return ERR_PTR(-EINVAL);
12818 	}
12819 
12820 	node = (cpu >= 0) ? cpu_to_node(cpu) : -1;
12821 	struct perf_event *event __free(__free_event) =
12822 		kmem_cache_alloc_node(perf_event_cache, GFP_KERNEL | __GFP_ZERO, node);
12823 	if (!event)
12824 		return ERR_PTR(-ENOMEM);
12825 
12826 	/*
12827 	 * Single events are their own group leaders, with an
12828 	 * empty sibling list:
12829 	 */
12830 	if (!group_leader)
12831 		group_leader = event;
12832 
12833 	mutex_init(&event->child_mutex);
12834 	INIT_LIST_HEAD(&event->child_list);
12835 
12836 	INIT_LIST_HEAD(&event->event_entry);
12837 	INIT_LIST_HEAD(&event->sibling_list);
12838 	INIT_LIST_HEAD(&event->active_list);
12839 	init_event_group(event);
12840 	INIT_LIST_HEAD(&event->rb_entry);
12841 	INIT_LIST_HEAD(&event->active_entry);
12842 	INIT_LIST_HEAD(&event->addr_filters.list);
12843 	INIT_HLIST_NODE(&event->hlist_entry);
12844 	INIT_LIST_HEAD(&event->pmu_list);
12845 
12846 
12847 	init_waitqueue_head(&event->waitq);
12848 	init_irq_work(&event->pending_irq, perf_pending_irq);
12849 	event->pending_disable_irq = IRQ_WORK_INIT_HARD(perf_pending_disable);
12850 	init_task_work(&event->pending_task, perf_pending_task);
12851 
12852 	mutex_init(&event->mmap_mutex);
12853 	raw_spin_lock_init(&event->addr_filters.lock);
12854 
12855 	atomic_long_set(&event->refcount, 1);
12856 	event->cpu		= cpu;
12857 	event->attr		= *attr;
12858 	event->group_leader	= group_leader;
12859 	event->pmu		= NULL;
12860 	event->oncpu		= -1;
12861 
12862 	event->parent		= parent_event;
12863 
12864 	event->ns		= get_pid_ns(task_active_pid_ns(current));
12865 	event->id		= atomic64_inc_return(&perf_event_id);
12866 
12867 	event->state		= PERF_EVENT_STATE_INACTIVE;
12868 
12869 	if (parent_event)
12870 		event->event_caps = parent_event->event_caps;
12871 
12872 	if (task) {
12873 		event->attach_state = PERF_ATTACH_TASK;
12874 		/*
12875 		 * XXX pmu::event_init needs to know what task to account to
12876 		 * and we cannot use the ctx information because we need the
12877 		 * pmu before we get a ctx.
12878 		 */
12879 		event->hw.target = get_task_struct(task);
12880 	}
12881 
12882 	event->clock = &local_clock;
12883 	if (parent_event)
12884 		event->clock = parent_event->clock;
12885 
12886 	if (!overflow_handler && parent_event) {
12887 		overflow_handler = parent_event->overflow_handler;
12888 		context = parent_event->overflow_handler_context;
12889 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
12890 		if (parent_event->prog) {
12891 			struct bpf_prog *prog = parent_event->prog;
12892 
12893 			bpf_prog_inc(prog);
12894 			event->prog = prog;
12895 		}
12896 #endif
12897 	}
12898 
12899 	if (overflow_handler) {
12900 		event->overflow_handler	= overflow_handler;
12901 		event->overflow_handler_context = context;
12902 	} else if (is_write_backward(event)){
12903 		event->overflow_handler = perf_event_output_backward;
12904 		event->overflow_handler_context = NULL;
12905 	} else {
12906 		event->overflow_handler = perf_event_output_forward;
12907 		event->overflow_handler_context = NULL;
12908 	}
12909 
12910 	perf_event__state_init(event);
12911 
12912 	pmu = NULL;
12913 
12914 	hwc = &event->hw;
12915 	hwc->sample_period = attr->sample_period;
12916 	if (is_event_in_freq_mode(event))
12917 		hwc->sample_period = 1;
12918 	hwc->last_period = hwc->sample_period;
12919 
12920 	local64_set(&hwc->period_left, hwc->sample_period);
12921 
12922 	/*
12923 	 * We do not support PERF_SAMPLE_READ on inherited events unless
12924 	 * PERF_SAMPLE_TID is also selected, which allows inherited events to
12925 	 * collect per-thread samples.
12926 	 * See perf_output_read().
12927 	 */
12928 	if (has_inherit_and_sample_read(attr) && !(attr->sample_type & PERF_SAMPLE_TID))
12929 		return ERR_PTR(-EINVAL);
12930 
12931 	if (!has_branch_stack(event))
12932 		event->attr.branch_sample_type = 0;
12933 
12934 	pmu = perf_init_event(event);
12935 	if (IS_ERR(pmu))
12936 		return (void*)pmu;
12937 
12938 	/*
12939 	 * The PERF_ATTACH_TASK_DATA is set in the event_init()->hw_config().
12940 	 * The attach should be right after the perf_init_event().
12941 	 * Otherwise, the __free_event() would mistakenly detach the non-exist
12942 	 * perf_ctx_data because of the other errors between them.
12943 	 */
12944 	if (event->attach_state & PERF_ATTACH_TASK_DATA) {
12945 		err = attach_perf_ctx_data(event);
12946 		if (err)
12947 			return ERR_PTR(err);
12948 	}
12949 
12950 	/*
12951 	 * Disallow uncore-task events. Similarly, disallow uncore-cgroup
12952 	 * events (they don't make sense as the cgroup will be different
12953 	 * on other CPUs in the uncore mask).
12954 	 */
12955 	if (pmu->task_ctx_nr == perf_invalid_context && (task || cgroup_fd != -1))
12956 		return ERR_PTR(-EINVAL);
12957 
12958 	if (event->attr.aux_output &&
12959 	    (!(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT) ||
12960 	     event->attr.aux_pause || event->attr.aux_resume))
12961 		return ERR_PTR(-EOPNOTSUPP);
12962 
12963 	if (event->attr.aux_pause && event->attr.aux_resume)
12964 		return ERR_PTR(-EINVAL);
12965 
12966 	if (event->attr.aux_start_paused) {
12967 		if (!(pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE))
12968 			return ERR_PTR(-EOPNOTSUPP);
12969 		event->hw.aux_paused = 1;
12970 	}
12971 
12972 	if (cgroup_fd != -1) {
12973 		err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
12974 		if (err)
12975 			return ERR_PTR(err);
12976 	}
12977 
12978 	err = exclusive_event_init(event);
12979 	if (err)
12980 		return ERR_PTR(err);
12981 
12982 	if (has_addr_filter(event)) {
12983 		event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
12984 						    sizeof(struct perf_addr_filter_range),
12985 						    GFP_KERNEL);
12986 		if (!event->addr_filter_ranges)
12987 			return ERR_PTR(-ENOMEM);
12988 
12989 		/*
12990 		 * Clone the parent's vma offsets: they are valid until exec()
12991 		 * even if the mm is not shared with the parent.
12992 		 */
12993 		if (event->parent) {
12994 			struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
12995 
12996 			raw_spin_lock_irq(&ifh->lock);
12997 			memcpy(event->addr_filter_ranges,
12998 			       event->parent->addr_filter_ranges,
12999 			       pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
13000 			raw_spin_unlock_irq(&ifh->lock);
13001 		}
13002 
13003 		/* force hw sync on the address filters */
13004 		event->addr_filters_gen = 1;
13005 	}
13006 
13007 	if (!event->parent) {
13008 		if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
13009 			err = get_callchain_buffers(attr->sample_max_stack);
13010 			if (err)
13011 				return ERR_PTR(err);
13012 			event->attach_state |= PERF_ATTACH_CALLCHAIN;
13013 		}
13014 	}
13015 
13016 	err = security_perf_event_alloc(event);
13017 	if (err)
13018 		return ERR_PTR(err);
13019 
13020 	/* symmetric to unaccount_event() in _free_event() */
13021 	account_event(event);
13022 
13023 	/*
13024 	 * Event creation should be under SRCU, see perf_pmu_unregister().
13025 	 */
13026 	lockdep_assert_held(&pmus_srcu);
13027 	scoped_guard (spinlock, &pmu->events_lock)
13028 		list_add(&event->pmu_list, &pmu->events);
13029 
13030 	return_ptr(event);
13031 }
13032 
perf_copy_attr(struct perf_event_attr __user * uattr,struct perf_event_attr * attr)13033 static int perf_copy_attr(struct perf_event_attr __user *uattr,
13034 			  struct perf_event_attr *attr)
13035 {
13036 	u32 size;
13037 	int ret;
13038 
13039 	/* Zero the full structure, so that a short copy will be nice. */
13040 	memset(attr, 0, sizeof(*attr));
13041 
13042 	ret = get_user(size, &uattr->size);
13043 	if (ret)
13044 		return ret;
13045 
13046 	/* ABI compatibility quirk: */
13047 	if (!size)
13048 		size = PERF_ATTR_SIZE_VER0;
13049 	if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
13050 		goto err_size;
13051 
13052 	ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
13053 	if (ret) {
13054 		if (ret == -E2BIG)
13055 			goto err_size;
13056 		return ret;
13057 	}
13058 
13059 	attr->size = size;
13060 
13061 	if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
13062 		return -EINVAL;
13063 
13064 	if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
13065 		return -EINVAL;
13066 
13067 	if (attr->read_format & ~(PERF_FORMAT_MAX-1))
13068 		return -EINVAL;
13069 
13070 	if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
13071 		u64 mask = attr->branch_sample_type;
13072 
13073 		/* only using defined bits */
13074 		if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
13075 			return -EINVAL;
13076 
13077 		/* at least one branch bit must be set */
13078 		if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
13079 			return -EINVAL;
13080 
13081 		/* propagate priv level, when not set for branch */
13082 		if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
13083 
13084 			/* exclude_kernel checked on syscall entry */
13085 			if (!attr->exclude_kernel)
13086 				mask |= PERF_SAMPLE_BRANCH_KERNEL;
13087 
13088 			if (!attr->exclude_user)
13089 				mask |= PERF_SAMPLE_BRANCH_USER;
13090 
13091 			if (!attr->exclude_hv)
13092 				mask |= PERF_SAMPLE_BRANCH_HV;
13093 			/*
13094 			 * adjust user setting (for HW filter setup)
13095 			 */
13096 			attr->branch_sample_type = mask;
13097 		}
13098 		/* privileged levels capture (kernel, hv): check permissions */
13099 		if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
13100 			ret = perf_allow_kernel();
13101 			if (ret)
13102 				return ret;
13103 		}
13104 	}
13105 
13106 	if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
13107 		ret = perf_reg_validate(attr->sample_regs_user);
13108 		if (ret)
13109 			return ret;
13110 	}
13111 
13112 	if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
13113 		if (!arch_perf_have_user_stack_dump())
13114 			return -ENOSYS;
13115 
13116 		/*
13117 		 * We have __u32 type for the size, but so far
13118 		 * we can only use __u16 as maximum due to the
13119 		 * __u16 sample size limit.
13120 		 */
13121 		if (attr->sample_stack_user >= USHRT_MAX)
13122 			return -EINVAL;
13123 		else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
13124 			return -EINVAL;
13125 	}
13126 
13127 	if (!attr->sample_max_stack)
13128 		attr->sample_max_stack = sysctl_perf_event_max_stack;
13129 
13130 	if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
13131 		ret = perf_reg_validate(attr->sample_regs_intr);
13132 
13133 #ifndef CONFIG_CGROUP_PERF
13134 	if (attr->sample_type & PERF_SAMPLE_CGROUP)
13135 		return -EINVAL;
13136 #endif
13137 	if ((attr->sample_type & PERF_SAMPLE_WEIGHT) &&
13138 	    (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT))
13139 		return -EINVAL;
13140 
13141 	if (!attr->inherit && attr->inherit_thread)
13142 		return -EINVAL;
13143 
13144 	if (attr->remove_on_exec && attr->enable_on_exec)
13145 		return -EINVAL;
13146 
13147 	if (attr->sigtrap && !attr->remove_on_exec)
13148 		return -EINVAL;
13149 
13150 out:
13151 	return ret;
13152 
13153 err_size:
13154 	put_user(sizeof(*attr), &uattr->size);
13155 	ret = -E2BIG;
13156 	goto out;
13157 }
13158 
mutex_lock_double(struct mutex * a,struct mutex * b)13159 static void mutex_lock_double(struct mutex *a, struct mutex *b)
13160 {
13161 	if (b < a)
13162 		swap(a, b);
13163 
13164 	mutex_lock(a);
13165 	mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
13166 }
13167 
13168 static int
perf_event_set_output(struct perf_event * event,struct perf_event * output_event)13169 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
13170 {
13171 	struct perf_buffer *rb = NULL;
13172 	int ret = -EINVAL;
13173 
13174 	if (!output_event) {
13175 		mutex_lock(&event->mmap_mutex);
13176 		goto set;
13177 	}
13178 
13179 	/* don't allow circular references */
13180 	if (event == output_event)
13181 		goto out;
13182 
13183 	/*
13184 	 * Don't allow cross-cpu buffers
13185 	 */
13186 	if (output_event->cpu != event->cpu)
13187 		goto out;
13188 
13189 	/*
13190 	 * If its not a per-cpu rb, it must be the same task.
13191 	 */
13192 	if (output_event->cpu == -1 && output_event->hw.target != event->hw.target)
13193 		goto out;
13194 
13195 	/*
13196 	 * Mixing clocks in the same buffer is trouble you don't need.
13197 	 */
13198 	if (output_event->clock != event->clock)
13199 		goto out;
13200 
13201 	/*
13202 	 * Either writing ring buffer from beginning or from end.
13203 	 * Mixing is not allowed.
13204 	 */
13205 	if (is_write_backward(output_event) != is_write_backward(event))
13206 		goto out;
13207 
13208 	/*
13209 	 * If both events generate aux data, they must be on the same PMU
13210 	 */
13211 	if (has_aux(event) && has_aux(output_event) &&
13212 	    event->pmu != output_event->pmu)
13213 		goto out;
13214 
13215 	/*
13216 	 * Hold both mmap_mutex to serialize against perf_mmap_close().  Since
13217 	 * output_event is already on rb->event_list, and the list iteration
13218 	 * restarts after every removal, it is guaranteed this new event is
13219 	 * observed *OR* if output_event is already removed, it's guaranteed we
13220 	 * observe !rb->mmap_count.
13221 	 */
13222 	mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex);
13223 set:
13224 	/* Can't redirect output if we've got an active mmap() */
13225 	if (atomic_read(&event->mmap_count))
13226 		goto unlock;
13227 
13228 	if (output_event) {
13229 		if (output_event->state <= PERF_EVENT_STATE_REVOKED)
13230 			goto unlock;
13231 
13232 		/* get the rb we want to redirect to */
13233 		rb = ring_buffer_get(output_event);
13234 		if (!rb)
13235 			goto unlock;
13236 
13237 		/* did we race against perf_mmap_close() */
13238 		if (!atomic_read(&rb->mmap_count)) {
13239 			ring_buffer_put(rb);
13240 			goto unlock;
13241 		}
13242 	}
13243 
13244 	ring_buffer_attach(event, rb);
13245 
13246 	ret = 0;
13247 unlock:
13248 	mutex_unlock(&event->mmap_mutex);
13249 	if (output_event)
13250 		mutex_unlock(&output_event->mmap_mutex);
13251 
13252 out:
13253 	return ret;
13254 }
13255 
perf_event_set_clock(struct perf_event * event,clockid_t clk_id)13256 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
13257 {
13258 	bool nmi_safe = false;
13259 
13260 	switch (clk_id) {
13261 	case CLOCK_MONOTONIC:
13262 		event->clock = &ktime_get_mono_fast_ns;
13263 		nmi_safe = true;
13264 		break;
13265 
13266 	case CLOCK_MONOTONIC_RAW:
13267 		event->clock = &ktime_get_raw_fast_ns;
13268 		nmi_safe = true;
13269 		break;
13270 
13271 	case CLOCK_REALTIME:
13272 		event->clock = &ktime_get_real_ns;
13273 		break;
13274 
13275 	case CLOCK_BOOTTIME:
13276 		event->clock = &ktime_get_boottime_ns;
13277 		break;
13278 
13279 	case CLOCK_TAI:
13280 		event->clock = &ktime_get_clocktai_ns;
13281 		break;
13282 
13283 	default:
13284 		return -EINVAL;
13285 	}
13286 
13287 	if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
13288 		return -EINVAL;
13289 
13290 	return 0;
13291 }
13292 
13293 static bool
perf_check_permission(struct perf_event_attr * attr,struct task_struct * task)13294 perf_check_permission(struct perf_event_attr *attr, struct task_struct *task)
13295 {
13296 	unsigned int ptrace_mode = PTRACE_MODE_READ_REALCREDS;
13297 	bool is_capable = perfmon_capable();
13298 
13299 	if (attr->sigtrap) {
13300 		/*
13301 		 * perf_event_attr::sigtrap sends signals to the other task.
13302 		 * Require the current task to also have CAP_KILL.
13303 		 */
13304 		rcu_read_lock();
13305 		is_capable &= ns_capable(__task_cred(task)->user_ns, CAP_KILL);
13306 		rcu_read_unlock();
13307 
13308 		/*
13309 		 * If the required capabilities aren't available, checks for
13310 		 * ptrace permissions: upgrade to ATTACH, since sending signals
13311 		 * can effectively change the target task.
13312 		 */
13313 		ptrace_mode = PTRACE_MODE_ATTACH_REALCREDS;
13314 	}
13315 
13316 	/*
13317 	 * Preserve ptrace permission check for backwards compatibility. The
13318 	 * ptrace check also includes checks that the current task and other
13319 	 * task have matching uids, and is therefore not done here explicitly.
13320 	 */
13321 	return is_capable || ptrace_may_access(task, ptrace_mode);
13322 }
13323 
13324 /**
13325  * sys_perf_event_open - open a performance event, associate it to a task/cpu
13326  *
13327  * @attr_uptr:	event_id type attributes for monitoring/sampling
13328  * @pid:		target pid
13329  * @cpu:		target cpu
13330  * @group_fd:		group leader event fd
13331  * @flags:		perf event open flags
13332  */
SYSCALL_DEFINE5(perf_event_open,struct perf_event_attr __user *,attr_uptr,pid_t,pid,int,cpu,int,group_fd,unsigned long,flags)13333 SYSCALL_DEFINE5(perf_event_open,
13334 		struct perf_event_attr __user *, attr_uptr,
13335 		pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
13336 {
13337 	struct perf_event *group_leader = NULL, *output_event = NULL;
13338 	struct perf_event_pmu_context *pmu_ctx;
13339 	struct perf_event *event, *sibling;
13340 	struct perf_event_attr attr;
13341 	struct perf_event_context *ctx;
13342 	struct file *event_file = NULL;
13343 	struct task_struct *task = NULL;
13344 	struct pmu *pmu;
13345 	int event_fd;
13346 	int move_group = 0;
13347 	int err;
13348 	int f_flags = O_RDWR;
13349 	int cgroup_fd = -1;
13350 
13351 	/* for future expandability... */
13352 	if (flags & ~PERF_FLAG_ALL)
13353 		return -EINVAL;
13354 
13355 	err = perf_copy_attr(attr_uptr, &attr);
13356 	if (err)
13357 		return err;
13358 
13359 	/* Do we allow access to perf_event_open(2) ? */
13360 	err = security_perf_event_open(PERF_SECURITY_OPEN);
13361 	if (err)
13362 		return err;
13363 
13364 	if (!attr.exclude_kernel) {
13365 		err = perf_allow_kernel();
13366 		if (err)
13367 			return err;
13368 	}
13369 
13370 	if (attr.namespaces) {
13371 		if (!perfmon_capable())
13372 			return -EACCES;
13373 	}
13374 
13375 	if (attr.freq) {
13376 		if (attr.sample_freq > sysctl_perf_event_sample_rate)
13377 			return -EINVAL;
13378 	} else {
13379 		if (attr.sample_period & (1ULL << 63))
13380 			return -EINVAL;
13381 	}
13382 
13383 	/* Only privileged users can get physical addresses */
13384 	if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
13385 		err = perf_allow_kernel();
13386 		if (err)
13387 			return err;
13388 	}
13389 
13390 	/* REGS_INTR can leak data, lockdown must prevent this */
13391 	if (attr.sample_type & PERF_SAMPLE_REGS_INTR) {
13392 		err = security_locked_down(LOCKDOWN_PERF);
13393 		if (err)
13394 			return err;
13395 	}
13396 
13397 	/*
13398 	 * In cgroup mode, the pid argument is used to pass the fd
13399 	 * opened to the cgroup directory in cgroupfs. The cpu argument
13400 	 * designates the cpu on which to monitor threads from that
13401 	 * cgroup.
13402 	 */
13403 	if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
13404 		return -EINVAL;
13405 
13406 	if (flags & PERF_FLAG_FD_CLOEXEC)
13407 		f_flags |= O_CLOEXEC;
13408 
13409 	event_fd = get_unused_fd_flags(f_flags);
13410 	if (event_fd < 0)
13411 		return event_fd;
13412 
13413 	/*
13414 	 * Event creation should be under SRCU, see perf_pmu_unregister().
13415 	 */
13416 	guard(srcu)(&pmus_srcu);
13417 
13418 	CLASS(fd, group)(group_fd);     // group_fd == -1 => empty
13419 	if (group_fd != -1) {
13420 		if (!is_perf_file(group)) {
13421 			err = -EBADF;
13422 			goto err_fd;
13423 		}
13424 		group_leader = fd_file(group)->private_data;
13425 		if (group_leader->state <= PERF_EVENT_STATE_REVOKED) {
13426 			err = -ENODEV;
13427 			goto err_fd;
13428 		}
13429 		if (flags & PERF_FLAG_FD_OUTPUT)
13430 			output_event = group_leader;
13431 		if (flags & PERF_FLAG_FD_NO_GROUP)
13432 			group_leader = NULL;
13433 	}
13434 
13435 	if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
13436 		task = find_lively_task_by_vpid(pid);
13437 		if (IS_ERR(task)) {
13438 			err = PTR_ERR(task);
13439 			goto err_fd;
13440 		}
13441 	}
13442 
13443 	if (task && group_leader &&
13444 	    group_leader->attr.inherit != attr.inherit) {
13445 		err = -EINVAL;
13446 		goto err_task;
13447 	}
13448 
13449 	if (flags & PERF_FLAG_PID_CGROUP)
13450 		cgroup_fd = pid;
13451 
13452 	event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
13453 				 NULL, NULL, cgroup_fd);
13454 	if (IS_ERR(event)) {
13455 		err = PTR_ERR(event);
13456 		goto err_task;
13457 	}
13458 
13459 	if (is_sampling_event(event)) {
13460 		if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
13461 			err = -EOPNOTSUPP;
13462 			goto err_alloc;
13463 		}
13464 	}
13465 
13466 	/*
13467 	 * Special case software events and allow them to be part of
13468 	 * any hardware group.
13469 	 */
13470 	pmu = event->pmu;
13471 
13472 	if (attr.use_clockid) {
13473 		err = perf_event_set_clock(event, attr.clockid);
13474 		if (err)
13475 			goto err_alloc;
13476 	}
13477 
13478 	if (pmu->task_ctx_nr == perf_sw_context)
13479 		event->event_caps |= PERF_EV_CAP_SOFTWARE;
13480 
13481 	if (task) {
13482 		err = down_read_interruptible(&task->signal->exec_update_lock);
13483 		if (err)
13484 			goto err_alloc;
13485 
13486 		/*
13487 		 * We must hold exec_update_lock across this and any potential
13488 		 * perf_install_in_context() call for this new event to
13489 		 * serialize against exec() altering our credentials (and the
13490 		 * perf_event_exit_task() that could imply).
13491 		 */
13492 		err = -EACCES;
13493 		if (!perf_check_permission(&attr, task))
13494 			goto err_cred;
13495 	}
13496 
13497 	/*
13498 	 * Get the target context (task or percpu):
13499 	 */
13500 	ctx = find_get_context(task, event);
13501 	if (IS_ERR(ctx)) {
13502 		err = PTR_ERR(ctx);
13503 		goto err_cred;
13504 	}
13505 
13506 	mutex_lock(&ctx->mutex);
13507 
13508 	if (ctx->task == TASK_TOMBSTONE) {
13509 		err = -ESRCH;
13510 		goto err_locked;
13511 	}
13512 
13513 	if (!task) {
13514 		/*
13515 		 * Check if the @cpu we're creating an event for is online.
13516 		 *
13517 		 * We use the perf_cpu_context::ctx::mutex to serialize against
13518 		 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
13519 		 */
13520 		struct perf_cpu_context *cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
13521 
13522 		if (!cpuctx->online) {
13523 			err = -ENODEV;
13524 			goto err_locked;
13525 		}
13526 	}
13527 
13528 	if (group_leader) {
13529 		err = -EINVAL;
13530 
13531 		/*
13532 		 * Do not allow a recursive hierarchy (this new sibling
13533 		 * becoming part of another group-sibling):
13534 		 */
13535 		if (group_leader->group_leader != group_leader)
13536 			goto err_locked;
13537 
13538 		/* All events in a group should have the same clock */
13539 		if (group_leader->clock != event->clock)
13540 			goto err_locked;
13541 
13542 		/*
13543 		 * Make sure we're both events for the same CPU;
13544 		 * grouping events for different CPUs is broken; since
13545 		 * you can never concurrently schedule them anyhow.
13546 		 */
13547 		if (group_leader->cpu != event->cpu)
13548 			goto err_locked;
13549 
13550 		/*
13551 		 * Make sure we're both on the same context; either task or cpu.
13552 		 */
13553 		if (group_leader->ctx != ctx)
13554 			goto err_locked;
13555 
13556 		/*
13557 		 * Only a group leader can be exclusive or pinned
13558 		 */
13559 		if (attr.exclusive || attr.pinned)
13560 			goto err_locked;
13561 
13562 		if (is_software_event(event) &&
13563 		    !in_software_context(group_leader)) {
13564 			/*
13565 			 * If the event is a sw event, but the group_leader
13566 			 * is on hw context.
13567 			 *
13568 			 * Allow the addition of software events to hw
13569 			 * groups, this is safe because software events
13570 			 * never fail to schedule.
13571 			 *
13572 			 * Note the comment that goes with struct
13573 			 * perf_event_pmu_context.
13574 			 */
13575 			pmu = group_leader->pmu_ctx->pmu;
13576 		} else if (!is_software_event(event)) {
13577 			if (is_software_event(group_leader) &&
13578 			    (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
13579 				/*
13580 				 * In case the group is a pure software group, and we
13581 				 * try to add a hardware event, move the whole group to
13582 				 * the hardware context.
13583 				 */
13584 				move_group = 1;
13585 			}
13586 
13587 			/* Don't allow group of multiple hw events from different pmus */
13588 			if (!in_software_context(group_leader) &&
13589 			    group_leader->pmu_ctx->pmu != pmu)
13590 				goto err_locked;
13591 		}
13592 	}
13593 
13594 	/*
13595 	 * Now that we're certain of the pmu; find the pmu_ctx.
13596 	 */
13597 	pmu_ctx = find_get_pmu_context(pmu, ctx, event);
13598 	if (IS_ERR(pmu_ctx)) {
13599 		err = PTR_ERR(pmu_ctx);
13600 		goto err_locked;
13601 	}
13602 	event->pmu_ctx = pmu_ctx;
13603 
13604 	if (output_event) {
13605 		err = perf_event_set_output(event, output_event);
13606 		if (err)
13607 			goto err_context;
13608 	}
13609 
13610 	if (!perf_event_validate_size(event)) {
13611 		err = -E2BIG;
13612 		goto err_context;
13613 	}
13614 
13615 	if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
13616 		err = -EINVAL;
13617 		goto err_context;
13618 	}
13619 
13620 	/*
13621 	 * Must be under the same ctx::mutex as perf_install_in_context(),
13622 	 * because we need to serialize with concurrent event creation.
13623 	 */
13624 	if (!exclusive_event_installable(event, ctx)) {
13625 		err = -EBUSY;
13626 		goto err_context;
13627 	}
13628 
13629 	WARN_ON_ONCE(ctx->parent_ctx);
13630 
13631 	event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags);
13632 	if (IS_ERR(event_file)) {
13633 		err = PTR_ERR(event_file);
13634 		event_file = NULL;
13635 		goto err_context;
13636 	}
13637 
13638 	/*
13639 	 * This is the point on no return; we cannot fail hereafter. This is
13640 	 * where we start modifying current state.
13641 	 */
13642 
13643 	if (move_group) {
13644 		perf_remove_from_context(group_leader, 0);
13645 		put_pmu_ctx(group_leader->pmu_ctx);
13646 
13647 		for_each_sibling_event(sibling, group_leader) {
13648 			perf_remove_from_context(sibling, 0);
13649 			put_pmu_ctx(sibling->pmu_ctx);
13650 		}
13651 
13652 		/*
13653 		 * Install the group siblings before the group leader.
13654 		 *
13655 		 * Because a group leader will try and install the entire group
13656 		 * (through the sibling list, which is still in-tact), we can
13657 		 * end up with siblings installed in the wrong context.
13658 		 *
13659 		 * By installing siblings first we NO-OP because they're not
13660 		 * reachable through the group lists.
13661 		 */
13662 		for_each_sibling_event(sibling, group_leader) {
13663 			sibling->pmu_ctx = pmu_ctx;
13664 			get_pmu_ctx(pmu_ctx);
13665 			perf_event__state_init(sibling);
13666 			perf_install_in_context(ctx, sibling, sibling->cpu);
13667 		}
13668 
13669 		/*
13670 		 * Removing from the context ends up with disabled
13671 		 * event. What we want here is event in the initial
13672 		 * startup state, ready to be add into new context.
13673 		 */
13674 		group_leader->pmu_ctx = pmu_ctx;
13675 		get_pmu_ctx(pmu_ctx);
13676 		perf_event__state_init(group_leader);
13677 		perf_install_in_context(ctx, group_leader, group_leader->cpu);
13678 	}
13679 
13680 	/*
13681 	 * Precalculate sample_data sizes; do while holding ctx::mutex such
13682 	 * that we're serialized against further additions and before
13683 	 * perf_install_in_context() which is the point the event is active and
13684 	 * can use these values.
13685 	 */
13686 	perf_event__header_size(event);
13687 	perf_event__id_header_size(event);
13688 
13689 	event->owner = current;
13690 
13691 	perf_install_in_context(ctx, event, event->cpu);
13692 	perf_unpin_context(ctx);
13693 
13694 	mutex_unlock(&ctx->mutex);
13695 
13696 	if (task) {
13697 		up_read(&task->signal->exec_update_lock);
13698 		put_task_struct(task);
13699 	}
13700 
13701 	mutex_lock(&current->perf_event_mutex);
13702 	list_add_tail(&event->owner_entry, &current->perf_event_list);
13703 	mutex_unlock(&current->perf_event_mutex);
13704 
13705 	/*
13706 	 * File reference in group guarantees that group_leader has been
13707 	 * kept alive until we place the new event on the sibling_list.
13708 	 * This ensures destruction of the group leader will find
13709 	 * the pointer to itself in perf_group_detach().
13710 	 */
13711 	fd_install(event_fd, event_file);
13712 	return event_fd;
13713 
13714 err_context:
13715 	put_pmu_ctx(event->pmu_ctx);
13716 	event->pmu_ctx = NULL; /* _free_event() */
13717 err_locked:
13718 	mutex_unlock(&ctx->mutex);
13719 	perf_unpin_context(ctx);
13720 	put_ctx(ctx);
13721 err_cred:
13722 	if (task)
13723 		up_read(&task->signal->exec_update_lock);
13724 err_alloc:
13725 	put_event(event);
13726 err_task:
13727 	if (task)
13728 		put_task_struct(task);
13729 err_fd:
13730 	put_unused_fd(event_fd);
13731 	return err;
13732 }
13733 
13734 /**
13735  * perf_event_create_kernel_counter
13736  *
13737  * @attr: attributes of the counter to create
13738  * @cpu: cpu in which the counter is bound
13739  * @task: task to profile (NULL for percpu)
13740  * @overflow_handler: callback to trigger when we hit the event
13741  * @context: context data could be used in overflow_handler callback
13742  */
13743 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)13744 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
13745 				 struct task_struct *task,
13746 				 perf_overflow_handler_t overflow_handler,
13747 				 void *context)
13748 {
13749 	struct perf_event_pmu_context *pmu_ctx;
13750 	struct perf_event_context *ctx;
13751 	struct perf_event *event;
13752 	struct pmu *pmu;
13753 	int err;
13754 
13755 	/*
13756 	 * Grouping is not supported for kernel events, neither is 'AUX',
13757 	 * make sure the caller's intentions are adjusted.
13758 	 */
13759 	if (attr->aux_output || attr->aux_action)
13760 		return ERR_PTR(-EINVAL);
13761 
13762 	/*
13763 	 * Event creation should be under SRCU, see perf_pmu_unregister().
13764 	 */
13765 	guard(srcu)(&pmus_srcu);
13766 
13767 	event = perf_event_alloc(attr, cpu, task, NULL, NULL,
13768 				 overflow_handler, context, -1);
13769 	if (IS_ERR(event)) {
13770 		err = PTR_ERR(event);
13771 		goto err;
13772 	}
13773 
13774 	/* Mark owner so we could distinguish it from user events. */
13775 	event->owner = TASK_TOMBSTONE;
13776 	pmu = event->pmu;
13777 
13778 	if (pmu->task_ctx_nr == perf_sw_context)
13779 		event->event_caps |= PERF_EV_CAP_SOFTWARE;
13780 
13781 	/*
13782 	 * Get the target context (task or percpu):
13783 	 */
13784 	ctx = find_get_context(task, event);
13785 	if (IS_ERR(ctx)) {
13786 		err = PTR_ERR(ctx);
13787 		goto err_alloc;
13788 	}
13789 
13790 	WARN_ON_ONCE(ctx->parent_ctx);
13791 	mutex_lock(&ctx->mutex);
13792 	if (ctx->task == TASK_TOMBSTONE) {
13793 		err = -ESRCH;
13794 		goto err_unlock;
13795 	}
13796 
13797 	pmu_ctx = find_get_pmu_context(pmu, ctx, event);
13798 	if (IS_ERR(pmu_ctx)) {
13799 		err = PTR_ERR(pmu_ctx);
13800 		goto err_unlock;
13801 	}
13802 	event->pmu_ctx = pmu_ctx;
13803 
13804 	if (!task) {
13805 		/*
13806 		 * Check if the @cpu we're creating an event for is online.
13807 		 *
13808 		 * We use the perf_cpu_context::ctx::mutex to serialize against
13809 		 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
13810 		 */
13811 		struct perf_cpu_context *cpuctx =
13812 			container_of(ctx, struct perf_cpu_context, ctx);
13813 		if (!cpuctx->online) {
13814 			err = -ENODEV;
13815 			goto err_pmu_ctx;
13816 		}
13817 	}
13818 
13819 	if (!exclusive_event_installable(event, ctx)) {
13820 		err = -EBUSY;
13821 		goto err_pmu_ctx;
13822 	}
13823 
13824 	perf_install_in_context(ctx, event, event->cpu);
13825 	perf_unpin_context(ctx);
13826 	mutex_unlock(&ctx->mutex);
13827 
13828 	return event;
13829 
13830 err_pmu_ctx:
13831 	put_pmu_ctx(pmu_ctx);
13832 	event->pmu_ctx = NULL; /* _free_event() */
13833 err_unlock:
13834 	mutex_unlock(&ctx->mutex);
13835 	perf_unpin_context(ctx);
13836 	put_ctx(ctx);
13837 err_alloc:
13838 	put_event(event);
13839 err:
13840 	return ERR_PTR(err);
13841 }
13842 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
13843 
__perf_pmu_remove(struct perf_event_context * ctx,int cpu,struct pmu * pmu,struct perf_event_groups * groups,struct list_head * events)13844 static void __perf_pmu_remove(struct perf_event_context *ctx,
13845 			      int cpu, struct pmu *pmu,
13846 			      struct perf_event_groups *groups,
13847 			      struct list_head *events)
13848 {
13849 	struct perf_event *event, *sibling;
13850 
13851 	perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) {
13852 		perf_remove_from_context(event, 0);
13853 		put_pmu_ctx(event->pmu_ctx);
13854 		list_add(&event->migrate_entry, events);
13855 
13856 		for_each_sibling_event(sibling, event) {
13857 			perf_remove_from_context(sibling, 0);
13858 			put_pmu_ctx(sibling->pmu_ctx);
13859 			list_add(&sibling->migrate_entry, events);
13860 		}
13861 	}
13862 }
13863 
__perf_pmu_install_event(struct pmu * pmu,struct perf_event_context * ctx,int cpu,struct perf_event * event)13864 static void __perf_pmu_install_event(struct pmu *pmu,
13865 				     struct perf_event_context *ctx,
13866 				     int cpu, struct perf_event *event)
13867 {
13868 	struct perf_event_pmu_context *epc;
13869 	struct perf_event_context *old_ctx = event->ctx;
13870 
13871 	get_ctx(ctx); /* normally find_get_context() */
13872 
13873 	event->cpu = cpu;
13874 	epc = find_get_pmu_context(pmu, ctx, event);
13875 	event->pmu_ctx = epc;
13876 
13877 	if (event->state >= PERF_EVENT_STATE_OFF)
13878 		event->state = PERF_EVENT_STATE_INACTIVE;
13879 	perf_install_in_context(ctx, event, cpu);
13880 
13881 	/*
13882 	 * Now that event->ctx is updated and visible, put the old ctx.
13883 	 */
13884 	put_ctx(old_ctx);
13885 }
13886 
__perf_pmu_install(struct perf_event_context * ctx,int cpu,struct pmu * pmu,struct list_head * events)13887 static void __perf_pmu_install(struct perf_event_context *ctx,
13888 			       int cpu, struct pmu *pmu, struct list_head *events)
13889 {
13890 	struct perf_event *event, *tmp;
13891 
13892 	/*
13893 	 * Re-instate events in 2 passes.
13894 	 *
13895 	 * Skip over group leaders and only install siblings on this first
13896 	 * pass, siblings will not get enabled without a leader, however a
13897 	 * leader will enable its siblings, even if those are still on the old
13898 	 * context.
13899 	 */
13900 	list_for_each_entry_safe(event, tmp, events, migrate_entry) {
13901 		if (event->group_leader == event)
13902 			continue;
13903 
13904 		list_del(&event->migrate_entry);
13905 		__perf_pmu_install_event(pmu, ctx, cpu, event);
13906 	}
13907 
13908 	/*
13909 	 * Once all the siblings are setup properly, install the group leaders
13910 	 * to make it go.
13911 	 */
13912 	list_for_each_entry_safe(event, tmp, events, migrate_entry) {
13913 		list_del(&event->migrate_entry);
13914 		__perf_pmu_install_event(pmu, ctx, cpu, event);
13915 	}
13916 }
13917 
perf_pmu_migrate_context(struct pmu * pmu,int src_cpu,int dst_cpu)13918 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
13919 {
13920 	struct perf_event_context *src_ctx, *dst_ctx;
13921 	LIST_HEAD(events);
13922 
13923 	/*
13924 	 * Since per-cpu context is persistent, no need to grab an extra
13925 	 * reference.
13926 	 */
13927 	src_ctx = &per_cpu_ptr(&perf_cpu_context, src_cpu)->ctx;
13928 	dst_ctx = &per_cpu_ptr(&perf_cpu_context, dst_cpu)->ctx;
13929 
13930 	/*
13931 	 * See perf_event_ctx_lock() for comments on the details
13932 	 * of swizzling perf_event::ctx.
13933 	 */
13934 	mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
13935 
13936 	__perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->pinned_groups, &events);
13937 	__perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->flexible_groups, &events);
13938 
13939 	if (!list_empty(&events)) {
13940 		/*
13941 		 * Wait for the events to quiesce before re-instating them.
13942 		 */
13943 		synchronize_rcu();
13944 
13945 		__perf_pmu_install(dst_ctx, dst_cpu, pmu, &events);
13946 	}
13947 
13948 	mutex_unlock(&dst_ctx->mutex);
13949 	mutex_unlock(&src_ctx->mutex);
13950 }
13951 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
13952 
sync_child_event(struct perf_event * child_event)13953 static void sync_child_event(struct perf_event *child_event)
13954 {
13955 	struct perf_event *parent_event = child_event->parent;
13956 	u64 child_val;
13957 
13958 	if (child_event->attr.inherit_stat) {
13959 		struct task_struct *task = child_event->ctx->task;
13960 
13961 		if (task && task != TASK_TOMBSTONE)
13962 			perf_event_read_event(child_event, task);
13963 	}
13964 
13965 	child_val = perf_event_count(child_event, false);
13966 
13967 	/*
13968 	 * Add back the child's count to the parent's count:
13969 	 */
13970 	atomic64_add(child_val, &parent_event->child_count);
13971 	atomic64_add(child_event->total_time_enabled,
13972 		     &parent_event->child_total_time_enabled);
13973 	atomic64_add(child_event->total_time_running,
13974 		     &parent_event->child_total_time_running);
13975 }
13976 
13977 static void
perf_event_exit_event(struct perf_event * event,struct perf_event_context * ctx,bool revoke)13978 perf_event_exit_event(struct perf_event *event,
13979 		      struct perf_event_context *ctx, bool revoke)
13980 {
13981 	struct perf_event *parent_event = event->parent;
13982 	unsigned long detach_flags = DETACH_EXIT;
13983 	unsigned int attach_state;
13984 
13985 	if (parent_event) {
13986 		/*
13987 		 * Do not destroy the 'original' grouping; because of the
13988 		 * context switch optimization the original events could've
13989 		 * ended up in a random child task.
13990 		 *
13991 		 * If we were to destroy the original group, all group related
13992 		 * operations would cease to function properly after this
13993 		 * random child dies.
13994 		 *
13995 		 * Do destroy all inherited groups, we don't care about those
13996 		 * and being thorough is better.
13997 		 */
13998 		detach_flags |= DETACH_GROUP | DETACH_CHILD;
13999 		mutex_lock(&parent_event->child_mutex);
14000 		/* PERF_ATTACH_ITRACE might be set concurrently */
14001 		attach_state = READ_ONCE(event->attach_state);
14002 	}
14003 
14004 	if (revoke)
14005 		detach_flags |= DETACH_GROUP | DETACH_REVOKE;
14006 
14007 	perf_remove_from_context(event, detach_flags);
14008 	/*
14009 	 * Child events can be freed.
14010 	 */
14011 	if (parent_event) {
14012 		mutex_unlock(&parent_event->child_mutex);
14013 
14014 		/*
14015 		 * Match the refcount initialization. Make sure it doesn't happen
14016 		 * twice if pmu_detach_event() calls it on an already exited task.
14017 		 */
14018 		if (attach_state & PERF_ATTACH_CHILD) {
14019 			/*
14020 			 * Kick perf_poll() for is_event_hup();
14021 			 */
14022 			perf_event_wakeup(parent_event);
14023 			/*
14024 			 * pmu_detach_event() will have an extra refcount.
14025 			 * perf_pending_task() might have one too.
14026 			 */
14027 			put_event(event);
14028 		}
14029 
14030 		return;
14031 	}
14032 
14033 	/*
14034 	 * Parent events are governed by their filedesc, retain them.
14035 	 */
14036 	perf_event_wakeup(event);
14037 }
14038 
perf_event_exit_task_context(struct task_struct * task,bool exit)14039 static void perf_event_exit_task_context(struct task_struct *task, bool exit)
14040 {
14041 	struct perf_event_context *ctx, *clone_ctx = NULL;
14042 	struct perf_event *child_event, *next;
14043 
14044 	ctx = perf_pin_task_context(task);
14045 	if (!ctx)
14046 		return;
14047 
14048 	/*
14049 	 * In order to reduce the amount of tricky in ctx tear-down, we hold
14050 	 * ctx::mutex over the entire thing. This serializes against almost
14051 	 * everything that wants to access the ctx.
14052 	 *
14053 	 * The exception is sys_perf_event_open() /
14054 	 * perf_event_create_kernel_count() which does find_get_context()
14055 	 * without ctx::mutex (it cannot because of the move_group double mutex
14056 	 * lock thing). See the comments in perf_install_in_context().
14057 	 */
14058 	mutex_lock(&ctx->mutex);
14059 
14060 	/*
14061 	 * In a single ctx::lock section, de-schedule the events and detach the
14062 	 * context from the task such that we cannot ever get it scheduled back
14063 	 * in.
14064 	 */
14065 	raw_spin_lock_irq(&ctx->lock);
14066 	if (exit)
14067 		task_ctx_sched_out(ctx, NULL, EVENT_ALL);
14068 
14069 	/*
14070 	 * Now that the context is inactive, destroy the task <-> ctx relation
14071 	 * and mark the context dead.
14072 	 */
14073 	RCU_INIT_POINTER(task->perf_event_ctxp, NULL);
14074 	put_ctx(ctx); /* cannot be last */
14075 	WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
14076 	put_task_struct(task); /* cannot be last */
14077 
14078 	clone_ctx = unclone_ctx(ctx);
14079 	raw_spin_unlock_irq(&ctx->lock);
14080 
14081 	if (clone_ctx)
14082 		put_ctx(clone_ctx);
14083 
14084 	/*
14085 	 * Report the task dead after unscheduling the events so that we
14086 	 * won't get any samples after PERF_RECORD_EXIT. We can however still
14087 	 * get a few PERF_RECORD_READ events.
14088 	 */
14089 	if (exit)
14090 		perf_event_task(task, ctx, 0);
14091 
14092 	list_for_each_entry_safe(child_event, next, &ctx->event_list, event_entry)
14093 		perf_event_exit_event(child_event, ctx, false);
14094 
14095 	mutex_unlock(&ctx->mutex);
14096 
14097 	if (!exit) {
14098 		/*
14099 		 * perf_event_release_kernel() could still have a reference on
14100 		 * this context. In that case we must wait for these events to
14101 		 * have been freed (in particular all their references to this
14102 		 * task must've been dropped).
14103 		 *
14104 		 * Without this copy_process() will unconditionally free this
14105 		 * task (irrespective of its reference count) and
14106 		 * _free_event()'s put_task_struct(event->hw.target) will be a
14107 		 * use-after-free.
14108 		 *
14109 		 * Wait for all events to drop their context reference.
14110 		 */
14111 		wait_var_event(&ctx->refcount,
14112 			       refcount_read(&ctx->refcount) == 1);
14113 	}
14114 	put_ctx(ctx);
14115 }
14116 
14117 /*
14118  * When a task exits, feed back event values to parent events.
14119  *
14120  * Can be called with exec_update_lock held when called from
14121  * setup_new_exec().
14122  */
perf_event_exit_task(struct task_struct * task)14123 void perf_event_exit_task(struct task_struct *task)
14124 {
14125 	struct perf_event *event, *tmp;
14126 
14127 	WARN_ON_ONCE(task != current);
14128 
14129 	mutex_lock(&task->perf_event_mutex);
14130 	list_for_each_entry_safe(event, tmp, &task->perf_event_list,
14131 				 owner_entry) {
14132 		list_del_init(&event->owner_entry);
14133 
14134 		/*
14135 		 * Ensure the list deletion is visible before we clear
14136 		 * the owner, closes a race against perf_release() where
14137 		 * we need to serialize on the owner->perf_event_mutex.
14138 		 */
14139 		smp_store_release(&event->owner, NULL);
14140 	}
14141 	mutex_unlock(&task->perf_event_mutex);
14142 
14143 	perf_event_exit_task_context(task, true);
14144 
14145 	/*
14146 	 * The perf_event_exit_task_context calls perf_event_task
14147 	 * with task's task_ctx, which generates EXIT events for
14148 	 * task contexts and sets task->perf_event_ctxp[] to NULL.
14149 	 * At this point we need to send EXIT events to cpu contexts.
14150 	 */
14151 	perf_event_task(task, NULL, 0);
14152 
14153 	/*
14154 	 * Detach the perf_ctx_data for the system-wide event.
14155 	 */
14156 	guard(percpu_read)(&global_ctx_data_rwsem);
14157 	detach_task_ctx_data(task);
14158 }
14159 
14160 /*
14161  * Free a context as created by inheritance by perf_event_init_task() below,
14162  * used by fork() in case of fail.
14163  *
14164  * Even though the task has never lived, the context and events have been
14165  * exposed through the child_list, so we must take care tearing it all down.
14166  */
perf_event_free_task(struct task_struct * task)14167 void perf_event_free_task(struct task_struct *task)
14168 {
14169 	perf_event_exit_task_context(task, false);
14170 }
14171 
perf_event_delayed_put(struct task_struct * task)14172 void perf_event_delayed_put(struct task_struct *task)
14173 {
14174 	WARN_ON_ONCE(task->perf_event_ctxp);
14175 }
14176 
perf_event_get(unsigned int fd)14177 struct file *perf_event_get(unsigned int fd)
14178 {
14179 	struct file *file = fget(fd);
14180 	if (!file)
14181 		return ERR_PTR(-EBADF);
14182 
14183 	if (file->f_op != &perf_fops) {
14184 		fput(file);
14185 		return ERR_PTR(-EBADF);
14186 	}
14187 
14188 	return file;
14189 }
14190 
perf_get_event(struct file * file)14191 const struct perf_event *perf_get_event(struct file *file)
14192 {
14193 	if (file->f_op != &perf_fops)
14194 		return ERR_PTR(-EINVAL);
14195 
14196 	return file->private_data;
14197 }
14198 
perf_event_attrs(struct perf_event * event)14199 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
14200 {
14201 	if (!event)
14202 		return ERR_PTR(-EINVAL);
14203 
14204 	return &event->attr;
14205 }
14206 
perf_allow_kernel(void)14207 int perf_allow_kernel(void)
14208 {
14209 	if (sysctl_perf_event_paranoid > 1 && !perfmon_capable())
14210 		return -EACCES;
14211 
14212 	return security_perf_event_open(PERF_SECURITY_KERNEL);
14213 }
14214 EXPORT_SYMBOL_GPL(perf_allow_kernel);
14215 
14216 /*
14217  * Inherit an event from parent task to child task.
14218  *
14219  * Returns:
14220  *  - valid pointer on success
14221  *  - NULL for orphaned events
14222  *  - IS_ERR() on error
14223  */
14224 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)14225 inherit_event(struct perf_event *parent_event,
14226 	      struct task_struct *parent,
14227 	      struct perf_event_context *parent_ctx,
14228 	      struct task_struct *child,
14229 	      struct perf_event *group_leader,
14230 	      struct perf_event_context *child_ctx)
14231 {
14232 	enum perf_event_state parent_state = parent_event->state;
14233 	struct perf_event_pmu_context *pmu_ctx;
14234 	struct perf_event *child_event;
14235 	unsigned long flags;
14236 
14237 	/*
14238 	 * Instead of creating recursive hierarchies of events,
14239 	 * we link inherited events back to the original parent,
14240 	 * which has a filp for sure, which we use as the reference
14241 	 * count:
14242 	 */
14243 	if (parent_event->parent)
14244 		parent_event = parent_event->parent;
14245 
14246 	if (parent_event->state <= PERF_EVENT_STATE_REVOKED)
14247 		return NULL;
14248 
14249 	/*
14250 	 * Event creation should be under SRCU, see perf_pmu_unregister().
14251 	 */
14252 	guard(srcu)(&pmus_srcu);
14253 
14254 	child_event = perf_event_alloc(&parent_event->attr,
14255 					   parent_event->cpu,
14256 					   child,
14257 					   group_leader, parent_event,
14258 					   NULL, NULL, -1);
14259 	if (IS_ERR(child_event))
14260 		return child_event;
14261 
14262 	get_ctx(child_ctx);
14263 	child_event->ctx = child_ctx;
14264 
14265 	pmu_ctx = find_get_pmu_context(child_event->pmu, child_ctx, child_event);
14266 	if (IS_ERR(pmu_ctx)) {
14267 		free_event(child_event);
14268 		return ERR_CAST(pmu_ctx);
14269 	}
14270 	child_event->pmu_ctx = pmu_ctx;
14271 
14272 	/*
14273 	 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
14274 	 * must be under the same lock in order to serialize against
14275 	 * perf_event_release_kernel(), such that either we must observe
14276 	 * is_orphaned_event() or they will observe us on the child_list.
14277 	 */
14278 	mutex_lock(&parent_event->child_mutex);
14279 	if (is_orphaned_event(parent_event) ||
14280 	    !atomic_long_inc_not_zero(&parent_event->refcount)) {
14281 		mutex_unlock(&parent_event->child_mutex);
14282 		free_event(child_event);
14283 		return NULL;
14284 	}
14285 
14286 	/*
14287 	 * Make the child state follow the state of the parent event,
14288 	 * not its attr.disabled bit.  We hold the parent's mutex,
14289 	 * so we won't race with perf_event_{en, dis}able_family.
14290 	 */
14291 	if (parent_state >= PERF_EVENT_STATE_INACTIVE)
14292 		child_event->state = PERF_EVENT_STATE_INACTIVE;
14293 	else
14294 		child_event->state = PERF_EVENT_STATE_OFF;
14295 
14296 	if (parent_event->attr.freq) {
14297 		u64 sample_period = parent_event->hw.sample_period;
14298 		struct hw_perf_event *hwc = &child_event->hw;
14299 
14300 		hwc->sample_period = sample_period;
14301 		hwc->last_period   = sample_period;
14302 
14303 		local64_set(&hwc->period_left, sample_period);
14304 	}
14305 
14306 	child_event->overflow_handler = parent_event->overflow_handler;
14307 	child_event->overflow_handler_context
14308 		= parent_event->overflow_handler_context;
14309 
14310 	/*
14311 	 * Precalculate sample_data sizes
14312 	 */
14313 	perf_event__header_size(child_event);
14314 	perf_event__id_header_size(child_event);
14315 
14316 	/*
14317 	 * Link it up in the child's context:
14318 	 */
14319 	raw_spin_lock_irqsave(&child_ctx->lock, flags);
14320 	add_event_to_ctx(child_event, child_ctx);
14321 	child_event->attach_state |= PERF_ATTACH_CHILD;
14322 	raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
14323 
14324 	/*
14325 	 * Link this into the parent event's child list
14326 	 */
14327 	list_add_tail(&child_event->child_list, &parent_event->child_list);
14328 	mutex_unlock(&parent_event->child_mutex);
14329 
14330 	return child_event;
14331 }
14332 
14333 /*
14334  * Inherits an event group.
14335  *
14336  * This will quietly suppress orphaned events; !inherit_event() is not an error.
14337  * This matches with perf_event_release_kernel() removing all child events.
14338  *
14339  * Returns:
14340  *  - 0 on success
14341  *  - <0 on error
14342  */
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)14343 static int inherit_group(struct perf_event *parent_event,
14344 	      struct task_struct *parent,
14345 	      struct perf_event_context *parent_ctx,
14346 	      struct task_struct *child,
14347 	      struct perf_event_context *child_ctx)
14348 {
14349 	struct perf_event *leader;
14350 	struct perf_event *sub;
14351 	struct perf_event *child_ctr;
14352 
14353 	leader = inherit_event(parent_event, parent, parent_ctx,
14354 				 child, NULL, child_ctx);
14355 	if (IS_ERR(leader))
14356 		return PTR_ERR(leader);
14357 	/*
14358 	 * @leader can be NULL here because of is_orphaned_event(). In this
14359 	 * case inherit_event() will create individual events, similar to what
14360 	 * perf_group_detach() would do anyway.
14361 	 */
14362 	for_each_sibling_event(sub, parent_event) {
14363 		child_ctr = inherit_event(sub, parent, parent_ctx,
14364 					    child, leader, child_ctx);
14365 		if (IS_ERR(child_ctr))
14366 			return PTR_ERR(child_ctr);
14367 
14368 		if (sub->aux_event == parent_event && child_ctr &&
14369 		    !perf_get_aux_event(child_ctr, leader))
14370 			return -EINVAL;
14371 	}
14372 	if (leader)
14373 		leader->group_generation = parent_event->group_generation;
14374 	return 0;
14375 }
14376 
14377 /*
14378  * Creates the child task context and tries to inherit the event-group.
14379  *
14380  * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
14381  * inherited_all set when we 'fail' to inherit an orphaned event; this is
14382  * consistent with perf_event_release_kernel() removing all child events.
14383  *
14384  * Returns:
14385  *  - 0 on success
14386  *  - <0 on error
14387  */
14388 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)14389 inherit_task_group(struct perf_event *event, struct task_struct *parent,
14390 		   struct perf_event_context *parent_ctx,
14391 		   struct task_struct *child,
14392 		   u64 clone_flags, int *inherited_all)
14393 {
14394 	struct perf_event_context *child_ctx;
14395 	int ret;
14396 
14397 	if (!event->attr.inherit ||
14398 	    (event->attr.inherit_thread && !(clone_flags & CLONE_THREAD)) ||
14399 	    /* Do not inherit if sigtrap and signal handlers were cleared. */
14400 	    (event->attr.sigtrap && (clone_flags & CLONE_CLEAR_SIGHAND))) {
14401 		*inherited_all = 0;
14402 		return 0;
14403 	}
14404 
14405 	child_ctx = child->perf_event_ctxp;
14406 	if (!child_ctx) {
14407 		/*
14408 		 * This is executed from the parent task context, so
14409 		 * inherit events that have been marked for cloning.
14410 		 * First allocate and initialize a context for the
14411 		 * child.
14412 		 */
14413 		child_ctx = alloc_perf_context(child);
14414 		if (!child_ctx)
14415 			return -ENOMEM;
14416 
14417 		child->perf_event_ctxp = child_ctx;
14418 	}
14419 
14420 	ret = inherit_group(event, parent, parent_ctx, child, child_ctx);
14421 	if (ret)
14422 		*inherited_all = 0;
14423 
14424 	return ret;
14425 }
14426 
14427 /*
14428  * Initialize the perf_event context in task_struct
14429  */
perf_event_init_context(struct task_struct * child,u64 clone_flags)14430 static int perf_event_init_context(struct task_struct *child, u64 clone_flags)
14431 {
14432 	struct perf_event_context *child_ctx, *parent_ctx;
14433 	struct perf_event_context *cloned_ctx;
14434 	struct perf_event *event;
14435 	struct task_struct *parent = current;
14436 	int inherited_all = 1;
14437 	unsigned long flags;
14438 	int ret = 0;
14439 
14440 	if (likely(!parent->perf_event_ctxp))
14441 		return 0;
14442 
14443 	/*
14444 	 * If the parent's context is a clone, pin it so it won't get
14445 	 * swapped under us.
14446 	 */
14447 	parent_ctx = perf_pin_task_context(parent);
14448 	if (!parent_ctx)
14449 		return 0;
14450 
14451 	/*
14452 	 * No need to check if parent_ctx != NULL here; since we saw
14453 	 * it non-NULL earlier, the only reason for it to become NULL
14454 	 * is if we exit, and since we're currently in the middle of
14455 	 * a fork we can't be exiting at the same time.
14456 	 */
14457 
14458 	/*
14459 	 * Lock the parent list. No need to lock the child - not PID
14460 	 * hashed yet and not running, so nobody can access it.
14461 	 */
14462 	mutex_lock(&parent_ctx->mutex);
14463 
14464 	/*
14465 	 * We dont have to disable NMIs - we are only looking at
14466 	 * the list, not manipulating it:
14467 	 */
14468 	perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
14469 		ret = inherit_task_group(event, parent, parent_ctx,
14470 					 child, clone_flags, &inherited_all);
14471 		if (ret)
14472 			goto out_unlock;
14473 	}
14474 
14475 	/*
14476 	 * We can't hold ctx->lock when iterating the ->flexible_group list due
14477 	 * to allocations, but we need to prevent rotation because
14478 	 * rotate_ctx() will change the list from interrupt context.
14479 	 */
14480 	raw_spin_lock_irqsave(&parent_ctx->lock, flags);
14481 	parent_ctx->rotate_disable = 1;
14482 	raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
14483 
14484 	perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
14485 		ret = inherit_task_group(event, parent, parent_ctx,
14486 					 child, clone_flags, &inherited_all);
14487 		if (ret)
14488 			goto out_unlock;
14489 	}
14490 
14491 	raw_spin_lock_irqsave(&parent_ctx->lock, flags);
14492 	parent_ctx->rotate_disable = 0;
14493 
14494 	child_ctx = child->perf_event_ctxp;
14495 
14496 	if (child_ctx && inherited_all) {
14497 		/*
14498 		 * Mark the child context as a clone of the parent
14499 		 * context, or of whatever the parent is a clone of.
14500 		 *
14501 		 * Note that if the parent is a clone, the holding of
14502 		 * parent_ctx->lock avoids it from being uncloned.
14503 		 */
14504 		cloned_ctx = parent_ctx->parent_ctx;
14505 		if (cloned_ctx) {
14506 			child_ctx->parent_ctx = cloned_ctx;
14507 			child_ctx->parent_gen = parent_ctx->parent_gen;
14508 		} else {
14509 			child_ctx->parent_ctx = parent_ctx;
14510 			child_ctx->parent_gen = parent_ctx->generation;
14511 		}
14512 		get_ctx(child_ctx->parent_ctx);
14513 	}
14514 
14515 	raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
14516 out_unlock:
14517 	mutex_unlock(&parent_ctx->mutex);
14518 
14519 	perf_unpin_context(parent_ctx);
14520 	put_ctx(parent_ctx);
14521 
14522 	return ret;
14523 }
14524 
14525 /*
14526  * Initialize the perf_event context in task_struct
14527  */
perf_event_init_task(struct task_struct * child,u64 clone_flags)14528 int perf_event_init_task(struct task_struct *child, u64 clone_flags)
14529 {
14530 	int ret;
14531 
14532 	memset(child->perf_recursion, 0, sizeof(child->perf_recursion));
14533 	child->perf_event_ctxp = NULL;
14534 	mutex_init(&child->perf_event_mutex);
14535 	INIT_LIST_HEAD(&child->perf_event_list);
14536 	child->perf_ctx_data = NULL;
14537 
14538 	ret = perf_event_init_context(child, clone_flags);
14539 	if (ret) {
14540 		perf_event_free_task(child);
14541 		return ret;
14542 	}
14543 
14544 	return 0;
14545 }
14546 
perf_event_init_all_cpus(void)14547 static void __init perf_event_init_all_cpus(void)
14548 {
14549 	struct swevent_htable *swhash;
14550 	struct perf_cpu_context *cpuctx;
14551 	int cpu;
14552 
14553 	zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
14554 	zalloc_cpumask_var(&perf_online_core_mask, GFP_KERNEL);
14555 	zalloc_cpumask_var(&perf_online_die_mask, GFP_KERNEL);
14556 	zalloc_cpumask_var(&perf_online_cluster_mask, GFP_KERNEL);
14557 	zalloc_cpumask_var(&perf_online_pkg_mask, GFP_KERNEL);
14558 	zalloc_cpumask_var(&perf_online_sys_mask, GFP_KERNEL);
14559 
14560 
14561 	for_each_possible_cpu(cpu) {
14562 		swhash = &per_cpu(swevent_htable, cpu);
14563 		mutex_init(&swhash->hlist_mutex);
14564 
14565 		INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
14566 		raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
14567 
14568 		INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
14569 
14570 		cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
14571 		__perf_event_init_context(&cpuctx->ctx);
14572 		lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
14573 		lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
14574 		cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
14575 		cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
14576 		cpuctx->heap = cpuctx->heap_default;
14577 	}
14578 }
14579 
perf_swevent_init_cpu(unsigned int cpu)14580 static void perf_swevent_init_cpu(unsigned int cpu)
14581 {
14582 	struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
14583 
14584 	mutex_lock(&swhash->hlist_mutex);
14585 	if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
14586 		struct swevent_hlist *hlist;
14587 
14588 		hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
14589 		WARN_ON(!hlist);
14590 		rcu_assign_pointer(swhash->swevent_hlist, hlist);
14591 	}
14592 	mutex_unlock(&swhash->hlist_mutex);
14593 }
14594 
14595 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
__perf_event_exit_context(void * __info)14596 static void __perf_event_exit_context(void *__info)
14597 {
14598 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
14599 	struct perf_event_context *ctx = __info;
14600 	struct perf_event *event;
14601 
14602 	raw_spin_lock(&ctx->lock);
14603 	ctx_sched_out(ctx, NULL, EVENT_TIME);
14604 	list_for_each_entry(event, &ctx->event_list, event_entry)
14605 		__perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
14606 	raw_spin_unlock(&ctx->lock);
14607 }
14608 
perf_event_clear_cpumask(unsigned int cpu)14609 static void perf_event_clear_cpumask(unsigned int cpu)
14610 {
14611 	int target[PERF_PMU_MAX_SCOPE];
14612 	unsigned int scope;
14613 	struct pmu *pmu;
14614 
14615 	cpumask_clear_cpu(cpu, perf_online_mask);
14616 
14617 	for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) {
14618 		const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu);
14619 		struct cpumask *pmu_cpumask = perf_scope_cpumask(scope);
14620 
14621 		target[scope] = -1;
14622 		if (WARN_ON_ONCE(!pmu_cpumask || !cpumask))
14623 			continue;
14624 
14625 		if (!cpumask_test_and_clear_cpu(cpu, pmu_cpumask))
14626 			continue;
14627 		target[scope] = cpumask_any_but(cpumask, cpu);
14628 		if (target[scope] < nr_cpu_ids)
14629 			cpumask_set_cpu(target[scope], pmu_cpumask);
14630 	}
14631 
14632 	/* migrate */
14633 	list_for_each_entry(pmu, &pmus, entry) {
14634 		if (pmu->scope == PERF_PMU_SCOPE_NONE ||
14635 		    WARN_ON_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE))
14636 			continue;
14637 
14638 		if (target[pmu->scope] >= 0 && target[pmu->scope] < nr_cpu_ids)
14639 			perf_pmu_migrate_context(pmu, cpu, target[pmu->scope]);
14640 	}
14641 }
14642 
perf_event_exit_cpu_context(int cpu)14643 static void perf_event_exit_cpu_context(int cpu)
14644 {
14645 	struct perf_cpu_context *cpuctx;
14646 	struct perf_event_context *ctx;
14647 
14648 	// XXX simplify cpuctx->online
14649 	mutex_lock(&pmus_lock);
14650 	/*
14651 	 * Clear the cpumasks, and migrate to other CPUs if possible.
14652 	 * Must be invoked before the __perf_event_exit_context.
14653 	 */
14654 	perf_event_clear_cpumask(cpu);
14655 	cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
14656 	ctx = &cpuctx->ctx;
14657 
14658 	mutex_lock(&ctx->mutex);
14659 	smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
14660 	cpuctx->online = 0;
14661 	mutex_unlock(&ctx->mutex);
14662 	mutex_unlock(&pmus_lock);
14663 }
14664 #else
14665 
perf_event_exit_cpu_context(int cpu)14666 static void perf_event_exit_cpu_context(int cpu) { }
14667 
14668 #endif
14669 
perf_event_setup_cpumask(unsigned int cpu)14670 static void perf_event_setup_cpumask(unsigned int cpu)
14671 {
14672 	struct cpumask *pmu_cpumask;
14673 	unsigned int scope;
14674 
14675 	/*
14676 	 * Early boot stage, the cpumask hasn't been set yet.
14677 	 * The perf_online_<domain>_masks includes the first CPU of each domain.
14678 	 * Always unconditionally set the boot CPU for the perf_online_<domain>_masks.
14679 	 */
14680 	if (cpumask_empty(perf_online_mask)) {
14681 		for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) {
14682 			pmu_cpumask = perf_scope_cpumask(scope);
14683 			if (WARN_ON_ONCE(!pmu_cpumask))
14684 				continue;
14685 			cpumask_set_cpu(cpu, pmu_cpumask);
14686 		}
14687 		goto end;
14688 	}
14689 
14690 	for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) {
14691 		const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu);
14692 
14693 		pmu_cpumask = perf_scope_cpumask(scope);
14694 
14695 		if (WARN_ON_ONCE(!pmu_cpumask || !cpumask))
14696 			continue;
14697 
14698 		if (!cpumask_empty(cpumask) &&
14699 		    cpumask_any_and(pmu_cpumask, cpumask) >= nr_cpu_ids)
14700 			cpumask_set_cpu(cpu, pmu_cpumask);
14701 	}
14702 end:
14703 	cpumask_set_cpu(cpu, perf_online_mask);
14704 }
14705 
perf_event_init_cpu(unsigned int cpu)14706 int perf_event_init_cpu(unsigned int cpu)
14707 {
14708 	struct perf_cpu_context *cpuctx;
14709 	struct perf_event_context *ctx;
14710 
14711 	perf_swevent_init_cpu(cpu);
14712 
14713 	mutex_lock(&pmus_lock);
14714 	perf_event_setup_cpumask(cpu);
14715 	cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
14716 	ctx = &cpuctx->ctx;
14717 
14718 	mutex_lock(&ctx->mutex);
14719 	cpuctx->online = 1;
14720 	mutex_unlock(&ctx->mutex);
14721 	mutex_unlock(&pmus_lock);
14722 
14723 	return 0;
14724 }
14725 
perf_event_exit_cpu(unsigned int cpu)14726 int perf_event_exit_cpu(unsigned int cpu)
14727 {
14728 	perf_event_exit_cpu_context(cpu);
14729 	return 0;
14730 }
14731 
14732 static int
perf_reboot(struct notifier_block * notifier,unsigned long val,void * v)14733 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
14734 {
14735 	int cpu;
14736 
14737 	for_each_online_cpu(cpu)
14738 		perf_event_exit_cpu(cpu);
14739 
14740 	return NOTIFY_OK;
14741 }
14742 
14743 /*
14744  * Run the perf reboot notifier at the very last possible moment so that
14745  * the generic watchdog code runs as long as possible.
14746  */
14747 static struct notifier_block perf_reboot_notifier = {
14748 	.notifier_call = perf_reboot,
14749 	.priority = INT_MIN,
14750 };
14751 
perf_event_init(void)14752 void __init perf_event_init(void)
14753 {
14754 	int ret;
14755 
14756 	idr_init(&pmu_idr);
14757 
14758 	perf_event_init_all_cpus();
14759 	init_srcu_struct(&pmus_srcu);
14760 	perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
14761 	perf_pmu_register(&perf_cpu_clock, "cpu_clock", -1);
14762 	perf_pmu_register(&perf_task_clock, "task_clock", -1);
14763 	perf_tp_register();
14764 	perf_event_init_cpu(smp_processor_id());
14765 	register_reboot_notifier(&perf_reboot_notifier);
14766 
14767 	ret = init_hw_breakpoint();
14768 	WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
14769 
14770 	perf_event_cache = KMEM_CACHE(perf_event, SLAB_PANIC);
14771 
14772 	/*
14773 	 * Build time assertion that we keep the data_head at the intended
14774 	 * location.  IOW, validation we got the __reserved[] size right.
14775 	 */
14776 	BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
14777 		     != 1024);
14778 }
14779 
perf_event_sysfs_show(struct device * dev,struct device_attribute * attr,char * page)14780 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
14781 			      char *page)
14782 {
14783 	struct perf_pmu_events_attr *pmu_attr =
14784 		container_of(attr, struct perf_pmu_events_attr, attr);
14785 
14786 	if (pmu_attr->event_str)
14787 		return sprintf(page, "%s\n", pmu_attr->event_str);
14788 
14789 	return 0;
14790 }
14791 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
14792 
perf_event_sysfs_init(void)14793 static int __init perf_event_sysfs_init(void)
14794 {
14795 	struct pmu *pmu;
14796 	int ret;
14797 
14798 	mutex_lock(&pmus_lock);
14799 
14800 	ret = bus_register(&pmu_bus);
14801 	if (ret)
14802 		goto unlock;
14803 
14804 	list_for_each_entry(pmu, &pmus, entry) {
14805 		if (pmu->dev)
14806 			continue;
14807 
14808 		ret = pmu_dev_alloc(pmu);
14809 		WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
14810 	}
14811 	pmu_bus_running = 1;
14812 	ret = 0;
14813 
14814 unlock:
14815 	mutex_unlock(&pmus_lock);
14816 
14817 	return ret;
14818 }
14819 device_initcall(perf_event_sysfs_init);
14820 
14821 #ifdef CONFIG_CGROUP_PERF
14822 static struct cgroup_subsys_state *
perf_cgroup_css_alloc(struct cgroup_subsys_state * parent_css)14823 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
14824 {
14825 	struct perf_cgroup *jc;
14826 
14827 	jc = kzalloc(sizeof(*jc), GFP_KERNEL);
14828 	if (!jc)
14829 		return ERR_PTR(-ENOMEM);
14830 
14831 	jc->info = alloc_percpu(struct perf_cgroup_info);
14832 	if (!jc->info) {
14833 		kfree(jc);
14834 		return ERR_PTR(-ENOMEM);
14835 	}
14836 
14837 	return &jc->css;
14838 }
14839 
perf_cgroup_css_free(struct cgroup_subsys_state * css)14840 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
14841 {
14842 	struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
14843 
14844 	free_percpu(jc->info);
14845 	kfree(jc);
14846 }
14847 
perf_cgroup_css_online(struct cgroup_subsys_state * css)14848 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
14849 {
14850 	perf_event_cgroup(css->cgroup);
14851 	return 0;
14852 }
14853 
__perf_cgroup_move(void * info)14854 static int __perf_cgroup_move(void *info)
14855 {
14856 	struct task_struct *task = info;
14857 
14858 	preempt_disable();
14859 	perf_cgroup_switch(task);
14860 	preempt_enable();
14861 
14862 	return 0;
14863 }
14864 
perf_cgroup_attach(struct cgroup_taskset * tset)14865 static void perf_cgroup_attach(struct cgroup_taskset *tset)
14866 {
14867 	struct task_struct *task;
14868 	struct cgroup_subsys_state *css;
14869 
14870 	cgroup_taskset_for_each(task, css, tset)
14871 		task_function_call(task, __perf_cgroup_move, task);
14872 }
14873 
14874 struct cgroup_subsys perf_event_cgrp_subsys = {
14875 	.css_alloc	= perf_cgroup_css_alloc,
14876 	.css_free	= perf_cgroup_css_free,
14877 	.css_online	= perf_cgroup_css_online,
14878 	.attach		= perf_cgroup_attach,
14879 	/*
14880 	 * Implicitly enable on dfl hierarchy so that perf events can
14881 	 * always be filtered by cgroup2 path as long as perf_event
14882 	 * controller is not mounted on a legacy hierarchy.
14883 	 */
14884 	.implicit_on_dfl = true,
14885 	.threaded	= true,
14886 };
14887 #endif /* CONFIG_CGROUP_PERF */
14888 
14889 DEFINE_STATIC_CALL_RET0(perf_snapshot_branch_stack, perf_snapshot_branch_stack_t);
14890