xref: /linux/kernel/events/core.c (revision 3d8d74100954a3b17e5c5e37adfe14e16b1db103)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Performance events core code:
4  *
5  *  Copyright (C) 2008 Linutronix GmbH, Thomas Gleixner <tglx@kernel.org>
6  *  Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
7  *  Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
8  *  Copyright  ©  2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
9  */
10 
11 #include <linux/fs.h>
12 #include <linux/mm.h>
13 #include <linux/cpu.h>
14 #include <linux/smp.h>
15 #include <linux/idr.h>
16 #include <linux/file.h>
17 #include <linux/poll.h>
18 #include <linux/slab.h>
19 #include <linux/hash.h>
20 #include <linux/tick.h>
21 #include <linux/sysfs.h>
22 #include <linux/dcache.h>
23 #include <linux/percpu.h>
24 #include <linux/ptrace.h>
25 #include <linux/reboot.h>
26 #include <linux/vmstat.h>
27 #include <linux/device.h>
28 #include <linux/export.h>
29 #include <linux/vmalloc.h>
30 #include <linux/hardirq.h>
31 #include <linux/hugetlb.h>
32 #include <linux/rculist.h>
33 #include <linux/uaccess.h>
34 #include <linux/syscalls.h>
35 #include <linux/anon_inodes.h>
36 #include <linux/kernel_stat.h>
37 #include <linux/cgroup.h>
38 #include <linux/perf_event.h>
39 #include <linux/trace_events.h>
40 #include <linux/hw_breakpoint.h>
41 #include <linux/mm_types.h>
42 #include <linux/module.h>
43 #include <linux/mman.h>
44 #include <linux/compat.h>
45 #include <linux/bpf.h>
46 #include <linux/filter.h>
47 #include <linux/namei.h>
48 #include <linux/parser.h>
49 #include <linux/sched/clock.h>
50 #include <linux/sched/mm.h>
51 #include <linux/proc_ns.h>
52 #include <linux/mount.h>
53 #include <linux/min_heap.h>
54 #include <linux/highmem.h>
55 #include <linux/pgtable.h>
56 #include <linux/buildid.h>
57 #include <linux/task_work.h>
58 #include <linux/percpu-rwsem.h>
59 #include <linux/unwind_deferred.h>
60 #include <linux/kvm_types.h>
61 #include <linux/seq_file.h>
62 
63 #include "internal.h"
64 
65 #include <asm/irq_regs.h>
66 
67 typedef int (*remote_function_f)(void *);
68 
69 struct remote_function_call {
70 	struct task_struct	*p;
71 	remote_function_f	func;
72 	void			*info;
73 	int			ret;
74 };
75 
76 static void remote_function(void *data)
77 {
78 	struct remote_function_call *tfc = data;
79 	struct task_struct *p = tfc->p;
80 
81 	if (p) {
82 		/* -EAGAIN */
83 		if (task_cpu(p) != smp_processor_id())
84 			return;
85 
86 		/*
87 		 * Now that we're on right CPU with IRQs disabled, we can test
88 		 * if we hit the right task without races.
89 		 */
90 
91 		tfc->ret = -ESRCH; /* No such (running) process */
92 		if (p != current)
93 			return;
94 	}
95 
96 	tfc->ret = tfc->func(tfc->info);
97 }
98 
99 /**
100  * task_function_call - call a function on the cpu on which a task runs
101  * @p:		the task to evaluate
102  * @func:	the function to be called
103  * @info:	the function call argument
104  *
105  * Calls the function @func when the task is currently running. This might
106  * be on the current CPU, which just calls the function directly.  This will
107  * retry due to any failures in smp_call_function_single(), such as if the
108  * task_cpu() goes offline concurrently.
109  *
110  * returns @func return value or -ESRCH or -ENXIO when the process isn't running
111  */
112 static int
113 task_function_call(struct task_struct *p, remote_function_f func, void *info)
114 {
115 	struct remote_function_call data = {
116 		.p	= p,
117 		.func	= func,
118 		.info	= info,
119 		.ret	= -EAGAIN,
120 	};
121 	int ret;
122 
123 	for (;;) {
124 		ret = smp_call_function_single(task_cpu(p), remote_function,
125 					       &data, 1);
126 		if (!ret)
127 			ret = data.ret;
128 
129 		if (ret != -EAGAIN)
130 			break;
131 
132 		cond_resched();
133 	}
134 
135 	return ret;
136 }
137 
138 /**
139  * cpu_function_call - call a function on the cpu
140  * @cpu:	target cpu to queue this function
141  * @func:	the function to be called
142  * @info:	the function call argument
143  *
144  * Calls the function @func on the remote cpu.
145  *
146  * returns: @func return value or -ENXIO when the cpu is offline
147  */
148 static int cpu_function_call(int cpu, remote_function_f func, void *info)
149 {
150 	struct remote_function_call data = {
151 		.p	= NULL,
152 		.func	= func,
153 		.info	= info,
154 		.ret	= -ENXIO, /* No such CPU */
155 	};
156 
157 	smp_call_function_single(cpu, remote_function, &data, 1);
158 
159 	return data.ret;
160 }
161 
162 enum event_type_t {
163 	EVENT_FLEXIBLE	= 0x01,
164 	EVENT_PINNED	= 0x02,
165 	EVENT_TIME	= 0x04,
166 	EVENT_FROZEN	= 0x08,
167 	/* see ctx_resched() for details */
168 	EVENT_CPU	= 0x10,
169 	EVENT_CGROUP	= 0x20,
170 
171 	/*
172 	 * EVENT_GUEST is set when scheduling in/out events between the host
173 	 * and a guest with a mediated vPMU.  Among other things, EVENT_GUEST
174 	 * is used:
175 	 *
176 	 * - In for_each_epc() to skip PMUs that don't support events in a
177 	 *   MEDIATED_VPMU guest, i.e. don't need to be context switched.
178 	 * - To indicate the start/end point of the events in a guest.  Guest
179 	 *   running time is deducted for host-only (exclude_guest) events.
180 	 */
181 	EVENT_GUEST	= 0x40,
182 	EVENT_FLAGS	= EVENT_CGROUP | EVENT_GUEST,
183 	/* compound helpers */
184 	EVENT_ALL         = EVENT_FLEXIBLE | EVENT_PINNED,
185 	EVENT_TIME_FROZEN = EVENT_TIME | EVENT_FROZEN,
186 };
187 
188 static inline void __perf_ctx_lock(struct perf_event_context *ctx)
189 {
190 	raw_spin_lock(&ctx->lock);
191 	WARN_ON_ONCE(ctx->is_active & EVENT_FROZEN);
192 }
193 
194 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
195 			  struct perf_event_context *ctx)
196 {
197 	__perf_ctx_lock(&cpuctx->ctx);
198 	if (ctx)
199 		__perf_ctx_lock(ctx);
200 }
201 
202 static inline void __perf_ctx_unlock(struct perf_event_context *ctx)
203 {
204 	/*
205 	 * If ctx_sched_in() didn't again set any ALL flags, clean up
206 	 * after ctx_sched_out() by clearing is_active.
207 	 */
208 	if (ctx->is_active & EVENT_FROZEN) {
209 		if (!(ctx->is_active & EVENT_ALL))
210 			ctx->is_active = 0;
211 		else
212 			ctx->is_active &= ~EVENT_FROZEN;
213 	}
214 	raw_spin_unlock(&ctx->lock);
215 }
216 
217 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
218 			    struct perf_event_context *ctx)
219 {
220 	if (ctx)
221 		__perf_ctx_unlock(ctx);
222 	__perf_ctx_unlock(&cpuctx->ctx);
223 }
224 
225 typedef struct {
226 	struct perf_cpu_context *cpuctx;
227 	struct perf_event_context *ctx;
228 } class_perf_ctx_lock_t;
229 
230 static inline void class_perf_ctx_lock_destructor(class_perf_ctx_lock_t *_T)
231 { perf_ctx_unlock(_T->cpuctx, _T->ctx); }
232 
233 static inline class_perf_ctx_lock_t
234 class_perf_ctx_lock_constructor(struct perf_cpu_context *cpuctx,
235 				struct perf_event_context *ctx)
236 { perf_ctx_lock(cpuctx, ctx); return (class_perf_ctx_lock_t){ cpuctx, ctx }; }
237 
238 #define TASK_TOMBSTONE ((void *)-1L)
239 
240 static bool is_kernel_event(struct perf_event *event)
241 {
242 	return READ_ONCE(event->owner) == TASK_TOMBSTONE;
243 }
244 
245 static DEFINE_PER_CPU(struct perf_cpu_context, perf_cpu_context);
246 
247 struct perf_event_context *perf_cpu_task_ctx(void)
248 {
249 	lockdep_assert_irqs_disabled();
250 	return this_cpu_ptr(&perf_cpu_context)->task_ctx;
251 }
252 
253 /*
254  * On task ctx scheduling...
255  *
256  * When !ctx->nr_events a task context will not be scheduled. This means
257  * we can disable the scheduler hooks (for performance) without leaving
258  * pending task ctx state.
259  *
260  * This however results in two special cases:
261  *
262  *  - removing the last event from a task ctx; this is relatively straight
263  *    forward and is done in __perf_remove_from_context.
264  *
265  *  - adding the first event to a task ctx; this is tricky because we cannot
266  *    rely on ctx->is_active and therefore cannot use event_function_call().
267  *    See perf_install_in_context().
268  *
269  * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
270  */
271 
272 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
273 			struct perf_event_context *, void *);
274 
275 struct event_function_struct {
276 	struct perf_event *event;
277 	event_f func;
278 	void *data;
279 };
280 
281 static int event_function(void *info)
282 {
283 	struct event_function_struct *efs = info;
284 	struct perf_event *event = efs->event;
285 	struct perf_event_context *ctx = event->ctx;
286 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
287 	struct perf_event_context *task_ctx = cpuctx->task_ctx;
288 	int ret = 0;
289 
290 	lockdep_assert_irqs_disabled();
291 
292 	perf_ctx_lock(cpuctx, task_ctx);
293 	/*
294 	 * Since we do the IPI call without holding ctx->lock things can have
295 	 * changed, double check we hit the task we set out to hit.
296 	 */
297 	if (ctx->task) {
298 		if (ctx->task != current) {
299 			ret = -ESRCH;
300 			goto unlock;
301 		}
302 
303 		/*
304 		 * We only use event_function_call() on established contexts,
305 		 * and event_function() is only ever called when active (or
306 		 * rather, we'll have bailed in task_function_call() or the
307 		 * above ctx->task != current test), therefore we must have
308 		 * ctx->is_active here.
309 		 */
310 		WARN_ON_ONCE(!ctx->is_active);
311 		/*
312 		 * And since we have ctx->is_active, cpuctx->task_ctx must
313 		 * match.
314 		 */
315 		WARN_ON_ONCE(task_ctx != ctx);
316 	} else {
317 		WARN_ON_ONCE(&cpuctx->ctx != ctx);
318 	}
319 
320 	efs->func(event, cpuctx, ctx, efs->data);
321 unlock:
322 	perf_ctx_unlock(cpuctx, task_ctx);
323 
324 	return ret;
325 }
326 
327 static void event_function_call(struct perf_event *event, event_f func, void *data)
328 {
329 	struct perf_event_context *ctx = event->ctx;
330 	struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
331 	struct perf_cpu_context *cpuctx;
332 	struct event_function_struct efs = {
333 		.event = event,
334 		.func = func,
335 		.data = data,
336 	};
337 
338 	if (!event->parent) {
339 		/*
340 		 * If this is a !child event, we must hold ctx::mutex to
341 		 * stabilize the event->ctx relation. See
342 		 * perf_event_ctx_lock().
343 		 */
344 		lockdep_assert_held(&ctx->mutex);
345 	}
346 
347 	if (!task) {
348 		cpu_function_call(event->cpu, event_function, &efs);
349 		return;
350 	}
351 
352 	if (task == TASK_TOMBSTONE)
353 		return;
354 
355 again:
356 	if (!task_function_call(task, event_function, &efs))
357 		return;
358 
359 	local_irq_disable();
360 	cpuctx = this_cpu_ptr(&perf_cpu_context);
361 	perf_ctx_lock(cpuctx, ctx);
362 	/*
363 	 * Reload the task pointer, it might have been changed by
364 	 * a concurrent perf_event_context_sched_out().
365 	 */
366 	task = ctx->task;
367 	if (task == TASK_TOMBSTONE)
368 		goto unlock;
369 	if (ctx->is_active) {
370 		perf_ctx_unlock(cpuctx, ctx);
371 		local_irq_enable();
372 		goto again;
373 	}
374 	func(event, NULL, ctx, data);
375 unlock:
376 	perf_ctx_unlock(cpuctx, ctx);
377 	local_irq_enable();
378 }
379 
380 /*
381  * Similar to event_function_call() + event_function(), but hard assumes IRQs
382  * are already disabled and we're on the right CPU.
383  */
384 static void event_function_local(struct perf_event *event, event_f func, void *data)
385 {
386 	struct perf_event_context *ctx = event->ctx;
387 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
388 	struct task_struct *task = READ_ONCE(ctx->task);
389 	struct perf_event_context *task_ctx = NULL;
390 
391 	lockdep_assert_irqs_disabled();
392 
393 	if (task) {
394 		if (task == TASK_TOMBSTONE)
395 			return;
396 
397 		task_ctx = ctx;
398 	}
399 
400 	perf_ctx_lock(cpuctx, task_ctx);
401 
402 	task = ctx->task;
403 	if (task == TASK_TOMBSTONE)
404 		goto unlock;
405 
406 	if (task) {
407 		/*
408 		 * We must be either inactive or active and the right task,
409 		 * otherwise we're screwed, since we cannot IPI to somewhere
410 		 * else.
411 		 */
412 		if (ctx->is_active) {
413 			if (WARN_ON_ONCE(task != current))
414 				goto unlock;
415 
416 			if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
417 				goto unlock;
418 		}
419 	} else {
420 		WARN_ON_ONCE(&cpuctx->ctx != ctx);
421 	}
422 
423 	func(event, cpuctx, ctx, data);
424 unlock:
425 	perf_ctx_unlock(cpuctx, task_ctx);
426 }
427 
428 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
429 		       PERF_FLAG_FD_OUTPUT  |\
430 		       PERF_FLAG_PID_CGROUP |\
431 		       PERF_FLAG_FD_CLOEXEC)
432 
433 /*
434  * branch priv levels that need permission checks
435  */
436 #define PERF_SAMPLE_BRANCH_PERM_PLM \
437 	(PERF_SAMPLE_BRANCH_KERNEL |\
438 	 PERF_SAMPLE_BRANCH_HV)
439 
440 /*
441  * perf_sched_events : >0 events exist
442  */
443 
444 static void perf_sched_delayed(struct work_struct *work);
445 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
446 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
447 static DEFINE_MUTEX(perf_sched_mutex);
448 static atomic_t perf_sched_count;
449 
450 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
451 
452 static atomic_t nr_mmap_events __read_mostly;
453 static atomic_t nr_comm_events __read_mostly;
454 static atomic_t nr_namespaces_events __read_mostly;
455 static atomic_t nr_task_events __read_mostly;
456 static atomic_t nr_freq_events __read_mostly;
457 static atomic_t nr_switch_events __read_mostly;
458 static atomic_t nr_ksymbol_events __read_mostly;
459 static atomic_t nr_bpf_events __read_mostly;
460 static atomic_t nr_cgroup_events __read_mostly;
461 static atomic_t nr_text_poke_events __read_mostly;
462 static atomic_t nr_build_id_events __read_mostly;
463 
464 static LIST_HEAD(pmus);
465 static DEFINE_MUTEX(pmus_lock);
466 static struct srcu_struct pmus_srcu;
467 static cpumask_var_t perf_online_mask;
468 static cpumask_var_t perf_online_core_mask;
469 static cpumask_var_t perf_online_die_mask;
470 static cpumask_var_t perf_online_cluster_mask;
471 static cpumask_var_t perf_online_pkg_mask;
472 static cpumask_var_t perf_online_sys_mask;
473 static struct kmem_cache *perf_event_cache;
474 
475 #ifdef CONFIG_PERF_GUEST_MEDIATED_PMU
476 static DEFINE_PER_CPU(bool, guest_ctx_loaded);
477 
478 static __always_inline bool is_guest_mediated_pmu_loaded(void)
479 {
480 	return __this_cpu_read(guest_ctx_loaded);
481 }
482 #else
483 static __always_inline bool is_guest_mediated_pmu_loaded(void)
484 {
485 	return false;
486 }
487 #endif
488 
489 /*
490  * perf event paranoia level:
491  *  -1 - not paranoid at all
492  *   0 - disallow raw tracepoint access for unpriv
493  *   1 - disallow cpu events for unpriv
494  *   2 - disallow kernel profiling for unpriv
495  */
496 int sysctl_perf_event_paranoid __read_mostly = 2;
497 
498 /* Minimum for 512 kiB + 1 user control page. 'free' kiB per user. */
499 static int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024);
500 
501 /*
502  * max perf event sample rate
503  */
504 #define DEFAULT_MAX_SAMPLE_RATE		100000
505 #define DEFAULT_SAMPLE_PERIOD_NS	(NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
506 #define DEFAULT_CPU_TIME_MAX_PERCENT	25
507 
508 int sysctl_perf_event_sample_rate __read_mostly	= DEFAULT_MAX_SAMPLE_RATE;
509 static int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
510 
511 static int max_samples_per_tick __read_mostly	= DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
512 static int perf_sample_period_ns __read_mostly	= DEFAULT_SAMPLE_PERIOD_NS;
513 
514 static int perf_sample_allowed_ns __read_mostly =
515 	DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
516 
517 static void update_perf_cpu_limits(void)
518 {
519 	u64 tmp = perf_sample_period_ns;
520 
521 	tmp *= sysctl_perf_cpu_time_max_percent;
522 	tmp = div_u64(tmp, 100);
523 	if (!tmp)
524 		tmp = 1;
525 
526 	WRITE_ONCE(perf_sample_allowed_ns, tmp);
527 }
528 
529 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc);
530 
531 static int perf_event_max_sample_rate_handler(const struct ctl_table *table, int write,
532 				       void *buffer, size_t *lenp, loff_t *ppos)
533 {
534 	int ret;
535 	int perf_cpu = sysctl_perf_cpu_time_max_percent;
536 	/*
537 	 * If throttling is disabled don't allow the write:
538 	 */
539 	if (write && (perf_cpu == 100 || perf_cpu == 0))
540 		return -EINVAL;
541 
542 	ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
543 	if (ret || !write)
544 		return ret;
545 
546 	max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
547 	perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
548 	update_perf_cpu_limits();
549 
550 	return 0;
551 }
552 
553 static int perf_cpu_time_max_percent_handler(const struct ctl_table *table, int write,
554 		void *buffer, size_t *lenp, loff_t *ppos)
555 {
556 	int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
557 
558 	if (ret || !write)
559 		return ret;
560 
561 	if (sysctl_perf_cpu_time_max_percent == 100 ||
562 	    sysctl_perf_cpu_time_max_percent == 0) {
563 		printk(KERN_WARNING
564 		       "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
565 		WRITE_ONCE(perf_sample_allowed_ns, 0);
566 	} else {
567 		update_perf_cpu_limits();
568 	}
569 
570 	return 0;
571 }
572 
573 static const struct ctl_table events_core_sysctl_table[] = {
574 	/*
575 	 * User-space relies on this file as a feature check for
576 	 * perf_events being enabled. It's an ABI, do not remove!
577 	 */
578 	{
579 		.procname	= "perf_event_paranoid",
580 		.data		= &sysctl_perf_event_paranoid,
581 		.maxlen		= sizeof(sysctl_perf_event_paranoid),
582 		.mode		= 0644,
583 		.proc_handler	= proc_dointvec,
584 	},
585 	{
586 		.procname	= "perf_event_mlock_kb",
587 		.data		= &sysctl_perf_event_mlock,
588 		.maxlen		= sizeof(sysctl_perf_event_mlock),
589 		.mode		= 0644,
590 		.proc_handler	= proc_dointvec,
591 	},
592 	{
593 		.procname	= "perf_event_max_sample_rate",
594 		.data		= &sysctl_perf_event_sample_rate,
595 		.maxlen		= sizeof(sysctl_perf_event_sample_rate),
596 		.mode		= 0644,
597 		.proc_handler	= perf_event_max_sample_rate_handler,
598 		.extra1		= SYSCTL_ONE,
599 	},
600 	{
601 		.procname	= "perf_cpu_time_max_percent",
602 		.data		= &sysctl_perf_cpu_time_max_percent,
603 		.maxlen		= sizeof(sysctl_perf_cpu_time_max_percent),
604 		.mode		= 0644,
605 		.proc_handler	= perf_cpu_time_max_percent_handler,
606 		.extra1		= SYSCTL_ZERO,
607 		.extra2		= SYSCTL_ONE_HUNDRED,
608 	},
609 };
610 
611 static int __init init_events_core_sysctls(void)
612 {
613 	register_sysctl_init("kernel", events_core_sysctl_table);
614 	return 0;
615 }
616 core_initcall(init_events_core_sysctls);
617 
618 
619 /*
620  * perf samples are done in some very critical code paths (NMIs).
621  * If they take too much CPU time, the system can lock up and not
622  * get any real work done.  This will drop the sample rate when
623  * we detect that events are taking too long.
624  */
625 #define NR_ACCUMULATED_SAMPLES 128
626 static DEFINE_PER_CPU(u64, running_sample_length);
627 
628 static u64 __report_avg;
629 static u64 __report_allowed;
630 
631 static void perf_duration_warn(struct irq_work *w)
632 {
633 	printk_ratelimited(KERN_INFO
634 		"perf: interrupt took too long (%lld > %lld), lowering "
635 		"kernel.perf_event_max_sample_rate to %d\n",
636 		__report_avg, __report_allowed,
637 		sysctl_perf_event_sample_rate);
638 }
639 
640 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
641 
642 void perf_sample_event_took(u64 sample_len_ns)
643 {
644 	u64 max_len = READ_ONCE(perf_sample_allowed_ns);
645 	u64 running_len;
646 	u64 avg_len;
647 	u32 max;
648 
649 	if (max_len == 0)
650 		return;
651 
652 	/* Decay the counter by 1 average sample. */
653 	running_len = __this_cpu_read(running_sample_length);
654 	running_len -= running_len/NR_ACCUMULATED_SAMPLES;
655 	running_len += sample_len_ns;
656 	__this_cpu_write(running_sample_length, running_len);
657 
658 	/*
659 	 * Note: this will be biased artificially low until we have
660 	 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
661 	 * from having to maintain a count.
662 	 */
663 	avg_len = running_len/NR_ACCUMULATED_SAMPLES;
664 	if (avg_len <= max_len)
665 		return;
666 
667 	__report_avg = avg_len;
668 	__report_allowed = max_len;
669 
670 	/*
671 	 * Compute a throttle threshold 25% below the current duration.
672 	 */
673 	avg_len += avg_len / 4;
674 	max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
675 	if (avg_len < max)
676 		max /= (u32)avg_len;
677 	else
678 		max = 1;
679 
680 	WRITE_ONCE(perf_sample_allowed_ns, avg_len);
681 	WRITE_ONCE(max_samples_per_tick, max);
682 
683 	sysctl_perf_event_sample_rate = max * HZ;
684 	perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
685 
686 	if (!irq_work_queue(&perf_duration_work)) {
687 		early_printk("perf: interrupt took too long (%lld > %lld), lowering "
688 			     "kernel.perf_event_max_sample_rate to %d\n",
689 			     __report_avg, __report_allowed,
690 			     sysctl_perf_event_sample_rate);
691 	}
692 }
693 
694 static atomic64_t perf_event_id;
695 
696 static void update_context_time(struct perf_event_context *ctx);
697 static u64 perf_event_time(struct perf_event *event);
698 
699 void __weak perf_event_print_debug(void)	{ }
700 
701 static inline u64 perf_clock(void)
702 {
703 	return local_clock();
704 }
705 
706 static inline u64 perf_event_clock(struct perf_event *event)
707 {
708 	return event->clock();
709 }
710 
711 /*
712  * State based event timekeeping...
713  *
714  * The basic idea is to use event->state to determine which (if any) time
715  * fields to increment with the current delta. This means we only need to
716  * update timestamps when we change state or when they are explicitly requested
717  * (read).
718  *
719  * Event groups make things a little more complicated, but not terribly so. The
720  * rules for a group are that if the group leader is OFF the entire group is
721  * OFF, irrespective of what the group member states are. This results in
722  * __perf_effective_state().
723  *
724  * A further ramification is that when a group leader flips between OFF and
725  * !OFF, we need to update all group member times.
726  *
727  *
728  * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
729  * need to make sure the relevant context time is updated before we try and
730  * update our timestamps.
731  */
732 
733 static __always_inline enum perf_event_state
734 __perf_effective_state(struct perf_event *event)
735 {
736 	struct perf_event *leader = event->group_leader;
737 
738 	if (leader->state <= PERF_EVENT_STATE_OFF)
739 		return leader->state;
740 
741 	return event->state;
742 }
743 
744 static __always_inline void
745 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
746 {
747 	enum perf_event_state state = __perf_effective_state(event);
748 	u64 delta = now - event->tstamp;
749 
750 	*enabled = event->total_time_enabled;
751 	if (state >= PERF_EVENT_STATE_INACTIVE)
752 		*enabled += delta;
753 
754 	*running = event->total_time_running;
755 	if (state >= PERF_EVENT_STATE_ACTIVE)
756 		*running += delta;
757 }
758 
759 static void perf_event_update_time(struct perf_event *event)
760 {
761 	u64 now = perf_event_time(event);
762 
763 	__perf_update_times(event, now, &event->total_time_enabled,
764 					&event->total_time_running);
765 	event->tstamp = now;
766 }
767 
768 static void perf_event_update_sibling_time(struct perf_event *leader)
769 {
770 	struct perf_event *sibling;
771 
772 	for_each_sibling_event(sibling, leader)
773 		perf_event_update_time(sibling);
774 }
775 
776 static void
777 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
778 {
779 	if (event->state == state)
780 		return;
781 
782 	perf_event_update_time(event);
783 	/*
784 	 * If a group leader gets enabled/disabled all its siblings
785 	 * are affected too.
786 	 */
787 	if ((event->state < 0) ^ (state < 0))
788 		perf_event_update_sibling_time(event);
789 
790 	WRITE_ONCE(event->state, state);
791 }
792 
793 /*
794  * UP store-release, load-acquire
795  */
796 
797 #define __store_release(ptr, val)					\
798 do {									\
799 	barrier();							\
800 	WRITE_ONCE(*(ptr), (val));					\
801 } while (0)
802 
803 #define __load_acquire(ptr)						\
804 ({									\
805 	__unqual_scalar_typeof(*(ptr)) ___p = READ_ONCE(*(ptr));	\
806 	barrier();							\
807 	___p;								\
808 })
809 
810 static bool perf_skip_pmu_ctx(struct perf_event_pmu_context *pmu_ctx,
811 			      enum event_type_t event_type)
812 {
813 	if ((event_type & EVENT_CGROUP) && !pmu_ctx->nr_cgroups)
814 		return true;
815 	if ((event_type & EVENT_GUEST) &&
816 	    !(pmu_ctx->pmu->capabilities & PERF_PMU_CAP_MEDIATED_VPMU))
817 		return true;
818 	return false;
819 }
820 
821 #define for_each_epc(_epc, _ctx, _pmu, _event_type)			\
822 	list_for_each_entry(_epc, &((_ctx)->pmu_ctx_list), pmu_ctx_entry) \
823 		if (perf_skip_pmu_ctx(_epc, _event_type))		\
824 			continue;					\
825 		else if (_pmu && _epc->pmu != _pmu)			\
826 			continue;					\
827 		else
828 
829 static void perf_ctx_disable(struct perf_event_context *ctx,
830 			     enum event_type_t event_type)
831 {
832 	struct perf_event_pmu_context *pmu_ctx;
833 
834 	for_each_epc(pmu_ctx, ctx, NULL, event_type)
835 		perf_pmu_disable(pmu_ctx->pmu);
836 }
837 
838 static void perf_ctx_enable(struct perf_event_context *ctx,
839 			    enum event_type_t event_type)
840 {
841 	struct perf_event_pmu_context *pmu_ctx;
842 
843 	for_each_epc(pmu_ctx, ctx, NULL, event_type)
844 		perf_pmu_enable(pmu_ctx->pmu);
845 }
846 
847 static void ctx_sched_out(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type);
848 static void ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type);
849 
850 static inline void update_perf_time_ctx(struct perf_time_ctx *time, u64 now, bool adv)
851 {
852 	if (adv)
853 		time->time += now - time->stamp;
854 	time->stamp = now;
855 
856 	/*
857 	 * The above: time' = time + (now - timestamp), can be re-arranged
858 	 * into: time` = now + (time - timestamp), which gives a single value
859 	 * offset to compute future time without locks on.
860 	 *
861 	 * See perf_event_time_now(), which can be used from NMI context where
862 	 * it's (obviously) not possible to acquire ctx->lock in order to read
863 	 * both the above values in a consistent manner.
864 	 */
865 	WRITE_ONCE(time->offset, time->time - time->stamp);
866 }
867 
868 static_assert(offsetof(struct perf_event_context, timeguest) -
869 	      offsetof(struct perf_event_context, time) ==
870 	      sizeof(struct perf_time_ctx));
871 
872 #define T_TOTAL		0
873 #define T_GUEST		1
874 
875 static inline u64 __perf_event_time_ctx(struct perf_event *event,
876 					struct perf_time_ctx *times)
877 {
878 	u64 time = times[T_TOTAL].time;
879 
880 	if (event->attr.exclude_guest)
881 		time -= times[T_GUEST].time;
882 
883 	return time;
884 }
885 
886 static inline u64 __perf_event_time_ctx_now(struct perf_event *event,
887 					    struct perf_time_ctx *times,
888 					    u64 now)
889 {
890 	if (is_guest_mediated_pmu_loaded() && event->attr.exclude_guest) {
891 		/*
892 		 * (now + times[total].offset) - (now + times[guest].offset) :=
893 		 * times[total].offset - times[guest].offset
894 		 */
895 		return READ_ONCE(times[T_TOTAL].offset) - READ_ONCE(times[T_GUEST].offset);
896 	}
897 
898 	return now + READ_ONCE(times[T_TOTAL].offset);
899 }
900 
901 #ifdef CONFIG_CGROUP_PERF
902 
903 static inline bool
904 perf_cgroup_match(struct perf_event *event)
905 {
906 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
907 
908 	/* @event doesn't care about cgroup */
909 	if (!event->cgrp)
910 		return true;
911 
912 	/* wants specific cgroup scope but @cpuctx isn't associated with any */
913 	if (!cpuctx->cgrp)
914 		return false;
915 
916 	/*
917 	 * Cgroup scoping is recursive.  An event enabled for a cgroup is
918 	 * also enabled for all its descendant cgroups.  If @cpuctx's
919 	 * cgroup is a descendant of @event's (the test covers identity
920 	 * case), it's a match.
921 	 */
922 	return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
923 				    event->cgrp->css.cgroup);
924 }
925 
926 static inline void perf_detach_cgroup(struct perf_event *event)
927 {
928 	css_put(&event->cgrp->css);
929 	event->cgrp = NULL;
930 }
931 
932 static inline int is_cgroup_event(struct perf_event *event)
933 {
934 	return event->cgrp != NULL;
935 }
936 
937 static_assert(offsetof(struct perf_cgroup_info, timeguest) -
938 	      offsetof(struct perf_cgroup_info, time) ==
939 	      sizeof(struct perf_time_ctx));
940 
941 static inline u64 perf_cgroup_event_time(struct perf_event *event)
942 {
943 	struct perf_cgroup_info *t;
944 
945 	t = per_cpu_ptr(event->cgrp->info, event->cpu);
946 	return __perf_event_time_ctx(event, &t->time);
947 }
948 
949 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
950 {
951 	struct perf_cgroup_info *t;
952 
953 	t = per_cpu_ptr(event->cgrp->info, event->cpu);
954 	if (!__load_acquire(&t->active))
955 		return __perf_event_time_ctx(event, &t->time);
956 
957 	return __perf_event_time_ctx_now(event, &t->time, now);
958 }
959 
960 static inline void __update_cgrp_guest_time(struct perf_cgroup_info *info, u64 now, bool adv)
961 {
962 	update_perf_time_ctx(&info->timeguest, now, adv);
963 }
964 
965 static inline void update_cgrp_time(struct perf_cgroup_info *info, u64 now)
966 {
967 	update_perf_time_ctx(&info->time, now, true);
968 	if (is_guest_mediated_pmu_loaded())
969 		__update_cgrp_guest_time(info, now, true);
970 }
971 
972 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx, bool final)
973 {
974 	struct perf_cgroup *cgrp = cpuctx->cgrp;
975 	struct cgroup_subsys_state *css;
976 	struct perf_cgroup_info *info;
977 
978 	if (cgrp) {
979 		u64 now = perf_clock();
980 
981 		for (css = &cgrp->css; css; css = css->parent) {
982 			cgrp = container_of(css, struct perf_cgroup, css);
983 			info = this_cpu_ptr(cgrp->info);
984 
985 			update_cgrp_time(info, now);
986 			if (final)
987 				__store_release(&info->active, 0);
988 		}
989 	}
990 }
991 
992 static inline void update_cgrp_time_from_event(struct perf_event *event)
993 {
994 	struct perf_cgroup_info *info;
995 
996 	/*
997 	 * ensure we access cgroup data only when needed and
998 	 * when we know the cgroup is pinned (css_get)
999 	 */
1000 	if (!is_cgroup_event(event))
1001 		return;
1002 
1003 	info = this_cpu_ptr(event->cgrp->info);
1004 	/*
1005 	 * Do not update time when cgroup is not active
1006 	 */
1007 	if (info->active)
1008 		update_cgrp_time(info, perf_clock());
1009 }
1010 
1011 static inline void
1012 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx, bool guest)
1013 {
1014 	struct perf_event_context *ctx = &cpuctx->ctx;
1015 	struct perf_cgroup *cgrp = cpuctx->cgrp;
1016 	struct perf_cgroup_info *info;
1017 	struct cgroup_subsys_state *css;
1018 
1019 	/*
1020 	 * ctx->lock held by caller
1021 	 * ensure we do not access cgroup data
1022 	 * unless we have the cgroup pinned (css_get)
1023 	 */
1024 	if (!cgrp)
1025 		return;
1026 
1027 	WARN_ON_ONCE(!ctx->nr_cgroups);
1028 
1029 	for (css = &cgrp->css; css; css = css->parent) {
1030 		cgrp = container_of(css, struct perf_cgroup, css);
1031 		info = this_cpu_ptr(cgrp->info);
1032 		if (guest) {
1033 			__update_cgrp_guest_time(info, ctx->time.stamp, false);
1034 		} else {
1035 			update_perf_time_ctx(&info->time, ctx->time.stamp, false);
1036 			__store_release(&info->active, 1);
1037 		}
1038 	}
1039 }
1040 
1041 /*
1042  * reschedule events based on the cgroup constraint of task.
1043  */
1044 static void perf_cgroup_switch(struct task_struct *task)
1045 {
1046 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
1047 	struct perf_cgroup *cgrp;
1048 
1049 	/*
1050 	 * cpuctx->cgrp is set when the first cgroup event enabled,
1051 	 * and is cleared when the last cgroup event disabled.
1052 	 */
1053 	if (READ_ONCE(cpuctx->cgrp) == NULL)
1054 		return;
1055 
1056 	cgrp = perf_cgroup_from_task(task, NULL);
1057 	if (READ_ONCE(cpuctx->cgrp) == cgrp)
1058 		return;
1059 
1060 	guard(perf_ctx_lock)(cpuctx, cpuctx->task_ctx);
1061 	/*
1062 	 * Re-check, could've raced vs perf_remove_from_context().
1063 	 */
1064 	if (READ_ONCE(cpuctx->cgrp) == NULL)
1065 		return;
1066 
1067 	WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
1068 	perf_ctx_disable(&cpuctx->ctx, EVENT_CGROUP);
1069 
1070 	ctx_sched_out(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP);
1071 	/*
1072 	 * must not be done before ctxswout due
1073 	 * to update_cgrp_time_from_cpuctx() in
1074 	 * ctx_sched_out()
1075 	 */
1076 	cpuctx->cgrp = cgrp;
1077 	/*
1078 	 * set cgrp before ctxsw in to allow
1079 	 * perf_cgroup_set_timestamp() in ctx_sched_in()
1080 	 * to not have to pass task around
1081 	 */
1082 	ctx_sched_in(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP);
1083 
1084 	perf_ctx_enable(&cpuctx->ctx, EVENT_CGROUP);
1085 }
1086 
1087 static int perf_cgroup_ensure_storage(struct perf_event *event,
1088 				struct cgroup_subsys_state *css)
1089 {
1090 	struct perf_cpu_context *cpuctx;
1091 	struct perf_event **storage;
1092 	int cpu, heap_size, ret = 0;
1093 
1094 	/*
1095 	 * Allow storage to have sufficient space for an iterator for each
1096 	 * possibly nested cgroup plus an iterator for events with no cgroup.
1097 	 */
1098 	for (heap_size = 1; css; css = css->parent)
1099 		heap_size++;
1100 
1101 	for_each_possible_cpu(cpu) {
1102 		cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
1103 		if (heap_size <= cpuctx->heap_size)
1104 			continue;
1105 
1106 		storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
1107 				       GFP_KERNEL, cpu_to_node(cpu));
1108 		if (!storage) {
1109 			ret = -ENOMEM;
1110 			break;
1111 		}
1112 
1113 		raw_spin_lock_irq(&cpuctx->ctx.lock);
1114 		if (cpuctx->heap_size < heap_size) {
1115 			swap(cpuctx->heap, storage);
1116 			if (storage == cpuctx->heap_default)
1117 				storage = NULL;
1118 			cpuctx->heap_size = heap_size;
1119 		}
1120 		raw_spin_unlock_irq(&cpuctx->ctx.lock);
1121 
1122 		kfree(storage);
1123 	}
1124 
1125 	return ret;
1126 }
1127 
1128 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
1129 				      struct perf_event_attr *attr,
1130 				      struct perf_event *group_leader)
1131 {
1132 	struct perf_cgroup *cgrp;
1133 	struct cgroup_subsys_state *css;
1134 	CLASS(fd, f)(fd);
1135 	int ret = 0;
1136 
1137 	if (fd_empty(f))
1138 		return -EBADF;
1139 
1140 	css = css_tryget_online_from_dir(fd_file(f)->f_path.dentry,
1141 					 &perf_event_cgrp_subsys);
1142 	if (IS_ERR(css))
1143 		return PTR_ERR(css);
1144 
1145 	ret = perf_cgroup_ensure_storage(event, css);
1146 	if (ret)
1147 		return ret;
1148 
1149 	cgrp = container_of(css, struct perf_cgroup, css);
1150 	event->cgrp = cgrp;
1151 
1152 	/*
1153 	 * all events in a group must monitor
1154 	 * the same cgroup because a task belongs
1155 	 * to only one perf cgroup at a time
1156 	 */
1157 	if (group_leader && group_leader->cgrp != cgrp) {
1158 		perf_detach_cgroup(event);
1159 		ret = -EINVAL;
1160 	}
1161 	return ret;
1162 }
1163 
1164 static inline void
1165 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1166 {
1167 	struct perf_cpu_context *cpuctx;
1168 
1169 	if (!is_cgroup_event(event))
1170 		return;
1171 
1172 	event->pmu_ctx->nr_cgroups++;
1173 
1174 	/*
1175 	 * Because cgroup events are always per-cpu events,
1176 	 * @ctx == &cpuctx->ctx.
1177 	 */
1178 	cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1179 
1180 	if (ctx->nr_cgroups++)
1181 		return;
1182 
1183 	cpuctx->cgrp = perf_cgroup_from_task(current, ctx);
1184 }
1185 
1186 static inline void
1187 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1188 {
1189 	struct perf_cpu_context *cpuctx;
1190 
1191 	if (!is_cgroup_event(event))
1192 		return;
1193 
1194 	event->pmu_ctx->nr_cgroups--;
1195 
1196 	/*
1197 	 * Because cgroup events are always per-cpu events,
1198 	 * @ctx == &cpuctx->ctx.
1199 	 */
1200 	cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1201 
1202 	if (--ctx->nr_cgroups)
1203 		return;
1204 
1205 	cpuctx->cgrp = NULL;
1206 }
1207 
1208 #else /* !CONFIG_CGROUP_PERF */
1209 
1210 static inline bool
1211 perf_cgroup_match(struct perf_event *event)
1212 {
1213 	return true;
1214 }
1215 
1216 static inline void perf_detach_cgroup(struct perf_event *event)
1217 {}
1218 
1219 static inline int is_cgroup_event(struct perf_event *event)
1220 {
1221 	return 0;
1222 }
1223 
1224 static inline void update_cgrp_time_from_event(struct perf_event *event)
1225 {
1226 }
1227 
1228 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx,
1229 						bool final)
1230 {
1231 }
1232 
1233 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1234 				      struct perf_event_attr *attr,
1235 				      struct perf_event *group_leader)
1236 {
1237 	return -EINVAL;
1238 }
1239 
1240 static inline void
1241 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx, bool guest)
1242 {
1243 }
1244 
1245 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1246 {
1247 	return 0;
1248 }
1249 
1250 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
1251 {
1252 	return 0;
1253 }
1254 
1255 static inline void
1256 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
1257 {
1258 }
1259 
1260 static inline void
1261 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1262 {
1263 }
1264 
1265 static void perf_cgroup_switch(struct task_struct *task)
1266 {
1267 }
1268 #endif
1269 
1270 /*
1271  * set default to be dependent on timer tick just
1272  * like original code
1273  */
1274 #define PERF_CPU_HRTIMER (1000 / HZ)
1275 /*
1276  * function must be called with interrupts disabled
1277  */
1278 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1279 {
1280 	struct perf_cpu_pmu_context *cpc;
1281 	bool rotations;
1282 
1283 	lockdep_assert_irqs_disabled();
1284 
1285 	cpc = container_of(hr, struct perf_cpu_pmu_context, hrtimer);
1286 	rotations = perf_rotate_context(cpc);
1287 
1288 	raw_spin_lock(&cpc->hrtimer_lock);
1289 	if (rotations)
1290 		hrtimer_forward_now(hr, cpc->hrtimer_interval);
1291 	else
1292 		cpc->hrtimer_active = 0;
1293 	raw_spin_unlock(&cpc->hrtimer_lock);
1294 
1295 	return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1296 }
1297 
1298 static void __perf_mux_hrtimer_init(struct perf_cpu_pmu_context *cpc, int cpu)
1299 {
1300 	struct hrtimer *timer = &cpc->hrtimer;
1301 	struct pmu *pmu = cpc->epc.pmu;
1302 	u64 interval;
1303 
1304 	/*
1305 	 * check default is sane, if not set then force to
1306 	 * default interval (1/tick)
1307 	 */
1308 	interval = pmu->hrtimer_interval_ms;
1309 	if (interval < 1)
1310 		interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1311 
1312 	cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1313 
1314 	raw_spin_lock_init(&cpc->hrtimer_lock);
1315 	hrtimer_setup(timer, perf_mux_hrtimer_handler, CLOCK_MONOTONIC,
1316 		      HRTIMER_MODE_ABS_PINNED_HARD);
1317 }
1318 
1319 static int perf_mux_hrtimer_restart(struct perf_cpu_pmu_context *cpc)
1320 {
1321 	struct hrtimer *timer = &cpc->hrtimer;
1322 	unsigned long flags;
1323 
1324 	raw_spin_lock_irqsave(&cpc->hrtimer_lock, flags);
1325 	if (!cpc->hrtimer_active) {
1326 		cpc->hrtimer_active = 1;
1327 		hrtimer_forward_now(timer, cpc->hrtimer_interval);
1328 		hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1329 	}
1330 	raw_spin_unlock_irqrestore(&cpc->hrtimer_lock, flags);
1331 
1332 	return 0;
1333 }
1334 
1335 static int perf_mux_hrtimer_restart_ipi(void *arg)
1336 {
1337 	return perf_mux_hrtimer_restart(arg);
1338 }
1339 
1340 static __always_inline struct perf_cpu_pmu_context *this_cpc(struct pmu *pmu)
1341 {
1342 	return *this_cpu_ptr(pmu->cpu_pmu_context);
1343 }
1344 
1345 void perf_pmu_disable(struct pmu *pmu)
1346 {
1347 	int *count = &this_cpc(pmu)->pmu_disable_count;
1348 	if (!(*count)++)
1349 		pmu->pmu_disable(pmu);
1350 }
1351 
1352 void perf_pmu_enable(struct pmu *pmu)
1353 {
1354 	int *count = &this_cpc(pmu)->pmu_disable_count;
1355 	if (!--(*count))
1356 		pmu->pmu_enable(pmu);
1357 }
1358 
1359 static void perf_assert_pmu_disabled(struct pmu *pmu)
1360 {
1361 	int *count = &this_cpc(pmu)->pmu_disable_count;
1362 	WARN_ON_ONCE(*count == 0);
1363 }
1364 
1365 static inline void perf_pmu_read(struct perf_event *event)
1366 {
1367 	if (event->state == PERF_EVENT_STATE_ACTIVE)
1368 		event->pmu->read(event);
1369 }
1370 
1371 static void get_ctx(struct perf_event_context *ctx)
1372 {
1373 	refcount_inc(&ctx->refcount);
1374 }
1375 
1376 static void free_ctx(struct rcu_head *head)
1377 {
1378 	struct perf_event_context *ctx;
1379 
1380 	ctx = container_of(head, struct perf_event_context, rcu_head);
1381 	kfree(ctx);
1382 }
1383 
1384 static void put_ctx(struct perf_event_context *ctx)
1385 {
1386 	if (refcount_dec_and_test(&ctx->refcount)) {
1387 		if (ctx->parent_ctx)
1388 			put_ctx(ctx->parent_ctx);
1389 		if (ctx->task && ctx->task != TASK_TOMBSTONE)
1390 			put_task_struct(ctx->task);
1391 		call_rcu(&ctx->rcu_head, free_ctx);
1392 	} else {
1393 		smp_mb__after_atomic(); /* pairs with wait_var_event() */
1394 		if (ctx->task == TASK_TOMBSTONE)
1395 			wake_up_var(&ctx->refcount);
1396 	}
1397 }
1398 
1399 /*
1400  * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1401  * perf_pmu_migrate_context() we need some magic.
1402  *
1403  * Those places that change perf_event::ctx will hold both
1404  * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1405  *
1406  * Lock ordering is by mutex address. There are two other sites where
1407  * perf_event_context::mutex nests and those are:
1408  *
1409  *  - perf_event_exit_task_context()	[ child , 0 ]
1410  *      perf_event_exit_event()
1411  *        put_event()			[ parent, 1 ]
1412  *
1413  *  - perf_event_init_context()		[ parent, 0 ]
1414  *      inherit_task_group()
1415  *        inherit_group()
1416  *          inherit_event()
1417  *            perf_event_alloc()
1418  *              perf_init_event()
1419  *                perf_try_init_event()	[ child , 1 ]
1420  *
1421  * While it appears there is an obvious deadlock here -- the parent and child
1422  * nesting levels are inverted between the two. This is in fact safe because
1423  * life-time rules separate them. That is an exiting task cannot fork, and a
1424  * spawning task cannot (yet) exit.
1425  *
1426  * But remember that these are parent<->child context relations, and
1427  * migration does not affect children, therefore these two orderings should not
1428  * interact.
1429  *
1430  * The change in perf_event::ctx does not affect children (as claimed above)
1431  * because the sys_perf_event_open() case will install a new event and break
1432  * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1433  * concerned with cpuctx and that doesn't have children.
1434  *
1435  * The places that change perf_event::ctx will issue:
1436  *
1437  *   perf_remove_from_context();
1438  *   synchronize_rcu();
1439  *   perf_install_in_context();
1440  *
1441  * to affect the change. The remove_from_context() + synchronize_rcu() should
1442  * quiesce the event, after which we can install it in the new location. This
1443  * means that only external vectors (perf_fops, prctl) can perturb the event
1444  * while in transit. Therefore all such accessors should also acquire
1445  * perf_event_context::mutex to serialize against this.
1446  *
1447  * However; because event->ctx can change while we're waiting to acquire
1448  * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1449  * function.
1450  *
1451  * Lock order:
1452  *    exec_update_lock
1453  *	task_struct::perf_event_mutex
1454  *	  perf_event_context::mutex
1455  *	    perf_event::child_mutex;
1456  *	      perf_event_context::lock
1457  *	    mmap_lock
1458  *	      perf_event::mmap_mutex
1459  *	        perf_buffer::aux_mutex
1460  *	      perf_addr_filters_head::lock
1461  *
1462  *    cpu_hotplug_lock
1463  *      pmus_lock
1464  *	  cpuctx->mutex / perf_event_context::mutex
1465  */
1466 static struct perf_event_context *
1467 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1468 {
1469 	struct perf_event_context *ctx;
1470 
1471 again:
1472 	rcu_read_lock();
1473 	ctx = READ_ONCE(event->ctx);
1474 	if (!refcount_inc_not_zero(&ctx->refcount)) {
1475 		rcu_read_unlock();
1476 		goto again;
1477 	}
1478 	rcu_read_unlock();
1479 
1480 	mutex_lock_nested(&ctx->mutex, nesting);
1481 	if (event->ctx != ctx) {
1482 		mutex_unlock(&ctx->mutex);
1483 		put_ctx(ctx);
1484 		goto again;
1485 	}
1486 
1487 	return ctx;
1488 }
1489 
1490 static inline struct perf_event_context *
1491 perf_event_ctx_lock(struct perf_event *event)
1492 {
1493 	return perf_event_ctx_lock_nested(event, 0);
1494 }
1495 
1496 static void perf_event_ctx_unlock(struct perf_event *event,
1497 				  struct perf_event_context *ctx)
1498 {
1499 	mutex_unlock(&ctx->mutex);
1500 	put_ctx(ctx);
1501 }
1502 
1503 /*
1504  * This must be done under the ctx->lock, such as to serialize against
1505  * context_equiv(), therefore we cannot call put_ctx() since that might end up
1506  * calling scheduler related locks and ctx->lock nests inside those.
1507  */
1508 static __must_check struct perf_event_context *
1509 unclone_ctx(struct perf_event_context *ctx)
1510 {
1511 	struct perf_event_context *parent_ctx = ctx->parent_ctx;
1512 
1513 	lockdep_assert_held(&ctx->lock);
1514 
1515 	if (parent_ctx)
1516 		ctx->parent_ctx = NULL;
1517 	ctx->generation++;
1518 
1519 	return parent_ctx;
1520 }
1521 
1522 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1523 				enum pid_type type)
1524 {
1525 	u32 nr;
1526 	/*
1527 	 * only top level events have the pid namespace they were created in
1528 	 */
1529 	if (event->parent)
1530 		event = event->parent;
1531 
1532 	nr = __task_pid_nr_ns(p, type, event->ns);
1533 	/* avoid -1 if it is idle thread or runs in another ns */
1534 	if (!nr && !pid_alive(p))
1535 		nr = -1;
1536 	return nr;
1537 }
1538 
1539 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1540 {
1541 	return perf_event_pid_type(event, p, PIDTYPE_TGID);
1542 }
1543 
1544 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1545 {
1546 	return perf_event_pid_type(event, p, PIDTYPE_PID);
1547 }
1548 
1549 /*
1550  * If we inherit events we want to return the parent event id
1551  * to userspace.
1552  */
1553 static u64 primary_event_id(struct perf_event *event)
1554 {
1555 	u64 id = event->id;
1556 
1557 	if (event->parent)
1558 		id = event->parent->id;
1559 
1560 	return id;
1561 }
1562 
1563 /*
1564  * Get the perf_event_context for a task and lock it.
1565  *
1566  * This has to cope with the fact that until it is locked,
1567  * the context could get moved to another task.
1568  */
1569 static struct perf_event_context *
1570 perf_lock_task_context(struct task_struct *task, unsigned long *flags)
1571 {
1572 	struct perf_event_context *ctx;
1573 
1574 retry:
1575 	/*
1576 	 * One of the few rules of preemptible RCU is that one cannot do
1577 	 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1578 	 * part of the read side critical section was irqs-enabled -- see
1579 	 * rcu_read_unlock_special().
1580 	 *
1581 	 * Since ctx->lock nests under rq->lock we must ensure the entire read
1582 	 * side critical section has interrupts disabled.
1583 	 */
1584 	local_irq_save(*flags);
1585 	rcu_read_lock();
1586 	ctx = rcu_dereference(task->perf_event_ctxp);
1587 	if (ctx) {
1588 		/*
1589 		 * If this context is a clone of another, it might
1590 		 * get swapped for another underneath us by
1591 		 * perf_event_task_sched_out, though the
1592 		 * rcu_read_lock() protects us from any context
1593 		 * getting freed.  Lock the context and check if it
1594 		 * got swapped before we could get the lock, and retry
1595 		 * if so.  If we locked the right context, then it
1596 		 * can't get swapped on us any more.
1597 		 */
1598 		raw_spin_lock(&ctx->lock);
1599 		if (ctx != rcu_dereference(task->perf_event_ctxp)) {
1600 			raw_spin_unlock(&ctx->lock);
1601 			rcu_read_unlock();
1602 			local_irq_restore(*flags);
1603 			goto retry;
1604 		}
1605 
1606 		if (ctx->task == TASK_TOMBSTONE ||
1607 		    !refcount_inc_not_zero(&ctx->refcount)) {
1608 			raw_spin_unlock(&ctx->lock);
1609 			ctx = NULL;
1610 		} else {
1611 			WARN_ON_ONCE(ctx->task != task);
1612 		}
1613 	}
1614 	rcu_read_unlock();
1615 	if (!ctx)
1616 		local_irq_restore(*flags);
1617 	return ctx;
1618 }
1619 
1620 /*
1621  * Get the context for a task and increment its pin_count so it
1622  * can't get swapped to another task.  This also increments its
1623  * reference count so that the context can't get freed.
1624  */
1625 static struct perf_event_context *
1626 perf_pin_task_context(struct task_struct *task)
1627 {
1628 	struct perf_event_context *ctx;
1629 	unsigned long flags;
1630 
1631 	ctx = perf_lock_task_context(task, &flags);
1632 	if (ctx) {
1633 		++ctx->pin_count;
1634 		raw_spin_unlock_irqrestore(&ctx->lock, flags);
1635 	}
1636 	return ctx;
1637 }
1638 
1639 static void perf_unpin_context(struct perf_event_context *ctx)
1640 {
1641 	unsigned long flags;
1642 
1643 	raw_spin_lock_irqsave(&ctx->lock, flags);
1644 	--ctx->pin_count;
1645 	raw_spin_unlock_irqrestore(&ctx->lock, flags);
1646 }
1647 
1648 /*
1649  * Update the record of the current time in a context.
1650  */
1651 static void __update_context_time(struct perf_event_context *ctx, bool adv)
1652 {
1653 	lockdep_assert_held(&ctx->lock);
1654 
1655 	update_perf_time_ctx(&ctx->time, perf_clock(), adv);
1656 }
1657 
1658 static void __update_context_guest_time(struct perf_event_context *ctx, bool adv)
1659 {
1660 	lockdep_assert_held(&ctx->lock);
1661 
1662 	/* must be called after __update_context_time(); */
1663 	update_perf_time_ctx(&ctx->timeguest, ctx->time.stamp, adv);
1664 }
1665 
1666 static void update_context_time(struct perf_event_context *ctx)
1667 {
1668 	__update_context_time(ctx, true);
1669 	if (is_guest_mediated_pmu_loaded())
1670 		__update_context_guest_time(ctx, true);
1671 }
1672 
1673 static u64 perf_event_time(struct perf_event *event)
1674 {
1675 	struct perf_event_context *ctx = event->ctx;
1676 
1677 	if (unlikely(!ctx))
1678 		return 0;
1679 
1680 	if (is_cgroup_event(event))
1681 		return perf_cgroup_event_time(event);
1682 
1683 	return __perf_event_time_ctx(event, &ctx->time);
1684 }
1685 
1686 static u64 perf_event_time_now(struct perf_event *event, u64 now)
1687 {
1688 	struct perf_event_context *ctx = event->ctx;
1689 
1690 	if (unlikely(!ctx))
1691 		return 0;
1692 
1693 	if (is_cgroup_event(event))
1694 		return perf_cgroup_event_time_now(event, now);
1695 
1696 	if (!(__load_acquire(&ctx->is_active) & EVENT_TIME))
1697 		return __perf_event_time_ctx(event, &ctx->time);
1698 
1699 	return __perf_event_time_ctx_now(event, &ctx->time, now);
1700 }
1701 
1702 static enum event_type_t get_event_type(struct perf_event *event)
1703 {
1704 	struct perf_event_context *ctx = event->ctx;
1705 	enum event_type_t event_type;
1706 
1707 	lockdep_assert_held(&ctx->lock);
1708 
1709 	/*
1710 	 * It's 'group type', really, because if our group leader is
1711 	 * pinned, so are we.
1712 	 */
1713 	if (event->group_leader != event)
1714 		event = event->group_leader;
1715 
1716 	event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1717 	if (!ctx->task)
1718 		event_type |= EVENT_CPU;
1719 
1720 	return event_type;
1721 }
1722 
1723 /*
1724  * Helper function to initialize event group nodes.
1725  */
1726 static void init_event_group(struct perf_event *event)
1727 {
1728 	RB_CLEAR_NODE(&event->group_node);
1729 	event->group_index = 0;
1730 }
1731 
1732 /*
1733  * Extract pinned or flexible groups from the context
1734  * based on event attrs bits.
1735  */
1736 static struct perf_event_groups *
1737 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1738 {
1739 	if (event->attr.pinned)
1740 		return &ctx->pinned_groups;
1741 	else
1742 		return &ctx->flexible_groups;
1743 }
1744 
1745 /*
1746  * Helper function to initializes perf_event_group trees.
1747  */
1748 static void perf_event_groups_init(struct perf_event_groups *groups)
1749 {
1750 	groups->tree = RB_ROOT;
1751 	groups->index = 0;
1752 }
1753 
1754 static inline struct cgroup *event_cgroup(const struct perf_event *event)
1755 {
1756 	struct cgroup *cgroup = NULL;
1757 
1758 #ifdef CONFIG_CGROUP_PERF
1759 	if (event->cgrp)
1760 		cgroup = event->cgrp->css.cgroup;
1761 #endif
1762 
1763 	return cgroup;
1764 }
1765 
1766 /*
1767  * Compare function for event groups;
1768  *
1769  * Implements complex key that first sorts by CPU and then by virtual index
1770  * which provides ordering when rotating groups for the same CPU.
1771  */
1772 static __always_inline int
1773 perf_event_groups_cmp(const int left_cpu, const struct pmu *left_pmu,
1774 		      const struct cgroup *left_cgroup, const u64 left_group_index,
1775 		      const struct perf_event *right)
1776 {
1777 	if (left_cpu < right->cpu)
1778 		return -1;
1779 	if (left_cpu > right->cpu)
1780 		return 1;
1781 
1782 	if (left_pmu) {
1783 		if (left_pmu < right->pmu_ctx->pmu)
1784 			return -1;
1785 		if (left_pmu > right->pmu_ctx->pmu)
1786 			return 1;
1787 	}
1788 
1789 #ifdef CONFIG_CGROUP_PERF
1790 	{
1791 		const struct cgroup *right_cgroup = event_cgroup(right);
1792 
1793 		if (left_cgroup != right_cgroup) {
1794 			if (!left_cgroup) {
1795 				/*
1796 				 * Left has no cgroup but right does, no
1797 				 * cgroups come first.
1798 				 */
1799 				return -1;
1800 			}
1801 			if (!right_cgroup) {
1802 				/*
1803 				 * Right has no cgroup but left does, no
1804 				 * cgroups come first.
1805 				 */
1806 				return 1;
1807 			}
1808 			/* Two dissimilar cgroups, order by id. */
1809 			if (cgroup_id(left_cgroup) < cgroup_id(right_cgroup))
1810 				return -1;
1811 
1812 			return 1;
1813 		}
1814 	}
1815 #endif
1816 
1817 	if (left_group_index < right->group_index)
1818 		return -1;
1819 	if (left_group_index > right->group_index)
1820 		return 1;
1821 
1822 	return 0;
1823 }
1824 
1825 #define __node_2_pe(node) \
1826 	rb_entry((node), struct perf_event, group_node)
1827 
1828 static inline bool __group_less(struct rb_node *a, const struct rb_node *b)
1829 {
1830 	struct perf_event *e = __node_2_pe(a);
1831 	return perf_event_groups_cmp(e->cpu, e->pmu_ctx->pmu, event_cgroup(e),
1832 				     e->group_index, __node_2_pe(b)) < 0;
1833 }
1834 
1835 struct __group_key {
1836 	int cpu;
1837 	struct pmu *pmu;
1838 	struct cgroup *cgroup;
1839 };
1840 
1841 static inline int __group_cmp(const void *key, const struct rb_node *node)
1842 {
1843 	const struct __group_key *a = key;
1844 	const struct perf_event *b = __node_2_pe(node);
1845 
1846 	/* partial/subtree match: @cpu, @pmu, @cgroup; ignore: @group_index */
1847 	return perf_event_groups_cmp(a->cpu, a->pmu, a->cgroup, b->group_index, b);
1848 }
1849 
1850 static inline int
1851 __group_cmp_ignore_cgroup(const void *key, const struct rb_node *node)
1852 {
1853 	const struct __group_key *a = key;
1854 	const struct perf_event *b = __node_2_pe(node);
1855 
1856 	/* partial/subtree match: @cpu, @pmu, ignore: @cgroup, @group_index */
1857 	return perf_event_groups_cmp(a->cpu, a->pmu, event_cgroup(b),
1858 				     b->group_index, b);
1859 }
1860 
1861 /*
1862  * Insert @event into @groups' tree; using
1863  *   {@event->cpu, @event->pmu_ctx->pmu, event_cgroup(@event), ++@groups->index}
1864  * as key. This places it last inside the {cpu,pmu,cgroup} subtree.
1865  */
1866 static void
1867 perf_event_groups_insert(struct perf_event_groups *groups,
1868 			 struct perf_event *event)
1869 {
1870 	event->group_index = ++groups->index;
1871 
1872 	rb_add(&event->group_node, &groups->tree, __group_less);
1873 }
1874 
1875 /*
1876  * Helper function to insert event into the pinned or flexible groups.
1877  */
1878 static void
1879 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1880 {
1881 	struct perf_event_groups *groups;
1882 
1883 	groups = get_event_groups(event, ctx);
1884 	perf_event_groups_insert(groups, event);
1885 }
1886 
1887 /*
1888  * Delete a group from a tree.
1889  */
1890 static void
1891 perf_event_groups_delete(struct perf_event_groups *groups,
1892 			 struct perf_event *event)
1893 {
1894 	WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1895 		     RB_EMPTY_ROOT(&groups->tree));
1896 
1897 	rb_erase(&event->group_node, &groups->tree);
1898 	init_event_group(event);
1899 }
1900 
1901 /*
1902  * Helper function to delete event from its groups.
1903  */
1904 static void
1905 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1906 {
1907 	struct perf_event_groups *groups;
1908 
1909 	groups = get_event_groups(event, ctx);
1910 	perf_event_groups_delete(groups, event);
1911 }
1912 
1913 /*
1914  * Get the leftmost event in the {cpu,pmu,cgroup} subtree.
1915  */
1916 static struct perf_event *
1917 perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1918 			struct pmu *pmu, struct cgroup *cgrp)
1919 {
1920 	struct __group_key key = {
1921 		.cpu = cpu,
1922 		.pmu = pmu,
1923 		.cgroup = cgrp,
1924 	};
1925 	struct rb_node *node;
1926 
1927 	node = rb_find_first(&key, &groups->tree, __group_cmp);
1928 	if (node)
1929 		return __node_2_pe(node);
1930 
1931 	return NULL;
1932 }
1933 
1934 static struct perf_event *
1935 perf_event_groups_next(struct perf_event *event, struct pmu *pmu)
1936 {
1937 	struct __group_key key = {
1938 		.cpu = event->cpu,
1939 		.pmu = pmu,
1940 		.cgroup = event_cgroup(event),
1941 	};
1942 	struct rb_node *next;
1943 
1944 	next = rb_next_match(&key, &event->group_node, __group_cmp);
1945 	if (next)
1946 		return __node_2_pe(next);
1947 
1948 	return NULL;
1949 }
1950 
1951 #define perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu)		\
1952 	for (event = perf_event_groups_first(groups, cpu, pmu, NULL);	\
1953 	     event; event = perf_event_groups_next(event, pmu))
1954 
1955 /*
1956  * Iterate through the whole groups tree.
1957  */
1958 #define perf_event_groups_for_each(event, groups)			\
1959 	for (event = rb_entry_safe(rb_first(&((groups)->tree)),		\
1960 				typeof(*event), group_node); event;	\
1961 		event = rb_entry_safe(rb_next(&event->group_node),	\
1962 				typeof(*event), group_node))
1963 
1964 /*
1965  * Does the event attribute request inherit with PERF_SAMPLE_READ
1966  */
1967 static inline bool has_inherit_and_sample_read(struct perf_event_attr *attr)
1968 {
1969 	return attr->inherit && (attr->sample_type & PERF_SAMPLE_READ);
1970 }
1971 
1972 /*
1973  * Add an event from the lists for its context.
1974  * Must be called with ctx->mutex and ctx->lock held.
1975  */
1976 static void
1977 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1978 {
1979 	lockdep_assert_held(&ctx->lock);
1980 
1981 	WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1982 	event->attach_state |= PERF_ATTACH_CONTEXT;
1983 
1984 	event->tstamp = perf_event_time(event);
1985 
1986 	/*
1987 	 * If we're a stand alone event or group leader, we go to the context
1988 	 * list, group events are kept attached to the group so that
1989 	 * perf_group_detach can, at all times, locate all siblings.
1990 	 */
1991 	if (event->group_leader == event) {
1992 		event->group_caps = event->event_caps;
1993 		add_event_to_groups(event, ctx);
1994 	}
1995 
1996 	list_add_rcu(&event->event_entry, &ctx->event_list);
1997 	ctx->nr_events++;
1998 	if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
1999 		ctx->nr_user++;
2000 	if (event->attr.inherit_stat)
2001 		ctx->nr_stat++;
2002 	if (has_inherit_and_sample_read(&event->attr))
2003 		local_inc(&ctx->nr_no_switch_fast);
2004 
2005 	if (event->state > PERF_EVENT_STATE_OFF)
2006 		perf_cgroup_event_enable(event, ctx);
2007 
2008 	ctx->generation++;
2009 	event->pmu_ctx->nr_events++;
2010 }
2011 
2012 /*
2013  * Initialize event state based on the perf_event_attr::disabled.
2014  */
2015 static inline void perf_event__state_init(struct perf_event *event)
2016 {
2017 	event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
2018 					      PERF_EVENT_STATE_INACTIVE;
2019 }
2020 
2021 static int __perf_event_read_size(u64 read_format, int nr_siblings)
2022 {
2023 	int entry = sizeof(u64); /* value */
2024 	int size = 0;
2025 	int nr = 1;
2026 
2027 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
2028 		size += sizeof(u64);
2029 
2030 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
2031 		size += sizeof(u64);
2032 
2033 	if (read_format & PERF_FORMAT_ID)
2034 		entry += sizeof(u64);
2035 
2036 	if (read_format & PERF_FORMAT_LOST)
2037 		entry += sizeof(u64);
2038 
2039 	if (read_format & PERF_FORMAT_GROUP) {
2040 		nr += nr_siblings;
2041 		size += sizeof(u64);
2042 	}
2043 
2044 	/*
2045 	 * Since perf_event_validate_size() limits this to 16k and inhibits
2046 	 * adding more siblings, this will never overflow.
2047 	 */
2048 	return size + nr * entry;
2049 }
2050 
2051 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
2052 {
2053 	struct perf_sample_data *data;
2054 	u16 size = 0;
2055 
2056 	if (sample_type & PERF_SAMPLE_IP)
2057 		size += sizeof(data->ip);
2058 
2059 	if (sample_type & PERF_SAMPLE_ADDR)
2060 		size += sizeof(data->addr);
2061 
2062 	if (sample_type & PERF_SAMPLE_PERIOD)
2063 		size += sizeof(data->period);
2064 
2065 	if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
2066 		size += sizeof(data->weight.full);
2067 
2068 	if (sample_type & PERF_SAMPLE_READ)
2069 		size += event->read_size;
2070 
2071 	if (sample_type & PERF_SAMPLE_DATA_SRC)
2072 		size += sizeof(data->data_src.val);
2073 
2074 	if (sample_type & PERF_SAMPLE_TRANSACTION)
2075 		size += sizeof(data->txn);
2076 
2077 	if (sample_type & PERF_SAMPLE_PHYS_ADDR)
2078 		size += sizeof(data->phys_addr);
2079 
2080 	if (sample_type & PERF_SAMPLE_CGROUP)
2081 		size += sizeof(data->cgroup);
2082 
2083 	if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
2084 		size += sizeof(data->data_page_size);
2085 
2086 	if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
2087 		size += sizeof(data->code_page_size);
2088 
2089 	event->header_size = size;
2090 }
2091 
2092 /*
2093  * Called at perf_event creation and when events are attached/detached from a
2094  * group.
2095  */
2096 static void perf_event__header_size(struct perf_event *event)
2097 {
2098 	event->read_size =
2099 		__perf_event_read_size(event->attr.read_format,
2100 				       event->group_leader->nr_siblings);
2101 	__perf_event_header_size(event, event->attr.sample_type);
2102 }
2103 
2104 static void perf_event__id_header_size(struct perf_event *event)
2105 {
2106 	struct perf_sample_data *data;
2107 	u64 sample_type = event->attr.sample_type;
2108 	u16 size = 0;
2109 
2110 	if (sample_type & PERF_SAMPLE_TID)
2111 		size += sizeof(data->tid_entry);
2112 
2113 	if (sample_type & PERF_SAMPLE_TIME)
2114 		size += sizeof(data->time);
2115 
2116 	if (sample_type & PERF_SAMPLE_IDENTIFIER)
2117 		size += sizeof(data->id);
2118 
2119 	if (sample_type & PERF_SAMPLE_ID)
2120 		size += sizeof(data->id);
2121 
2122 	if (sample_type & PERF_SAMPLE_STREAM_ID)
2123 		size += sizeof(data->stream_id);
2124 
2125 	if (sample_type & PERF_SAMPLE_CPU)
2126 		size += sizeof(data->cpu_entry);
2127 
2128 	event->id_header_size = size;
2129 }
2130 
2131 /*
2132  * Check that adding an event to the group does not result in anybody
2133  * overflowing the 64k event limit imposed by the output buffer.
2134  *
2135  * Specifically, check that the read_size for the event does not exceed 16k,
2136  * read_size being the one term that grows with groups size. Since read_size
2137  * depends on per-event read_format, also (re)check the existing events.
2138  *
2139  * This leaves 48k for the constant size fields and things like callchains,
2140  * branch stacks and register sets.
2141  */
2142 static bool perf_event_validate_size(struct perf_event *event)
2143 {
2144 	struct perf_event *sibling, *group_leader = event->group_leader;
2145 
2146 	if (__perf_event_read_size(event->attr.read_format,
2147 				   group_leader->nr_siblings + 1) > 16*1024)
2148 		return false;
2149 
2150 	if (__perf_event_read_size(group_leader->attr.read_format,
2151 				   group_leader->nr_siblings + 1) > 16*1024)
2152 		return false;
2153 
2154 	/*
2155 	 * When creating a new group leader, group_leader->ctx is initialized
2156 	 * after the size has been validated, but we cannot safely use
2157 	 * for_each_sibling_event() until group_leader->ctx is set. A new group
2158 	 * leader cannot have any siblings yet, so we can safely skip checking
2159 	 * the non-existent siblings.
2160 	 */
2161 	if (event == group_leader)
2162 		return true;
2163 
2164 	for_each_sibling_event(sibling, group_leader) {
2165 		if (__perf_event_read_size(sibling->attr.read_format,
2166 					   group_leader->nr_siblings + 1) > 16*1024)
2167 			return false;
2168 	}
2169 
2170 	return true;
2171 }
2172 
2173 static void perf_group_attach(struct perf_event *event)
2174 {
2175 	struct perf_event *group_leader = event->group_leader, *pos;
2176 
2177 	lockdep_assert_held(&event->ctx->lock);
2178 
2179 	/*
2180 	 * We can have double attach due to group movement (move_group) in
2181 	 * perf_event_open().
2182 	 */
2183 	if (event->attach_state & PERF_ATTACH_GROUP)
2184 		return;
2185 
2186 	event->attach_state |= PERF_ATTACH_GROUP;
2187 
2188 	if (group_leader == event)
2189 		return;
2190 
2191 	WARN_ON_ONCE(group_leader->ctx != event->ctx);
2192 
2193 	group_leader->group_caps &= event->event_caps;
2194 
2195 	list_add_tail(&event->sibling_list, &group_leader->sibling_list);
2196 	group_leader->nr_siblings++;
2197 	group_leader->group_generation++;
2198 
2199 	perf_event__header_size(group_leader);
2200 
2201 	for_each_sibling_event(pos, group_leader)
2202 		perf_event__header_size(pos);
2203 }
2204 
2205 /*
2206  * Remove an event from the lists for its context.
2207  * Must be called with ctx->mutex and ctx->lock held.
2208  */
2209 static void
2210 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
2211 {
2212 	WARN_ON_ONCE(event->ctx != ctx);
2213 	lockdep_assert_held(&ctx->lock);
2214 
2215 	/*
2216 	 * We can have double detach due to exit/hot-unplug + close.
2217 	 */
2218 	if (!(event->attach_state & PERF_ATTACH_CONTEXT))
2219 		return;
2220 
2221 	event->attach_state &= ~PERF_ATTACH_CONTEXT;
2222 
2223 	ctx->nr_events--;
2224 	if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
2225 		ctx->nr_user--;
2226 	if (event->attr.inherit_stat)
2227 		ctx->nr_stat--;
2228 	if (has_inherit_and_sample_read(&event->attr))
2229 		local_dec(&ctx->nr_no_switch_fast);
2230 
2231 	list_del_rcu(&event->event_entry);
2232 
2233 	if (event->group_leader == event)
2234 		del_event_from_groups(event, ctx);
2235 
2236 	ctx->generation++;
2237 	event->pmu_ctx->nr_events--;
2238 }
2239 
2240 static int
2241 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2242 {
2243 	if (!has_aux(aux_event))
2244 		return 0;
2245 
2246 	if (!event->pmu->aux_output_match)
2247 		return 0;
2248 
2249 	return event->pmu->aux_output_match(aux_event);
2250 }
2251 
2252 static void put_event(struct perf_event *event);
2253 static void __event_disable(struct perf_event *event,
2254 			    struct perf_event_context *ctx,
2255 			    enum perf_event_state state);
2256 
2257 static void perf_put_aux_event(struct perf_event *event)
2258 {
2259 	struct perf_event_context *ctx = event->ctx;
2260 	struct perf_event *iter;
2261 
2262 	/*
2263 	 * If event uses aux_event tear down the link
2264 	 */
2265 	if (event->aux_event) {
2266 		iter = event->aux_event;
2267 		event->aux_event = NULL;
2268 		put_event(iter);
2269 		return;
2270 	}
2271 
2272 	/*
2273 	 * If the event is an aux_event, tear down all links to
2274 	 * it from other events.
2275 	 */
2276 	for_each_sibling_event(iter, event) {
2277 		if (iter->aux_event != event)
2278 			continue;
2279 
2280 		iter->aux_event = NULL;
2281 		put_event(event);
2282 
2283 		/*
2284 		 * If it's ACTIVE, schedule it out and put it into ERROR
2285 		 * state so that we don't try to schedule it again. Note
2286 		 * that perf_event_enable() will clear the ERROR status.
2287 		 */
2288 		__event_disable(iter, ctx, PERF_EVENT_STATE_ERROR);
2289 	}
2290 }
2291 
2292 static bool perf_need_aux_event(struct perf_event *event)
2293 {
2294 	return event->attr.aux_output || has_aux_action(event);
2295 }
2296 
2297 static int perf_get_aux_event(struct perf_event *event,
2298 			      struct perf_event *group_leader)
2299 {
2300 	/*
2301 	 * Our group leader must be an aux event if we want to be
2302 	 * an aux_output. This way, the aux event will precede its
2303 	 * aux_output events in the group, and therefore will always
2304 	 * schedule first.
2305 	 */
2306 	if (!group_leader)
2307 		return 0;
2308 
2309 	/*
2310 	 * aux_output and aux_sample_size are mutually exclusive.
2311 	 */
2312 	if (event->attr.aux_output && event->attr.aux_sample_size)
2313 		return 0;
2314 
2315 	if (event->attr.aux_output &&
2316 	    !perf_aux_output_match(event, group_leader))
2317 		return 0;
2318 
2319 	if ((event->attr.aux_pause || event->attr.aux_resume) &&
2320 	    !(group_leader->pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE))
2321 		return 0;
2322 
2323 	if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
2324 		return 0;
2325 
2326 	if (!atomic_long_inc_not_zero(&group_leader->refcount))
2327 		return 0;
2328 
2329 	/*
2330 	 * Link aux_outputs to their aux event; this is undone in
2331 	 * perf_group_detach() by perf_put_aux_event(). When the
2332 	 * group in torn down, the aux_output events loose their
2333 	 * link to the aux_event and can't schedule any more.
2334 	 */
2335 	event->aux_event = group_leader;
2336 
2337 	return 1;
2338 }
2339 
2340 static inline struct list_head *get_event_list(struct perf_event *event)
2341 {
2342 	return event->attr.pinned ? &event->pmu_ctx->pinned_active :
2343 				    &event->pmu_ctx->flexible_active;
2344 }
2345 
2346 /* @sibling must already be unlinked from its old leader's sibling_list. */
2347 static void perf_promote_sibling_to_leader(struct perf_event *sibling,
2348 					   struct perf_event_context *ctx,
2349 					   int group_caps)
2350 {
2351 	/*
2352 	 * Events that have PERF_EV_CAP_SIBLING require being part of
2353 	 * a group and cannot exist on their own, schedule them out
2354 	 * and move them into the ERROR state. Also see
2355 	 * _perf_event_enable(), it will not be able to recover this
2356 	 * ERROR state.
2357 	 */
2358 	if (sibling->event_caps & PERF_EV_CAP_SIBLING)
2359 		__event_disable(sibling, ctx, PERF_EVENT_STATE_ERROR);
2360 
2361 	sibling->group_leader = sibling;
2362 	sibling->group_caps = group_caps;
2363 
2364 	if (sibling->attach_state & PERF_ATTACH_CONTEXT) {
2365 		add_event_to_groups(sibling, ctx);
2366 
2367 		if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2368 			list_add_tail(&sibling->active_list, get_event_list(sibling));
2369 	}
2370 
2371 	perf_event__header_size(sibling);
2372 }
2373 
2374 static void perf_group_detach(struct perf_event *event)
2375 {
2376 	struct perf_event *leader = event->group_leader;
2377 	struct perf_event *sibling, *tmp;
2378 	struct perf_event_context *ctx = event->ctx;
2379 
2380 	lockdep_assert_held(&ctx->lock);
2381 
2382 	/*
2383 	 * We can have double detach due to exit/hot-unplug + close.
2384 	 */
2385 	if (!(event->attach_state & PERF_ATTACH_GROUP))
2386 		return;
2387 
2388 	event->attach_state &= ~PERF_ATTACH_GROUP;
2389 
2390 	perf_put_aux_event(event);
2391 
2392 	/*
2393 	 * If this is a sibling, remove it from its group.
2394 	 */
2395 	if (leader != event) {
2396 		list_del_init(&event->sibling_list);
2397 		leader->nr_siblings--;
2398 		leader->group_generation++;
2399 		perf_promote_sibling_to_leader(event, ctx, event->event_caps);
2400 		goto out;
2401 	}
2402 
2403 	/*
2404 	 * If this was a group event with sibling events then
2405 	 * upgrade the siblings to singleton events by adding them
2406 	 * to whatever list we are on.
2407 	 */
2408 	list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2409 		list_del_init(&sibling->sibling_list);
2410 
2411 		/* Inherit group flags from the previous leader */
2412 		perf_promote_sibling_to_leader(sibling, ctx, event->group_caps);
2413 
2414 		WARN_ON_ONCE(sibling->ctx != event->ctx);
2415 	}
2416 	event->nr_siblings = 0;
2417 
2418 out:
2419 	for_each_sibling_event(tmp, leader)
2420 		perf_event__header_size(tmp);
2421 
2422 	perf_event__header_size(leader);
2423 }
2424 
2425 static void perf_child_detach(struct perf_event *event)
2426 {
2427 	struct perf_event *parent_event = event->parent;
2428 
2429 	if (!(event->attach_state & PERF_ATTACH_CHILD))
2430 		return;
2431 
2432 	event->attach_state &= ~PERF_ATTACH_CHILD;
2433 
2434 	if (WARN_ON_ONCE(!parent_event))
2435 		return;
2436 
2437 	/*
2438 	 * Can't check this from an IPI, the holder is likey another CPU.
2439 	 *
2440 	lockdep_assert_held(&parent_event->child_mutex);
2441 	 */
2442 
2443 	list_del_init(&event->child_list);
2444 }
2445 
2446 static bool is_orphaned_event(struct perf_event *event)
2447 {
2448 	return event->state == PERF_EVENT_STATE_DEAD;
2449 }
2450 
2451 static inline int
2452 event_filter_match(struct perf_event *event)
2453 {
2454 	return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2455 	       perf_cgroup_match(event);
2456 }
2457 
2458 static inline bool is_event_in_freq_mode(struct perf_event *event)
2459 {
2460 	return event->attr.freq && event->attr.sample_freq;
2461 }
2462 
2463 static void
2464 event_sched_out(struct perf_event *event, struct perf_event_context *ctx)
2465 {
2466 	struct perf_event_pmu_context *epc = event->pmu_ctx;
2467 	struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu);
2468 	enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2469 
2470 	// XXX cpc serialization, probably per-cpu IRQ disabled
2471 
2472 	WARN_ON_ONCE(event->ctx != ctx);
2473 	lockdep_assert_held(&ctx->lock);
2474 
2475 	if (event->state != PERF_EVENT_STATE_ACTIVE)
2476 		return;
2477 
2478 	/*
2479 	 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2480 	 * we can schedule events _OUT_ individually through things like
2481 	 * __perf_remove_from_context().
2482 	 */
2483 	list_del_init(&event->active_list);
2484 
2485 	perf_pmu_disable(event->pmu);
2486 
2487 	event->pmu->del(event, 0);
2488 	event->oncpu = -1;
2489 
2490 	if (event->pending_disable) {
2491 		event->pending_disable = 0;
2492 		perf_cgroup_event_disable(event, ctx);
2493 		state = PERF_EVENT_STATE_OFF;
2494 	}
2495 
2496 	perf_event_set_state(event, state);
2497 
2498 	if (!is_software_event(event))
2499 		cpc->active_oncpu--;
2500 	if (is_event_in_freq_mode(event)) {
2501 		ctx->nr_freq--;
2502 		epc->nr_freq--;
2503 	}
2504 	if (event->attr.exclusive || !cpc->active_oncpu)
2505 		cpc->exclusive = 0;
2506 
2507 	perf_pmu_enable(event->pmu);
2508 }
2509 
2510 static void
2511 group_sched_out(struct perf_event *group_event, struct perf_event_context *ctx)
2512 {
2513 	struct perf_event *event;
2514 
2515 	if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2516 		return;
2517 
2518 	perf_assert_pmu_disabled(group_event->pmu_ctx->pmu);
2519 
2520 	event_sched_out(group_event, ctx);
2521 
2522 	/*
2523 	 * Schedule out siblings (if any):
2524 	 */
2525 	for_each_sibling_event(event, group_event)
2526 		event_sched_out(event, ctx);
2527 }
2528 
2529 static inline void
2530 __ctx_time_update(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx,
2531 		  bool final, enum event_type_t event_type)
2532 {
2533 	if (ctx->is_active & EVENT_TIME) {
2534 		if (ctx->is_active & EVENT_FROZEN)
2535 			return;
2536 
2537 		update_context_time(ctx);
2538 		/* vPMU should not stop time */
2539 		update_cgrp_time_from_cpuctx(cpuctx, !(event_type & EVENT_GUEST) && final);
2540 	}
2541 }
2542 
2543 static inline void
2544 ctx_time_update(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx)
2545 {
2546 	__ctx_time_update(cpuctx, ctx, false, 0);
2547 }
2548 
2549 /*
2550  * To be used inside perf_ctx_lock() / perf_ctx_unlock(). Lasts until perf_ctx_unlock().
2551  */
2552 static inline void
2553 ctx_time_freeze(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx)
2554 {
2555 	ctx_time_update(cpuctx, ctx);
2556 	if (ctx->is_active & EVENT_TIME)
2557 		ctx->is_active |= EVENT_FROZEN;
2558 }
2559 
2560 static inline void
2561 ctx_time_update_event(struct perf_event_context *ctx, struct perf_event *event)
2562 {
2563 	if (ctx->is_active & EVENT_TIME) {
2564 		if (ctx->is_active & EVENT_FROZEN)
2565 			return;
2566 		update_context_time(ctx);
2567 		update_cgrp_time_from_event(event);
2568 	}
2569 }
2570 
2571 #define DETACH_GROUP	0x01UL
2572 #define DETACH_CHILD	0x02UL
2573 #define DETACH_EXIT	0x04UL
2574 #define DETACH_REVOKE	0x08UL
2575 #define DETACH_DEAD	0x10UL
2576 
2577 /*
2578  * Cross CPU call to remove a performance event
2579  *
2580  * We disable the event on the hardware level first. After that we
2581  * remove it from the context list.
2582  */
2583 static void
2584 __perf_remove_from_context(struct perf_event *event,
2585 			   struct perf_cpu_context *cpuctx,
2586 			   struct perf_event_context *ctx,
2587 			   void *info)
2588 {
2589 	struct perf_event_pmu_context *pmu_ctx = event->pmu_ctx;
2590 	enum perf_event_state state = PERF_EVENT_STATE_OFF;
2591 	unsigned long flags = (unsigned long)info;
2592 
2593 	ctx_time_update(cpuctx, ctx);
2594 
2595 	/*
2596 	 * Ensure event_sched_out() switches to OFF, at the very least
2597 	 * this avoids raising perf_pending_task() at this time.
2598 	 */
2599 	if (flags & DETACH_EXIT)
2600 		state = PERF_EVENT_STATE_EXIT;
2601 	if (flags & DETACH_REVOKE)
2602 		state = PERF_EVENT_STATE_REVOKED;
2603 	if (flags & DETACH_DEAD)
2604 		state = PERF_EVENT_STATE_DEAD;
2605 
2606 	__event_disable(event, ctx, state);
2607 
2608 	if (flags & DETACH_GROUP)
2609 		perf_group_detach(event);
2610 	if (flags & DETACH_CHILD)
2611 		perf_child_detach(event);
2612 	list_del_event(event, ctx);
2613 
2614 	if (!pmu_ctx->nr_events) {
2615 		pmu_ctx->rotate_necessary = 0;
2616 
2617 		if (ctx->task && ctx->is_active) {
2618 			struct perf_cpu_pmu_context *cpc = this_cpc(pmu_ctx->pmu);
2619 
2620 			WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
2621 			cpc->task_epc = NULL;
2622 		}
2623 	}
2624 
2625 	if (!ctx->nr_events && ctx->is_active) {
2626 		if (ctx == &cpuctx->ctx)
2627 			update_cgrp_time_from_cpuctx(cpuctx, true);
2628 
2629 		ctx->is_active = 0;
2630 		if (ctx->task) {
2631 			WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2632 			cpuctx->task_ctx = NULL;
2633 		}
2634 	}
2635 }
2636 
2637 /*
2638  * Remove the event from a task's (or a CPU's) list of events.
2639  *
2640  * If event->ctx is a cloned context, callers must make sure that
2641  * every task struct that event->ctx->task could possibly point to
2642  * remains valid.  This is OK when called from perf_release since
2643  * that only calls us on the top-level context, which can't be a clone.
2644  * When called from perf_event_exit_task, it's OK because the
2645  * context has been detached from its task.
2646  */
2647 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2648 {
2649 	struct perf_event_context *ctx = event->ctx;
2650 
2651 	lockdep_assert_held(&ctx->mutex);
2652 
2653 	/*
2654 	 * Because of perf_event_exit_task(), perf_remove_from_context() ought
2655 	 * to work in the face of TASK_TOMBSTONE, unlike every other
2656 	 * event_function_call() user.
2657 	 */
2658 	raw_spin_lock_irq(&ctx->lock);
2659 	if (!ctx->is_active) {
2660 		__perf_remove_from_context(event, this_cpu_ptr(&perf_cpu_context),
2661 					   ctx, (void *)flags);
2662 		raw_spin_unlock_irq(&ctx->lock);
2663 		return;
2664 	}
2665 	raw_spin_unlock_irq(&ctx->lock);
2666 
2667 	event_function_call(event, __perf_remove_from_context, (void *)flags);
2668 }
2669 
2670 static void __event_disable(struct perf_event *event,
2671 			    struct perf_event_context *ctx,
2672 			    enum perf_event_state state)
2673 {
2674 	event_sched_out(event, ctx);
2675 	if (event->state > PERF_EVENT_STATE_OFF)
2676 		perf_cgroup_event_disable(event, ctx);
2677 	perf_event_set_state(event, min(event->state, state));
2678 }
2679 
2680 /*
2681  * Cross CPU call to disable a performance event
2682  */
2683 static void __perf_event_disable(struct perf_event *event,
2684 				 struct perf_cpu_context *cpuctx,
2685 				 struct perf_event_context *ctx,
2686 				 void *info)
2687 {
2688 	if (event->state < PERF_EVENT_STATE_INACTIVE)
2689 		return;
2690 
2691 	perf_pmu_disable(event->pmu_ctx->pmu);
2692 	ctx_time_update_event(ctx, event);
2693 
2694 	/*
2695 	 * When disabling a group leader, the whole group becomes ineligible
2696 	 * to run, so schedule out the full group.
2697 	 */
2698 	if (event == event->group_leader)
2699 		group_sched_out(event, ctx);
2700 
2701 	/*
2702 	 * But only mark the leader OFF; the siblings will remain
2703 	 * INACTIVE.
2704 	 */
2705 	__event_disable(event, ctx, PERF_EVENT_STATE_OFF);
2706 
2707 	perf_pmu_enable(event->pmu_ctx->pmu);
2708 }
2709 
2710 /*
2711  * Disable an event.
2712  *
2713  * If event->ctx is a cloned context, callers must make sure that
2714  * every task struct that event->ctx->task could possibly point to
2715  * remains valid.  This condition is satisfied when called through
2716  * perf_event_for_each_child or perf_event_for_each because they
2717  * hold the top-level event's child_mutex, so any descendant that
2718  * goes to exit will block in perf_event_exit_event().
2719  *
2720  * When called from perf_pending_disable it's OK because event->ctx
2721  * is the current context on this CPU and preemption is disabled,
2722  * hence we can't get into perf_event_task_sched_out for this context.
2723  */
2724 static void _perf_event_disable(struct perf_event *event)
2725 {
2726 	struct perf_event_context *ctx = event->ctx;
2727 
2728 	raw_spin_lock_irq(&ctx->lock);
2729 	if (event->state <= PERF_EVENT_STATE_OFF) {
2730 		raw_spin_unlock_irq(&ctx->lock);
2731 		return;
2732 	}
2733 	raw_spin_unlock_irq(&ctx->lock);
2734 
2735 	event_function_call(event, __perf_event_disable, NULL);
2736 }
2737 
2738 void perf_event_disable_local(struct perf_event *event)
2739 {
2740 	event_function_local(event, __perf_event_disable, NULL);
2741 }
2742 
2743 /*
2744  * Strictly speaking kernel users cannot create groups and therefore this
2745  * interface does not need the perf_event_ctx_lock() magic.
2746  */
2747 void perf_event_disable(struct perf_event *event)
2748 {
2749 	struct perf_event_context *ctx;
2750 
2751 	ctx = perf_event_ctx_lock(event);
2752 	_perf_event_disable(event);
2753 	perf_event_ctx_unlock(event, ctx);
2754 }
2755 EXPORT_SYMBOL_GPL(perf_event_disable);
2756 
2757 void perf_event_disable_inatomic(struct perf_event *event)
2758 {
2759 	event->pending_disable = 1;
2760 	irq_work_queue(&event->pending_disable_irq);
2761 }
2762 
2763 #define MAX_INTERRUPTS (~0ULL)
2764 
2765 static void perf_log_throttle(struct perf_event *event, int enable);
2766 static void perf_log_itrace_start(struct perf_event *event);
2767 
2768 static void perf_event_unthrottle(struct perf_event *event, bool start)
2769 {
2770 	if (event->state != PERF_EVENT_STATE_ACTIVE)
2771 		return;
2772 
2773 	event->hw.interrupts = 0;
2774 	if (start)
2775 		event->pmu->start(event, 0);
2776 	if (event == event->group_leader)
2777 		perf_log_throttle(event, 1);
2778 }
2779 
2780 static void perf_event_throttle(struct perf_event *event)
2781 {
2782 	if (event->state != PERF_EVENT_STATE_ACTIVE)
2783 		return;
2784 
2785 	event->hw.interrupts = MAX_INTERRUPTS;
2786 	event->pmu->stop(event, 0);
2787 	if (event == event->group_leader)
2788 		perf_log_throttle(event, 0);
2789 }
2790 
2791 static void perf_event_unthrottle_group(struct perf_event *event, bool skip_start_event)
2792 {
2793 	struct perf_event *sibling, *leader = event->group_leader;
2794 
2795 	perf_event_unthrottle(leader, skip_start_event ? leader != event : true);
2796 	for_each_sibling_event(sibling, leader)
2797 		perf_event_unthrottle(sibling, skip_start_event ? sibling != event : true);
2798 }
2799 
2800 static void perf_event_throttle_group(struct perf_event *event)
2801 {
2802 	struct perf_event *sibling, *leader = event->group_leader;
2803 
2804 	perf_event_throttle(leader);
2805 	for_each_sibling_event(sibling, leader)
2806 		perf_event_throttle(sibling);
2807 }
2808 
2809 static int
2810 event_sched_in(struct perf_event *event, struct perf_event_context *ctx)
2811 {
2812 	struct perf_event_pmu_context *epc = event->pmu_ctx;
2813 	struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu);
2814 	int ret = 0;
2815 
2816 	WARN_ON_ONCE(event->ctx != ctx);
2817 
2818 	lockdep_assert_held(&ctx->lock);
2819 
2820 	if (event->state <= PERF_EVENT_STATE_OFF)
2821 		return 0;
2822 
2823 	WRITE_ONCE(event->oncpu, smp_processor_id());
2824 	/*
2825 	 * Order event::oncpu write to happen before the ACTIVE state is
2826 	 * visible. This allows perf_event_{stop,read}() to observe the correct
2827 	 * ->oncpu if it sees ACTIVE.
2828 	 */
2829 	smp_wmb();
2830 	perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2831 
2832 	/*
2833 	 * Unthrottle events, since we scheduled we might have missed several
2834 	 * ticks already, also for a heavily scheduling task there is little
2835 	 * guarantee it'll get a tick in a timely manner.
2836 	 */
2837 	if (unlikely(event->hw.interrupts == MAX_INTERRUPTS))
2838 		perf_event_unthrottle(event, false);
2839 
2840 	perf_pmu_disable(event->pmu);
2841 
2842 	perf_log_itrace_start(event);
2843 
2844 	if (event->pmu->add(event, PERF_EF_START)) {
2845 		perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2846 		event->oncpu = -1;
2847 		ret = -EAGAIN;
2848 		goto out;
2849 	}
2850 
2851 	if (!is_software_event(event))
2852 		cpc->active_oncpu++;
2853 	if (is_event_in_freq_mode(event)) {
2854 		ctx->nr_freq++;
2855 		epc->nr_freq++;
2856 	}
2857 	if (event->attr.exclusive)
2858 		cpc->exclusive = 1;
2859 
2860 out:
2861 	perf_pmu_enable(event->pmu);
2862 
2863 	return ret;
2864 }
2865 
2866 static int
2867 group_sched_in(struct perf_event *group_event, struct perf_event_context *ctx)
2868 {
2869 	struct perf_event *event, *partial_group = NULL;
2870 	struct pmu *pmu = group_event->pmu_ctx->pmu;
2871 
2872 	if (group_event->state == PERF_EVENT_STATE_OFF)
2873 		return 0;
2874 
2875 	pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2876 
2877 	if (event_sched_in(group_event, ctx))
2878 		goto error;
2879 
2880 	/*
2881 	 * Schedule in siblings as one group (if any):
2882 	 */
2883 	for_each_sibling_event(event, group_event) {
2884 		if (event_sched_in(event, ctx)) {
2885 			partial_group = event;
2886 			goto group_error;
2887 		}
2888 	}
2889 
2890 	if (!pmu->commit_txn(pmu))
2891 		return 0;
2892 
2893 group_error:
2894 	/*
2895 	 * Groups can be scheduled in as one unit only, so undo any
2896 	 * partial group before returning:
2897 	 * The events up to the failed event are scheduled out normally.
2898 	 */
2899 	for_each_sibling_event(event, group_event) {
2900 		if (event == partial_group)
2901 			break;
2902 
2903 		event_sched_out(event, ctx);
2904 	}
2905 	event_sched_out(group_event, ctx);
2906 
2907 error:
2908 	pmu->cancel_txn(pmu);
2909 	return -EAGAIN;
2910 }
2911 
2912 /*
2913  * Work out whether we can put this event group on the CPU now.
2914  */
2915 static int group_can_go_on(struct perf_event *event, int can_add_hw)
2916 {
2917 	struct perf_event_pmu_context *epc = event->pmu_ctx;
2918 	struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu);
2919 
2920 	/*
2921 	 * Groups consisting entirely of software events can always go on.
2922 	 */
2923 	if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2924 		return 1;
2925 	/*
2926 	 * If an exclusive group is already on, no other hardware
2927 	 * events can go on.
2928 	 */
2929 	if (cpc->exclusive)
2930 		return 0;
2931 	/*
2932 	 * If this group is exclusive and there are already
2933 	 * events on the CPU, it can't go on.
2934 	 */
2935 	if (event->attr.exclusive && !list_empty(get_event_list(event)))
2936 		return 0;
2937 	/*
2938 	 * Otherwise, try to add it if all previous groups were able
2939 	 * to go on.
2940 	 */
2941 	return can_add_hw;
2942 }
2943 
2944 static void add_event_to_ctx(struct perf_event *event,
2945 			       struct perf_event_context *ctx)
2946 {
2947 	list_add_event(event, ctx);
2948 	perf_group_attach(event);
2949 }
2950 
2951 static void task_ctx_sched_out(struct perf_event_context *ctx,
2952 			       struct pmu *pmu,
2953 			       enum event_type_t event_type)
2954 {
2955 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2956 
2957 	if (!cpuctx->task_ctx)
2958 		return;
2959 
2960 	if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2961 		return;
2962 
2963 	ctx_sched_out(ctx, pmu, event_type);
2964 }
2965 
2966 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2967 				struct perf_event_context *ctx,
2968 				struct pmu *pmu,
2969 				enum event_type_t event_type)
2970 {
2971 	ctx_sched_in(&cpuctx->ctx, pmu, EVENT_PINNED | event_type);
2972 	if (ctx)
2973 		ctx_sched_in(ctx, pmu, EVENT_PINNED | event_type);
2974 	ctx_sched_in(&cpuctx->ctx, pmu, EVENT_FLEXIBLE | event_type);
2975 	if (ctx)
2976 		ctx_sched_in(ctx, pmu, EVENT_FLEXIBLE | event_type);
2977 }
2978 
2979 /*
2980  * We want to maintain the following priority of scheduling:
2981  *  - CPU pinned (EVENT_CPU | EVENT_PINNED)
2982  *  - task pinned (EVENT_PINNED)
2983  *  - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2984  *  - task flexible (EVENT_FLEXIBLE).
2985  *
2986  * In order to avoid unscheduling and scheduling back in everything every
2987  * time an event is added, only do it for the groups of equal priority and
2988  * below.
2989  *
2990  * This can be called after a batch operation on task events, in which case
2991  * event_type is a bit mask of the types of events involved. For CPU events,
2992  * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2993  */
2994 static void ctx_resched(struct perf_cpu_context *cpuctx,
2995 			struct perf_event_context *task_ctx,
2996 			struct pmu *pmu, enum event_type_t event_type)
2997 {
2998 	bool cpu_event = !!(event_type & EVENT_CPU);
2999 	struct perf_event_pmu_context *epc;
3000 
3001 	/*
3002 	 * If pinned groups are involved, flexible groups also need to be
3003 	 * scheduled out.
3004 	 */
3005 	if (event_type & EVENT_PINNED)
3006 		event_type |= EVENT_FLEXIBLE;
3007 
3008 	event_type &= EVENT_ALL;
3009 
3010 	for_each_epc(epc, &cpuctx->ctx, pmu, 0)
3011 		perf_pmu_disable(epc->pmu);
3012 
3013 	if (task_ctx) {
3014 		for_each_epc(epc, task_ctx, pmu, 0)
3015 			perf_pmu_disable(epc->pmu);
3016 
3017 		task_ctx_sched_out(task_ctx, pmu, event_type);
3018 	}
3019 
3020 	/*
3021 	 * Decide which cpu ctx groups to schedule out based on the types
3022 	 * of events that caused rescheduling:
3023 	 *  - EVENT_CPU: schedule out corresponding groups;
3024 	 *  - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
3025 	 *  - otherwise, do nothing more.
3026 	 */
3027 	if (cpu_event)
3028 		ctx_sched_out(&cpuctx->ctx, pmu, event_type);
3029 	else if (event_type & EVENT_PINNED)
3030 		ctx_sched_out(&cpuctx->ctx, pmu, EVENT_FLEXIBLE);
3031 
3032 	perf_event_sched_in(cpuctx, task_ctx, pmu, 0);
3033 
3034 	for_each_epc(epc, &cpuctx->ctx, pmu, 0)
3035 		perf_pmu_enable(epc->pmu);
3036 
3037 	if (task_ctx) {
3038 		for_each_epc(epc, task_ctx, pmu, 0)
3039 			perf_pmu_enable(epc->pmu);
3040 	}
3041 }
3042 
3043 void perf_pmu_resched(struct pmu *pmu)
3044 {
3045 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3046 	struct perf_event_context *task_ctx = cpuctx->task_ctx;
3047 
3048 	perf_ctx_lock(cpuctx, task_ctx);
3049 	ctx_resched(cpuctx, task_ctx, pmu, EVENT_ALL|EVENT_CPU);
3050 	perf_ctx_unlock(cpuctx, task_ctx);
3051 }
3052 
3053 /*
3054  * Cross CPU call to install and enable a performance event
3055  *
3056  * Very similar to remote_function() + event_function() but cannot assume that
3057  * things like ctx->is_active and cpuctx->task_ctx are set.
3058  */
3059 static int  __perf_install_in_context(void *info)
3060 {
3061 	struct perf_event *event = info;
3062 	struct perf_event_context *ctx = event->ctx;
3063 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3064 	struct perf_event_context *task_ctx = cpuctx->task_ctx;
3065 	bool reprogram = true;
3066 	int ret = 0;
3067 
3068 	raw_spin_lock(&cpuctx->ctx.lock);
3069 	if (ctx->task) {
3070 		raw_spin_lock(&ctx->lock);
3071 		task_ctx = ctx;
3072 
3073 		reprogram = (ctx->task == current);
3074 
3075 		/*
3076 		 * If the task is running, it must be running on this CPU,
3077 		 * otherwise we cannot reprogram things.
3078 		 *
3079 		 * If its not running, we don't care, ctx->lock will
3080 		 * serialize against it becoming runnable.
3081 		 */
3082 		if (task_curr(ctx->task) && !reprogram) {
3083 			ret = -ESRCH;
3084 			goto unlock;
3085 		}
3086 
3087 		WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
3088 	} else if (task_ctx) {
3089 		raw_spin_lock(&task_ctx->lock);
3090 	}
3091 
3092 #ifdef CONFIG_CGROUP_PERF
3093 	if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
3094 		/*
3095 		 * If the current cgroup doesn't match the event's
3096 		 * cgroup, we should not try to schedule it.
3097 		 */
3098 		struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
3099 		reprogram = cgroup_is_descendant(cgrp->css.cgroup,
3100 					event->cgrp->css.cgroup);
3101 	}
3102 #endif
3103 
3104 	if (reprogram) {
3105 		ctx_time_freeze(cpuctx, ctx);
3106 		add_event_to_ctx(event, ctx);
3107 		ctx_resched(cpuctx, task_ctx, event->pmu_ctx->pmu,
3108 			    get_event_type(event));
3109 	} else {
3110 		add_event_to_ctx(event, ctx);
3111 	}
3112 
3113 unlock:
3114 	perf_ctx_unlock(cpuctx, task_ctx);
3115 
3116 	return ret;
3117 }
3118 
3119 static bool exclusive_event_installable(struct perf_event *event,
3120 					struct perf_event_context *ctx);
3121 
3122 /*
3123  * Attach a performance event to a context.
3124  *
3125  * Very similar to event_function_call, see comment there.
3126  */
3127 static void
3128 perf_install_in_context(struct perf_event_context *ctx,
3129 			struct perf_event *event,
3130 			int cpu)
3131 {
3132 	struct task_struct *task = READ_ONCE(ctx->task);
3133 
3134 	lockdep_assert_held(&ctx->mutex);
3135 
3136 	WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
3137 
3138 	if (event->cpu != -1)
3139 		WARN_ON_ONCE(event->cpu != cpu);
3140 
3141 	/*
3142 	 * Ensures that if we can observe event->ctx, both the event and ctx
3143 	 * will be 'complete'. See perf_iterate_sb_cpu().
3144 	 */
3145 	smp_store_release(&event->ctx, ctx);
3146 
3147 	/*
3148 	 * perf_event_attr::disabled events will not run and can be initialized
3149 	 * without IPI. Except when this is the first event for the context, in
3150 	 * that case we need the magic of the IPI to set ctx->is_active.
3151 	 *
3152 	 * The IOC_ENABLE that is sure to follow the creation of a disabled
3153 	 * event will issue the IPI and reprogram the hardware.
3154 	 */
3155 	if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF &&
3156 	    ctx->nr_events && !is_cgroup_event(event)) {
3157 		raw_spin_lock_irq(&ctx->lock);
3158 		if (ctx->task == TASK_TOMBSTONE) {
3159 			raw_spin_unlock_irq(&ctx->lock);
3160 			return;
3161 		}
3162 		add_event_to_ctx(event, ctx);
3163 		raw_spin_unlock_irq(&ctx->lock);
3164 		return;
3165 	}
3166 
3167 	if (!task) {
3168 		cpu_function_call(cpu, __perf_install_in_context, event);
3169 		return;
3170 	}
3171 
3172 	/*
3173 	 * Should not happen, we validate the ctx is still alive before calling.
3174 	 */
3175 	if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
3176 		return;
3177 
3178 	/*
3179 	 * Installing events is tricky because we cannot rely on ctx->is_active
3180 	 * to be set in case this is the nr_events 0 -> 1 transition.
3181 	 *
3182 	 * Instead we use task_curr(), which tells us if the task is running.
3183 	 * However, since we use task_curr() outside of rq::lock, we can race
3184 	 * against the actual state. This means the result can be wrong.
3185 	 *
3186 	 * If we get a false positive, we retry, this is harmless.
3187 	 *
3188 	 * If we get a false negative, things are complicated. If we are after
3189 	 * perf_event_context_sched_in() ctx::lock will serialize us, and the
3190 	 * value must be correct. If we're before, it doesn't matter since
3191 	 * perf_event_context_sched_in() will program the counter.
3192 	 *
3193 	 * However, this hinges on the remote context switch having observed
3194 	 * our task->perf_event_ctxp[] store, such that it will in fact take
3195 	 * ctx::lock in perf_event_context_sched_in().
3196 	 *
3197 	 * We do this by task_function_call(), if the IPI fails to hit the task
3198 	 * we know any future context switch of task must see the
3199 	 * perf_event_ctpx[] store.
3200 	 */
3201 
3202 	/*
3203 	 * This smp_mb() orders the task->perf_event_ctxp[] store with the
3204 	 * task_cpu() load, such that if the IPI then does not find the task
3205 	 * running, a future context switch of that task must observe the
3206 	 * store.
3207 	 */
3208 	smp_mb();
3209 again:
3210 	if (!task_function_call(task, __perf_install_in_context, event))
3211 		return;
3212 
3213 	raw_spin_lock_irq(&ctx->lock);
3214 	task = ctx->task;
3215 	if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
3216 		/*
3217 		 * Cannot happen because we already checked above (which also
3218 		 * cannot happen), and we hold ctx->mutex, which serializes us
3219 		 * against perf_event_exit_task_context().
3220 		 */
3221 		raw_spin_unlock_irq(&ctx->lock);
3222 		return;
3223 	}
3224 	/*
3225 	 * If the task is not running, ctx->lock will avoid it becoming so,
3226 	 * thus we can safely install the event.
3227 	 */
3228 	if (task_curr(task)) {
3229 		raw_spin_unlock_irq(&ctx->lock);
3230 		goto again;
3231 	}
3232 	add_event_to_ctx(event, ctx);
3233 	raw_spin_unlock_irq(&ctx->lock);
3234 }
3235 
3236 /*
3237  * Cross CPU call to enable a performance event
3238  */
3239 static void __perf_event_enable(struct perf_event *event,
3240 				struct perf_cpu_context *cpuctx,
3241 				struct perf_event_context *ctx,
3242 				void *info)
3243 {
3244 	struct perf_event *leader = event->group_leader;
3245 	struct perf_event_context *task_ctx;
3246 
3247 	if (event->state >= PERF_EVENT_STATE_INACTIVE ||
3248 	    event->state <= PERF_EVENT_STATE_ERROR)
3249 		return;
3250 
3251 	ctx_time_freeze(cpuctx, ctx);
3252 
3253 	perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
3254 	perf_cgroup_event_enable(event, ctx);
3255 
3256 	if (!ctx->is_active)
3257 		return;
3258 
3259 	if (!event_filter_match(event))
3260 		return;
3261 
3262 	/*
3263 	 * If the event is in a group and isn't the group leader,
3264 	 * then don't put it on unless the group is on.
3265 	 */
3266 	if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
3267 		return;
3268 
3269 	task_ctx = cpuctx->task_ctx;
3270 	if (ctx->task)
3271 		WARN_ON_ONCE(task_ctx != ctx);
3272 
3273 	ctx_resched(cpuctx, task_ctx, event->pmu_ctx->pmu, get_event_type(event));
3274 }
3275 
3276 /*
3277  * Enable an event.
3278  *
3279  * If event->ctx is a cloned context, callers must make sure that
3280  * every task struct that event->ctx->task could possibly point to
3281  * remains valid.  This condition is satisfied when called through
3282  * perf_event_for_each_child or perf_event_for_each as described
3283  * for perf_event_disable.
3284  */
3285 static void _perf_event_enable(struct perf_event *event)
3286 {
3287 	struct perf_event_context *ctx = event->ctx;
3288 
3289 	raw_spin_lock_irq(&ctx->lock);
3290 	if (event->state >= PERF_EVENT_STATE_INACTIVE ||
3291 	    event->state <  PERF_EVENT_STATE_ERROR) {
3292 out:
3293 		raw_spin_unlock_irq(&ctx->lock);
3294 		return;
3295 	}
3296 
3297 	/*
3298 	 * If the event is in error state, clear that first.
3299 	 *
3300 	 * That way, if we see the event in error state below, we know that it
3301 	 * has gone back into error state, as distinct from the task having
3302 	 * been scheduled away before the cross-call arrived.
3303 	 */
3304 	if (event->state == PERF_EVENT_STATE_ERROR) {
3305 		/*
3306 		 * Detached SIBLING events cannot leave ERROR state.
3307 		 */
3308 		if (event->event_caps & PERF_EV_CAP_SIBLING &&
3309 		    event->group_leader == event)
3310 			goto out;
3311 
3312 		event->state = PERF_EVENT_STATE_OFF;
3313 	}
3314 	raw_spin_unlock_irq(&ctx->lock);
3315 
3316 	event_function_call(event, __perf_event_enable, NULL);
3317 }
3318 
3319 /*
3320  * See perf_event_disable();
3321  */
3322 void perf_event_enable(struct perf_event *event)
3323 {
3324 	struct perf_event_context *ctx;
3325 
3326 	ctx = perf_event_ctx_lock(event);
3327 	_perf_event_enable(event);
3328 	perf_event_ctx_unlock(event, ctx);
3329 }
3330 EXPORT_SYMBOL_GPL(perf_event_enable);
3331 
3332 struct stop_event_data {
3333 	struct perf_event	*event;
3334 	unsigned int		restart;
3335 };
3336 
3337 static int __perf_event_stop(void *info)
3338 {
3339 	struct stop_event_data *sd = info;
3340 	struct perf_event *event = sd->event;
3341 
3342 	/* if it's already INACTIVE, do nothing */
3343 	if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3344 		return 0;
3345 
3346 	/* matches smp_wmb() in event_sched_in() */
3347 	smp_rmb();
3348 
3349 	/*
3350 	 * There is a window with interrupts enabled before we get here,
3351 	 * so we need to check again lest we try to stop another CPU's event.
3352 	 */
3353 	if (READ_ONCE(event->oncpu) != smp_processor_id())
3354 		return -EAGAIN;
3355 
3356 	event->pmu->stop(event, PERF_EF_UPDATE);
3357 
3358 	/*
3359 	 * May race with the actual stop (through perf_pmu_output_stop()),
3360 	 * but it is only used for events with AUX ring buffer, and such
3361 	 * events will refuse to restart because of rb::aux_mmap_count==0,
3362 	 * see comments in perf_aux_output_begin().
3363 	 *
3364 	 * Since this is happening on an event-local CPU, no trace is lost
3365 	 * while restarting.
3366 	 */
3367 	if (sd->restart)
3368 		event->pmu->start(event, 0);
3369 
3370 	return 0;
3371 }
3372 
3373 static int perf_event_stop(struct perf_event *event, int restart)
3374 {
3375 	struct stop_event_data sd = {
3376 		.event		= event,
3377 		.restart	= restart,
3378 	};
3379 	int ret = 0;
3380 
3381 	do {
3382 		if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3383 			return 0;
3384 
3385 		/* matches smp_wmb() in event_sched_in() */
3386 		smp_rmb();
3387 
3388 		/*
3389 		 * We only want to restart ACTIVE events, so if the event goes
3390 		 * inactive here (event->oncpu==-1), there's nothing more to do;
3391 		 * fall through with ret==-ENXIO.
3392 		 */
3393 		ret = cpu_function_call(READ_ONCE(event->oncpu),
3394 					__perf_event_stop, &sd);
3395 	} while (ret == -EAGAIN);
3396 
3397 	return ret;
3398 }
3399 
3400 /*
3401  * In order to contain the amount of racy and tricky in the address filter
3402  * configuration management, it is a two part process:
3403  *
3404  * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3405  *      we update the addresses of corresponding vmas in
3406  *	event::addr_filter_ranges array and bump the event::addr_filters_gen;
3407  * (p2) when an event is scheduled in (pmu::add), it calls
3408  *      perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3409  *      if the generation has changed since the previous call.
3410  *
3411  * If (p1) happens while the event is active, we restart it to force (p2).
3412  *
3413  * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3414  *     pre-existing mappings, called once when new filters arrive via SET_FILTER
3415  *     ioctl;
3416  * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3417  *     registered mapping, called for every new mmap(), with mm::mmap_lock down
3418  *     for reading;
3419  * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3420  *     of exec.
3421  */
3422 void perf_event_addr_filters_sync(struct perf_event *event)
3423 {
3424 	struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3425 
3426 	if (!has_addr_filter(event))
3427 		return;
3428 
3429 	raw_spin_lock(&ifh->lock);
3430 	if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3431 		event->pmu->addr_filters_sync(event);
3432 		event->hw.addr_filters_gen = event->addr_filters_gen;
3433 	}
3434 	raw_spin_unlock(&ifh->lock);
3435 }
3436 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3437 
3438 static int _perf_event_refresh(struct perf_event *event, int refresh)
3439 {
3440 	/*
3441 	 * not supported on inherited events
3442 	 */
3443 	if (event->attr.inherit || !is_sampling_event(event))
3444 		return -EINVAL;
3445 
3446 	atomic_add(refresh, &event->event_limit);
3447 	_perf_event_enable(event);
3448 
3449 	return 0;
3450 }
3451 
3452 /*
3453  * See perf_event_disable()
3454  */
3455 int perf_event_refresh(struct perf_event *event, int refresh)
3456 {
3457 	struct perf_event_context *ctx;
3458 	int ret;
3459 
3460 	ctx = perf_event_ctx_lock(event);
3461 	ret = _perf_event_refresh(event, refresh);
3462 	perf_event_ctx_unlock(event, ctx);
3463 
3464 	return ret;
3465 }
3466 EXPORT_SYMBOL_GPL(perf_event_refresh);
3467 
3468 static int perf_event_modify_breakpoint(struct perf_event *bp,
3469 					 struct perf_event_attr *attr)
3470 {
3471 	int err;
3472 
3473 	_perf_event_disable(bp);
3474 
3475 	err = modify_user_hw_breakpoint_check(bp, attr, true);
3476 
3477 	if (!bp->attr.disabled)
3478 		_perf_event_enable(bp);
3479 
3480 	return err;
3481 }
3482 
3483 /*
3484  * Copy event-type-independent attributes that may be modified.
3485  */
3486 static void perf_event_modify_copy_attr(struct perf_event_attr *to,
3487 					const struct perf_event_attr *from)
3488 {
3489 	to->sig_data = from->sig_data;
3490 }
3491 
3492 static int perf_event_modify_attr(struct perf_event *event,
3493 				  struct perf_event_attr *attr)
3494 {
3495 	int (*func)(struct perf_event *, struct perf_event_attr *);
3496 	struct perf_event *child;
3497 	int err;
3498 
3499 	if (event->attr.type != attr->type)
3500 		return -EINVAL;
3501 
3502 	switch (event->attr.type) {
3503 	case PERF_TYPE_BREAKPOINT:
3504 		func = perf_event_modify_breakpoint;
3505 		break;
3506 	default:
3507 		/* Place holder for future additions. */
3508 		return -EOPNOTSUPP;
3509 	}
3510 
3511 	WARN_ON_ONCE(event->ctx->parent_ctx);
3512 
3513 	mutex_lock(&event->child_mutex);
3514 	/*
3515 	 * Event-type-independent attributes must be copied before event-type
3516 	 * modification, which will validate that final attributes match the
3517 	 * source attributes after all relevant attributes have been copied.
3518 	 */
3519 	perf_event_modify_copy_attr(&event->attr, attr);
3520 	err = func(event, attr);
3521 	if (err)
3522 		goto out;
3523 	list_for_each_entry(child, &event->child_list, child_list) {
3524 		perf_event_modify_copy_attr(&child->attr, attr);
3525 		err = func(child, attr);
3526 		if (err)
3527 			goto out;
3528 	}
3529 out:
3530 	mutex_unlock(&event->child_mutex);
3531 	return err;
3532 }
3533 
3534 static void __pmu_ctx_sched_out(struct perf_event_pmu_context *pmu_ctx,
3535 				enum event_type_t event_type)
3536 {
3537 	struct perf_event_context *ctx = pmu_ctx->ctx;
3538 	struct perf_event *event, *tmp;
3539 	struct pmu *pmu = pmu_ctx->pmu;
3540 
3541 	if (ctx->task && !(ctx->is_active & EVENT_ALL)) {
3542 		struct perf_cpu_pmu_context *cpc = this_cpc(pmu);
3543 
3544 		WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
3545 		cpc->task_epc = NULL;
3546 	}
3547 
3548 	if (!(event_type & EVENT_ALL))
3549 		return;
3550 
3551 	perf_pmu_disable(pmu);
3552 	if (event_type & EVENT_PINNED) {
3553 		list_for_each_entry_safe(event, tmp,
3554 					 &pmu_ctx->pinned_active,
3555 					 active_list)
3556 			group_sched_out(event, ctx);
3557 	}
3558 
3559 	if (event_type & EVENT_FLEXIBLE) {
3560 		list_for_each_entry_safe(event, tmp,
3561 					 &pmu_ctx->flexible_active,
3562 					 active_list)
3563 			group_sched_out(event, ctx);
3564 		/*
3565 		 * Since we cleared EVENT_FLEXIBLE, also clear
3566 		 * rotate_necessary, is will be reset by
3567 		 * ctx_flexible_sched_in() when needed.
3568 		 */
3569 		pmu_ctx->rotate_necessary = 0;
3570 	}
3571 	perf_pmu_enable(pmu);
3572 }
3573 
3574 /*
3575  * Be very careful with the @pmu argument since this will change ctx state.
3576  * The @pmu argument works for ctx_resched(), because that is symmetric in
3577  * ctx_sched_out() / ctx_sched_in() usage and the ctx state ends up invariant.
3578  *
3579  * However, if you were to be asymmetrical, you could end up with messed up
3580  * state, eg. ctx->is_active cleared even though most EPCs would still actually
3581  * be active.
3582  */
3583 static void
3584 ctx_sched_out(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type)
3585 {
3586 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3587 	enum event_type_t active_type = event_type & ~EVENT_FLAGS;
3588 	struct perf_event_pmu_context *pmu_ctx;
3589 	int is_active = ctx->is_active;
3590 
3591 
3592 	lockdep_assert_held(&ctx->lock);
3593 
3594 	if (likely(!ctx->nr_events)) {
3595 		/*
3596 		 * See __perf_remove_from_context().
3597 		 */
3598 		WARN_ON_ONCE(ctx->is_active);
3599 		if (ctx->task)
3600 			WARN_ON_ONCE(cpuctx->task_ctx);
3601 		return;
3602 	}
3603 
3604 	/*
3605 	 * Always update time if it was set; not only when it changes.
3606 	 * Otherwise we can 'forget' to update time for any but the last
3607 	 * context we sched out. For example:
3608 	 *
3609 	 *   ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3610 	 *   ctx_sched_out(.event_type = EVENT_PINNED)
3611 	 *
3612 	 * would only update time for the pinned events.
3613 	 */
3614 	__ctx_time_update(cpuctx, ctx, ctx == &cpuctx->ctx, event_type);
3615 
3616 	/*
3617 	 * CPU-release for the below ->is_active store,
3618 	 * see __load_acquire() in perf_event_time_now()
3619 	 */
3620 	barrier();
3621 	ctx->is_active &= ~active_type;
3622 
3623 	if (!(ctx->is_active & EVENT_ALL)) {
3624 		/*
3625 		 * For FROZEN, preserve TIME|FROZEN such that perf_event_time_now()
3626 		 * does not observe a hole. perf_ctx_unlock() will clean up.
3627 		 */
3628 		if (ctx->is_active & EVENT_FROZEN)
3629 			ctx->is_active &= EVENT_TIME_FROZEN;
3630 		else
3631 			ctx->is_active = 0;
3632 	}
3633 
3634 	if (ctx->task) {
3635 		WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3636 		if (!(ctx->is_active & EVENT_ALL))
3637 			cpuctx->task_ctx = NULL;
3638 	}
3639 
3640 	if (event_type & EVENT_GUEST) {
3641 		/*
3642 		 * Schedule out all exclude_guest events of PMU
3643 		 * with PERF_PMU_CAP_MEDIATED_VPMU.
3644 		 */
3645 		is_active = EVENT_ALL;
3646 		__update_context_guest_time(ctx, false);
3647 		perf_cgroup_set_timestamp(cpuctx, true);
3648 		barrier();
3649 	} else {
3650 		is_active ^= ctx->is_active; /* changed bits */
3651 	}
3652 
3653 	for_each_epc(pmu_ctx, ctx, pmu, event_type)
3654 		__pmu_ctx_sched_out(pmu_ctx, is_active);
3655 }
3656 
3657 /*
3658  * Test whether two contexts are equivalent, i.e. whether they have both been
3659  * cloned from the same version of the same context.
3660  *
3661  * Equivalence is measured using a generation number in the context that is
3662  * incremented on each modification to it; see unclone_ctx(), list_add_event()
3663  * and list_del_event().
3664  */
3665 static int context_equiv(struct perf_event_context *ctx1,
3666 			 struct perf_event_context *ctx2)
3667 {
3668 	lockdep_assert_held(&ctx1->lock);
3669 	lockdep_assert_held(&ctx2->lock);
3670 
3671 	/* Pinning disables the swap optimization */
3672 	if (ctx1->pin_count || ctx2->pin_count)
3673 		return 0;
3674 
3675 	/* If ctx1 is the parent of ctx2 */
3676 	if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3677 		return 1;
3678 
3679 	/* If ctx2 is the parent of ctx1 */
3680 	if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3681 		return 1;
3682 
3683 	/*
3684 	 * If ctx1 and ctx2 have the same parent; we flatten the parent
3685 	 * hierarchy, see perf_event_init_context().
3686 	 */
3687 	if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3688 			ctx1->parent_gen == ctx2->parent_gen)
3689 		return 1;
3690 
3691 	/* Unmatched */
3692 	return 0;
3693 }
3694 
3695 static void __perf_event_sync_stat(struct perf_event *event,
3696 				     struct perf_event *next_event)
3697 {
3698 	u64 value;
3699 
3700 	if (!event->attr.inherit_stat)
3701 		return;
3702 
3703 	/*
3704 	 * Update the event value, we cannot use perf_event_read()
3705 	 * because we're in the middle of a context switch and have IRQs
3706 	 * disabled, which upsets smp_call_function_single(), however
3707 	 * we know the event must be on the current CPU, therefore we
3708 	 * don't need to use it.
3709 	 */
3710 	perf_pmu_read(event);
3711 
3712 	perf_event_update_time(event);
3713 
3714 	/*
3715 	 * In order to keep per-task stats reliable we need to flip the event
3716 	 * values when we flip the contexts.
3717 	 */
3718 	value = local64_read(&next_event->count);
3719 	value = local64_xchg(&event->count, value);
3720 	local64_set(&next_event->count, value);
3721 
3722 	swap(event->total_time_enabled, next_event->total_time_enabled);
3723 	swap(event->total_time_running, next_event->total_time_running);
3724 
3725 	/*
3726 	 * Since we swizzled the values, update the user visible data too.
3727 	 */
3728 	perf_event_update_userpage(event);
3729 	perf_event_update_userpage(next_event);
3730 }
3731 
3732 static void perf_event_sync_stat(struct perf_event_context *ctx,
3733 				   struct perf_event_context *next_ctx)
3734 {
3735 	struct perf_event *event, *next_event;
3736 
3737 	if (!ctx->nr_stat)
3738 		return;
3739 
3740 	update_context_time(ctx);
3741 
3742 	event = list_first_entry(&ctx->event_list,
3743 				   struct perf_event, event_entry);
3744 
3745 	next_event = list_first_entry(&next_ctx->event_list,
3746 					struct perf_event, event_entry);
3747 
3748 	while (&event->event_entry != &ctx->event_list &&
3749 	       &next_event->event_entry != &next_ctx->event_list) {
3750 
3751 		__perf_event_sync_stat(event, next_event);
3752 
3753 		event = list_next_entry(event, event_entry);
3754 		next_event = list_next_entry(next_event, event_entry);
3755 	}
3756 }
3757 
3758 static void perf_ctx_sched_task_cb(struct perf_event_context *ctx,
3759 				   struct task_struct *task, bool sched_in)
3760 {
3761 	struct perf_event_pmu_context *pmu_ctx;
3762 	struct perf_cpu_pmu_context *cpc;
3763 
3764 	list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
3765 		cpc = this_cpc(pmu_ctx->pmu);
3766 
3767 		if (cpc->task_epc != pmu_ctx)
3768 			continue;
3769 
3770 		if (cpc->sched_cb_usage && pmu_ctx->pmu->sched_task)
3771 			pmu_ctx->pmu->sched_task(pmu_ctx, task, sched_in);
3772 	}
3773 }
3774 
3775 static void
3776 perf_event_context_sched_out(struct task_struct *task, struct task_struct *next)
3777 {
3778 	struct perf_event_context *ctx = task->perf_event_ctxp;
3779 	struct perf_event_context *next_ctx;
3780 	struct perf_event_context *parent, *next_parent;
3781 	int do_switch = 1;
3782 
3783 	if (likely(!ctx))
3784 		return;
3785 
3786 	rcu_read_lock();
3787 	next_ctx = rcu_dereference(next->perf_event_ctxp);
3788 	if (!next_ctx)
3789 		goto unlock;
3790 
3791 	parent = rcu_dereference(ctx->parent_ctx);
3792 	next_parent = rcu_dereference(next_ctx->parent_ctx);
3793 
3794 	/* If neither context have a parent context; they cannot be clones. */
3795 	if (!parent && !next_parent)
3796 		goto unlock;
3797 
3798 	if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3799 		/*
3800 		 * Looks like the two contexts are clones, so we might be
3801 		 * able to optimize the context switch.  We lock both
3802 		 * contexts and check that they are clones under the
3803 		 * lock (including re-checking that neither has been
3804 		 * uncloned in the meantime).  It doesn't matter which
3805 		 * order we take the locks because no other cpu could
3806 		 * be trying to lock both of these tasks.
3807 		 */
3808 		raw_spin_lock(&ctx->lock);
3809 		raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3810 		if (context_equiv(ctx, next_ctx)) {
3811 
3812 			perf_ctx_disable(ctx, 0);
3813 
3814 			/* PMIs are disabled; ctx->nr_no_switch_fast is stable. */
3815 			if (local_read(&ctx->nr_no_switch_fast) ||
3816 			    local_read(&next_ctx->nr_no_switch_fast)) {
3817 				/*
3818 				 * Must not swap out ctx when there's pending
3819 				 * events that rely on the ctx->task relation.
3820 				 *
3821 				 * Likewise, when a context contains inherit +
3822 				 * SAMPLE_READ events they should be switched
3823 				 * out using the slow path so that they are
3824 				 * treated as if they were distinct contexts.
3825 				 */
3826 				raw_spin_unlock(&next_ctx->lock);
3827 				rcu_read_unlock();
3828 				goto inside_switch;
3829 			}
3830 
3831 			WRITE_ONCE(ctx->task, next);
3832 			WRITE_ONCE(next_ctx->task, task);
3833 
3834 			perf_ctx_sched_task_cb(ctx, task, false);
3835 
3836 			perf_ctx_enable(ctx, 0);
3837 
3838 			/*
3839 			 * RCU_INIT_POINTER here is safe because we've not
3840 			 * modified the ctx and the above modification of
3841 			 * ctx->task is immaterial since this value is
3842 			 * always verified under ctx->lock which we're now
3843 			 * holding.
3844 			 */
3845 			RCU_INIT_POINTER(task->perf_event_ctxp, next_ctx);
3846 			RCU_INIT_POINTER(next->perf_event_ctxp, ctx);
3847 
3848 			do_switch = 0;
3849 
3850 			perf_event_sync_stat(ctx, next_ctx);
3851 		}
3852 		raw_spin_unlock(&next_ctx->lock);
3853 		raw_spin_unlock(&ctx->lock);
3854 	}
3855 unlock:
3856 	rcu_read_unlock();
3857 
3858 	if (do_switch) {
3859 		raw_spin_lock(&ctx->lock);
3860 		perf_ctx_disable(ctx, 0);
3861 
3862 inside_switch:
3863 		perf_ctx_sched_task_cb(ctx, task, false);
3864 		task_ctx_sched_out(ctx, NULL, EVENT_ALL);
3865 
3866 		perf_ctx_enable(ctx, 0);
3867 		raw_spin_unlock(&ctx->lock);
3868 	}
3869 }
3870 
3871 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3872 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
3873 
3874 void perf_sched_cb_dec(struct pmu *pmu)
3875 {
3876 	struct perf_cpu_pmu_context *cpc = this_cpc(pmu);
3877 
3878 	this_cpu_dec(perf_sched_cb_usages);
3879 	barrier();
3880 
3881 	if (!--cpc->sched_cb_usage)
3882 		list_del(&cpc->sched_cb_entry);
3883 }
3884 
3885 
3886 void perf_sched_cb_inc(struct pmu *pmu)
3887 {
3888 	struct perf_cpu_pmu_context *cpc = this_cpc(pmu);
3889 
3890 	if (!cpc->sched_cb_usage++)
3891 		list_add(&cpc->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3892 
3893 	barrier();
3894 	this_cpu_inc(perf_sched_cb_usages);
3895 }
3896 
3897 /*
3898  * This function provides the context switch callback to the lower code
3899  * layer. It is invoked ONLY when the context switch callback is enabled.
3900  *
3901  * This callback is relevant even to per-cpu events; for example multi event
3902  * PEBS requires this to provide PID/TID information. This requires we flush
3903  * all queued PEBS records before we context switch to a new task.
3904  */
3905 static void __perf_pmu_sched_task(struct perf_cpu_pmu_context *cpc,
3906 				  struct task_struct *task, bool sched_in)
3907 {
3908 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3909 	struct pmu *pmu;
3910 
3911 	pmu = cpc->epc.pmu;
3912 
3913 	/* software PMUs will not have sched_task */
3914 	if (WARN_ON_ONCE(!pmu->sched_task))
3915 		return;
3916 
3917 	perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3918 	perf_pmu_disable(pmu);
3919 
3920 	pmu->sched_task(&cpc->epc, task, sched_in);
3921 
3922 	perf_pmu_enable(pmu);
3923 	perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3924 }
3925 
3926 static void perf_pmu_sched_task(struct task_struct *prev,
3927 				struct task_struct *next,
3928 				bool sched_in)
3929 {
3930 	struct perf_cpu_pmu_context *cpc, *cpc2;
3931 
3932 	if (prev == next)
3933 		return;
3934 
3935 	list_for_each_entry_safe(cpc, cpc2, this_cpu_ptr(&sched_cb_list), sched_cb_entry) {
3936 		if (cpc->task_epc)
3937 			continue;
3938 
3939 		__perf_pmu_sched_task(cpc, sched_in ? next : prev, sched_in);
3940 	}
3941 }
3942 
3943 static void perf_event_switch(struct task_struct *task,
3944 			      struct task_struct *next_prev, bool sched_in);
3945 
3946 /*
3947  * Called from scheduler to remove the events of the current task,
3948  * with interrupts disabled.
3949  *
3950  * We stop each event and update the event value in event->count.
3951  *
3952  * This does not protect us against NMI, but disable()
3953  * sets the disabled bit in the control field of event _before_
3954  * accessing the event control register. If a NMI hits, then it will
3955  * not restart the event.
3956  */
3957 void __perf_event_task_sched_out(struct task_struct *task,
3958 				 struct task_struct *next)
3959 {
3960 	if (__this_cpu_read(perf_sched_cb_usages))
3961 		perf_pmu_sched_task(task, next, false);
3962 
3963 	if (atomic_read(&nr_switch_events))
3964 		perf_event_switch(task, next, false);
3965 
3966 	perf_event_context_sched_out(task, next);
3967 
3968 	/*
3969 	 * if cgroup events exist on this CPU, then we need
3970 	 * to check if we have to switch out PMU state.
3971 	 * cgroup event are system-wide mode only
3972 	 */
3973 	perf_cgroup_switch(next);
3974 }
3975 
3976 static bool perf_less_group_idx(const void *l, const void *r, void __always_unused *args)
3977 {
3978 	const struct perf_event *le = *(const struct perf_event **)l;
3979 	const struct perf_event *re = *(const struct perf_event **)r;
3980 
3981 	return le->group_index < re->group_index;
3982 }
3983 
3984 DEFINE_MIN_HEAP(struct perf_event *, perf_event_min_heap);
3985 
3986 static const struct min_heap_callbacks perf_min_heap = {
3987 	.less = perf_less_group_idx,
3988 	.swp = NULL,
3989 };
3990 
3991 static void __heap_add(struct perf_event_min_heap *heap, struct perf_event *event)
3992 {
3993 	struct perf_event **itrs = heap->data;
3994 
3995 	if (event) {
3996 		itrs[heap->nr] = event;
3997 		heap->nr++;
3998 	}
3999 }
4000 
4001 static void __link_epc(struct perf_event_pmu_context *pmu_ctx)
4002 {
4003 	struct perf_cpu_pmu_context *cpc;
4004 
4005 	if (!pmu_ctx->ctx->task)
4006 		return;
4007 
4008 	cpc = this_cpc(pmu_ctx->pmu);
4009 	WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
4010 	cpc->task_epc = pmu_ctx;
4011 }
4012 
4013 static noinline int visit_groups_merge(struct perf_event_context *ctx,
4014 				struct perf_event_groups *groups, int cpu,
4015 				struct pmu *pmu,
4016 				int (*func)(struct perf_event *, void *),
4017 				void *data)
4018 {
4019 #ifdef CONFIG_CGROUP_PERF
4020 	struct cgroup_subsys_state *css = NULL;
4021 #endif
4022 	struct perf_cpu_context *cpuctx = NULL;
4023 	/* Space for per CPU and/or any CPU event iterators. */
4024 	struct perf_event *itrs[2];
4025 	struct perf_event_min_heap event_heap;
4026 	struct perf_event **evt;
4027 	int ret;
4028 
4029 	if (pmu->filter && pmu->filter(pmu, cpu))
4030 		return 0;
4031 
4032 	if (!ctx->task) {
4033 		cpuctx = this_cpu_ptr(&perf_cpu_context);
4034 		event_heap = (struct perf_event_min_heap){
4035 			.data = cpuctx->heap,
4036 			.nr = 0,
4037 			.size = cpuctx->heap_size,
4038 		};
4039 
4040 		lockdep_assert_held(&cpuctx->ctx.lock);
4041 
4042 #ifdef CONFIG_CGROUP_PERF
4043 		if (cpuctx->cgrp)
4044 			css = &cpuctx->cgrp->css;
4045 #endif
4046 	} else {
4047 		event_heap = (struct perf_event_min_heap){
4048 			.data = itrs,
4049 			.nr = 0,
4050 			.size = ARRAY_SIZE(itrs),
4051 		};
4052 		/* Events not within a CPU context may be on any CPU. */
4053 		__heap_add(&event_heap, perf_event_groups_first(groups, -1, pmu, NULL));
4054 	}
4055 	evt = event_heap.data;
4056 
4057 	__heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, NULL));
4058 
4059 #ifdef CONFIG_CGROUP_PERF
4060 	for (; css; css = css->parent)
4061 		__heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, css->cgroup));
4062 #endif
4063 
4064 	if (event_heap.nr) {
4065 		__link_epc((*evt)->pmu_ctx);
4066 		perf_assert_pmu_disabled((*evt)->pmu_ctx->pmu);
4067 	}
4068 
4069 	min_heapify_all_inline(&event_heap, &perf_min_heap, NULL);
4070 
4071 	while (event_heap.nr) {
4072 		ret = func(*evt, data);
4073 		if (ret)
4074 			return ret;
4075 
4076 		*evt = perf_event_groups_next(*evt, pmu);
4077 		if (*evt)
4078 			min_heap_sift_down_inline(&event_heap, 0, &perf_min_heap, NULL);
4079 		else
4080 			min_heap_pop_inline(&event_heap, &perf_min_heap, NULL);
4081 	}
4082 
4083 	return 0;
4084 }
4085 
4086 /*
4087  * Because the userpage is strictly per-event (there is no concept of context,
4088  * so there cannot be a context indirection), every userpage must be updated
4089  * when context time starts :-(
4090  *
4091  * IOW, we must not miss EVENT_TIME edges.
4092  */
4093 static inline bool event_update_userpage(struct perf_event *event)
4094 {
4095 	if (likely(!refcount_read(&event->mmap_count)))
4096 		return false;
4097 
4098 	perf_event_update_time(event);
4099 	perf_event_update_userpage(event);
4100 
4101 	return true;
4102 }
4103 
4104 static inline void group_update_userpage(struct perf_event *group_event)
4105 {
4106 	struct perf_event *event;
4107 
4108 	if (!event_update_userpage(group_event))
4109 		return;
4110 
4111 	for_each_sibling_event(event, group_event)
4112 		event_update_userpage(event);
4113 }
4114 
4115 struct merge_sched_data {
4116 	int can_add_hw;
4117 	enum event_type_t event_type;
4118 };
4119 
4120 static int merge_sched_in(struct perf_event *event, void *data)
4121 {
4122 	struct perf_event_context *ctx = event->ctx;
4123 	struct merge_sched_data *msd = data;
4124 
4125 	if (event->state <= PERF_EVENT_STATE_OFF)
4126 		return 0;
4127 
4128 	if (!event_filter_match(event))
4129 		return 0;
4130 
4131 	/*
4132 	 * Don't schedule in any host events from PMU with
4133 	 * PERF_PMU_CAP_MEDIATED_VPMU, while a guest is running.
4134 	 */
4135 	if (is_guest_mediated_pmu_loaded() &&
4136 	    event->pmu_ctx->pmu->capabilities & PERF_PMU_CAP_MEDIATED_VPMU &&
4137 	    !(msd->event_type & EVENT_GUEST))
4138 		return 0;
4139 
4140 	if (group_can_go_on(event, msd->can_add_hw)) {
4141 		if (!group_sched_in(event, ctx))
4142 			list_add_tail(&event->active_list, get_event_list(event));
4143 	}
4144 
4145 	if (event->state == PERF_EVENT_STATE_INACTIVE) {
4146 		msd->can_add_hw = 0;
4147 		if (event->attr.pinned) {
4148 			perf_cgroup_event_disable(event, ctx);
4149 			perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
4150 
4151 			if (*perf_event_fasync(event))
4152 				event->pending_kill = POLL_ERR;
4153 
4154 			event->pending_wakeup = 1;
4155 			irq_work_queue(&event->pending_irq);
4156 		} else {
4157 			struct perf_cpu_pmu_context *cpc = this_cpc(event->pmu_ctx->pmu);
4158 
4159 			event->pmu_ctx->rotate_necessary = 1;
4160 			perf_mux_hrtimer_restart(cpc);
4161 			group_update_userpage(event);
4162 		}
4163 	}
4164 
4165 	return 0;
4166 }
4167 
4168 static void pmu_groups_sched_in(struct perf_event_context *ctx,
4169 				struct perf_event_groups *groups,
4170 				struct pmu *pmu,
4171 				enum event_type_t event_type)
4172 {
4173 	struct merge_sched_data msd = {
4174 		.can_add_hw = 1,
4175 		.event_type = event_type,
4176 	};
4177 	visit_groups_merge(ctx, groups, smp_processor_id(), pmu,
4178 			   merge_sched_in, &msd);
4179 }
4180 
4181 static void __pmu_ctx_sched_in(struct perf_event_pmu_context *pmu_ctx,
4182 			       enum event_type_t event_type)
4183 {
4184 	struct perf_event_context *ctx = pmu_ctx->ctx;
4185 
4186 	if (event_type & EVENT_PINNED)
4187 		pmu_groups_sched_in(ctx, &ctx->pinned_groups, pmu_ctx->pmu, event_type);
4188 	if (event_type & EVENT_FLEXIBLE)
4189 		pmu_groups_sched_in(ctx, &ctx->flexible_groups, pmu_ctx->pmu, event_type);
4190 }
4191 
4192 static void
4193 ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type)
4194 {
4195 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4196 	enum event_type_t active_type = event_type & ~EVENT_FLAGS;
4197 	struct perf_event_pmu_context *pmu_ctx;
4198 	int is_active = ctx->is_active;
4199 
4200 	lockdep_assert_held(&ctx->lock);
4201 
4202 	if (likely(!ctx->nr_events))
4203 		return;
4204 
4205 	if (!(is_active & EVENT_TIME)) {
4206 		/* EVENT_TIME should be active while the guest runs */
4207 		WARN_ON_ONCE(event_type & EVENT_GUEST);
4208 		/* start ctx time */
4209 		__update_context_time(ctx, false);
4210 		perf_cgroup_set_timestamp(cpuctx, false);
4211 		/*
4212 		 * CPU-release for the below ->is_active store,
4213 		 * see __load_acquire() in perf_event_time_now()
4214 		 */
4215 		barrier();
4216 	}
4217 
4218 	ctx->is_active |= active_type | EVENT_TIME;
4219 	if (ctx->task) {
4220 		if (!(is_active & EVENT_ALL))
4221 			cpuctx->task_ctx = ctx;
4222 		else
4223 			WARN_ON_ONCE(cpuctx->task_ctx != ctx);
4224 	}
4225 
4226 	if (event_type & EVENT_GUEST) {
4227 		/*
4228 		 * Schedule in the required exclude_guest events of PMU
4229 		 * with PERF_PMU_CAP_MEDIATED_VPMU.
4230 		 */
4231 		is_active = event_type & EVENT_ALL;
4232 
4233 		/*
4234 		 * Update ctx time to set the new start time for
4235 		 * the exclude_guest events.
4236 		 */
4237 		update_context_time(ctx);
4238 		update_cgrp_time_from_cpuctx(cpuctx, false);
4239 		barrier();
4240 	} else {
4241 		is_active ^= ctx->is_active; /* changed bits */
4242 	}
4243 
4244 	/*
4245 	 * First go through the list and put on any pinned groups
4246 	 * in order to give them the best chance of going on.
4247 	 */
4248 	if (is_active & EVENT_PINNED) {
4249 		for_each_epc(pmu_ctx, ctx, pmu, event_type)
4250 			__pmu_ctx_sched_in(pmu_ctx, EVENT_PINNED | (event_type & EVENT_GUEST));
4251 	}
4252 
4253 	/* Then walk through the lower prio flexible groups */
4254 	if (is_active & EVENT_FLEXIBLE) {
4255 		for_each_epc(pmu_ctx, ctx, pmu, event_type)
4256 			__pmu_ctx_sched_in(pmu_ctx, EVENT_FLEXIBLE | (event_type & EVENT_GUEST));
4257 	}
4258 }
4259 
4260 static void perf_event_context_sched_in(struct task_struct *task)
4261 {
4262 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4263 	struct perf_event_context *ctx;
4264 
4265 	rcu_read_lock();
4266 	ctx = rcu_dereference(task->perf_event_ctxp);
4267 	if (!ctx)
4268 		goto rcu_unlock;
4269 
4270 	if (cpuctx->task_ctx == ctx) {
4271 		perf_ctx_lock(cpuctx, ctx);
4272 		perf_ctx_disable(ctx, 0);
4273 
4274 		perf_ctx_sched_task_cb(ctx, task, true);
4275 
4276 		perf_ctx_enable(ctx, 0);
4277 		perf_ctx_unlock(cpuctx, ctx);
4278 		goto rcu_unlock;
4279 	}
4280 
4281 	perf_ctx_lock(cpuctx, ctx);
4282 	/*
4283 	 * We must check ctx->nr_events while holding ctx->lock, such
4284 	 * that we serialize against perf_install_in_context().
4285 	 */
4286 	if (!ctx->nr_events)
4287 		goto unlock;
4288 
4289 	perf_ctx_disable(ctx, 0);
4290 	/*
4291 	 * We want to keep the following priority order:
4292 	 * cpu pinned (that don't need to move), task pinned,
4293 	 * cpu flexible, task flexible.
4294 	 *
4295 	 * However, if task's ctx is not carrying any pinned
4296 	 * events, no need to flip the cpuctx's events around.
4297 	 */
4298 	if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree)) {
4299 		perf_ctx_disable(&cpuctx->ctx, 0);
4300 		ctx_sched_out(&cpuctx->ctx, NULL, EVENT_FLEXIBLE);
4301 	}
4302 
4303 	perf_event_sched_in(cpuctx, ctx, NULL, 0);
4304 
4305 	perf_ctx_sched_task_cb(cpuctx->task_ctx, task, true);
4306 
4307 	if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
4308 		perf_ctx_enable(&cpuctx->ctx, 0);
4309 
4310 	perf_ctx_enable(ctx, 0);
4311 
4312 unlock:
4313 	perf_ctx_unlock(cpuctx, ctx);
4314 rcu_unlock:
4315 	rcu_read_unlock();
4316 }
4317 
4318 /*
4319  * Called from scheduler to add the events of the current task
4320  * with interrupts disabled.
4321  *
4322  * We restore the event value and then enable it.
4323  *
4324  * This does not protect us against NMI, but enable()
4325  * sets the enabled bit in the control field of event _before_
4326  * accessing the event control register. If a NMI hits, then it will
4327  * keep the event running.
4328  */
4329 void __perf_event_task_sched_in(struct task_struct *prev,
4330 				struct task_struct *task)
4331 {
4332 	perf_event_context_sched_in(task);
4333 
4334 	if (atomic_read(&nr_switch_events))
4335 		perf_event_switch(task, prev, true);
4336 
4337 	if (__this_cpu_read(perf_sched_cb_usages))
4338 		perf_pmu_sched_task(prev, task, true);
4339 }
4340 
4341 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
4342 {
4343 	u64 frequency = event->attr.sample_freq;
4344 	u64 sec = NSEC_PER_SEC;
4345 	u64 divisor, dividend;
4346 
4347 	int count_fls, nsec_fls, frequency_fls, sec_fls;
4348 
4349 	count_fls = fls64(count);
4350 	nsec_fls = fls64(nsec);
4351 	frequency_fls = fls64(frequency);
4352 	sec_fls = 30;
4353 
4354 	/*
4355 	 * We got @count in @nsec, with a target of sample_freq HZ
4356 	 * the target period becomes:
4357 	 *
4358 	 *             @count * 10^9
4359 	 * period = -------------------
4360 	 *          @nsec * sample_freq
4361 	 *
4362 	 */
4363 
4364 	/*
4365 	 * Reduce accuracy by one bit such that @a and @b converge
4366 	 * to a similar magnitude.
4367 	 */
4368 #define REDUCE_FLS(a, b)		\
4369 do {					\
4370 	if (a##_fls > b##_fls) {	\
4371 		a >>= 1;		\
4372 		a##_fls--;		\
4373 	} else {			\
4374 		b >>= 1;		\
4375 		b##_fls--;		\
4376 	}				\
4377 } while (0)
4378 
4379 	/*
4380 	 * Reduce accuracy until either term fits in a u64, then proceed with
4381 	 * the other, so that finally we can do a u64/u64 division.
4382 	 */
4383 	while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
4384 		REDUCE_FLS(nsec, frequency);
4385 		REDUCE_FLS(sec, count);
4386 	}
4387 
4388 	if (count_fls + sec_fls > 64) {
4389 		divisor = nsec * frequency;
4390 
4391 		while (count_fls + sec_fls > 64) {
4392 			REDUCE_FLS(count, sec);
4393 			divisor >>= 1;
4394 		}
4395 
4396 		dividend = count * sec;
4397 	} else {
4398 		dividend = count * sec;
4399 
4400 		while (nsec_fls + frequency_fls > 64) {
4401 			REDUCE_FLS(nsec, frequency);
4402 			dividend >>= 1;
4403 		}
4404 
4405 		divisor = nsec * frequency;
4406 	}
4407 
4408 	if (!divisor)
4409 		return dividend;
4410 
4411 	return div64_u64(dividend, divisor);
4412 }
4413 
4414 static DEFINE_PER_CPU(int, perf_throttled_count);
4415 static DEFINE_PER_CPU(u64, perf_throttled_seq);
4416 
4417 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
4418 {
4419 	struct hw_perf_event *hwc = &event->hw;
4420 	s64 period, sample_period;
4421 	s64 delta;
4422 
4423 	period = perf_calculate_period(event, nsec, count);
4424 
4425 	delta = (s64)(period - hwc->sample_period);
4426 	if (delta >= 0)
4427 		delta += 7;
4428 	else
4429 		delta -= 7;
4430 	delta /= 8; /* low pass filter */
4431 
4432 	sample_period = hwc->sample_period + delta;
4433 
4434 	if (!sample_period)
4435 		sample_period = 1;
4436 
4437 	hwc->sample_period = sample_period;
4438 
4439 	if (local64_read(&hwc->period_left) > 8*sample_period) {
4440 		if (disable)
4441 			event->pmu->stop(event, PERF_EF_UPDATE);
4442 
4443 		local64_set(&hwc->period_left, 0);
4444 
4445 		if (disable)
4446 			event->pmu->start(event, PERF_EF_RELOAD);
4447 	}
4448 }
4449 
4450 static void perf_adjust_freq_unthr_events(struct list_head *event_list)
4451 {
4452 	struct perf_event *event;
4453 	struct hw_perf_event *hwc;
4454 	u64 now, period = TICK_NSEC;
4455 	s64 delta;
4456 
4457 	list_for_each_entry(event, event_list, active_list) {
4458 		if (event->state != PERF_EVENT_STATE_ACTIVE)
4459 			continue;
4460 
4461 		// XXX use visit thingy to avoid the -1,cpu match
4462 		if (!event_filter_match(event))
4463 			continue;
4464 
4465 		hwc = &event->hw;
4466 
4467 		if (hwc->interrupts == MAX_INTERRUPTS)
4468 			perf_event_unthrottle_group(event, is_event_in_freq_mode(event));
4469 
4470 		if (!is_event_in_freq_mode(event))
4471 			continue;
4472 
4473 		/*
4474 		 * stop the event and update event->count
4475 		 */
4476 		event->pmu->stop(event, PERF_EF_UPDATE);
4477 
4478 		now = local64_read(&event->count);
4479 		delta = now - hwc->freq_count_stamp;
4480 		hwc->freq_count_stamp = now;
4481 
4482 		/*
4483 		 * restart the event
4484 		 * reload only if value has changed
4485 		 * we have stopped the event so tell that
4486 		 * to perf_adjust_period() to avoid stopping it
4487 		 * twice.
4488 		 */
4489 		if (delta > 0)
4490 			perf_adjust_period(event, period, delta, false);
4491 
4492 		event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
4493 	}
4494 }
4495 
4496 /*
4497  * combine freq adjustment with unthrottling to avoid two passes over the
4498  * events. At the same time, make sure, having freq events does not change
4499  * the rate of unthrottling as that would introduce bias.
4500  */
4501 static void
4502 perf_adjust_freq_unthr_context(struct perf_event_context *ctx, bool unthrottle)
4503 {
4504 	struct perf_event_pmu_context *pmu_ctx;
4505 
4506 	/*
4507 	 * only need to iterate over all events iff:
4508 	 * - context have events in frequency mode (needs freq adjust)
4509 	 * - there are events to unthrottle on this cpu
4510 	 */
4511 	if (!(ctx->nr_freq || unthrottle))
4512 		return;
4513 
4514 	raw_spin_lock(&ctx->lock);
4515 
4516 	list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
4517 		if (!(pmu_ctx->nr_freq || unthrottle))
4518 			continue;
4519 		if (!perf_pmu_ctx_is_active(pmu_ctx))
4520 			continue;
4521 		if (pmu_ctx->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT)
4522 			continue;
4523 
4524 		perf_pmu_disable(pmu_ctx->pmu);
4525 		perf_adjust_freq_unthr_events(&pmu_ctx->pinned_active);
4526 		perf_adjust_freq_unthr_events(&pmu_ctx->flexible_active);
4527 		perf_pmu_enable(pmu_ctx->pmu);
4528 	}
4529 
4530 	raw_spin_unlock(&ctx->lock);
4531 }
4532 
4533 /*
4534  * Move @event to the tail of the @ctx's elegible events.
4535  */
4536 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
4537 {
4538 	/*
4539 	 * Rotate the first entry last of non-pinned groups. Rotation might be
4540 	 * disabled by the inheritance code.
4541 	 */
4542 	if (ctx->rotate_disable)
4543 		return;
4544 
4545 	perf_event_groups_delete(&ctx->flexible_groups, event);
4546 	perf_event_groups_insert(&ctx->flexible_groups, event);
4547 }
4548 
4549 /* pick an event from the flexible_groups to rotate */
4550 static inline struct perf_event *
4551 ctx_event_to_rotate(struct perf_event_pmu_context *pmu_ctx)
4552 {
4553 	struct perf_event *event;
4554 	struct rb_node *node;
4555 	struct rb_root *tree;
4556 	struct __group_key key = {
4557 		.pmu = pmu_ctx->pmu,
4558 	};
4559 
4560 	/* pick the first active flexible event */
4561 	event = list_first_entry_or_null(&pmu_ctx->flexible_active,
4562 					 struct perf_event, active_list);
4563 	if (event)
4564 		goto out;
4565 
4566 	/* if no active flexible event, pick the first event */
4567 	tree = &pmu_ctx->ctx->flexible_groups.tree;
4568 
4569 	if (!pmu_ctx->ctx->task) {
4570 		key.cpu = smp_processor_id();
4571 
4572 		node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4573 		if (node)
4574 			event = __node_2_pe(node);
4575 		goto out;
4576 	}
4577 
4578 	key.cpu = -1;
4579 	node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4580 	if (node) {
4581 		event = __node_2_pe(node);
4582 		goto out;
4583 	}
4584 
4585 	key.cpu = smp_processor_id();
4586 	node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4587 	if (node)
4588 		event = __node_2_pe(node);
4589 
4590 out:
4591 	/*
4592 	 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4593 	 * finds there are unschedulable events, it will set it again.
4594 	 */
4595 	pmu_ctx->rotate_necessary = 0;
4596 
4597 	return event;
4598 }
4599 
4600 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc)
4601 {
4602 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4603 	struct perf_event_pmu_context *cpu_epc, *task_epc = NULL;
4604 	struct perf_event *cpu_event = NULL, *task_event = NULL;
4605 	int cpu_rotate, task_rotate;
4606 	struct pmu *pmu;
4607 
4608 	/*
4609 	 * Since we run this from IRQ context, nobody can install new
4610 	 * events, thus the event count values are stable.
4611 	 */
4612 
4613 	cpu_epc = &cpc->epc;
4614 	pmu = cpu_epc->pmu;
4615 	task_epc = cpc->task_epc;
4616 
4617 	cpu_rotate = cpu_epc->rotate_necessary;
4618 	task_rotate = task_epc ? task_epc->rotate_necessary : 0;
4619 
4620 	if (!(cpu_rotate || task_rotate))
4621 		return false;
4622 
4623 	perf_ctx_lock(cpuctx, cpuctx->task_ctx);
4624 	perf_pmu_disable(pmu);
4625 
4626 	if (task_rotate)
4627 		task_event = ctx_event_to_rotate(task_epc);
4628 	if (cpu_rotate)
4629 		cpu_event = ctx_event_to_rotate(cpu_epc);
4630 
4631 	/*
4632 	 * As per the order given at ctx_resched() first 'pop' task flexible
4633 	 * and then, if needed CPU flexible.
4634 	 */
4635 	if (task_event || (task_epc && cpu_event)) {
4636 		update_context_time(task_epc->ctx);
4637 		__pmu_ctx_sched_out(task_epc, EVENT_FLEXIBLE);
4638 	}
4639 
4640 	if (cpu_event) {
4641 		update_context_time(&cpuctx->ctx);
4642 		__pmu_ctx_sched_out(cpu_epc, EVENT_FLEXIBLE);
4643 		rotate_ctx(&cpuctx->ctx, cpu_event);
4644 		__pmu_ctx_sched_in(cpu_epc, EVENT_FLEXIBLE);
4645 	}
4646 
4647 	if (task_event)
4648 		rotate_ctx(task_epc->ctx, task_event);
4649 
4650 	if (task_event || (task_epc && cpu_event))
4651 		__pmu_ctx_sched_in(task_epc, EVENT_FLEXIBLE);
4652 
4653 	perf_pmu_enable(pmu);
4654 	perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
4655 
4656 	return true;
4657 }
4658 
4659 void perf_event_task_tick(void)
4660 {
4661 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4662 	struct perf_event_context *ctx;
4663 	int throttled;
4664 
4665 	lockdep_assert_irqs_disabled();
4666 
4667 	__this_cpu_inc(perf_throttled_seq);
4668 	throttled = __this_cpu_xchg(perf_throttled_count, 0);
4669 	tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
4670 
4671 	perf_adjust_freq_unthr_context(&cpuctx->ctx, !!throttled);
4672 
4673 	rcu_read_lock();
4674 	ctx = rcu_dereference(current->perf_event_ctxp);
4675 	if (ctx)
4676 		perf_adjust_freq_unthr_context(ctx, !!throttled);
4677 	rcu_read_unlock();
4678 }
4679 
4680 static int event_enable_on_exec(struct perf_event *event,
4681 				struct perf_event_context *ctx)
4682 {
4683 	if (!event->attr.enable_on_exec)
4684 		return 0;
4685 
4686 	event->attr.enable_on_exec = 0;
4687 	if (event->state >= PERF_EVENT_STATE_INACTIVE)
4688 		return 0;
4689 
4690 	perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
4691 
4692 	return 1;
4693 }
4694 
4695 /*
4696  * Enable all of a task's events that have been marked enable-on-exec.
4697  * This expects task == current.
4698  */
4699 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
4700 {
4701 	struct perf_event_context *clone_ctx = NULL;
4702 	enum event_type_t event_type = 0;
4703 	struct perf_cpu_context *cpuctx;
4704 	struct perf_event *event;
4705 	unsigned long flags;
4706 	int enabled = 0;
4707 
4708 	local_irq_save(flags);
4709 	if (WARN_ON_ONCE(current->perf_event_ctxp != ctx))
4710 		goto out;
4711 
4712 	if (!ctx->nr_events)
4713 		goto out;
4714 
4715 	cpuctx = this_cpu_ptr(&perf_cpu_context);
4716 	perf_ctx_lock(cpuctx, ctx);
4717 	ctx_time_freeze(cpuctx, ctx);
4718 
4719 	list_for_each_entry(event, &ctx->event_list, event_entry) {
4720 		enabled |= event_enable_on_exec(event, ctx);
4721 		event_type |= get_event_type(event);
4722 	}
4723 
4724 	/*
4725 	 * Unclone and reschedule this context if we enabled any event.
4726 	 */
4727 	if (enabled) {
4728 		clone_ctx = unclone_ctx(ctx);
4729 		ctx_resched(cpuctx, ctx, NULL, event_type);
4730 	}
4731 	perf_ctx_unlock(cpuctx, ctx);
4732 
4733 out:
4734 	local_irq_restore(flags);
4735 
4736 	if (clone_ctx)
4737 		put_ctx(clone_ctx);
4738 }
4739 
4740 static void perf_remove_from_owner(struct perf_event *event);
4741 static void perf_event_exit_event(struct perf_event *event,
4742 				  struct perf_event_context *ctx,
4743 				  struct task_struct *task,
4744 				  unsigned long detach_flags);
4745 
4746 /*
4747  * Removes all events from the current task that have been marked
4748  * remove-on-exec, and feeds their values back to parent events.
4749  */
4750 static void perf_event_remove_on_exec(struct perf_event_context *ctx)
4751 {
4752 	struct perf_event_context *clone_ctx = NULL;
4753 	struct perf_event *event, *next;
4754 	unsigned long flags;
4755 	bool modified = false;
4756 
4757 	mutex_lock(&ctx->mutex);
4758 
4759 	if (WARN_ON_ONCE(ctx->task != current))
4760 		goto unlock;
4761 
4762 	list_for_each_entry_safe(event, next, &ctx->event_list, event_entry) {
4763 		if (!event->attr.remove_on_exec)
4764 			continue;
4765 
4766 		if (!is_kernel_event(event))
4767 			perf_remove_from_owner(event);
4768 
4769 		modified = true;
4770 
4771 		perf_event_exit_event(event, ctx, ctx->task, DETACH_GROUP);
4772 	}
4773 
4774 	raw_spin_lock_irqsave(&ctx->lock, flags);
4775 	if (modified)
4776 		clone_ctx = unclone_ctx(ctx);
4777 	raw_spin_unlock_irqrestore(&ctx->lock, flags);
4778 
4779 unlock:
4780 	mutex_unlock(&ctx->mutex);
4781 
4782 	if (clone_ctx)
4783 		put_ctx(clone_ctx);
4784 }
4785 
4786 struct perf_read_data {
4787 	struct perf_event *event;
4788 	bool group;
4789 	int ret;
4790 };
4791 
4792 static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu);
4793 
4794 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
4795 {
4796 	int local_cpu = smp_processor_id();
4797 	u16 local_pkg, event_pkg;
4798 
4799 	if ((unsigned)event_cpu >= nr_cpu_ids)
4800 		return event_cpu;
4801 
4802 	if (event->group_caps & PERF_EV_CAP_READ_SCOPE) {
4803 		const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(event->pmu->scope, event_cpu);
4804 
4805 		if (cpumask && cpumask_test_cpu(local_cpu, cpumask))
4806 			return local_cpu;
4807 	}
4808 
4809 	if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
4810 		event_pkg = topology_physical_package_id(event_cpu);
4811 		local_pkg = topology_physical_package_id(local_cpu);
4812 
4813 		if (event_pkg == local_pkg)
4814 			return local_cpu;
4815 	}
4816 
4817 	return event_cpu;
4818 }
4819 
4820 /*
4821  * Cross CPU call to read the hardware event
4822  */
4823 static void __perf_event_read(void *info)
4824 {
4825 	struct perf_read_data *data = info;
4826 	struct perf_event *sub, *event = data->event;
4827 	struct perf_event_context *ctx = event->ctx;
4828 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4829 	struct pmu *pmu;
4830 
4831 	/*
4832 	 * If this is a task context, we need to check whether it is
4833 	 * the current task context of this cpu.  If not it has been
4834 	 * scheduled out before the smp call arrived.  In that case
4835 	 * event->count would have been updated to a recent sample
4836 	 * when the event was scheduled out.
4837 	 */
4838 	if (ctx->task && cpuctx->task_ctx != ctx)
4839 		return;
4840 
4841 	guard(raw_spinlock)(&ctx->lock);
4842 	ctx_time_update_event(ctx, event);
4843 
4844 	perf_event_update_time(event);
4845 	if (data->group)
4846 		perf_event_update_sibling_time(event);
4847 
4848 	if (event->state != PERF_EVENT_STATE_ACTIVE)
4849 		return;
4850 
4851 	if (!data->group) {
4852 		perf_pmu_read(event);
4853 		data->ret = 0;
4854 		return;
4855 	}
4856 
4857 	pmu = event->pmu_ctx->pmu;
4858 	pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4859 
4860 	perf_pmu_read(event);
4861 	for_each_sibling_event(sub, event)
4862 		perf_pmu_read(sub);
4863 
4864 	data->ret = pmu->commit_txn(pmu);
4865 }
4866 
4867 static inline u64 perf_event_count(struct perf_event *event, bool self)
4868 {
4869 	if (self)
4870 		return local64_read(&event->count);
4871 
4872 	return local64_read(&event->count) + atomic64_read(&event->child_count);
4873 }
4874 
4875 static void calc_timer_values(struct perf_event *event,
4876 				u64 *now,
4877 				u64 *enabled,
4878 				u64 *running)
4879 {
4880 	u64 ctx_time;
4881 
4882 	*now = perf_clock();
4883 	ctx_time = perf_event_time_now(event, *now);
4884 	__perf_update_times(event, ctx_time, enabled, running);
4885 }
4886 
4887 /*
4888  * NMI-safe method to read a local event, that is an event that
4889  * is:
4890  *   - either for the current task, or for this CPU
4891  *   - does not have inherit set, for inherited task events
4892  *     will not be local and we cannot read them atomically
4893  *   - must not have a pmu::count method
4894  */
4895 int perf_event_read_local(struct perf_event *event, u64 *value,
4896 			  u64 *enabled, u64 *running)
4897 {
4898 	unsigned long flags;
4899 	int event_oncpu;
4900 	int event_cpu;
4901 	int ret = 0;
4902 
4903 	/*
4904 	 * Disabling interrupts avoids all counter scheduling (context
4905 	 * switches, timer based rotation and IPIs).
4906 	 */
4907 	local_irq_save(flags);
4908 
4909 	/*
4910 	 * It must not be an event with inherit set, we cannot read
4911 	 * all child counters from atomic context.
4912 	 */
4913 	if (event->attr.inherit) {
4914 		ret = -EOPNOTSUPP;
4915 		goto out;
4916 	}
4917 
4918 	/* If this is a per-task event, it must be for current */
4919 	if ((event->attach_state & PERF_ATTACH_TASK) &&
4920 	    event->hw.target != current) {
4921 		ret = -EINVAL;
4922 		goto out;
4923 	}
4924 
4925 	/*
4926 	 * Get the event CPU numbers, and adjust them to local if the event is
4927 	 * a per-package event that can be read locally
4928 	 */
4929 	event_oncpu = __perf_event_read_cpu(event, event->oncpu);
4930 	event_cpu = __perf_event_read_cpu(event, event->cpu);
4931 
4932 	/* If this is a per-CPU event, it must be for this CPU */
4933 	if (!(event->attach_state & PERF_ATTACH_TASK) &&
4934 	    event_cpu != smp_processor_id()) {
4935 		ret = -EINVAL;
4936 		goto out;
4937 	}
4938 
4939 	/* If this is a pinned event it must be running on this CPU */
4940 	if (event->attr.pinned && event_oncpu != smp_processor_id()) {
4941 		ret = -EBUSY;
4942 		goto out;
4943 	}
4944 
4945 	/*
4946 	 * If the event is currently on this CPU, its either a per-task event,
4947 	 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4948 	 * oncpu == -1).
4949 	 */
4950 	if (event_oncpu == smp_processor_id())
4951 		event->pmu->read(event);
4952 
4953 	*value = local64_read(&event->count);
4954 	if (enabled || running) {
4955 		u64 __enabled, __running, __now;
4956 
4957 		calc_timer_values(event, &__now, &__enabled, &__running);
4958 		if (enabled)
4959 			*enabled = __enabled;
4960 		if (running)
4961 			*running = __running;
4962 	}
4963 out:
4964 	local_irq_restore(flags);
4965 
4966 	return ret;
4967 }
4968 
4969 static int perf_event_read(struct perf_event *event, bool group)
4970 {
4971 	enum perf_event_state state = READ_ONCE(event->state);
4972 	int event_cpu, ret = 0;
4973 
4974 	/*
4975 	 * If event is enabled and currently active on a CPU, update the
4976 	 * value in the event structure:
4977 	 */
4978 again:
4979 	if (state == PERF_EVENT_STATE_ACTIVE) {
4980 		struct perf_read_data data;
4981 
4982 		/*
4983 		 * Orders the ->state and ->oncpu loads such that if we see
4984 		 * ACTIVE we must also see the right ->oncpu.
4985 		 *
4986 		 * Matches the smp_wmb() from event_sched_in().
4987 		 */
4988 		smp_rmb();
4989 
4990 		event_cpu = READ_ONCE(event->oncpu);
4991 		if ((unsigned)event_cpu >= nr_cpu_ids)
4992 			return 0;
4993 
4994 		data = (struct perf_read_data){
4995 			.event = event,
4996 			.group = group,
4997 			.ret = 0,
4998 		};
4999 
5000 		preempt_disable();
5001 		event_cpu = __perf_event_read_cpu(event, event_cpu);
5002 
5003 		/*
5004 		 * Purposely ignore the smp_call_function_single() return
5005 		 * value.
5006 		 *
5007 		 * If event_cpu isn't a valid CPU it means the event got
5008 		 * scheduled out and that will have updated the event count.
5009 		 *
5010 		 * Therefore, either way, we'll have an up-to-date event count
5011 		 * after this.
5012 		 */
5013 		(void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
5014 		preempt_enable();
5015 		ret = data.ret;
5016 
5017 	} else if (state == PERF_EVENT_STATE_INACTIVE) {
5018 		struct perf_event_context *ctx = event->ctx;
5019 		unsigned long flags;
5020 
5021 		raw_spin_lock_irqsave(&ctx->lock, flags);
5022 		state = event->state;
5023 		if (state != PERF_EVENT_STATE_INACTIVE) {
5024 			raw_spin_unlock_irqrestore(&ctx->lock, flags);
5025 			goto again;
5026 		}
5027 
5028 		/*
5029 		 * May read while context is not active (e.g., thread is
5030 		 * blocked), in that case we cannot update context time
5031 		 */
5032 		ctx_time_update_event(ctx, event);
5033 
5034 		perf_event_update_time(event);
5035 		if (group)
5036 			perf_event_update_sibling_time(event);
5037 		raw_spin_unlock_irqrestore(&ctx->lock, flags);
5038 	}
5039 
5040 	return ret;
5041 }
5042 
5043 /*
5044  * Initialize the perf_event context in a task_struct:
5045  */
5046 static void __perf_event_init_context(struct perf_event_context *ctx)
5047 {
5048 	raw_spin_lock_init(&ctx->lock);
5049 	mutex_init(&ctx->mutex);
5050 	INIT_LIST_HEAD(&ctx->pmu_ctx_list);
5051 	perf_event_groups_init(&ctx->pinned_groups);
5052 	perf_event_groups_init(&ctx->flexible_groups);
5053 	INIT_LIST_HEAD(&ctx->event_list);
5054 	refcount_set(&ctx->refcount, 1);
5055 }
5056 
5057 static void
5058 __perf_init_event_pmu_context(struct perf_event_pmu_context *epc, struct pmu *pmu)
5059 {
5060 	epc->pmu = pmu;
5061 	INIT_LIST_HEAD(&epc->pmu_ctx_entry);
5062 	INIT_LIST_HEAD(&epc->pinned_active);
5063 	INIT_LIST_HEAD(&epc->flexible_active);
5064 	atomic_set(&epc->refcount, 1);
5065 }
5066 
5067 static struct perf_event_context *
5068 alloc_perf_context(struct task_struct *task)
5069 {
5070 	struct perf_event_context *ctx;
5071 
5072 	ctx = kzalloc_obj(struct perf_event_context);
5073 	if (!ctx)
5074 		return NULL;
5075 
5076 	__perf_event_init_context(ctx);
5077 	if (task)
5078 		ctx->task = get_task_struct(task);
5079 
5080 	return ctx;
5081 }
5082 
5083 static struct task_struct *
5084 find_lively_task_by_vpid(pid_t vpid)
5085 {
5086 	struct task_struct *task;
5087 
5088 	rcu_read_lock();
5089 	if (!vpid)
5090 		task = current;
5091 	else
5092 		task = find_task_by_vpid(vpid);
5093 	if (task)
5094 		get_task_struct(task);
5095 	rcu_read_unlock();
5096 
5097 	if (!task)
5098 		return ERR_PTR(-ESRCH);
5099 
5100 	return task;
5101 }
5102 
5103 /*
5104  * Returns a matching context with refcount and pincount.
5105  */
5106 static struct perf_event_context *
5107 find_get_context(struct task_struct *task, struct perf_event *event)
5108 {
5109 	struct perf_event_context *ctx, *clone_ctx = NULL;
5110 	struct perf_cpu_context *cpuctx;
5111 	unsigned long flags;
5112 	int err;
5113 
5114 	if (!task) {
5115 		/* Must be root to operate on a CPU event: */
5116 		err = perf_allow_cpu();
5117 		if (err)
5118 			return ERR_PTR(err);
5119 
5120 		cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
5121 		ctx = &cpuctx->ctx;
5122 		get_ctx(ctx);
5123 		raw_spin_lock_irqsave(&ctx->lock, flags);
5124 		++ctx->pin_count;
5125 		raw_spin_unlock_irqrestore(&ctx->lock, flags);
5126 
5127 		return ctx;
5128 	}
5129 
5130 	err = -EINVAL;
5131 retry:
5132 	ctx = perf_lock_task_context(task, &flags);
5133 	if (ctx) {
5134 		clone_ctx = unclone_ctx(ctx);
5135 		++ctx->pin_count;
5136 
5137 		raw_spin_unlock_irqrestore(&ctx->lock, flags);
5138 
5139 		if (clone_ctx)
5140 			put_ctx(clone_ctx);
5141 	} else {
5142 		ctx = alloc_perf_context(task);
5143 		err = -ENOMEM;
5144 		if (!ctx)
5145 			goto errout;
5146 
5147 		err = 0;
5148 		mutex_lock(&task->perf_event_mutex);
5149 		/*
5150 		 * If it has already passed perf_event_exit_task().
5151 		 * we must see PF_EXITING, it takes this mutex too.
5152 		 */
5153 		if (task->flags & PF_EXITING)
5154 			err = -ESRCH;
5155 		else if (task->perf_event_ctxp)
5156 			err = -EAGAIN;
5157 		else {
5158 			get_ctx(ctx);
5159 			++ctx->pin_count;
5160 			rcu_assign_pointer(task->perf_event_ctxp, ctx);
5161 		}
5162 		mutex_unlock(&task->perf_event_mutex);
5163 
5164 		if (unlikely(err)) {
5165 			put_ctx(ctx);
5166 
5167 			if (err == -EAGAIN)
5168 				goto retry;
5169 			goto errout;
5170 		}
5171 	}
5172 
5173 	return ctx;
5174 
5175 errout:
5176 	return ERR_PTR(err);
5177 }
5178 
5179 static struct perf_event_pmu_context *
5180 find_get_pmu_context(struct pmu *pmu, struct perf_event_context *ctx,
5181 		     struct perf_event *event)
5182 {
5183 	struct perf_event_pmu_context *new = NULL, *pos = NULL, *epc;
5184 
5185 	if (!ctx->task) {
5186 		/*
5187 		 * perf_pmu_migrate_context() / __perf_pmu_install_event()
5188 		 * relies on the fact that find_get_pmu_context() cannot fail
5189 		 * for CPU contexts.
5190 		 */
5191 		struct perf_cpu_pmu_context *cpc;
5192 
5193 		cpc = *per_cpu_ptr(pmu->cpu_pmu_context, event->cpu);
5194 		epc = &cpc->epc;
5195 		raw_spin_lock_irq(&ctx->lock);
5196 		if (!epc->ctx) {
5197 			/*
5198 			 * One extra reference for the pmu; see perf_pmu_free().
5199 			 */
5200 			atomic_set(&epc->refcount, 2);
5201 			epc->embedded = 1;
5202 			list_add(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
5203 			epc->ctx = ctx;
5204 		} else {
5205 			WARN_ON_ONCE(epc->ctx != ctx);
5206 			atomic_inc(&epc->refcount);
5207 		}
5208 		raw_spin_unlock_irq(&ctx->lock);
5209 		return epc;
5210 	}
5211 
5212 	new = kzalloc_obj(*epc);
5213 	if (!new)
5214 		return ERR_PTR(-ENOMEM);
5215 
5216 	__perf_init_event_pmu_context(new, pmu);
5217 
5218 	/*
5219 	 * XXX
5220 	 *
5221 	 * lockdep_assert_held(&ctx->mutex);
5222 	 *
5223 	 * can't because perf_event_init_task() doesn't actually hold the
5224 	 * child_ctx->mutex.
5225 	 */
5226 
5227 	raw_spin_lock_irq(&ctx->lock);
5228 	list_for_each_entry(epc, &ctx->pmu_ctx_list, pmu_ctx_entry) {
5229 		if (epc->pmu == pmu) {
5230 			WARN_ON_ONCE(epc->ctx != ctx);
5231 			atomic_inc(&epc->refcount);
5232 			goto found_epc;
5233 		}
5234 		/* Make sure the pmu_ctx_list is sorted by PMU type: */
5235 		if (!pos && epc->pmu->type > pmu->type)
5236 			pos = epc;
5237 	}
5238 
5239 	epc = new;
5240 	new = NULL;
5241 
5242 	if (!pos)
5243 		list_add_tail(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
5244 	else
5245 		list_add(&epc->pmu_ctx_entry, pos->pmu_ctx_entry.prev);
5246 
5247 	epc->ctx = ctx;
5248 
5249 found_epc:
5250 	raw_spin_unlock_irq(&ctx->lock);
5251 	kfree(new);
5252 
5253 	return epc;
5254 }
5255 
5256 static void get_pmu_ctx(struct perf_event_pmu_context *epc)
5257 {
5258 	WARN_ON_ONCE(!atomic_inc_not_zero(&epc->refcount));
5259 }
5260 
5261 static void free_cpc_rcu(struct rcu_head *head)
5262 {
5263 	struct perf_cpu_pmu_context *cpc =
5264 		container_of(head, typeof(*cpc), epc.rcu_head);
5265 
5266 	kfree(cpc);
5267 }
5268 
5269 static void free_epc_rcu(struct rcu_head *head)
5270 {
5271 	struct perf_event_pmu_context *epc = container_of(head, typeof(*epc), rcu_head);
5272 
5273 	kfree(epc);
5274 }
5275 
5276 static void put_pmu_ctx(struct perf_event_pmu_context *epc)
5277 {
5278 	struct perf_event_context *ctx = epc->ctx;
5279 	unsigned long flags;
5280 
5281 	/*
5282 	 * XXX
5283 	 *
5284 	 * lockdep_assert_held(&ctx->mutex);
5285 	 *
5286 	 * can't because of the call-site in _free_event()/put_event()
5287 	 * which isn't always called under ctx->mutex.
5288 	 */
5289 	if (!atomic_dec_and_raw_lock_irqsave(&epc->refcount, &ctx->lock, flags))
5290 		return;
5291 
5292 	WARN_ON_ONCE(list_empty(&epc->pmu_ctx_entry));
5293 
5294 	list_del_init(&epc->pmu_ctx_entry);
5295 	epc->ctx = NULL;
5296 
5297 	WARN_ON_ONCE(!list_empty(&epc->pinned_active));
5298 	WARN_ON_ONCE(!list_empty(&epc->flexible_active));
5299 
5300 	raw_spin_unlock_irqrestore(&ctx->lock, flags);
5301 
5302 	if (epc->embedded) {
5303 		call_rcu(&epc->rcu_head, free_cpc_rcu);
5304 		return;
5305 	}
5306 
5307 	call_rcu(&epc->rcu_head, free_epc_rcu);
5308 }
5309 
5310 static void perf_event_free_filter(struct perf_event *event);
5311 
5312 static void free_event_rcu(struct rcu_head *head)
5313 {
5314 	struct perf_event *event = container_of(head, typeof(*event), rcu_head);
5315 
5316 	if (event->ns)
5317 		put_pid_ns(event->ns);
5318 	perf_event_free_filter(event);
5319 	kfree(event->addr_filter_ranges);
5320 	kmem_cache_free(perf_event_cache, event);
5321 }
5322 
5323 static void ring_buffer_attach(struct perf_event *event,
5324 			       struct perf_buffer *rb);
5325 
5326 static void detach_sb_event(struct perf_event *event)
5327 {
5328 	struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
5329 
5330 	raw_spin_lock(&pel->lock);
5331 	list_del_rcu(&event->sb_list);
5332 	raw_spin_unlock(&pel->lock);
5333 }
5334 
5335 static bool is_sb_event(struct perf_event *event)
5336 {
5337 	struct perf_event_attr *attr = &event->attr;
5338 
5339 	if (event->parent)
5340 		return false;
5341 
5342 	if (event->attach_state & PERF_ATTACH_TASK)
5343 		return false;
5344 
5345 	if (attr->mmap || attr->mmap_data || attr->mmap2 ||
5346 	    attr->comm || attr->comm_exec ||
5347 	    attr->task || attr->ksymbol ||
5348 	    attr->context_switch || attr->text_poke ||
5349 	    attr->bpf_event)
5350 		return true;
5351 
5352 	return false;
5353 }
5354 
5355 static void unaccount_pmu_sb_event(struct perf_event *event)
5356 {
5357 	if (is_sb_event(event))
5358 		detach_sb_event(event);
5359 }
5360 
5361 #ifdef CONFIG_NO_HZ_FULL
5362 static DEFINE_SPINLOCK(nr_freq_lock);
5363 #endif
5364 
5365 static void unaccount_freq_event_nohz(void)
5366 {
5367 #ifdef CONFIG_NO_HZ_FULL
5368 	spin_lock(&nr_freq_lock);
5369 	if (atomic_dec_and_test(&nr_freq_events))
5370 		tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
5371 	spin_unlock(&nr_freq_lock);
5372 #endif
5373 }
5374 
5375 static void unaccount_freq_event(void)
5376 {
5377 	if (tick_nohz_full_enabled())
5378 		unaccount_freq_event_nohz();
5379 	else
5380 		atomic_dec(&nr_freq_events);
5381 }
5382 
5383 
5384 static struct perf_ctx_data *
5385 alloc_perf_ctx_data(struct kmem_cache *ctx_cache, bool global, gfp_t gfp_flags)
5386 {
5387 	struct perf_ctx_data *cd;
5388 
5389 	cd = kzalloc_obj(*cd, gfp_flags);
5390 	if (!cd)
5391 		return NULL;
5392 
5393 	cd->data = kmem_cache_zalloc(ctx_cache, gfp_flags);
5394 	if (!cd->data) {
5395 		kfree(cd);
5396 		return NULL;
5397 	}
5398 
5399 	cd->global = global;
5400 	cd->ctx_cache = ctx_cache;
5401 	refcount_set(&cd->refcount, 1);
5402 
5403 	return cd;
5404 }
5405 
5406 static void free_perf_ctx_data(struct perf_ctx_data *cd)
5407 {
5408 	kmem_cache_free(cd->ctx_cache, cd->data);
5409 	kfree(cd);
5410 }
5411 
5412 static void __free_perf_ctx_data_rcu(struct rcu_head *rcu_head)
5413 {
5414 	struct perf_ctx_data *cd;
5415 
5416 	cd = container_of(rcu_head, struct perf_ctx_data, rcu_head);
5417 	free_perf_ctx_data(cd);
5418 }
5419 
5420 static inline void perf_free_ctx_data_rcu(struct perf_ctx_data *cd)
5421 {
5422 	call_rcu(&cd->rcu_head, __free_perf_ctx_data_rcu);
5423 }
5424 
5425 static int
5426 attach_task_ctx_data(struct task_struct *task, struct kmem_cache *ctx_cache,
5427 		     bool global, gfp_t gfp_flags)
5428 {
5429 	struct perf_ctx_data *cd, *old = NULL;
5430 
5431 	cd = alloc_perf_ctx_data(ctx_cache, global, gfp_flags);
5432 	if (!cd)
5433 		return -ENOMEM;
5434 
5435 	for (;;) {
5436 		if (try_cmpxchg(&task->perf_ctx_data, &old, cd)) {
5437 			if (old)
5438 				perf_free_ctx_data_rcu(old);
5439 			/*
5440 			 * Above try_cmpxchg() pairs with try_cmpxchg() from
5441 			 * detach_task_ctx_data() such that
5442 			 * if we race with perf_event_exit_task(), we must
5443 			 * observe PF_EXITING.
5444 			 */
5445 			if (task->flags & PF_EXITING) {
5446 				/* detach_task_ctx_data() may free it already */
5447 				if (try_cmpxchg(&task->perf_ctx_data, &cd, NULL))
5448 					perf_free_ctx_data_rcu(cd);
5449 			}
5450 			return 0;
5451 		}
5452 
5453 		if (!old) {
5454 			/*
5455 			 * After seeing a dead @old, we raced with
5456 			 * removal and lost, try again to install @cd.
5457 			 */
5458 			continue;
5459 		}
5460 
5461 		if (refcount_inc_not_zero(&old->refcount)) {
5462 			if (global)
5463 				old->global = true;
5464 			free_perf_ctx_data(cd); /* unused */
5465 			return 0;
5466 		}
5467 
5468 		/*
5469 		 * @old is a dead object, refcount==0 is stable, try and
5470 		 * replace it with @cd.
5471 		 */
5472 	}
5473 	return 0;
5474 }
5475 
5476 static void __detach_global_ctx_data(void);
5477 DEFINE_STATIC_PERCPU_RWSEM(global_ctx_data_rwsem);
5478 static refcount_t global_ctx_data_ref;
5479 
5480 static int
5481 attach_global_ctx_data(struct kmem_cache *ctx_cache)
5482 {
5483 	struct task_struct *g, *p;
5484 	struct perf_ctx_data *cd;
5485 	int ret;
5486 
5487 	if (refcount_inc_not_zero(&global_ctx_data_ref))
5488 		return 0;
5489 
5490 	guard(percpu_write)(&global_ctx_data_rwsem);
5491 	if (refcount_inc_not_zero(&global_ctx_data_ref))
5492 		return 0;
5493 again:
5494 	/* Allocate everything */
5495 	scoped_guard (rcu) {
5496 		for_each_process_thread(g, p) {
5497 			if (p->flags & PF_EXITING)
5498 				continue;
5499 			cd = rcu_dereference(p->perf_ctx_data);
5500 			if (cd && !cd->global) {
5501 				cd->global = 1;
5502 				if (!refcount_inc_not_zero(&cd->refcount))
5503 					cd = NULL;
5504 			}
5505 			if (!cd) {
5506 				/*
5507 				 * Try to allocate context quickly before
5508 				 * traversing the whole thread list again.
5509 				 */
5510 				if (!attach_task_ctx_data(p, ctx_cache, true, GFP_NOWAIT))
5511 					continue;
5512 				get_task_struct(p);
5513 				goto alloc;
5514 			}
5515 		}
5516 	}
5517 
5518 	refcount_set(&global_ctx_data_ref, 1);
5519 
5520 	return 0;
5521 alloc:
5522 	ret = attach_task_ctx_data(p, ctx_cache, true, GFP_KERNEL);
5523 	put_task_struct(p);
5524 	if (ret) {
5525 		__detach_global_ctx_data();
5526 		return ret;
5527 	}
5528 	goto again;
5529 }
5530 
5531 static int
5532 attach_perf_ctx_data(struct perf_event *event)
5533 {
5534 	struct task_struct *task = event->hw.target;
5535 	struct kmem_cache *ctx_cache = event->pmu->task_ctx_cache;
5536 	int ret;
5537 
5538 	if (!ctx_cache)
5539 		return -ENOMEM;
5540 
5541 	if (task)
5542 		return attach_task_ctx_data(task, ctx_cache, false, GFP_KERNEL);
5543 
5544 	ret = attach_global_ctx_data(ctx_cache);
5545 	if (ret)
5546 		return ret;
5547 
5548 	event->attach_state |= PERF_ATTACH_GLOBAL_DATA;
5549 	return 0;
5550 }
5551 
5552 static void
5553 detach_task_ctx_data(struct task_struct *p)
5554 {
5555 	struct perf_ctx_data *cd;
5556 
5557 	scoped_guard (rcu) {
5558 		cd = rcu_dereference(p->perf_ctx_data);
5559 		if (!cd || !refcount_dec_and_test(&cd->refcount))
5560 			return;
5561 	}
5562 
5563 	/*
5564 	 * The old ctx_data may be lost because of the race.
5565 	 * Nothing is required to do for the case.
5566 	 * See attach_task_ctx_data().
5567 	 */
5568 	if (try_cmpxchg((struct perf_ctx_data **)&p->perf_ctx_data, &cd, NULL))
5569 		perf_free_ctx_data_rcu(cd);
5570 }
5571 
5572 static void __detach_global_ctx_data(void)
5573 {
5574 	struct task_struct *g, *p;
5575 	struct perf_ctx_data *cd;
5576 
5577 	scoped_guard (rcu) {
5578 		for_each_process_thread(g, p) {
5579 			cd = rcu_dereference(p->perf_ctx_data);
5580 			if (cd && cd->global) {
5581 				cd->global = 0;
5582 				detach_task_ctx_data(p);
5583 			}
5584 		}
5585 	}
5586 }
5587 
5588 static void detach_global_ctx_data(void)
5589 {
5590 	if (refcount_dec_not_one(&global_ctx_data_ref))
5591 		return;
5592 
5593 	guard(percpu_write)(&global_ctx_data_rwsem);
5594 	if (!refcount_dec_and_test(&global_ctx_data_ref))
5595 		return;
5596 
5597 	/* remove everything */
5598 	__detach_global_ctx_data();
5599 }
5600 
5601 static void detach_perf_ctx_data(struct perf_event *event)
5602 {
5603 	struct task_struct *task = event->hw.target;
5604 
5605 	event->attach_state &= ~PERF_ATTACH_TASK_DATA;
5606 
5607 	if (task)
5608 		return detach_task_ctx_data(task);
5609 
5610 	if (event->attach_state & PERF_ATTACH_GLOBAL_DATA) {
5611 		detach_global_ctx_data();
5612 		event->attach_state &= ~PERF_ATTACH_GLOBAL_DATA;
5613 	}
5614 }
5615 
5616 static void unaccount_event(struct perf_event *event)
5617 {
5618 	bool dec = false;
5619 
5620 	if (event->parent)
5621 		return;
5622 
5623 	if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
5624 		dec = true;
5625 	if (event->attr.mmap || event->attr.mmap_data)
5626 		atomic_dec(&nr_mmap_events);
5627 	if (event->attr.build_id)
5628 		atomic_dec(&nr_build_id_events);
5629 	if (event->attr.comm)
5630 		atomic_dec(&nr_comm_events);
5631 	if (event->attr.namespaces)
5632 		atomic_dec(&nr_namespaces_events);
5633 	if (event->attr.cgroup)
5634 		atomic_dec(&nr_cgroup_events);
5635 	if (event->attr.task)
5636 		atomic_dec(&nr_task_events);
5637 	if (event->attr.freq)
5638 		unaccount_freq_event();
5639 	if (event->attr.context_switch) {
5640 		dec = true;
5641 		atomic_dec(&nr_switch_events);
5642 	}
5643 	if (is_cgroup_event(event))
5644 		dec = true;
5645 	if (has_branch_stack(event))
5646 		dec = true;
5647 	if (event->attr.ksymbol)
5648 		atomic_dec(&nr_ksymbol_events);
5649 	if (event->attr.bpf_event)
5650 		atomic_dec(&nr_bpf_events);
5651 	if (event->attr.text_poke)
5652 		atomic_dec(&nr_text_poke_events);
5653 
5654 	if (dec) {
5655 		if (!atomic_add_unless(&perf_sched_count, -1, 1))
5656 			schedule_delayed_work(&perf_sched_work, HZ);
5657 	}
5658 
5659 	unaccount_pmu_sb_event(event);
5660 }
5661 
5662 static void perf_sched_delayed(struct work_struct *work)
5663 {
5664 	mutex_lock(&perf_sched_mutex);
5665 	if (atomic_dec_and_test(&perf_sched_count))
5666 		static_branch_disable(&perf_sched_events);
5667 	mutex_unlock(&perf_sched_mutex);
5668 }
5669 
5670 /*
5671  * The following implement mutual exclusion of events on "exclusive" pmus
5672  * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
5673  * at a time, so we disallow creating events that might conflict, namely:
5674  *
5675  *  1) cpu-wide events in the presence of per-task events,
5676  *  2) per-task events in the presence of cpu-wide events,
5677  *  3) two matching events on the same perf_event_context.
5678  *
5679  * The former two cases are handled in the allocation path (perf_event_alloc(),
5680  * _free_event()), the latter -- before the first perf_install_in_context().
5681  */
5682 static int exclusive_event_init(struct perf_event *event)
5683 {
5684 	struct pmu *pmu = event->pmu;
5685 
5686 	if (!is_exclusive_pmu(pmu))
5687 		return 0;
5688 
5689 	/*
5690 	 * Prevent co-existence of per-task and cpu-wide events on the
5691 	 * same exclusive pmu.
5692 	 *
5693 	 * Negative pmu::exclusive_cnt means there are cpu-wide
5694 	 * events on this "exclusive" pmu, positive means there are
5695 	 * per-task events.
5696 	 *
5697 	 * Since this is called in perf_event_alloc() path, event::ctx
5698 	 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
5699 	 * to mean "per-task event", because unlike other attach states it
5700 	 * never gets cleared.
5701 	 */
5702 	if (event->attach_state & PERF_ATTACH_TASK) {
5703 		if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
5704 			return -EBUSY;
5705 	} else {
5706 		if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
5707 			return -EBUSY;
5708 	}
5709 
5710 	event->attach_state |= PERF_ATTACH_EXCLUSIVE;
5711 
5712 	return 0;
5713 }
5714 
5715 static void exclusive_event_destroy(struct perf_event *event)
5716 {
5717 	struct pmu *pmu = event->pmu;
5718 
5719 	/* see comment in exclusive_event_init() */
5720 	if (event->attach_state & PERF_ATTACH_TASK)
5721 		atomic_dec(&pmu->exclusive_cnt);
5722 	else
5723 		atomic_inc(&pmu->exclusive_cnt);
5724 
5725 	event->attach_state &= ~PERF_ATTACH_EXCLUSIVE;
5726 }
5727 
5728 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
5729 {
5730 	if ((e1->pmu == e2->pmu) &&
5731 	    (e1->cpu == e2->cpu ||
5732 	     e1->cpu == -1 ||
5733 	     e2->cpu == -1))
5734 		return true;
5735 	return false;
5736 }
5737 
5738 static bool exclusive_event_installable(struct perf_event *event,
5739 					struct perf_event_context *ctx)
5740 {
5741 	struct perf_event *iter_event;
5742 	struct pmu *pmu = event->pmu;
5743 
5744 	lockdep_assert_held(&ctx->mutex);
5745 
5746 	if (!is_exclusive_pmu(pmu))
5747 		return true;
5748 
5749 	list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
5750 		if (exclusive_event_match(iter_event, event))
5751 			return false;
5752 	}
5753 
5754 	return true;
5755 }
5756 
5757 static void perf_free_addr_filters(struct perf_event *event);
5758 
5759 /* vs perf_event_alloc() error */
5760 static void __free_event(struct perf_event *event)
5761 {
5762 	struct pmu *pmu = event->pmu;
5763 
5764 	security_perf_event_free(event);
5765 
5766 	if (event->attach_state & PERF_ATTACH_CALLCHAIN)
5767 		put_callchain_buffers();
5768 
5769 	if (event->attach_state & PERF_ATTACH_EXCLUSIVE)
5770 		exclusive_event_destroy(event);
5771 
5772 	if (is_cgroup_event(event))
5773 		perf_detach_cgroup(event);
5774 
5775 	if (event->attach_state & PERF_ATTACH_TASK_DATA)
5776 		detach_perf_ctx_data(event);
5777 
5778 	if (event->destroy)
5779 		event->destroy(event);
5780 
5781 	/*
5782 	 * Must be after ->destroy(), due to uprobe_perf_close() using
5783 	 * hw.target.
5784 	 */
5785 	if (event->hw.target)
5786 		put_task_struct(event->hw.target);
5787 
5788 	if (event->pmu_ctx) {
5789 		/*
5790 		 * put_pmu_ctx() needs an event->ctx reference, because of
5791 		 * epc->ctx.
5792 		 */
5793 		WARN_ON_ONCE(!pmu);
5794 		WARN_ON_ONCE(!event->ctx);
5795 		WARN_ON_ONCE(event->pmu_ctx->ctx != event->ctx);
5796 		put_pmu_ctx(event->pmu_ctx);
5797 	}
5798 
5799 	/*
5800 	 * perf_event_free_task() relies on put_ctx() being 'last', in
5801 	 * particular all task references must be cleaned up.
5802 	 */
5803 	if (event->ctx)
5804 		put_ctx(event->ctx);
5805 
5806 	if (pmu) {
5807 		module_put(pmu->module);
5808 		scoped_guard (spinlock, &pmu->events_lock) {
5809 			list_del(&event->pmu_list);
5810 			wake_up_var(pmu);
5811 		}
5812 	}
5813 
5814 	call_rcu(&event->rcu_head, free_event_rcu);
5815 }
5816 
5817 static void mediated_pmu_unaccount_event(struct perf_event *event);
5818 
5819 DEFINE_FREE(__free_event, struct perf_event *, if (_T) __free_event(_T))
5820 
5821 /* vs perf_event_alloc() success */
5822 static void _free_event(struct perf_event *event)
5823 {
5824 	irq_work_sync(&event->pending_irq);
5825 	irq_work_sync(&event->pending_disable_irq);
5826 
5827 	unaccount_event(event);
5828 	mediated_pmu_unaccount_event(event);
5829 
5830 	if (event->rb) {
5831 		/*
5832 		 * Can happen when we close an event with re-directed output.
5833 		 *
5834 		 * Since we have a 0 refcount, perf_mmap_close() will skip
5835 		 * over us; possibly making our ring_buffer_put() the last.
5836 		 */
5837 		mutex_lock(&event->mmap_mutex);
5838 		ring_buffer_attach(event, NULL);
5839 		mutex_unlock(&event->mmap_mutex);
5840 	}
5841 
5842 	perf_event_free_bpf_prog(event);
5843 	perf_free_addr_filters(event);
5844 
5845 	__free_event(event);
5846 }
5847 
5848 /*
5849  * Used to free events which have a known refcount of 1, such as in error paths
5850  * of inherited events.
5851  */
5852 static void free_event(struct perf_event *event)
5853 {
5854 	if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
5855 				     "unexpected event refcount: %ld; ptr=%p\n",
5856 				     atomic_long_read(&event->refcount), event)) {
5857 		/* leak to avoid use-after-free */
5858 		return;
5859 	}
5860 
5861 	_free_event(event);
5862 }
5863 
5864 /*
5865  * Remove user event from the owner task.
5866  */
5867 static void perf_remove_from_owner(struct perf_event *event)
5868 {
5869 	struct task_struct *owner;
5870 
5871 	rcu_read_lock();
5872 	/*
5873 	 * Matches the smp_store_release() in perf_event_exit_task(). If we
5874 	 * observe !owner it means the list deletion is complete and we can
5875 	 * indeed free this event, otherwise we need to serialize on
5876 	 * owner->perf_event_mutex.
5877 	 */
5878 	owner = READ_ONCE(event->owner);
5879 	if (owner) {
5880 		/*
5881 		 * Since delayed_put_task_struct() also drops the last
5882 		 * task reference we can safely take a new reference
5883 		 * while holding the rcu_read_lock().
5884 		 */
5885 		get_task_struct(owner);
5886 	}
5887 	rcu_read_unlock();
5888 
5889 	if (owner) {
5890 		/*
5891 		 * If we're here through perf_event_exit_task() we're already
5892 		 * holding ctx->mutex which would be an inversion wrt. the
5893 		 * normal lock order.
5894 		 *
5895 		 * However we can safely take this lock because its the child
5896 		 * ctx->mutex.
5897 		 */
5898 		mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
5899 
5900 		/*
5901 		 * We have to re-check the event->owner field, if it is cleared
5902 		 * we raced with perf_event_exit_task(), acquiring the mutex
5903 		 * ensured they're done, and we can proceed with freeing the
5904 		 * event.
5905 		 */
5906 		if (event->owner) {
5907 			list_del_init(&event->owner_entry);
5908 			smp_store_release(&event->owner, NULL);
5909 		}
5910 		mutex_unlock(&owner->perf_event_mutex);
5911 		put_task_struct(owner);
5912 	}
5913 }
5914 
5915 static void put_event(struct perf_event *event)
5916 {
5917 	struct perf_event *parent;
5918 
5919 	if (!atomic_long_dec_and_test(&event->refcount))
5920 		return;
5921 
5922 	parent = event->parent;
5923 	_free_event(event);
5924 
5925 	/* Matches the refcount bump in inherit_event() */
5926 	if (parent)
5927 		put_event(parent);
5928 }
5929 
5930 /*
5931  * Kill an event dead; while event:refcount will preserve the event
5932  * object, it will not preserve its functionality. Once the last 'user'
5933  * gives up the object, we'll destroy the thing.
5934  */
5935 int perf_event_release_kernel(struct perf_event *event)
5936 {
5937 	struct perf_event_context *ctx = event->ctx;
5938 	struct perf_event *child, *tmp;
5939 
5940 	/*
5941 	 * If we got here through err_alloc: free_event(event); we will not
5942 	 * have attached to a context yet.
5943 	 */
5944 	if (!ctx) {
5945 		WARN_ON_ONCE(event->attach_state &
5946 				(PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
5947 		goto no_ctx;
5948 	}
5949 
5950 	if (!is_kernel_event(event))
5951 		perf_remove_from_owner(event);
5952 
5953 	ctx = perf_event_ctx_lock(event);
5954 	WARN_ON_ONCE(ctx->parent_ctx);
5955 
5956 	/*
5957 	 * Mark this event as STATE_DEAD, there is no external reference to it
5958 	 * anymore.
5959 	 *
5960 	 * Anybody acquiring event->child_mutex after the below loop _must_
5961 	 * also see this, most importantly inherit_event() which will avoid
5962 	 * placing more children on the list.
5963 	 *
5964 	 * Thus this guarantees that we will in fact observe and kill _ALL_
5965 	 * child events.
5966 	 */
5967 	if (event->state > PERF_EVENT_STATE_REVOKED) {
5968 		perf_remove_from_context(event, DETACH_GROUP|DETACH_DEAD);
5969 	} else {
5970 		event->state = PERF_EVENT_STATE_DEAD;
5971 	}
5972 
5973 	perf_event_ctx_unlock(event, ctx);
5974 
5975 again:
5976 	mutex_lock(&event->child_mutex);
5977 	list_for_each_entry(child, &event->child_list, child_list) {
5978 		/*
5979 		 * Cannot change, child events are not migrated, see the
5980 		 * comment with perf_event_ctx_lock_nested().
5981 		 */
5982 		ctx = READ_ONCE(child->ctx);
5983 		/*
5984 		 * Since child_mutex nests inside ctx::mutex, we must jump
5985 		 * through hoops. We start by grabbing a reference on the ctx.
5986 		 *
5987 		 * Since the event cannot get freed while we hold the
5988 		 * child_mutex, the context must also exist and have a !0
5989 		 * reference count.
5990 		 */
5991 		get_ctx(ctx);
5992 
5993 		/*
5994 		 * Now that we have a ctx ref, we can drop child_mutex, and
5995 		 * acquire ctx::mutex without fear of it going away. Then we
5996 		 * can re-acquire child_mutex.
5997 		 */
5998 		mutex_unlock(&event->child_mutex);
5999 		mutex_lock(&ctx->mutex);
6000 		mutex_lock(&event->child_mutex);
6001 
6002 		/*
6003 		 * Now that we hold ctx::mutex and child_mutex, revalidate our
6004 		 * state, if child is still the first entry, it didn't get freed
6005 		 * and we can continue doing so.
6006 		 */
6007 		tmp = list_first_entry_or_null(&event->child_list,
6008 					       struct perf_event, child_list);
6009 		if (tmp == child) {
6010 			perf_remove_from_context(child, DETACH_GROUP | DETACH_CHILD);
6011 		} else {
6012 			child = NULL;
6013 		}
6014 
6015 		mutex_unlock(&event->child_mutex);
6016 		mutex_unlock(&ctx->mutex);
6017 
6018 		if (child) {
6019 			/* Last reference unless ->pending_task work is pending */
6020 			put_event(child);
6021 		}
6022 		put_ctx(ctx);
6023 
6024 		goto again;
6025 	}
6026 	mutex_unlock(&event->child_mutex);
6027 
6028 no_ctx:
6029 	/*
6030 	 * Last reference unless ->pending_task work is pending on this event
6031 	 * or any of its children.
6032 	 */
6033 	put_event(event);
6034 	return 0;
6035 }
6036 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
6037 
6038 /*
6039  * Called when the last reference to the file is gone.
6040  */
6041 static int perf_release(struct inode *inode, struct file *file)
6042 {
6043 	perf_event_release_kernel(file->private_data);
6044 	return 0;
6045 }
6046 
6047 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
6048 {
6049 	struct perf_event *child;
6050 	u64 total = 0;
6051 
6052 	*enabled = 0;
6053 	*running = 0;
6054 
6055 	mutex_lock(&event->child_mutex);
6056 
6057 	(void)perf_event_read(event, false);
6058 	total += perf_event_count(event, false);
6059 
6060 	*enabled += event->total_time_enabled +
6061 			atomic64_read(&event->child_total_time_enabled);
6062 	*running += event->total_time_running +
6063 			atomic64_read(&event->child_total_time_running);
6064 
6065 	list_for_each_entry(child, &event->child_list, child_list) {
6066 		(void)perf_event_read(child, false);
6067 		total += perf_event_count(child, false);
6068 		*enabled += child->total_time_enabled;
6069 		*running += child->total_time_running;
6070 	}
6071 	mutex_unlock(&event->child_mutex);
6072 
6073 	return total;
6074 }
6075 
6076 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
6077 {
6078 	struct perf_event_context *ctx;
6079 	u64 count;
6080 
6081 	ctx = perf_event_ctx_lock(event);
6082 	count = __perf_event_read_value(event, enabled, running);
6083 	perf_event_ctx_unlock(event, ctx);
6084 
6085 	return count;
6086 }
6087 EXPORT_SYMBOL_GPL(perf_event_read_value);
6088 
6089 static int __perf_read_group_add(struct perf_event *leader,
6090 					u64 read_format, u64 *values)
6091 {
6092 	struct perf_event_context *ctx = leader->ctx;
6093 	struct perf_event *sub, *parent;
6094 	unsigned long flags;
6095 	int n = 1; /* skip @nr */
6096 	int ret;
6097 
6098 	ret = perf_event_read(leader, true);
6099 	if (ret)
6100 		return ret;
6101 
6102 	raw_spin_lock_irqsave(&ctx->lock, flags);
6103 	/*
6104 	 * Verify the grouping between the parent and child (inherited)
6105 	 * events is still in tact.
6106 	 *
6107 	 * Specifically:
6108 	 *  - leader->ctx->lock pins leader->sibling_list
6109 	 *  - parent->child_mutex pins parent->child_list
6110 	 *  - parent->ctx->mutex pins parent->sibling_list
6111 	 *
6112 	 * Because parent->ctx != leader->ctx (and child_list nests inside
6113 	 * ctx->mutex), group destruction is not atomic between children, also
6114 	 * see perf_event_release_kernel(). Additionally, parent can grow the
6115 	 * group.
6116 	 *
6117 	 * Therefore it is possible to have parent and child groups in a
6118 	 * different configuration and summing over such a beast makes no sense
6119 	 * what so ever.
6120 	 *
6121 	 * Reject this.
6122 	 */
6123 	parent = leader->parent;
6124 	if (parent &&
6125 	    (parent->group_generation != leader->group_generation ||
6126 	     parent->nr_siblings != leader->nr_siblings)) {
6127 		ret = -ECHILD;
6128 		goto unlock;
6129 	}
6130 
6131 	/*
6132 	 * Since we co-schedule groups, {enabled,running} times of siblings
6133 	 * will be identical to those of the leader, so we only publish one
6134 	 * set.
6135 	 */
6136 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
6137 		values[n++] += leader->total_time_enabled +
6138 			atomic64_read(&leader->child_total_time_enabled);
6139 	}
6140 
6141 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
6142 		values[n++] += leader->total_time_running +
6143 			atomic64_read(&leader->child_total_time_running);
6144 	}
6145 
6146 	/*
6147 	 * Write {count,id} tuples for every sibling.
6148 	 */
6149 	values[n++] += perf_event_count(leader, false);
6150 	if (read_format & PERF_FORMAT_ID)
6151 		values[n++] = primary_event_id(leader);
6152 	if (read_format & PERF_FORMAT_LOST)
6153 		values[n++] = atomic64_read(&leader->lost_samples);
6154 
6155 	for_each_sibling_event(sub, leader) {
6156 		values[n++] += perf_event_count(sub, false);
6157 		if (read_format & PERF_FORMAT_ID)
6158 			values[n++] = primary_event_id(sub);
6159 		if (read_format & PERF_FORMAT_LOST)
6160 			values[n++] = atomic64_read(&sub->lost_samples);
6161 	}
6162 
6163 unlock:
6164 	raw_spin_unlock_irqrestore(&ctx->lock, flags);
6165 	return ret;
6166 }
6167 
6168 static int perf_read_group(struct perf_event *event,
6169 				   u64 read_format, char __user *buf)
6170 {
6171 	struct perf_event *leader = event->group_leader, *child;
6172 	struct perf_event_context *ctx = leader->ctx;
6173 	int ret;
6174 	u64 *values;
6175 
6176 	lockdep_assert_held(&ctx->mutex);
6177 
6178 	values = kzalloc(event->read_size, GFP_KERNEL);
6179 	if (!values)
6180 		return -ENOMEM;
6181 
6182 	values[0] = 1 + leader->nr_siblings;
6183 
6184 	mutex_lock(&leader->child_mutex);
6185 
6186 	ret = __perf_read_group_add(leader, read_format, values);
6187 	if (ret)
6188 		goto unlock;
6189 
6190 	list_for_each_entry(child, &leader->child_list, child_list) {
6191 		ret = __perf_read_group_add(child, read_format, values);
6192 		if (ret)
6193 			goto unlock;
6194 	}
6195 
6196 	mutex_unlock(&leader->child_mutex);
6197 
6198 	ret = event->read_size;
6199 	if (copy_to_user(buf, values, event->read_size))
6200 		ret = -EFAULT;
6201 	goto out;
6202 
6203 unlock:
6204 	mutex_unlock(&leader->child_mutex);
6205 out:
6206 	kfree(values);
6207 	return ret;
6208 }
6209 
6210 static int perf_read_one(struct perf_event *event,
6211 				 u64 read_format, char __user *buf)
6212 {
6213 	u64 enabled, running;
6214 	u64 values[5];
6215 	int n = 0;
6216 
6217 	values[n++] = __perf_event_read_value(event, &enabled, &running);
6218 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6219 		values[n++] = enabled;
6220 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6221 		values[n++] = running;
6222 	if (read_format & PERF_FORMAT_ID)
6223 		values[n++] = primary_event_id(event);
6224 	if (read_format & PERF_FORMAT_LOST)
6225 		values[n++] = atomic64_read(&event->lost_samples);
6226 
6227 	if (copy_to_user(buf, values, n * sizeof(u64)))
6228 		return -EFAULT;
6229 
6230 	return n * sizeof(u64);
6231 }
6232 
6233 static bool is_event_hup(struct perf_event *event)
6234 {
6235 	bool no_children;
6236 
6237 	if (event->state > PERF_EVENT_STATE_EXIT)
6238 		return false;
6239 
6240 	mutex_lock(&event->child_mutex);
6241 	no_children = list_empty(&event->child_list);
6242 	mutex_unlock(&event->child_mutex);
6243 	return no_children;
6244 }
6245 
6246 /*
6247  * Read the performance event - simple non blocking version for now
6248  */
6249 static ssize_t
6250 __perf_read(struct perf_event *event, char __user *buf, size_t count)
6251 {
6252 	u64 read_format = event->attr.read_format;
6253 	int ret;
6254 
6255 	/*
6256 	 * Return end-of-file for a read on an event that is in
6257 	 * error state (i.e. because it was pinned but it couldn't be
6258 	 * scheduled on to the CPU at some point).
6259 	 */
6260 	if (event->state == PERF_EVENT_STATE_ERROR)
6261 		return 0;
6262 
6263 	if (count < event->read_size)
6264 		return -ENOSPC;
6265 
6266 	WARN_ON_ONCE(event->ctx->parent_ctx);
6267 	if (read_format & PERF_FORMAT_GROUP)
6268 		ret = perf_read_group(event, read_format, buf);
6269 	else
6270 		ret = perf_read_one(event, read_format, buf);
6271 
6272 	return ret;
6273 }
6274 
6275 static ssize_t
6276 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
6277 {
6278 	struct perf_event *event = file->private_data;
6279 	struct perf_event_context *ctx;
6280 	int ret;
6281 
6282 	ret = security_perf_event_read(event);
6283 	if (ret)
6284 		return ret;
6285 
6286 	ctx = perf_event_ctx_lock(event);
6287 	ret = __perf_read(event, buf, count);
6288 	perf_event_ctx_unlock(event, ctx);
6289 
6290 	return ret;
6291 }
6292 
6293 static __poll_t perf_poll(struct file *file, poll_table *wait)
6294 {
6295 	struct perf_event *event = file->private_data;
6296 	struct perf_buffer *rb;
6297 	__poll_t events = EPOLLHUP;
6298 
6299 	if (event->state <= PERF_EVENT_STATE_REVOKED)
6300 		return EPOLLERR;
6301 
6302 	poll_wait(file, &event->waitq, wait);
6303 
6304 	if (event->state <= PERF_EVENT_STATE_REVOKED)
6305 		return EPOLLERR;
6306 
6307 	if (is_event_hup(event))
6308 		return events;
6309 
6310 	if (unlikely(READ_ONCE(event->state) == PERF_EVENT_STATE_ERROR &&
6311 		     event->attr.pinned))
6312 		return EPOLLERR;
6313 
6314 	/*
6315 	 * Pin the event->rb by taking event->mmap_mutex; otherwise
6316 	 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
6317 	 */
6318 	mutex_lock(&event->mmap_mutex);
6319 	rb = event->rb;
6320 	if (rb)
6321 		events = atomic_xchg(&rb->poll, 0);
6322 	mutex_unlock(&event->mmap_mutex);
6323 	return events;
6324 }
6325 
6326 static void _perf_event_reset(struct perf_event *event)
6327 {
6328 	(void)perf_event_read(event, false);
6329 	local64_set(&event->count, 0);
6330 	perf_event_update_userpage(event);
6331 }
6332 
6333 /* Assume it's not an event with inherit set. */
6334 u64 perf_event_pause(struct perf_event *event, bool reset)
6335 {
6336 	struct perf_event_context *ctx;
6337 	u64 count;
6338 
6339 	ctx = perf_event_ctx_lock(event);
6340 	WARN_ON_ONCE(event->attr.inherit);
6341 	_perf_event_disable(event);
6342 	count = local64_read(&event->count);
6343 	if (reset)
6344 		local64_set(&event->count, 0);
6345 	perf_event_ctx_unlock(event, ctx);
6346 
6347 	return count;
6348 }
6349 EXPORT_SYMBOL_GPL(perf_event_pause);
6350 
6351 #ifdef CONFIG_PERF_GUEST_MEDIATED_PMU
6352 static atomic_t nr_include_guest_events __read_mostly;
6353 
6354 static atomic_t nr_mediated_pmu_vms __read_mostly;
6355 static DEFINE_MUTEX(perf_mediated_pmu_mutex);
6356 
6357 /* !exclude_guest event of PMU with PERF_PMU_CAP_MEDIATED_VPMU */
6358 static inline bool is_include_guest_event(struct perf_event *event)
6359 {
6360 	if (!event->pmu)
6361 		return false;
6362 
6363 	if ((event->pmu->capabilities & PERF_PMU_CAP_MEDIATED_VPMU) &&
6364 	    !event->attr.exclude_guest)
6365 		return true;
6366 
6367 	return false;
6368 }
6369 
6370 static int mediated_pmu_account_event(struct perf_event *event)
6371 {
6372 	if (!is_include_guest_event(event))
6373 		return 0;
6374 
6375 	if (atomic_inc_not_zero(&nr_include_guest_events))
6376 		return 0;
6377 
6378 	guard(mutex)(&perf_mediated_pmu_mutex);
6379 	if (atomic_read(&nr_mediated_pmu_vms))
6380 		return -EOPNOTSUPP;
6381 
6382 	atomic_inc(&nr_include_guest_events);
6383 	return 0;
6384 }
6385 
6386 static void mediated_pmu_unaccount_event(struct perf_event *event)
6387 {
6388 	if (!is_include_guest_event(event))
6389 		return;
6390 
6391 	if (WARN_ON_ONCE(!atomic_read(&nr_include_guest_events)))
6392 		return;
6393 
6394 	atomic_dec(&nr_include_guest_events);
6395 }
6396 
6397 /*
6398  * Currently invoked at VM creation to
6399  * - Check whether there are existing !exclude_guest events of PMU with
6400  *   PERF_PMU_CAP_MEDIATED_VPMU
6401  * - Set nr_mediated_pmu_vms to prevent !exclude_guest event creation on
6402  *   PMUs with PERF_PMU_CAP_MEDIATED_VPMU
6403  *
6404  * No impact for the PMU without PERF_PMU_CAP_MEDIATED_VPMU. The perf
6405  * still owns all the PMU resources.
6406  */
6407 int perf_create_mediated_pmu(void)
6408 {
6409 	if (atomic_inc_not_zero(&nr_mediated_pmu_vms))
6410 		return 0;
6411 
6412 	guard(mutex)(&perf_mediated_pmu_mutex);
6413 	if (atomic_read(&nr_include_guest_events))
6414 		return -EBUSY;
6415 
6416 	atomic_inc(&nr_mediated_pmu_vms);
6417 	return 0;
6418 }
6419 EXPORT_SYMBOL_FOR_KVM(perf_create_mediated_pmu);
6420 
6421 void perf_release_mediated_pmu(void)
6422 {
6423 	if (WARN_ON_ONCE(!atomic_read(&nr_mediated_pmu_vms)))
6424 		return;
6425 
6426 	atomic_dec(&nr_mediated_pmu_vms);
6427 }
6428 EXPORT_SYMBOL_FOR_KVM(perf_release_mediated_pmu);
6429 
6430 /* When loading a guest's mediated PMU, schedule out all exclude_guest events. */
6431 void perf_load_guest_context(void)
6432 {
6433 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
6434 
6435 	lockdep_assert_irqs_disabled();
6436 
6437 	guard(perf_ctx_lock)(cpuctx, cpuctx->task_ctx);
6438 
6439 	if (WARN_ON_ONCE(__this_cpu_read(guest_ctx_loaded)))
6440 		return;
6441 
6442 	perf_ctx_disable(&cpuctx->ctx, EVENT_GUEST);
6443 	ctx_sched_out(&cpuctx->ctx, NULL, EVENT_GUEST);
6444 	if (cpuctx->task_ctx) {
6445 		perf_ctx_disable(cpuctx->task_ctx, EVENT_GUEST);
6446 		task_ctx_sched_out(cpuctx->task_ctx, NULL, EVENT_GUEST);
6447 	}
6448 
6449 	perf_ctx_enable(&cpuctx->ctx, EVENT_GUEST);
6450 	if (cpuctx->task_ctx)
6451 		perf_ctx_enable(cpuctx->task_ctx, EVENT_GUEST);
6452 
6453 	__this_cpu_write(guest_ctx_loaded, true);
6454 }
6455 EXPORT_SYMBOL_GPL(perf_load_guest_context);
6456 
6457 void perf_put_guest_context(void)
6458 {
6459 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
6460 
6461 	lockdep_assert_irqs_disabled();
6462 
6463 	guard(perf_ctx_lock)(cpuctx, cpuctx->task_ctx);
6464 
6465 	if (WARN_ON_ONCE(!__this_cpu_read(guest_ctx_loaded)))
6466 		return;
6467 
6468 	perf_ctx_disable(&cpuctx->ctx, EVENT_GUEST);
6469 	if (cpuctx->task_ctx)
6470 		perf_ctx_disable(cpuctx->task_ctx, EVENT_GUEST);
6471 
6472 	perf_event_sched_in(cpuctx, cpuctx->task_ctx, NULL, EVENT_GUEST);
6473 
6474 	if (cpuctx->task_ctx)
6475 		perf_ctx_enable(cpuctx->task_ctx, EVENT_GUEST);
6476 	perf_ctx_enable(&cpuctx->ctx, EVENT_GUEST);
6477 
6478 	__this_cpu_write(guest_ctx_loaded, false);
6479 }
6480 EXPORT_SYMBOL_GPL(perf_put_guest_context);
6481 #else
6482 static int mediated_pmu_account_event(struct perf_event *event) { return 0; }
6483 static void mediated_pmu_unaccount_event(struct perf_event *event) {}
6484 #endif
6485 
6486 /*
6487  * Holding the top-level event's child_mutex means that any
6488  * descendant process that has inherited this event will block
6489  * in perf_event_exit_event() if it goes to exit, thus satisfying the
6490  * task existence requirements of perf_event_enable/disable.
6491  */
6492 static void perf_event_for_each_child(struct perf_event *event,
6493 					void (*func)(struct perf_event *))
6494 {
6495 	struct perf_event *child;
6496 
6497 	WARN_ON_ONCE(event->ctx->parent_ctx);
6498 
6499 	mutex_lock(&event->child_mutex);
6500 	func(event);
6501 	list_for_each_entry(child, &event->child_list, child_list)
6502 		func(child);
6503 	mutex_unlock(&event->child_mutex);
6504 }
6505 
6506 static void perf_event_for_each(struct perf_event *event,
6507 				  void (*func)(struct perf_event *))
6508 {
6509 	struct perf_event_context *ctx = event->ctx;
6510 	struct perf_event *sibling;
6511 
6512 	lockdep_assert_held(&ctx->mutex);
6513 
6514 	event = event->group_leader;
6515 
6516 	perf_event_for_each_child(event, func);
6517 	for_each_sibling_event(sibling, event)
6518 		perf_event_for_each_child(sibling, func);
6519 }
6520 
6521 static void __perf_event_period(struct perf_event *event,
6522 				struct perf_cpu_context *cpuctx,
6523 				struct perf_event_context *ctx,
6524 				void *info)
6525 {
6526 	u64 value = *((u64 *)info);
6527 	bool active;
6528 
6529 	if (event->attr.freq) {
6530 		event->attr.sample_freq = value;
6531 	} else {
6532 		event->attr.sample_period = value;
6533 		event->hw.sample_period = value;
6534 	}
6535 
6536 	active = (event->state == PERF_EVENT_STATE_ACTIVE);
6537 	if (active) {
6538 		perf_pmu_disable(event->pmu);
6539 		event->pmu->stop(event, PERF_EF_UPDATE);
6540 	}
6541 
6542 	local64_set(&event->hw.period_left, 0);
6543 
6544 	if (active) {
6545 		event->pmu->start(event, PERF_EF_RELOAD);
6546 		/*
6547 		 * Once the period is force-reset, the event starts immediately.
6548 		 * But the event/group could be throttled. Unthrottle the
6549 		 * event/group now to avoid the next tick trying to unthrottle
6550 		 * while we already re-started the event/group.
6551 		 */
6552 		if (event->hw.interrupts == MAX_INTERRUPTS)
6553 			perf_event_unthrottle_group(event, true);
6554 		perf_pmu_enable(event->pmu);
6555 	}
6556 }
6557 
6558 static int perf_event_check_period(struct perf_event *event, u64 value)
6559 {
6560 	return event->pmu->check_period(event, value);
6561 }
6562 
6563 static int _perf_event_period(struct perf_event *event, u64 value)
6564 {
6565 	if (!is_sampling_event(event))
6566 		return -EINVAL;
6567 
6568 	if (!value)
6569 		return -EINVAL;
6570 
6571 	if (event->attr.freq) {
6572 		if (value > sysctl_perf_event_sample_rate)
6573 			return -EINVAL;
6574 	} else {
6575 		if (perf_event_check_period(event, value))
6576 			return -EINVAL;
6577 		if (value & (1ULL << 63))
6578 			return -EINVAL;
6579 	}
6580 
6581 	event_function_call(event, __perf_event_period, &value);
6582 
6583 	return 0;
6584 }
6585 
6586 int perf_event_period(struct perf_event *event, u64 value)
6587 {
6588 	struct perf_event_context *ctx;
6589 	int ret;
6590 
6591 	ctx = perf_event_ctx_lock(event);
6592 	ret = _perf_event_period(event, value);
6593 	perf_event_ctx_unlock(event, ctx);
6594 
6595 	return ret;
6596 }
6597 EXPORT_SYMBOL_GPL(perf_event_period);
6598 
6599 static const struct file_operations perf_fops;
6600 
6601 static inline bool is_perf_file(struct fd f)
6602 {
6603 	return !fd_empty(f) && fd_file(f)->f_op == &perf_fops;
6604 }
6605 
6606 static int perf_event_set_output(struct perf_event *event,
6607 				 struct perf_event *output_event);
6608 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
6609 static int perf_copy_attr(struct perf_event_attr __user *uattr,
6610 			  struct perf_event_attr *attr);
6611 static int __perf_event_set_bpf_prog(struct perf_event *event,
6612 				     struct bpf_prog *prog,
6613 				     u64 bpf_cookie);
6614 
6615 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
6616 {
6617 	void (*func)(struct perf_event *);
6618 	u32 flags = arg;
6619 
6620 	if (event->state <= PERF_EVENT_STATE_REVOKED)
6621 		return -ENODEV;
6622 
6623 	switch (cmd) {
6624 	case PERF_EVENT_IOC_ENABLE:
6625 		func = _perf_event_enable;
6626 		break;
6627 	case PERF_EVENT_IOC_DISABLE:
6628 		func = _perf_event_disable;
6629 		break;
6630 	case PERF_EVENT_IOC_RESET:
6631 		func = _perf_event_reset;
6632 		break;
6633 
6634 	case PERF_EVENT_IOC_REFRESH:
6635 		return _perf_event_refresh(event, arg);
6636 
6637 	case PERF_EVENT_IOC_PERIOD:
6638 	{
6639 		u64 value;
6640 
6641 		if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
6642 			return -EFAULT;
6643 
6644 		return _perf_event_period(event, value);
6645 	}
6646 	case PERF_EVENT_IOC_ID:
6647 	{
6648 		u64 id = primary_event_id(event);
6649 
6650 		if (copy_to_user((void __user *)arg, &id, sizeof(id)))
6651 			return -EFAULT;
6652 		return 0;
6653 	}
6654 
6655 	case PERF_EVENT_IOC_SET_OUTPUT:
6656 	{
6657 		CLASS(fd, output)(arg);	     // arg == -1 => empty
6658 		struct perf_event *output_event = NULL;
6659 		if (arg != -1) {
6660 			if (!is_perf_file(output))
6661 				return -EBADF;
6662 			output_event = fd_file(output)->private_data;
6663 		}
6664 		return perf_event_set_output(event, output_event);
6665 	}
6666 
6667 	case PERF_EVENT_IOC_SET_FILTER:
6668 		return perf_event_set_filter(event, (void __user *)arg);
6669 
6670 	case PERF_EVENT_IOC_SET_BPF:
6671 	{
6672 		struct bpf_prog *prog;
6673 		int err;
6674 
6675 		prog = bpf_prog_get(arg);
6676 		if (IS_ERR(prog))
6677 			return PTR_ERR(prog);
6678 
6679 		err = __perf_event_set_bpf_prog(event, prog, 0);
6680 		if (err) {
6681 			bpf_prog_put(prog);
6682 			return err;
6683 		}
6684 
6685 		return 0;
6686 	}
6687 
6688 	case PERF_EVENT_IOC_PAUSE_OUTPUT: {
6689 		struct perf_buffer *rb;
6690 
6691 		rcu_read_lock();
6692 		rb = rcu_dereference(event->rb);
6693 		if (!rb || !rb->nr_pages) {
6694 			rcu_read_unlock();
6695 			return -EINVAL;
6696 		}
6697 		rb_toggle_paused(rb, !!arg);
6698 		rcu_read_unlock();
6699 		return 0;
6700 	}
6701 
6702 	case PERF_EVENT_IOC_QUERY_BPF:
6703 		return perf_event_query_prog_array(event, (void __user *)arg);
6704 
6705 	case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
6706 		struct perf_event_attr new_attr;
6707 		int err = perf_copy_attr((struct perf_event_attr __user *)arg,
6708 					 &new_attr);
6709 
6710 		if (err)
6711 			return err;
6712 
6713 		return perf_event_modify_attr(event,  &new_attr);
6714 	}
6715 	default:
6716 		return -ENOTTY;
6717 	}
6718 
6719 	if (flags & PERF_IOC_FLAG_GROUP)
6720 		perf_event_for_each(event, func);
6721 	else
6722 		perf_event_for_each_child(event, func);
6723 
6724 	return 0;
6725 }
6726 
6727 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
6728 {
6729 	struct perf_event *event = file->private_data;
6730 	struct perf_event_context *ctx;
6731 	long ret;
6732 
6733 	/* Treat ioctl like writes as it is likely a mutating operation. */
6734 	ret = security_perf_event_write(event);
6735 	if (ret)
6736 		return ret;
6737 
6738 	ctx = perf_event_ctx_lock(event);
6739 	ret = _perf_ioctl(event, cmd, arg);
6740 	perf_event_ctx_unlock(event, ctx);
6741 
6742 	return ret;
6743 }
6744 
6745 #ifdef CONFIG_COMPAT
6746 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
6747 				unsigned long arg)
6748 {
6749 	switch (_IOC_NR(cmd)) {
6750 	case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
6751 	case _IOC_NR(PERF_EVENT_IOC_ID):
6752 	case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
6753 	case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
6754 		/* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
6755 		if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
6756 			cmd &= ~IOCSIZE_MASK;
6757 			cmd |= sizeof(void *) << IOCSIZE_SHIFT;
6758 		}
6759 		break;
6760 	}
6761 	return perf_ioctl(file, cmd, arg);
6762 }
6763 #else
6764 # define perf_compat_ioctl NULL
6765 #endif
6766 
6767 int perf_event_task_enable(void)
6768 {
6769 	struct perf_event_context *ctx;
6770 	struct perf_event *event;
6771 
6772 	mutex_lock(&current->perf_event_mutex);
6773 	list_for_each_entry(event, &current->perf_event_list, owner_entry) {
6774 		ctx = perf_event_ctx_lock(event);
6775 		perf_event_for_each_child(event, _perf_event_enable);
6776 		perf_event_ctx_unlock(event, ctx);
6777 	}
6778 	mutex_unlock(&current->perf_event_mutex);
6779 
6780 	return 0;
6781 }
6782 
6783 int perf_event_task_disable(void)
6784 {
6785 	struct perf_event_context *ctx;
6786 	struct perf_event *event;
6787 
6788 	mutex_lock(&current->perf_event_mutex);
6789 	list_for_each_entry(event, &current->perf_event_list, owner_entry) {
6790 		ctx = perf_event_ctx_lock(event);
6791 		perf_event_for_each_child(event, _perf_event_disable);
6792 		perf_event_ctx_unlock(event, ctx);
6793 	}
6794 	mutex_unlock(&current->perf_event_mutex);
6795 
6796 	return 0;
6797 }
6798 
6799 static int perf_event_index(struct perf_event *event)
6800 {
6801 	if (event->hw.state & PERF_HES_STOPPED)
6802 		return 0;
6803 
6804 	if (event->state != PERF_EVENT_STATE_ACTIVE)
6805 		return 0;
6806 
6807 	return event->pmu->event_idx(event);
6808 }
6809 
6810 static void perf_event_init_userpage(struct perf_event *event)
6811 {
6812 	struct perf_event_mmap_page *userpg;
6813 	struct perf_buffer *rb;
6814 
6815 	rcu_read_lock();
6816 	rb = rcu_dereference(event->rb);
6817 	if (!rb)
6818 		goto unlock;
6819 
6820 	userpg = rb->user_page;
6821 
6822 	/* Allow new userspace to detect that bit 0 is deprecated */
6823 	userpg->cap_bit0_is_deprecated = 1;
6824 	userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
6825 	userpg->data_offset = PAGE_SIZE;
6826 	userpg->data_size = perf_data_size(rb);
6827 
6828 unlock:
6829 	rcu_read_unlock();
6830 }
6831 
6832 void __weak arch_perf_update_userpage(
6833 	struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
6834 {
6835 }
6836 
6837 /*
6838  * Callers need to ensure there can be no nesting of this function, otherwise
6839  * the seqlock logic goes bad. We can not serialize this because the arch
6840  * code calls this from NMI context.
6841  */
6842 void perf_event_update_userpage(struct perf_event *event)
6843 {
6844 	struct perf_event_mmap_page *userpg;
6845 	struct perf_buffer *rb;
6846 	u64 enabled, running, now;
6847 
6848 	rcu_read_lock();
6849 	rb = rcu_dereference(event->rb);
6850 	if (!rb)
6851 		goto unlock;
6852 
6853 	/*
6854 	 * Disable preemption to guarantee consistent time stamps are stored to
6855 	 * the user page.
6856 	 */
6857 	preempt_disable();
6858 
6859 	/*
6860 	 * Compute total_time_enabled, total_time_running based on snapshot
6861 	 * values taken when the event was last scheduled in.
6862 	 *
6863 	 * We cannot simply call update_context_time() because doing so would
6864 	 * lead to deadlock when called from NMI context.
6865 	 */
6866 	calc_timer_values(event, &now, &enabled, &running);
6867 
6868 	userpg = rb->user_page;
6869 
6870 	++userpg->lock;
6871 	barrier();
6872 	userpg->index = perf_event_index(event);
6873 	userpg->offset = perf_event_count(event, false);
6874 	if (userpg->index)
6875 		userpg->offset -= local64_read(&event->hw.prev_count);
6876 
6877 	userpg->time_enabled = enabled +
6878 			atomic64_read(&event->child_total_time_enabled);
6879 
6880 	userpg->time_running = running +
6881 			atomic64_read(&event->child_total_time_running);
6882 
6883 	arch_perf_update_userpage(event, userpg, now);
6884 
6885 	barrier();
6886 	++userpg->lock;
6887 	preempt_enable();
6888 unlock:
6889 	rcu_read_unlock();
6890 }
6891 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
6892 
6893 static void ring_buffer_attach(struct perf_event *event,
6894 			       struct perf_buffer *rb)
6895 {
6896 	struct perf_buffer *old_rb = NULL;
6897 	unsigned long flags;
6898 
6899 	WARN_ON_ONCE(event->parent);
6900 
6901 	if (event->rb) {
6902 		/*
6903 		 * Should be impossible, we set this when removing
6904 		 * event->rb_entry and wait/clear when adding event->rb_entry.
6905 		 */
6906 		WARN_ON_ONCE(event->rcu_pending);
6907 
6908 		old_rb = event->rb;
6909 		spin_lock_irqsave(&old_rb->event_lock, flags);
6910 		list_del_rcu(&event->rb_entry);
6911 		spin_unlock_irqrestore(&old_rb->event_lock, flags);
6912 
6913 		event->rcu_batches = get_state_synchronize_rcu();
6914 		event->rcu_pending = 1;
6915 	}
6916 
6917 	if (rb) {
6918 		if (event->rcu_pending) {
6919 			cond_synchronize_rcu(event->rcu_batches);
6920 			event->rcu_pending = 0;
6921 		}
6922 
6923 		spin_lock_irqsave(&rb->event_lock, flags);
6924 		list_add_rcu(&event->rb_entry, &rb->event_list);
6925 		spin_unlock_irqrestore(&rb->event_lock, flags);
6926 	}
6927 
6928 	/*
6929 	 * Avoid racing with perf_mmap_close(AUX): stop the event
6930 	 * before swizzling the event::rb pointer; if it's getting
6931 	 * unmapped, its aux_mmap_count will be 0 and it won't
6932 	 * restart. See the comment in __perf_pmu_output_stop().
6933 	 *
6934 	 * Data will inevitably be lost when set_output is done in
6935 	 * mid-air, but then again, whoever does it like this is
6936 	 * not in for the data anyway.
6937 	 */
6938 	if (has_aux(event))
6939 		perf_event_stop(event, 0);
6940 
6941 	rcu_assign_pointer(event->rb, rb);
6942 
6943 	if (old_rb) {
6944 		ring_buffer_put(old_rb);
6945 		/*
6946 		 * Since we detached before setting the new rb, so that we
6947 		 * could attach the new rb, we could have missed a wakeup.
6948 		 * Provide it now.
6949 		 */
6950 		wake_up_all(&event->waitq);
6951 	}
6952 }
6953 
6954 static void ring_buffer_wakeup(struct perf_event *event)
6955 {
6956 	struct perf_buffer *rb;
6957 
6958 	if (event->parent)
6959 		event = event->parent;
6960 
6961 	rcu_read_lock();
6962 	rb = rcu_dereference(event->rb);
6963 	if (rb) {
6964 		list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
6965 			wake_up_all(&event->waitq);
6966 	}
6967 	rcu_read_unlock();
6968 }
6969 
6970 struct perf_buffer *ring_buffer_get(struct perf_event *event)
6971 {
6972 	struct perf_buffer *rb;
6973 
6974 	if (event->parent)
6975 		event = event->parent;
6976 
6977 	rcu_read_lock();
6978 	rb = rcu_dereference(event->rb);
6979 	if (rb) {
6980 		if (!refcount_inc_not_zero(&rb->refcount))
6981 			rb = NULL;
6982 	}
6983 	rcu_read_unlock();
6984 
6985 	return rb;
6986 }
6987 
6988 void ring_buffer_put(struct perf_buffer *rb)
6989 {
6990 	if (!refcount_dec_and_test(&rb->refcount))
6991 		return;
6992 
6993 	WARN_ON_ONCE(!list_empty(&rb->event_list));
6994 
6995 	call_rcu(&rb->rcu_head, rb_free_rcu);
6996 }
6997 
6998 typedef void (*mapped_f)(struct perf_event *event, struct mm_struct *mm);
6999 
7000 #define get_mapped(event, func)			\
7001 ({	struct pmu *pmu;			\
7002 	mapped_f f = NULL;			\
7003 	guard(rcu)();				\
7004 	pmu = READ_ONCE(event->pmu);		\
7005 	if (pmu)				\
7006 		f = pmu->func;			\
7007 	f;					\
7008 })
7009 
7010 static void perf_mmap_open(struct vm_area_struct *vma)
7011 {
7012 	struct perf_event *event = vma->vm_file->private_data;
7013 	mapped_f mapped = get_mapped(event, event_mapped);
7014 
7015 	refcount_inc(&event->mmap_count);
7016 	refcount_inc(&event->rb->mmap_count);
7017 
7018 	if (vma_start_pgoff(vma))
7019 		refcount_inc(&event->rb->aux_mmap_count);
7020 
7021 	if (mapped)
7022 		mapped(event, vma->vm_mm);
7023 }
7024 
7025 static void perf_pmu_output_stop(struct perf_event *event);
7026 static void perf_mmap_unaccount(struct vm_area_struct *vma, struct perf_buffer *rb);
7027 
7028 /*
7029  * A buffer can be mmap()ed multiple times; either directly through the same
7030  * event, or through other events by use of perf_event_set_output().
7031  *
7032  * In order to undo the VM accounting done by perf_mmap() we need to destroy
7033  * the buffer here, where we still have a VM context. This means we need
7034  * to detach all events redirecting to us.
7035  */
7036 static void perf_mmap_close(struct vm_area_struct *vma)
7037 {
7038 	struct perf_event *event = vma->vm_file->private_data;
7039 	mapped_f unmapped = get_mapped(event, event_unmapped);
7040 	struct perf_buffer *rb = ring_buffer_get(event);
7041 	struct user_struct *mmap_user = rb->mmap_user;
7042 
7043 	/* FIXIES vs perf_pmu_unregister() */
7044 	if (unmapped)
7045 		unmapped(event, vma->vm_mm);
7046 
7047 	/*
7048 	 * The AUX buffer is strictly a sub-buffer, serialize using aux_mutex
7049 	 * to avoid complications.
7050 	 */
7051 	if (rb_has_aux(rb) && vma_start_pgoff(vma) == rb->aux_pgoff &&
7052 	    refcount_dec_and_mutex_lock(&rb->aux_mmap_count, &rb->aux_mutex)) {
7053 		/*
7054 		 * Stop all AUX events that are writing to this buffer,
7055 		 * so that we can free its AUX pages and corresponding PMU
7056 		 * data. Note that after rb::aux_mmap_count dropped to zero,
7057 		 * they won't start any more (see perf_aux_output_begin()).
7058 		 */
7059 		perf_pmu_output_stop(event);
7060 
7061 		/* now it's safe to free the pages */
7062 		atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
7063 		atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
7064 
7065 		/* this has to be the last one */
7066 		rb_free_aux(rb);
7067 		WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
7068 
7069 		mutex_unlock(&rb->aux_mutex);
7070 	}
7071 
7072 	/*
7073 	 * Drop references in reverse order of perf_mmap() to prevent
7074 	 * rb revival after rb->mmap_count reaches zero.
7075 	 */
7076 	if (refcount_dec_and_mutex_lock(&event->mmap_count,
7077 					&event->mmap_mutex)) {
7078 		ring_buffer_attach(event, NULL);
7079 		mutex_unlock(&event->mmap_mutex);
7080 	}
7081 
7082 	/* If there's still other mmap()s of this buffer, we're done. */
7083 	if (!refcount_dec_and_test(&rb->mmap_count))
7084 		goto out_put;
7085 
7086 	/*
7087 	 * No other mmap()s, detach from all other events that might redirect
7088 	 * into the now unreachable buffer. Somewhat complicated by the
7089 	 * fact that rb::event_lock otherwise nests inside mmap_mutex.
7090 	 */
7091 again:
7092 	rcu_read_lock();
7093 	list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
7094 		if (!atomic_long_inc_not_zero(&event->refcount)) {
7095 			/*
7096 			 * This event is en-route to free_event() which will
7097 			 * detach it and remove it from the list.
7098 			 */
7099 			continue;
7100 		}
7101 		rcu_read_unlock();
7102 
7103 		mutex_lock(&event->mmap_mutex);
7104 		/*
7105 		 * Check we didn't race with perf_event_set_output() which can
7106 		 * swizzle the rb from under us while we were waiting to
7107 		 * acquire mmap_mutex.
7108 		 *
7109 		 * If we find a different rb; ignore this event, a next
7110 		 * iteration will no longer find it on the list. We have to
7111 		 * still restart the iteration to make sure we're not now
7112 		 * iterating the wrong list.
7113 		 */
7114 		if (event->rb == rb)
7115 			ring_buffer_attach(event, NULL);
7116 
7117 		mutex_unlock(&event->mmap_mutex);
7118 		put_event(event);
7119 
7120 		/*
7121 		 * Restart the iteration; either we're on the wrong list or
7122 		 * destroyed its integrity by doing a deletion.
7123 		 */
7124 		goto again;
7125 	}
7126 	rcu_read_unlock();
7127 
7128 	/*
7129 	 * It could be there's still a few 0-ref events on the list; they'll
7130 	 * get cleaned up by free_event() -- they'll also still have their
7131 	 * ref on the rb and will free it whenever they are done with it.
7132 	 *
7133 	 * Aside from that, this buffer is 'fully' detached and unmapped,
7134 	 * undo the VM accounting.
7135 	 */
7136 	perf_mmap_unaccount(vma, rb);
7137 
7138 out_put:
7139 	ring_buffer_put(rb); /* could be last */
7140 }
7141 
7142 static vm_fault_t perf_mmap_pfn_mkwrite(struct vm_fault *vmf)
7143 {
7144 	/* The first page is the user control page, others are read-only. */
7145 	return vmf->pgoff == 0 ? 0 : VM_FAULT_SIGBUS;
7146 }
7147 
7148 static int perf_mmap_may_split(struct vm_area_struct *vma, unsigned long addr)
7149 {
7150 	/*
7151 	 * Forbid splitting perf mappings to prevent refcount leaks due to
7152 	 * the resulting non-matching offsets and sizes. See open()/close().
7153 	 */
7154 	return -EINVAL;
7155 }
7156 
7157 static const struct vm_operations_struct perf_mmap_vmops = {
7158 	.open		= perf_mmap_open,
7159 	.close		= perf_mmap_close, /* non mergeable */
7160 	.pfn_mkwrite	= perf_mmap_pfn_mkwrite,
7161 	.may_split	= perf_mmap_may_split,
7162 };
7163 
7164 static int map_range(struct perf_buffer *rb, struct vm_area_struct *vma)
7165 {
7166 	unsigned long nr_pages = vma_pages(vma);
7167 	int err = 0;
7168 	unsigned long pagenum;
7169 
7170 	guard(mutex)(&rb->aux_mutex);
7171 
7172 	/*
7173 	 * We map this as a VM_PFNMAP VMA.
7174 	 *
7175 	 * This is not ideal as this is designed broadly for mappings of PFNs
7176 	 * referencing memory-mapped I/O ranges or non-system RAM i.e. for which
7177 	 * !pfn_valid(pfn).
7178 	 *
7179 	 * We are mapping kernel-allocated memory (memory we manage ourselves)
7180 	 * which would more ideally be mapped using vm_insert_page() or a
7181 	 * similar mechanism, that is as a VM_MIXEDMAP mapping.
7182 	 *
7183 	 * However this won't work here, because:
7184 	 *
7185 	 * 1. It uses vma->vm_page_prot, but this field has not been completely
7186 	 *    setup at the point of the f_op->mmp() hook, so we are unable to
7187 	 *    indicate that this should be mapped CoW in order that the
7188 	 *    mkwrite() hook can be invoked to make the first page R/W and the
7189 	 *    rest R/O as desired.
7190 	 *
7191 	 * 2. Anything other than a VM_PFNMAP of valid PFNs will result in
7192 	 *    vm_normal_page() returning a struct page * pointer, which means
7193 	 *    vm_ops->page_mkwrite() will be invoked rather than
7194 	 *    vm_ops->pfn_mkwrite(), and this means we have to set page->mapping
7195 	 *    to work around retry logic in the fault handler, however this
7196 	 *    field is no longer allowed to be used within struct page.
7197 	 *
7198 	 * 3. Having a struct page * made available in the fault logic also
7199 	 *    means that the page gets put on the rmap and becomes
7200 	 *    inappropriately accessible and subject to map and ref counting.
7201 	 *
7202 	 * Ideally we would have a mechanism that could explicitly express our
7203 	 * desires, but this is not currently the case, so we instead use
7204 	 * VM_PFNMAP.
7205 	 *
7206 	 * We manage the lifetime of these mappings with internal refcounts (see
7207 	 * perf_mmap_open() and perf_mmap_close()) so we ensure the lifetime of
7208 	 * this mapping is maintained correctly.
7209 	 */
7210 	for (pagenum = 0; pagenum < nr_pages; pagenum++) {
7211 		unsigned long va = vma->vm_start + PAGE_SIZE * pagenum;
7212 		struct page *page = perf_mmap_to_page(rb,
7213 				vma_start_pgoff(vma) + pagenum);
7214 
7215 		if (page == NULL) {
7216 			err = -EINVAL;
7217 			break;
7218 		}
7219 
7220 		/* Map readonly, perf_mmap_pfn_mkwrite() called on write fault. */
7221 		err = remap_pfn_range(vma, va, page_to_pfn(page), PAGE_SIZE,
7222 				      vm_get_page_prot(vma->vm_flags & ~VM_SHARED));
7223 		if (err)
7224 			break;
7225 	}
7226 
7227 #ifdef CONFIG_MMU
7228 	/* Clear any partial mappings on error. */
7229 	if (err)
7230 		zap_vma_range(vma, vma->vm_start, nr_pages * PAGE_SIZE);
7231 #endif
7232 
7233 	return err;
7234 }
7235 
7236 static bool perf_mmap_calc_limits(struct vm_area_struct *vma, long *user_extra, long *extra)
7237 {
7238 	unsigned long user_locked, user_lock_limit, locked, lock_limit;
7239 	struct user_struct *user = current_user();
7240 
7241 	user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
7242 	/* Increase the limit linearly with more CPUs */
7243 	user_lock_limit *= num_online_cpus();
7244 
7245 	user_locked = atomic_long_read(&user->locked_vm);
7246 
7247 	/*
7248 	 * sysctl_perf_event_mlock may have changed, so that
7249 	 *     user->locked_vm > user_lock_limit
7250 	 */
7251 	if (user_locked > user_lock_limit)
7252 		user_locked = user_lock_limit;
7253 	user_locked += *user_extra;
7254 
7255 	if (user_locked > user_lock_limit) {
7256 		/*
7257 		 * charge locked_vm until it hits user_lock_limit;
7258 		 * charge the rest from pinned_vm
7259 		 */
7260 		*extra = user_locked - user_lock_limit;
7261 		*user_extra -= *extra;
7262 	}
7263 
7264 	lock_limit = rlimit(RLIMIT_MEMLOCK);
7265 	lock_limit >>= PAGE_SHIFT;
7266 	locked = atomic64_read(&vma->vm_mm->pinned_vm) + *extra;
7267 
7268 	return locked <= lock_limit || !perf_is_paranoid() || capable(CAP_IPC_LOCK);
7269 }
7270 
7271 static void perf_mmap_account(struct vm_area_struct *vma, long user_extra, long extra)
7272 {
7273 	struct user_struct *user = current_user();
7274 
7275 	atomic_long_add(user_extra, &user->locked_vm);
7276 	atomic64_add(extra, &vma->vm_mm->pinned_vm);
7277 }
7278 
7279 static void perf_mmap_unaccount(struct vm_area_struct *vma, struct perf_buffer *rb)
7280 {
7281 	struct user_struct *user = rb->mmap_user;
7282 
7283 	atomic_long_sub((perf_data_size(rb) >> PAGE_SHIFT) + 1 - rb->mmap_locked,
7284 			&user->locked_vm);
7285 	atomic64_sub(rb->mmap_locked, &vma->vm_mm->pinned_vm);
7286 }
7287 
7288 static int perf_mmap_rb(struct vm_area_struct *vma, struct perf_event *event,
7289 			unsigned long nr_pages)
7290 {
7291 	long extra = 0, user_extra = nr_pages;
7292 	struct perf_buffer *rb;
7293 	int rb_flags = 0;
7294 
7295 	nr_pages -= 1;
7296 
7297 	/*
7298 	 * If we have rb pages ensure they're a power-of-two number, so we
7299 	 * can do bitmasks instead of modulo.
7300 	 */
7301 	if (nr_pages != 0 && !is_power_of_2(nr_pages))
7302 		return -EINVAL;
7303 
7304 	WARN_ON_ONCE(event->ctx->parent_ctx);
7305 
7306 	if (event->rb) {
7307 		if (data_page_nr(event->rb) != nr_pages)
7308 			return -EINVAL;
7309 
7310 		/*
7311 		 * If this event doesn't have mmap_count, we're attempting to
7312 		 * create an alias of another event's mmap(); this would mean
7313 		 * both events will end up scribbling the same user_page;
7314 		 * which makes no sense.
7315 		 */
7316 		if (!refcount_read(&event->mmap_count))
7317 			return -EBUSY;
7318 
7319 		if (refcount_inc_not_zero(&event->rb->mmap_count)) {
7320 			/*
7321 			 * Success -- managed to mmap() the same buffer
7322 			 * multiple times.
7323 			 */
7324 			perf_mmap_account(vma, user_extra, extra);
7325 			refcount_inc(&event->mmap_count);
7326 			return 0;
7327 		}
7328 
7329 		/*
7330 		 * Raced against perf_mmap_close()'s
7331 		 * refcount_dec_and_mutex_lock() remove the
7332 		 * event and continue as if !event->rb
7333 		 */
7334 		ring_buffer_attach(event, NULL);
7335 	}
7336 
7337 	if (!perf_mmap_calc_limits(vma, &user_extra, &extra))
7338 		return -EPERM;
7339 
7340 	if (vma->vm_flags & VM_WRITE)
7341 		rb_flags |= RING_BUFFER_WRITABLE;
7342 
7343 	rb = rb_alloc(nr_pages,
7344 		      event->attr.watermark ? event->attr.wakeup_watermark : 0,
7345 		      event->cpu, rb_flags);
7346 
7347 	if (!rb)
7348 		return -ENOMEM;
7349 
7350 	rb->mmap_locked = extra;
7351 
7352 	ring_buffer_attach(event, rb);
7353 
7354 	perf_event_update_time(event);
7355 	perf_event_init_userpage(event);
7356 	perf_event_update_userpage(event);
7357 
7358 	perf_mmap_account(vma, user_extra, extra);
7359 	refcount_set(&event->mmap_count, 1);
7360 
7361 	return 0;
7362 }
7363 
7364 static int perf_mmap_aux(struct vm_area_struct *vma, struct perf_event *event,
7365 			 unsigned long nr_pages)
7366 {
7367 	const pgoff_t pgoff_start = vma_start_pgoff(vma);
7368 	long extra = 0, user_extra = nr_pages;
7369 	u64 aux_offset, aux_size;
7370 	struct perf_buffer *rb;
7371 	int ret, rb_flags = 0;
7372 
7373 	rb = event->rb;
7374 	if (!rb)
7375 		return -EINVAL;
7376 
7377 	guard(mutex)(&rb->aux_mutex);
7378 
7379 	/*
7380 	 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
7381 	 * mapped, all subsequent mappings should have the same size
7382 	 * and offset. Must be above the normal perf buffer.
7383 	 */
7384 	aux_offset = READ_ONCE(rb->user_page->aux_offset);
7385 	aux_size = READ_ONCE(rb->user_page->aux_size);
7386 
7387 	if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
7388 		return -EINVAL;
7389 
7390 	if (aux_offset != pgoff_start << PAGE_SHIFT)
7391 		return -EINVAL;
7392 
7393 	/* already mapped with a different offset */
7394 	if (rb_has_aux(rb) && rb->aux_pgoff != pgoff_start)
7395 		return -EINVAL;
7396 
7397 	if (aux_size != nr_pages * PAGE_SIZE)
7398 		return -EINVAL;
7399 
7400 	/* already mapped with a different size */
7401 	if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
7402 		return -EINVAL;
7403 
7404 	if (!is_power_of_2(nr_pages))
7405 		return -EINVAL;
7406 
7407 	if (!refcount_inc_not_zero(&rb->mmap_count))
7408 		return -EINVAL;
7409 
7410 	if (rb_has_aux(rb)) {
7411 		refcount_inc(&rb->aux_mmap_count);
7412 
7413 	} else {
7414 		if (!perf_mmap_calc_limits(vma, &user_extra, &extra)) {
7415 			refcount_dec(&rb->mmap_count);
7416 			return -EPERM;
7417 		}
7418 
7419 		WARN_ON(!rb && event->rb);
7420 
7421 		if (vma->vm_flags & VM_WRITE)
7422 			rb_flags |= RING_BUFFER_WRITABLE;
7423 
7424 		ret = rb_alloc_aux(rb, event, pgoff_start, nr_pages,
7425 				   event->attr.aux_watermark, rb_flags);
7426 		if (ret) {
7427 			refcount_dec(&rb->mmap_count);
7428 			return ret;
7429 		}
7430 
7431 		refcount_set(&rb->aux_mmap_count, 1);
7432 		rb->aux_mmap_locked = extra;
7433 	}
7434 
7435 	perf_mmap_account(vma, user_extra, extra);
7436 	refcount_inc(&event->mmap_count);
7437 
7438 	return 0;
7439 }
7440 
7441 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
7442 {
7443 	struct perf_event *event = file->private_data;
7444 	unsigned long vma_size, nr_pages;
7445 	mapped_f mapped;
7446 	int ret;
7447 
7448 	/*
7449 	 * Don't allow mmap() of inherited per-task counters. This would
7450 	 * create a performance issue due to all children writing to the
7451 	 * same rb.
7452 	 */
7453 	if (event->cpu == -1 && event->attr.inherit)
7454 		return -EINVAL;
7455 
7456 	if (!(vma->vm_flags & VM_SHARED))
7457 		return -EINVAL;
7458 
7459 	ret = security_perf_event_read(event);
7460 	if (ret)
7461 		return ret;
7462 
7463 	vma_size = vma->vm_end - vma->vm_start;
7464 	nr_pages = vma_size / PAGE_SIZE;
7465 
7466 	if (nr_pages > INT_MAX)
7467 		return -ENOMEM;
7468 
7469 	if (vma_size != PAGE_SIZE * nr_pages)
7470 		return -EINVAL;
7471 
7472 	scoped_guard (mutex, &event->mmap_mutex) {
7473 		/*
7474 		 * This relies on __pmu_detach_event() taking mmap_mutex after marking
7475 		 * the event REVOKED. Either we observe the state, or __pmu_detach_event()
7476 		 * will detach the rb created here.
7477 		 */
7478 		if (event->state <= PERF_EVENT_STATE_REVOKED)
7479 			return -ENODEV;
7480 
7481 		if (!vma_start_pgoff(vma))
7482 			ret = perf_mmap_rb(vma, event, nr_pages);
7483 		else
7484 			ret = perf_mmap_aux(vma, event, nr_pages);
7485 		if (ret)
7486 			return ret;
7487 
7488 		/*
7489 		 * Since pinned accounting is per vm we cannot allow fork() to copy our
7490 		 * vma.
7491 		 */
7492 		vm_flags_set(vma, VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP);
7493 		vma->vm_ops = &perf_mmap_vmops;
7494 
7495 		mapped = get_mapped(event, event_mapped);
7496 		if (mapped)
7497 			mapped(event, vma->vm_mm);
7498 
7499 		/*
7500 		 * Try to map it into the page table. On fail undo the above,
7501 		 * as the callsite expects full cleanup in this case and
7502 		 * therefore does not invoke vmops::close().
7503 		 */
7504 		ret = map_range(event->rb, vma);
7505 		if (likely(!ret))
7506 			return 0;
7507 
7508 		/* Error path */
7509 
7510 		/*
7511 		 * If this is the first mmap(), then event->mmap_count should
7512 		 * be stable at 1. It is only modified by:
7513 		 * perf_mmap_{open,close}() and perf_mmap().
7514 		 *
7515 		 * The former are not possible because this mmap() hasn't been
7516 		 * successful yet, and the latter is serialized by
7517 		 * event->mmap_mutex which we still hold (note that mmap_lock
7518 		 * is not strictly sufficient here, because the event fd can
7519 		 * be passed to another process through trivial means like
7520 		 * fork(), leading to concurrent mmap() from different mm).
7521 		 *
7522 		 * Make sure to remove event->rb before releasing
7523 		 * event->mmap_mutex, such that any concurrent mmap() will not
7524 		 * attempt use this failed buffer.
7525 		 */
7526 		if (refcount_read(&event->mmap_count) == 1) {
7527 			/*
7528 			 * Minimal perf_mmap_close(); there can't be AUX or
7529 			 * other events on account of this being the first.
7530 			 */
7531 			mapped = get_mapped(event, event_unmapped);
7532 			if (mapped)
7533 				mapped(event, vma->vm_mm);
7534 			perf_mmap_unaccount(vma, event->rb);
7535 			ring_buffer_attach(event, NULL);	/* drops last rb->refcount */
7536 			refcount_set(&event->mmap_count, 0);
7537 			return ret;
7538 		}
7539 
7540 		/*
7541 		 * Otherwise this is an already existing buffer, and there is
7542 		 * no race vs first exposure, so fall-through and call
7543 		 * perf_mmap_close().
7544 		 */
7545 	}
7546 
7547 	perf_mmap_close(vma);
7548 	return ret;
7549 }
7550 
7551 static int perf_fasync(int fd, struct file *filp, int on)
7552 {
7553 	struct inode *inode = file_inode(filp);
7554 	struct perf_event *event = filp->private_data;
7555 	int retval;
7556 
7557 	if (event->state <= PERF_EVENT_STATE_REVOKED)
7558 		return -ENODEV;
7559 
7560 	inode_lock(inode);
7561 	retval = fasync_helper(fd, filp, on, &event->fasync);
7562 	inode_unlock(inode);
7563 
7564 	if (retval < 0)
7565 		return retval;
7566 
7567 	return 0;
7568 }
7569 
7570 static void perf_show_fdinfo(struct seq_file *m, struct file *f)
7571 {
7572 	struct perf_event *event = f->private_data;
7573 	struct perf_event_context *ctx;
7574 	struct mutex *child_mutex;
7575 
7576 	ctx = perf_event_ctx_lock(event);
7577 	child_mutex = event->parent ? &event->parent->child_mutex : &event->child_mutex;
7578 	mutex_lock(child_mutex);
7579 
7580 	seq_printf(m, "perf_event_attr.type:\t%u\n", event->orig_type);
7581 	if (event->pmu)
7582 		seq_printf(m, "pmu_type:\t%u\n", event->pmu->type);
7583 	seq_printf(m, "perf_event_attr.config:\t0x%llx\n", (unsigned long long)event->attr.config);
7584 	seq_printf(m, "perf_event_attr.config1:\t0x%llx\n",
7585 		   (unsigned long long)event->attr.config1);
7586 	seq_printf(m, "perf_event_attr.config2:\t0x%llx\n",
7587 		   (unsigned long long)event->attr.config2);
7588 	seq_printf(m, "perf_event_attr.config3:\t0x%llx\n",
7589 		   (unsigned long long)event->attr.config3);
7590 	seq_printf(m, "perf_event_attr.config4:\t0x%llx\n",
7591 		   (unsigned long long)event->attr.config4);
7592 
7593 	mutex_unlock(child_mutex);
7594 	perf_event_ctx_unlock(event, ctx);
7595 }
7596 
7597 static const struct file_operations perf_fops = {
7598 	.release		= perf_release,
7599 	.read			= perf_read,
7600 	.poll			= perf_poll,
7601 	.unlocked_ioctl		= perf_ioctl,
7602 	.compat_ioctl		= perf_compat_ioctl,
7603 	.mmap			= perf_mmap,
7604 	.fasync			= perf_fasync,
7605 	.show_fdinfo		= perf_show_fdinfo,
7606 };
7607 
7608 /*
7609  * Perf event wakeup
7610  *
7611  * If there's data, ensure we set the poll() state and publish everything
7612  * to user-space before waking everybody up.
7613  */
7614 
7615 void perf_event_wakeup(struct perf_event *event)
7616 {
7617 	ring_buffer_wakeup(event);
7618 
7619 	if (event->pending_kill) {
7620 		kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
7621 		event->pending_kill = 0;
7622 	}
7623 }
7624 
7625 static void perf_sigtrap(struct perf_event *event)
7626 {
7627 	/*
7628 	 * Both perf_pending_task() and perf_pending_irq() can race with the
7629 	 * task exiting.
7630 	 */
7631 	if (current->flags & PF_EXITING)
7632 		return;
7633 
7634 	/*
7635 	 * We'd expect this to only occur if the irq_work is delayed and either
7636 	 * ctx->task or current has changed in the meantime. This can be the
7637 	 * case on architectures that do not implement arch_irq_work_raise().
7638 	 */
7639 	if (WARN_ON_ONCE(event->ctx->task != current))
7640 		return;
7641 
7642 	send_sig_perf((void __user *)event->pending_addr,
7643 		      event->orig_type, event->attr.sig_data);
7644 }
7645 
7646 /*
7647  * Deliver the pending work in-event-context or follow the context.
7648  */
7649 static void __perf_pending_disable(struct perf_event *event)
7650 {
7651 	int cpu = READ_ONCE(event->oncpu);
7652 
7653 	/*
7654 	 * If the event isn't running; we done. event_sched_out() will have
7655 	 * taken care of things.
7656 	 */
7657 	if (cpu < 0)
7658 		return;
7659 
7660 	/*
7661 	 * Yay, we hit home and are in the context of the event.
7662 	 */
7663 	if (cpu == smp_processor_id()) {
7664 		if (event->pending_disable) {
7665 			event->pending_disable = 0;
7666 			perf_event_disable_local(event);
7667 		}
7668 		return;
7669 	}
7670 
7671 	/*
7672 	 *  CPU-A			CPU-B
7673 	 *
7674 	 *  perf_event_disable_inatomic()
7675 	 *    @pending_disable = 1;
7676 	 *    irq_work_queue();
7677 	 *
7678 	 *  sched-out
7679 	 *    @pending_disable = 0;
7680 	 *
7681 	 *				sched-in
7682 	 *				perf_event_disable_inatomic()
7683 	 *				  @pending_disable = 1;
7684 	 *				  irq_work_queue(); // FAILS
7685 	 *
7686 	 *  irq_work_run()
7687 	 *    perf_pending_disable()
7688 	 *
7689 	 * But the event runs on CPU-B and wants disabling there.
7690 	 */
7691 	irq_work_queue_on(&event->pending_disable_irq, cpu);
7692 }
7693 
7694 static void perf_pending_disable(struct irq_work *entry)
7695 {
7696 	struct perf_event *event = container_of(entry, struct perf_event, pending_disable_irq);
7697 	int rctx;
7698 
7699 	/*
7700 	 * If we 'fail' here, that's OK, it means recursion is already disabled
7701 	 * and we won't recurse 'further'.
7702 	 */
7703 	rctx = perf_swevent_get_recursion_context();
7704 	__perf_pending_disable(event);
7705 	if (rctx >= 0)
7706 		perf_swevent_put_recursion_context(rctx);
7707 }
7708 
7709 static void perf_pending_irq(struct irq_work *entry)
7710 {
7711 	struct perf_event *event = container_of(entry, struct perf_event, pending_irq);
7712 	int rctx;
7713 
7714 	/*
7715 	 * If we 'fail' here, that's OK, it means recursion is already disabled
7716 	 * and we won't recurse 'further'.
7717 	 */
7718 	rctx = perf_swevent_get_recursion_context();
7719 
7720 	/*
7721 	 * The wakeup isn't bound to the context of the event -- it can happen
7722 	 * irrespective of where the event is.
7723 	 */
7724 	if (event->pending_wakeup) {
7725 		event->pending_wakeup = 0;
7726 		perf_event_wakeup(event);
7727 	}
7728 
7729 	if (rctx >= 0)
7730 		perf_swevent_put_recursion_context(rctx);
7731 }
7732 
7733 static void perf_pending_task(struct callback_head *head)
7734 {
7735 	struct perf_event *event = container_of(head, struct perf_event, pending_task);
7736 	int rctx;
7737 
7738 	/*
7739 	 * If we 'fail' here, that's OK, it means recursion is already disabled
7740 	 * and we won't recurse 'further'.
7741 	 */
7742 	rctx = perf_swevent_get_recursion_context();
7743 
7744 	if (event->pending_work) {
7745 		event->pending_work = 0;
7746 		perf_sigtrap(event);
7747 		local_dec(&event->ctx->nr_no_switch_fast);
7748 	}
7749 	put_event(event);
7750 
7751 	if (rctx >= 0)
7752 		perf_swevent_put_recursion_context(rctx);
7753 }
7754 
7755 #ifdef CONFIG_GUEST_PERF_EVENTS
7756 struct perf_guest_info_callbacks __rcu *perf_guest_cbs;
7757 
7758 DEFINE_STATIC_CALL_RET0(__perf_guest_state, *perf_guest_cbs->state);
7759 DEFINE_STATIC_CALL_RET0(__perf_guest_get_ip, *perf_guest_cbs->get_ip);
7760 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr);
7761 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_mediated_pmi, *perf_guest_cbs->handle_mediated_pmi);
7762 
7763 void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
7764 {
7765 	if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs)))
7766 		return;
7767 
7768 	rcu_assign_pointer(perf_guest_cbs, cbs);
7769 	static_call_update(__perf_guest_state, cbs->state);
7770 	static_call_update(__perf_guest_get_ip, cbs->get_ip);
7771 
7772 	/* Implementing ->handle_intel_pt_intr is optional. */
7773 	if (cbs->handle_intel_pt_intr)
7774 		static_call_update(__perf_guest_handle_intel_pt_intr,
7775 				   cbs->handle_intel_pt_intr);
7776 
7777 	if (cbs->handle_mediated_pmi)
7778 		static_call_update(__perf_guest_handle_mediated_pmi,
7779 				   cbs->handle_mediated_pmi);
7780 }
7781 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
7782 
7783 void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
7784 {
7785 	if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs) != cbs))
7786 		return;
7787 
7788 	rcu_assign_pointer(perf_guest_cbs, NULL);
7789 	static_call_update(__perf_guest_state, (void *)&__static_call_return0);
7790 	static_call_update(__perf_guest_get_ip, (void *)&__static_call_return0);
7791 	static_call_update(__perf_guest_handle_intel_pt_intr, (void *)&__static_call_return0);
7792 	static_call_update(__perf_guest_handle_mediated_pmi, (void *)&__static_call_return0);
7793 	synchronize_rcu();
7794 }
7795 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
7796 #endif
7797 
7798 static bool should_sample_guest(struct perf_event *event)
7799 {
7800 	return !event->attr.exclude_guest && perf_guest_state();
7801 }
7802 
7803 unsigned long perf_misc_flags(struct perf_event *event,
7804 			      struct pt_regs *regs)
7805 {
7806 	if (should_sample_guest(event))
7807 		return perf_arch_guest_misc_flags(regs);
7808 
7809 	return perf_arch_misc_flags(regs);
7810 }
7811 
7812 unsigned long perf_instruction_pointer(struct perf_event *event,
7813 				       struct pt_regs *regs)
7814 {
7815 	/*
7816 	 * Hardware skid can lead to a scenario where a PMI is
7817 	 * delivered after the CPU has already entered kernel mode.
7818 	 * In that case, user-space sampling must not expose kernel
7819 	 * register state.
7820 	 */
7821 	if (should_sample_guest(event)) {
7822 		return event->attr.exclude_kernel &&
7823 		       !(perf_guest_state() & PERF_GUEST_USER) ?
7824 			0 : perf_guest_get_ip();
7825 	}
7826 
7827 	return event->attr.exclude_kernel && !user_mode(regs) ?
7828 		0 : perf_arch_instruction_pointer(regs);
7829 }
7830 
7831 static void
7832 perf_output_sample_regs(struct perf_output_handle *handle,
7833 			struct pt_regs *regs, u64 mask)
7834 {
7835 	int bit;
7836 	DECLARE_BITMAP(_mask, 64);
7837 
7838 	bitmap_from_u64(_mask, mask);
7839 	for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
7840 		u64 val;
7841 
7842 		val = perf_reg_value(regs, bit);
7843 		perf_output_put(handle, val);
7844 	}
7845 }
7846 
7847 static void perf_sample_regs_user(struct perf_regs *regs_user,
7848 				  struct pt_regs *regs)
7849 {
7850 	if (user_mode(regs)) {
7851 		regs_user->abi = perf_reg_abi(current);
7852 		regs_user->regs = regs;
7853 	} else if (is_user_task(current)) {
7854 		perf_get_regs_user(regs_user, regs);
7855 	} else {
7856 		regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
7857 		regs_user->regs = NULL;
7858 	}
7859 }
7860 
7861 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
7862 				  struct pt_regs *regs,
7863 				  bool exclude_kernel)
7864 {
7865 	/*
7866 	 * Hardware skid can lead to a scenario where a PMI is
7867 	 * delivered after the CPU has already entered kernel mode.
7868 	 * In that case, user-space sampling must not expose kernel
7869 	 * register state.
7870 	 */
7871 	if (exclude_kernel && !user_mode(regs)) {
7872 		regs_intr->abi = PERF_SAMPLE_REGS_ABI_NONE;
7873 		regs_intr->regs = NULL;
7874 	} else {
7875 		regs_intr->regs = regs;
7876 		regs_intr->abi = perf_reg_abi(current);
7877 	}
7878 }
7879 
7880 
7881 /*
7882  * Get remaining task size from user stack pointer.
7883  *
7884  * It'd be better to take stack vma map and limit this more
7885  * precisely, but there's no way to get it safely under interrupt,
7886  * so using TASK_SIZE as limit.
7887  */
7888 static u64 perf_ustack_task_size(struct pt_regs *regs)
7889 {
7890 	unsigned long addr = perf_user_stack_pointer(regs);
7891 
7892 	if (!addr || addr >= TASK_SIZE)
7893 		return 0;
7894 
7895 	return TASK_SIZE - addr;
7896 }
7897 
7898 static u16
7899 perf_sample_ustack_size(u16 stack_size, u16 header_size,
7900 			struct pt_regs *regs)
7901 {
7902 	u64 task_size;
7903 
7904 	/* No regs, no stack pointer, no dump. */
7905 	if (!regs)
7906 		return 0;
7907 
7908 	/* No mm, no stack, no dump. */
7909 	if (!current->mm)
7910 		return 0;
7911 
7912 	/*
7913 	 * Check if we fit in with the requested stack size into the:
7914 	 * - TASK_SIZE
7915 	 *   If we don't, we limit the size to the TASK_SIZE.
7916 	 *
7917 	 * - remaining sample size
7918 	 *   If we don't, we customize the stack size to
7919 	 *   fit in to the remaining sample size.
7920 	 */
7921 
7922 	task_size  = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
7923 	stack_size = min(stack_size, (u16) task_size);
7924 
7925 	/* Current header size plus static size and dynamic size. */
7926 	header_size += 2 * sizeof(u64);
7927 
7928 	/* Do we fit in with the current stack dump size? */
7929 	if ((u16) (header_size + stack_size) < header_size) {
7930 		/*
7931 		 * If we overflow the maximum size for the sample,
7932 		 * we customize the stack dump size to fit in.
7933 		 */
7934 		stack_size = USHRT_MAX - header_size - sizeof(u64);
7935 		stack_size = round_up(stack_size, sizeof(u64));
7936 	}
7937 
7938 	return stack_size;
7939 }
7940 
7941 static void
7942 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
7943 			  struct pt_regs *regs)
7944 {
7945 	/* Case of a kernel thread, nothing to dump */
7946 	if (!regs) {
7947 		u64 size = 0;
7948 		perf_output_put(handle, size);
7949 	} else {
7950 		unsigned long sp;
7951 		unsigned int rem;
7952 		u64 dyn_size;
7953 
7954 		/*
7955 		 * We dump:
7956 		 * static size
7957 		 *   - the size requested by user or the best one we can fit
7958 		 *     in to the sample max size
7959 		 * data
7960 		 *   - user stack dump data
7961 		 * dynamic size
7962 		 *   - the actual dumped size
7963 		 */
7964 
7965 		/* Static size. */
7966 		perf_output_put(handle, dump_size);
7967 
7968 		/* Data. */
7969 		sp = perf_user_stack_pointer(regs);
7970 		rem = __output_copy_user(handle, (void *) sp, dump_size);
7971 		dyn_size = dump_size - rem;
7972 
7973 		perf_output_skip(handle, rem);
7974 
7975 		/* Dynamic size. */
7976 		perf_output_put(handle, dyn_size);
7977 	}
7978 }
7979 
7980 static unsigned long perf_prepare_sample_aux(struct perf_event *event,
7981 					  struct perf_sample_data *data,
7982 					  size_t size)
7983 {
7984 	struct perf_event *sampler = event->aux_event;
7985 	struct perf_buffer *rb;
7986 
7987 	data->aux_size = 0;
7988 
7989 	if (!sampler)
7990 		goto out;
7991 
7992 	if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
7993 		goto out;
7994 
7995 	if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
7996 		goto out;
7997 
7998 	rb = ring_buffer_get(sampler);
7999 	if (!rb)
8000 		goto out;
8001 
8002 	/*
8003 	 * If this is an NMI hit inside sampling code, don't take
8004 	 * the sample. See also perf_aux_sample_output().
8005 	 */
8006 	if (READ_ONCE(rb->aux_in_sampling)) {
8007 		data->aux_size = 0;
8008 	} else {
8009 		size = min_t(size_t, size, perf_aux_size(rb));
8010 		data->aux_size = ALIGN(size, sizeof(u64));
8011 	}
8012 	ring_buffer_put(rb);
8013 
8014 out:
8015 	return data->aux_size;
8016 }
8017 
8018 static long perf_pmu_snapshot_aux(struct perf_buffer *rb,
8019                                  struct perf_event *event,
8020                                  struct perf_output_handle *handle,
8021                                  unsigned long size)
8022 {
8023 	unsigned long flags;
8024 	long ret;
8025 
8026 	/*
8027 	 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
8028 	 * paths. If we start calling them in NMI context, they may race with
8029 	 * the IRQ ones, that is, for example, re-starting an event that's just
8030 	 * been stopped, which is why we're using a separate callback that
8031 	 * doesn't change the event state.
8032 	 *
8033 	 * IRQs need to be disabled to prevent IPIs from racing with us.
8034 	 */
8035 	local_irq_save(flags);
8036 	/*
8037 	 * Guard against NMI hits inside the critical section;
8038 	 * see also perf_prepare_sample_aux().
8039 	 */
8040 	WRITE_ONCE(rb->aux_in_sampling, 1);
8041 	barrier();
8042 
8043 	ret = event->pmu->snapshot_aux(event, handle, size);
8044 
8045 	barrier();
8046 	WRITE_ONCE(rb->aux_in_sampling, 0);
8047 	local_irq_restore(flags);
8048 
8049 	return ret;
8050 }
8051 
8052 static void perf_aux_sample_output(struct perf_event *event,
8053 				   struct perf_output_handle *handle,
8054 				   struct perf_sample_data *data)
8055 {
8056 	struct perf_event *sampler = event->aux_event;
8057 	struct perf_buffer *rb;
8058 	unsigned long pad;
8059 	long size;
8060 
8061 	if (WARN_ON_ONCE(!sampler || !data->aux_size))
8062 		return;
8063 
8064 	rb = ring_buffer_get(sampler);
8065 	if (!rb)
8066 		return;
8067 
8068 	size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
8069 
8070 	/*
8071 	 * An error here means that perf_output_copy() failed (returned a
8072 	 * non-zero surplus that it didn't copy), which in its current
8073 	 * enlightened implementation is not possible. If that changes, we'd
8074 	 * like to know.
8075 	 */
8076 	if (WARN_ON_ONCE(size < 0))
8077 		goto out_put;
8078 
8079 	/*
8080 	 * The pad comes from ALIGN()ing data->aux_size up to u64 in
8081 	 * perf_prepare_sample_aux(), so should not be more than that.
8082 	 */
8083 	pad = data->aux_size - size;
8084 	if (WARN_ON_ONCE(pad >= sizeof(u64)))
8085 		pad = 8;
8086 
8087 	if (pad) {
8088 		u64 zero = 0;
8089 		perf_output_copy(handle, &zero, pad);
8090 	}
8091 
8092 out_put:
8093 	ring_buffer_put(rb);
8094 }
8095 
8096 /*
8097  * A set of common sample data types saved even for non-sample records
8098  * when event->attr.sample_id_all is set.
8099  */
8100 #define PERF_SAMPLE_ID_ALL  (PERF_SAMPLE_TID | PERF_SAMPLE_TIME |	\
8101 			     PERF_SAMPLE_ID | PERF_SAMPLE_STREAM_ID |	\
8102 			     PERF_SAMPLE_CPU | PERF_SAMPLE_IDENTIFIER)
8103 
8104 static void __perf_event_header__init_id(struct perf_sample_data *data,
8105 					 struct perf_event *event,
8106 					 u64 sample_type)
8107 {
8108 	data->type = event->attr.sample_type;
8109 	data->sample_flags |= data->type & PERF_SAMPLE_ID_ALL;
8110 
8111 	if (sample_type & PERF_SAMPLE_TID) {
8112 		/* namespace issues */
8113 		data->tid_entry.pid = perf_event_pid(event, current);
8114 		data->tid_entry.tid = perf_event_tid(event, current);
8115 	}
8116 
8117 	if (sample_type & PERF_SAMPLE_TIME)
8118 		data->time = perf_event_clock(event);
8119 
8120 	if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
8121 		data->id = primary_event_id(event);
8122 
8123 	if (sample_type & PERF_SAMPLE_STREAM_ID)
8124 		data->stream_id = event->id;
8125 
8126 	if (sample_type & PERF_SAMPLE_CPU) {
8127 		data->cpu_entry.cpu	 = raw_smp_processor_id();
8128 		data->cpu_entry.reserved = 0;
8129 	}
8130 }
8131 
8132 void perf_event_header__init_id(struct perf_event_header *header,
8133 				struct perf_sample_data *data,
8134 				struct perf_event *event)
8135 {
8136 	if (event->attr.sample_id_all) {
8137 		header->size += event->id_header_size;
8138 		__perf_event_header__init_id(data, event, event->attr.sample_type);
8139 	}
8140 }
8141 
8142 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
8143 					   struct perf_sample_data *data)
8144 {
8145 	u64 sample_type = data->type;
8146 
8147 	if (sample_type & PERF_SAMPLE_TID)
8148 		perf_output_put(handle, data->tid_entry);
8149 
8150 	if (sample_type & PERF_SAMPLE_TIME)
8151 		perf_output_put(handle, data->time);
8152 
8153 	if (sample_type & PERF_SAMPLE_ID)
8154 		perf_output_put(handle, data->id);
8155 
8156 	if (sample_type & PERF_SAMPLE_STREAM_ID)
8157 		perf_output_put(handle, data->stream_id);
8158 
8159 	if (sample_type & PERF_SAMPLE_CPU)
8160 		perf_output_put(handle, data->cpu_entry);
8161 
8162 	if (sample_type & PERF_SAMPLE_IDENTIFIER)
8163 		perf_output_put(handle, data->id);
8164 }
8165 
8166 void perf_event__output_id_sample(struct perf_event *event,
8167 				  struct perf_output_handle *handle,
8168 				  struct perf_sample_data *sample)
8169 {
8170 	if (event->attr.sample_id_all)
8171 		__perf_event__output_id_sample(handle, sample);
8172 }
8173 
8174 static void perf_output_read_one(struct perf_output_handle *handle,
8175 				 struct perf_event *event,
8176 				 u64 enabled, u64 running)
8177 {
8178 	u64 read_format = event->attr.read_format;
8179 	u64 values[5];
8180 	int n = 0;
8181 
8182 	values[n++] = perf_event_count(event, has_inherit_and_sample_read(&event->attr));
8183 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
8184 		values[n++] = enabled +
8185 			atomic64_read(&event->child_total_time_enabled);
8186 	}
8187 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
8188 		values[n++] = running +
8189 			atomic64_read(&event->child_total_time_running);
8190 	}
8191 	if (read_format & PERF_FORMAT_ID)
8192 		values[n++] = primary_event_id(event);
8193 	if (read_format & PERF_FORMAT_LOST)
8194 		values[n++] = atomic64_read(&event->lost_samples);
8195 
8196 	__output_copy(handle, values, n * sizeof(u64));
8197 }
8198 
8199 static void perf_output_read_group(struct perf_output_handle *handle,
8200 				   struct perf_event *event,
8201 				   u64 enabled, u64 running)
8202 {
8203 	struct perf_event *leader = event->group_leader, *sub;
8204 	u64 read_format = event->attr.read_format;
8205 	unsigned long flags;
8206 	u64 values[6];
8207 	int n = 0;
8208 	bool self = has_inherit_and_sample_read(&event->attr);
8209 
8210 	/*
8211 	 * Disabling interrupts avoids all counter scheduling
8212 	 * (context switches, timer based rotation and IPIs).
8213 	 */
8214 	local_irq_save(flags);
8215 
8216 	values[n++] = 1 + leader->nr_siblings;
8217 
8218 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
8219 		values[n++] = enabled;
8220 
8221 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
8222 		values[n++] = running;
8223 
8224 	if ((leader != event) && !handle->skip_read)
8225 		perf_pmu_read(leader);
8226 
8227 	values[n++] = perf_event_count(leader, self);
8228 	if (read_format & PERF_FORMAT_ID)
8229 		values[n++] = primary_event_id(leader);
8230 	if (read_format & PERF_FORMAT_LOST)
8231 		values[n++] = atomic64_read(&leader->lost_samples);
8232 
8233 	__output_copy(handle, values, n * sizeof(u64));
8234 
8235 	for_each_sibling_event(sub, leader) {
8236 		n = 0;
8237 
8238 		if ((sub != event) && !handle->skip_read)
8239 			perf_pmu_read(sub);
8240 
8241 		values[n++] = perf_event_count(sub, self);
8242 		if (read_format & PERF_FORMAT_ID)
8243 			values[n++] = primary_event_id(sub);
8244 		if (read_format & PERF_FORMAT_LOST)
8245 			values[n++] = atomic64_read(&sub->lost_samples);
8246 
8247 		__output_copy(handle, values, n * sizeof(u64));
8248 	}
8249 
8250 	local_irq_restore(flags);
8251 }
8252 
8253 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
8254 				 PERF_FORMAT_TOTAL_TIME_RUNNING)
8255 
8256 /*
8257  * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
8258  *
8259  * The problem is that its both hard and excessively expensive to iterate the
8260  * child list, not to mention that its impossible to IPI the children running
8261  * on another CPU, from interrupt/NMI context.
8262  *
8263  * Instead the combination of PERF_SAMPLE_READ and inherit will track per-thread
8264  * counts rather than attempting to accumulate some value across all children on
8265  * all cores.
8266  */
8267 static void perf_output_read(struct perf_output_handle *handle,
8268 			     struct perf_event *event)
8269 {
8270 	u64 enabled = 0, running = 0, now;
8271 	u64 read_format = event->attr.read_format;
8272 
8273 	/*
8274 	 * Compute total_time_enabled, total_time_running based on snapshot
8275 	 * values taken when the event was last scheduled in.
8276 	 *
8277 	 * We cannot simply call update_context_time() because doing so would
8278 	 * lead to deadlock when called from NMI context.
8279 	 */
8280 	if (read_format & PERF_FORMAT_TOTAL_TIMES)
8281 		calc_timer_values(event, &now, &enabled, &running);
8282 
8283 	if (event->attr.read_format & PERF_FORMAT_GROUP)
8284 		perf_output_read_group(handle, event, enabled, running);
8285 	else
8286 		perf_output_read_one(handle, event, enabled, running);
8287 }
8288 
8289 void perf_output_sample(struct perf_output_handle *handle,
8290 			struct perf_event_header *header,
8291 			struct perf_sample_data *data,
8292 			struct perf_event *event)
8293 {
8294 	u64 sample_type = data->type;
8295 
8296 	if (data->sample_flags & PERF_SAMPLE_READ)
8297 		handle->skip_read = 1;
8298 
8299 	perf_output_put(handle, *header);
8300 
8301 	if (sample_type & PERF_SAMPLE_IDENTIFIER)
8302 		perf_output_put(handle, data->id);
8303 
8304 	if (sample_type & PERF_SAMPLE_IP)
8305 		perf_output_put(handle, data->ip);
8306 
8307 	if (sample_type & PERF_SAMPLE_TID)
8308 		perf_output_put(handle, data->tid_entry);
8309 
8310 	if (sample_type & PERF_SAMPLE_TIME)
8311 		perf_output_put(handle, data->time);
8312 
8313 	if (sample_type & PERF_SAMPLE_ADDR)
8314 		perf_output_put(handle, data->addr);
8315 
8316 	if (sample_type & PERF_SAMPLE_ID)
8317 		perf_output_put(handle, data->id);
8318 
8319 	if (sample_type & PERF_SAMPLE_STREAM_ID)
8320 		perf_output_put(handle, data->stream_id);
8321 
8322 	if (sample_type & PERF_SAMPLE_CPU)
8323 		perf_output_put(handle, data->cpu_entry);
8324 
8325 	if (sample_type & PERF_SAMPLE_PERIOD)
8326 		perf_output_put(handle, data->period);
8327 
8328 	if (sample_type & PERF_SAMPLE_READ)
8329 		perf_output_read(handle, event);
8330 
8331 	if (sample_type & PERF_SAMPLE_CALLCHAIN) {
8332 		int size = 1;
8333 
8334 		size += data->callchain->nr;
8335 		size *= sizeof(u64);
8336 		__output_copy(handle, data->callchain, size);
8337 	}
8338 
8339 	if (sample_type & PERF_SAMPLE_RAW) {
8340 		struct perf_raw_record *raw = data->raw;
8341 
8342 		if (raw) {
8343 			struct perf_raw_frag *frag = &raw->frag;
8344 
8345 			perf_output_put(handle, raw->size);
8346 			do {
8347 				if (frag->copy) {
8348 					__output_custom(handle, frag->copy,
8349 							frag->data, frag->size);
8350 				} else {
8351 					__output_copy(handle, frag->data,
8352 						      frag->size);
8353 				}
8354 				if (perf_raw_frag_last(frag))
8355 					break;
8356 				frag = frag->next;
8357 			} while (1);
8358 			if (frag->pad)
8359 				__output_skip(handle, NULL, frag->pad);
8360 		} else {
8361 			struct {
8362 				u32	size;
8363 				u32	data;
8364 			} raw = {
8365 				.size = sizeof(u32),
8366 				.data = 0,
8367 			};
8368 			perf_output_put(handle, raw);
8369 		}
8370 	}
8371 
8372 	if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
8373 		if (data->br_stack) {
8374 			size_t size;
8375 
8376 			size = data->br_stack->nr
8377 			     * sizeof(struct perf_branch_entry);
8378 
8379 			perf_output_put(handle, data->br_stack->nr);
8380 			if (branch_sample_hw_index(event))
8381 				perf_output_put(handle, data->br_stack->hw_idx);
8382 			perf_output_copy(handle, data->br_stack->entries, size);
8383 			/*
8384 			 * Add the extension space which is appended
8385 			 * right after the struct perf_branch_stack.
8386 			 */
8387 			if (data->br_stack_cntr) {
8388 				size = data->br_stack->nr * sizeof(u64);
8389 				perf_output_copy(handle, data->br_stack_cntr, size);
8390 			}
8391 		} else {
8392 			/*
8393 			 * we always store at least the value of nr
8394 			 */
8395 			u64 nr = 0;
8396 			perf_output_put(handle, nr);
8397 		}
8398 	}
8399 
8400 	if (sample_type & PERF_SAMPLE_REGS_USER) {
8401 		u64 abi = data->regs_user.abi;
8402 
8403 		/*
8404 		 * If there are no regs to dump, notice it through
8405 		 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
8406 		 */
8407 		perf_output_put(handle, abi);
8408 
8409 		if (abi) {
8410 			u64 mask = event->attr.sample_regs_user;
8411 			perf_output_sample_regs(handle,
8412 						data->regs_user.regs,
8413 						mask);
8414 		}
8415 	}
8416 
8417 	if (sample_type & PERF_SAMPLE_STACK_USER) {
8418 		perf_output_sample_ustack(handle,
8419 					  data->stack_user_size,
8420 					  data->regs_user.regs);
8421 	}
8422 
8423 	if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
8424 		perf_output_put(handle, data->weight.full);
8425 
8426 	if (sample_type & PERF_SAMPLE_DATA_SRC)
8427 		perf_output_put(handle, data->data_src.val);
8428 
8429 	if (sample_type & PERF_SAMPLE_TRANSACTION)
8430 		perf_output_put(handle, data->txn);
8431 
8432 	if (sample_type & PERF_SAMPLE_REGS_INTR) {
8433 		u64 abi = data->regs_intr.abi;
8434 		/*
8435 		 * If there are no regs to dump, notice it through
8436 		 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
8437 		 */
8438 		perf_output_put(handle, abi);
8439 
8440 		if (abi) {
8441 			u64 mask = event->attr.sample_regs_intr;
8442 
8443 			perf_output_sample_regs(handle,
8444 						data->regs_intr.regs,
8445 						mask);
8446 		}
8447 	}
8448 
8449 	if (sample_type & PERF_SAMPLE_PHYS_ADDR)
8450 		perf_output_put(handle, data->phys_addr);
8451 
8452 	if (sample_type & PERF_SAMPLE_CGROUP)
8453 		perf_output_put(handle, data->cgroup);
8454 
8455 	if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
8456 		perf_output_put(handle, data->data_page_size);
8457 
8458 	if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
8459 		perf_output_put(handle, data->code_page_size);
8460 
8461 	if (sample_type & PERF_SAMPLE_AUX) {
8462 		perf_output_put(handle, data->aux_size);
8463 
8464 		if (data->aux_size)
8465 			perf_aux_sample_output(event, handle, data);
8466 	}
8467 
8468 	if (!event->attr.watermark) {
8469 		int wakeup_events = event->attr.wakeup_events;
8470 
8471 		if (wakeup_events) {
8472 			struct perf_buffer *rb = handle->rb;
8473 			int events = local_inc_return(&rb->events);
8474 
8475 			if (events >= wakeup_events) {
8476 				local_sub(wakeup_events, &rb->events);
8477 				local_inc(&rb->wakeup);
8478 			}
8479 		}
8480 	}
8481 }
8482 
8483 static u64 perf_virt_to_phys(u64 virt)
8484 {
8485 	u64 phys_addr = 0;
8486 
8487 	if (!virt)
8488 		return 0;
8489 
8490 	if (virt >= TASK_SIZE) {
8491 		/* If it's vmalloc()d memory, leave phys_addr as 0 */
8492 		if (virt_addr_valid((void *)(uintptr_t)virt) &&
8493 		    !(virt >= VMALLOC_START && virt < VMALLOC_END))
8494 			phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
8495 	} else {
8496 		/*
8497 		 * Walking the pages tables for user address.
8498 		 * Interrupts are disabled, so it prevents any tear down
8499 		 * of the page tables.
8500 		 * Try IRQ-safe get_user_page_fast_only first.
8501 		 * If failed, leave phys_addr as 0.
8502 		 */
8503 		if (is_user_task(current)) {
8504 			struct page *p;
8505 
8506 			pagefault_disable();
8507 			if (get_user_page_fast_only(virt, 0, &p)) {
8508 				phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
8509 				put_page(p);
8510 			}
8511 			pagefault_enable();
8512 		}
8513 	}
8514 
8515 	return phys_addr;
8516 }
8517 
8518 /*
8519  * Return the pagetable size of a given virtual address.
8520  */
8521 static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
8522 {
8523 	u64 size = 0;
8524 
8525 #ifdef CONFIG_HAVE_GUP_FAST
8526 	pgd_t *pgdp, pgd;
8527 	p4d_t *p4dp, p4d;
8528 	pud_t *pudp, pud;
8529 	pmd_t *pmdp, pmd;
8530 	pte_t *ptep, pte;
8531 
8532 	pgdp = pgd_offset(mm, addr);
8533 	pgd = pgdp_get(pgdp);
8534 	if (pgd_none(pgd))
8535 		return 0;
8536 
8537 	if (pgd_leaf(pgd))
8538 		return pgd_leaf_size(pgd);
8539 
8540 	p4dp = p4d_offset_lockless(pgdp, pgd, addr);
8541 	p4d = p4dp_get(p4dp);
8542 	if (!p4d_present(p4d))
8543 		return 0;
8544 
8545 	if (p4d_leaf(p4d))
8546 		return p4d_leaf_size(p4d);
8547 
8548 	pudp = pud_offset_lockless(p4dp, p4d, addr);
8549 	pud = pudp_get(pudp);
8550 	if (!pud_present(pud))
8551 		return 0;
8552 
8553 	if (pud_leaf(pud))
8554 		return pud_leaf_size(pud);
8555 
8556 	pmdp = pmd_offset_lockless(pudp, pud, addr);
8557 again:
8558 	pmd = pmdp_get_lockless(pmdp);
8559 	if (!pmd_present(pmd))
8560 		return 0;
8561 
8562 	if (pmd_leaf(pmd))
8563 		return pmd_leaf_size(pmd);
8564 
8565 	ptep = pte_offset_map(&pmd, addr);
8566 	if (!ptep)
8567 		goto again;
8568 
8569 	pte = ptep_get_lockless(ptep);
8570 	if (pte_present(pte))
8571 		size = __pte_leaf_size(pmd, pte);
8572 	pte_unmap(ptep);
8573 #endif /* CONFIG_HAVE_GUP_FAST */
8574 
8575 	return size;
8576 }
8577 
8578 static u64 perf_get_page_size(unsigned long addr)
8579 {
8580 	struct mm_struct *mm;
8581 	unsigned long flags;
8582 	u64 size;
8583 
8584 	if (!addr)
8585 		return 0;
8586 
8587 	/*
8588 	 * Software page-table walkers must disable IRQs,
8589 	 * which prevents any tear down of the page tables.
8590 	 */
8591 	local_irq_save(flags);
8592 
8593 	mm = current->mm;
8594 	if (!mm) {
8595 		/*
8596 		 * For kernel threads and the like, use init_mm so that
8597 		 * we can find kernel memory.
8598 		 */
8599 		mm = &init_mm;
8600 	}
8601 
8602 	size = perf_get_pgtable_size(mm, addr);
8603 
8604 	local_irq_restore(flags);
8605 
8606 	return size;
8607 }
8608 
8609 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
8610 
8611 static struct unwind_work perf_unwind_work;
8612 
8613 struct perf_callchain_entry *
8614 perf_callchain(struct perf_event *event, struct pt_regs *regs)
8615 {
8616 	bool kernel = !event->attr.exclude_callchain_kernel;
8617 	bool user   = !event->attr.exclude_callchain_user &&
8618 		is_user_task(current);
8619 	/* Disallow cross-task user callchains. */
8620 	bool crosstask = event->ctx->task && event->ctx->task != current;
8621 	bool defer_user = IS_ENABLED(CONFIG_UNWIND_USER) && user &&
8622 			  event->attr.defer_callchain;
8623 	const u32 max_stack = event->attr.sample_max_stack;
8624 	struct perf_callchain_entry *callchain;
8625 	u64 defer_cookie;
8626 
8627 	if (!current->mm)
8628 		user = false;
8629 
8630 	if (!kernel && !user)
8631 		return &__empty_callchain;
8632 
8633 	if (!(user && defer_user && !crosstask &&
8634 	      unwind_deferred_request(&perf_unwind_work, &defer_cookie) >= 0))
8635 		defer_cookie = 0;
8636 
8637 	callchain = get_perf_callchain(regs, kernel, user, max_stack,
8638 				       crosstask, true, defer_cookie);
8639 
8640 	return callchain ?: &__empty_callchain;
8641 }
8642 
8643 static __always_inline u64 __cond_set(u64 flags, u64 s, u64 d)
8644 {
8645 	return d * !!(flags & s);
8646 }
8647 
8648 void perf_prepare_sample(struct perf_sample_data *data,
8649 			 struct perf_event *event,
8650 			 struct pt_regs *regs)
8651 {
8652 	u64 sample_type = event->attr.sample_type;
8653 	u64 filtered_sample_type;
8654 
8655 	/*
8656 	 * Add the sample flags that are dependent to others.  And clear the
8657 	 * sample flags that have already been done by the PMU driver.
8658 	 */
8659 	filtered_sample_type = sample_type;
8660 	filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_CODE_PAGE_SIZE,
8661 					   PERF_SAMPLE_IP);
8662 	filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_DATA_PAGE_SIZE |
8663 					   PERF_SAMPLE_PHYS_ADDR, PERF_SAMPLE_ADDR);
8664 	filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_STACK_USER,
8665 					   PERF_SAMPLE_REGS_USER);
8666 	filtered_sample_type &= ~data->sample_flags;
8667 
8668 	if (filtered_sample_type == 0) {
8669 		/* Make sure it has the correct data->type for output */
8670 		data->type = event->attr.sample_type;
8671 		return;
8672 	}
8673 
8674 	__perf_event_header__init_id(data, event, filtered_sample_type);
8675 
8676 	if (filtered_sample_type & PERF_SAMPLE_IP) {
8677 		data->ip = perf_instruction_pointer(event, regs);
8678 		data->sample_flags |= PERF_SAMPLE_IP;
8679 	}
8680 
8681 	if (filtered_sample_type & PERF_SAMPLE_CALLCHAIN)
8682 		perf_sample_save_callchain(data, event, regs);
8683 
8684 	if (filtered_sample_type & PERF_SAMPLE_RAW) {
8685 		data->raw = NULL;
8686 		data->dyn_size += sizeof(u64);
8687 		data->sample_flags |= PERF_SAMPLE_RAW;
8688 	}
8689 
8690 	if (filtered_sample_type & PERF_SAMPLE_BRANCH_STACK) {
8691 		data->br_stack = NULL;
8692 		data->dyn_size += sizeof(u64);
8693 		data->sample_flags |= PERF_SAMPLE_BRANCH_STACK;
8694 	}
8695 
8696 	if (filtered_sample_type & PERF_SAMPLE_REGS_USER)
8697 		perf_sample_regs_user(&data->regs_user, regs);
8698 
8699 	/*
8700 	 * It cannot use the filtered_sample_type here as REGS_USER can be set
8701 	 * by STACK_USER (using __cond_set() above) and we don't want to update
8702 	 * the dyn_size if it's not requested by users.
8703 	 */
8704 	if ((sample_type & ~data->sample_flags) & PERF_SAMPLE_REGS_USER) {
8705 		/* regs dump ABI info */
8706 		int size = sizeof(u64);
8707 
8708 		if (data->regs_user.regs) {
8709 			u64 mask = event->attr.sample_regs_user;
8710 			size += hweight64(mask) * sizeof(u64);
8711 		}
8712 
8713 		data->dyn_size += size;
8714 		data->sample_flags |= PERF_SAMPLE_REGS_USER;
8715 	}
8716 
8717 	if (filtered_sample_type & PERF_SAMPLE_STACK_USER) {
8718 		/*
8719 		 * Either we need PERF_SAMPLE_STACK_USER bit to be always
8720 		 * processed as the last one or have additional check added
8721 		 * in case new sample type is added, because we could eat
8722 		 * up the rest of the sample size.
8723 		 */
8724 		u16 stack_size = event->attr.sample_stack_user;
8725 		u16 header_size = perf_sample_data_size(data, event);
8726 		u16 size = sizeof(u64);
8727 
8728 		stack_size = perf_sample_ustack_size(stack_size, header_size,
8729 						     data->regs_user.regs);
8730 
8731 		/*
8732 		 * If there is something to dump, add space for the dump
8733 		 * itself and for the field that tells the dynamic size,
8734 		 * which is how many have been actually dumped.
8735 		 */
8736 		if (stack_size)
8737 			size += sizeof(u64) + stack_size;
8738 
8739 		data->stack_user_size = stack_size;
8740 		data->dyn_size += size;
8741 		data->sample_flags |= PERF_SAMPLE_STACK_USER;
8742 	}
8743 
8744 	if (filtered_sample_type & PERF_SAMPLE_WEIGHT_TYPE) {
8745 		data->weight.full = 0;
8746 		data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE;
8747 	}
8748 
8749 	if (filtered_sample_type & PERF_SAMPLE_DATA_SRC) {
8750 		data->data_src.val = PERF_MEM_NA;
8751 		data->sample_flags |= PERF_SAMPLE_DATA_SRC;
8752 	}
8753 
8754 	if (filtered_sample_type & PERF_SAMPLE_TRANSACTION) {
8755 		data->txn = 0;
8756 		data->sample_flags |= PERF_SAMPLE_TRANSACTION;
8757 	}
8758 
8759 	if (filtered_sample_type & PERF_SAMPLE_ADDR) {
8760 		data->addr = 0;
8761 		data->sample_flags |= PERF_SAMPLE_ADDR;
8762 	}
8763 
8764 	if (filtered_sample_type & PERF_SAMPLE_REGS_INTR) {
8765 		/* regs dump ABI info */
8766 		int size = sizeof(u64);
8767 
8768 		perf_sample_regs_intr(&data->regs_intr, regs,
8769 				      event->attr.exclude_kernel);
8770 
8771 		if (data->regs_intr.regs) {
8772 			u64 mask = event->attr.sample_regs_intr;
8773 
8774 			size += hweight64(mask) * sizeof(u64);
8775 		}
8776 
8777 		data->dyn_size += size;
8778 		data->sample_flags |= PERF_SAMPLE_REGS_INTR;
8779 	}
8780 
8781 	if (filtered_sample_type & PERF_SAMPLE_PHYS_ADDR) {
8782 		data->phys_addr = perf_virt_to_phys(data->addr);
8783 		data->sample_flags |= PERF_SAMPLE_PHYS_ADDR;
8784 	}
8785 
8786 #ifdef CONFIG_CGROUP_PERF
8787 	if (filtered_sample_type & PERF_SAMPLE_CGROUP) {
8788 		struct cgroup *cgrp;
8789 
8790 		/* protected by RCU */
8791 		cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
8792 		data->cgroup = cgroup_id(cgrp);
8793 		data->sample_flags |= PERF_SAMPLE_CGROUP;
8794 	}
8795 #endif
8796 
8797 	/*
8798 	 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't
8799 	 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr,
8800 	 * but the value will not dump to the userspace.
8801 	 */
8802 	if (filtered_sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) {
8803 		data->data_page_size = perf_get_page_size(data->addr);
8804 		data->sample_flags |= PERF_SAMPLE_DATA_PAGE_SIZE;
8805 	}
8806 
8807 	if (filtered_sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) {
8808 		data->code_page_size = perf_get_page_size(data->ip);
8809 		data->sample_flags |= PERF_SAMPLE_CODE_PAGE_SIZE;
8810 	}
8811 
8812 	if (filtered_sample_type & PERF_SAMPLE_AUX) {
8813 		u64 size;
8814 		u16 header_size = perf_sample_data_size(data, event);
8815 
8816 		header_size += sizeof(u64); /* size */
8817 
8818 		/*
8819 		 * Given the 16bit nature of header::size, an AUX sample can
8820 		 * easily overflow it, what with all the preceding sample bits.
8821 		 * Make sure this doesn't happen by using up to U16_MAX bytes
8822 		 * per sample in total (rounded down to 8 byte boundary).
8823 		 */
8824 		size = min_t(size_t, U16_MAX - header_size,
8825 			     event->attr.aux_sample_size);
8826 		size = rounddown(size, 8);
8827 		size = perf_prepare_sample_aux(event, data, size);
8828 
8829 		WARN_ON_ONCE(size + header_size > U16_MAX);
8830 		data->dyn_size += size + sizeof(u64); /* size above */
8831 		data->sample_flags |= PERF_SAMPLE_AUX;
8832 	}
8833 }
8834 
8835 void perf_prepare_header(struct perf_event_header *header,
8836 			 struct perf_sample_data *data,
8837 			 struct perf_event *event,
8838 			 struct pt_regs *regs)
8839 {
8840 	header->type = PERF_RECORD_SAMPLE;
8841 	header->size = perf_sample_data_size(data, event);
8842 	header->misc = perf_misc_flags(event, regs);
8843 
8844 	/*
8845 	 * If you're adding more sample types here, you likely need to do
8846 	 * something about the overflowing header::size, like repurpose the
8847 	 * lowest 3 bits of size, which should be always zero at the moment.
8848 	 * This raises a more important question, do we really need 512k sized
8849 	 * samples and why, so good argumentation is in order for whatever you
8850 	 * do here next.
8851 	 */
8852 	WARN_ON_ONCE(header->size & 7);
8853 }
8854 
8855 static void __perf_event_aux_pause(struct perf_event *event, bool pause)
8856 {
8857 	if (pause) {
8858 		if (!event->hw.aux_paused) {
8859 			event->hw.aux_paused = 1;
8860 			event->pmu->stop(event, PERF_EF_PAUSE);
8861 		}
8862 	} else {
8863 		if (event->hw.aux_paused) {
8864 			event->hw.aux_paused = 0;
8865 			event->pmu->start(event, PERF_EF_RESUME);
8866 		}
8867 	}
8868 }
8869 
8870 static void perf_event_aux_pause(struct perf_event *event, bool pause)
8871 {
8872 	struct perf_buffer *rb;
8873 
8874 	if (WARN_ON_ONCE(!event))
8875 		return;
8876 
8877 	rb = ring_buffer_get(event);
8878 	if (!rb)
8879 		return;
8880 
8881 	scoped_guard (irqsave) {
8882 		/*
8883 		 * Guard against self-recursion here. Another event could trip
8884 		 * this same from NMI context.
8885 		 */
8886 		if (READ_ONCE(rb->aux_in_pause_resume))
8887 			break;
8888 
8889 		WRITE_ONCE(rb->aux_in_pause_resume, 1);
8890 		barrier();
8891 		__perf_event_aux_pause(event, pause);
8892 		barrier();
8893 		WRITE_ONCE(rb->aux_in_pause_resume, 0);
8894 	}
8895 	ring_buffer_put(rb);
8896 }
8897 
8898 static __always_inline int
8899 __perf_event_output(struct perf_event *event,
8900 		    struct perf_sample_data *data,
8901 		    struct pt_regs *regs,
8902 		    int (*output_begin)(struct perf_output_handle *,
8903 					struct perf_sample_data *,
8904 					struct perf_event *,
8905 					unsigned int))
8906 {
8907 	struct perf_output_handle handle;
8908 	struct perf_event_header header;
8909 	int err;
8910 
8911 	/* protect the callchain buffers */
8912 	rcu_read_lock();
8913 
8914 	perf_prepare_sample(data, event, regs);
8915 	perf_prepare_header(&header, data, event, regs);
8916 
8917 	err = output_begin(&handle, data, event, header.size);
8918 	if (err)
8919 		goto exit;
8920 
8921 	perf_output_sample(&handle, &header, data, event);
8922 
8923 	perf_output_end(&handle);
8924 
8925 exit:
8926 	rcu_read_unlock();
8927 	return err;
8928 }
8929 
8930 void
8931 perf_event_output_forward(struct perf_event *event,
8932 			 struct perf_sample_data *data,
8933 			 struct pt_regs *regs)
8934 {
8935 	__perf_event_output(event, data, regs, perf_output_begin_forward);
8936 }
8937 
8938 void
8939 perf_event_output_backward(struct perf_event *event,
8940 			   struct perf_sample_data *data,
8941 			   struct pt_regs *regs)
8942 {
8943 	__perf_event_output(event, data, regs, perf_output_begin_backward);
8944 }
8945 
8946 int
8947 perf_event_output(struct perf_event *event,
8948 		  struct perf_sample_data *data,
8949 		  struct pt_regs *regs)
8950 {
8951 	return __perf_event_output(event, data, regs, perf_output_begin);
8952 }
8953 
8954 /*
8955  * read event_id
8956  */
8957 
8958 struct perf_read_event {
8959 	struct perf_event_header	header;
8960 
8961 	u32				pid;
8962 	u32				tid;
8963 };
8964 
8965 static void
8966 perf_event_read_event(struct perf_event *event,
8967 			struct task_struct *task)
8968 {
8969 	struct perf_output_handle handle;
8970 	struct perf_sample_data sample;
8971 	struct perf_read_event read_event = {
8972 		.header = {
8973 			.type = PERF_RECORD_READ,
8974 			.misc = 0,
8975 			.size = sizeof(read_event) + event->read_size,
8976 		},
8977 		.pid = perf_event_pid(event, task),
8978 		.tid = perf_event_tid(event, task),
8979 	};
8980 	int ret;
8981 
8982 	perf_event_header__init_id(&read_event.header, &sample, event);
8983 	ret = perf_output_begin(&handle, &sample, event, read_event.header.size);
8984 	if (ret)
8985 		return;
8986 
8987 	perf_output_put(&handle, read_event);
8988 	perf_output_read(&handle, event);
8989 	perf_event__output_id_sample(event, &handle, &sample);
8990 
8991 	perf_output_end(&handle);
8992 }
8993 
8994 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
8995 
8996 static void
8997 perf_iterate_ctx(struct perf_event_context *ctx,
8998 		   perf_iterate_f output,
8999 		   void *data, bool all)
9000 {
9001 	struct perf_event *event;
9002 
9003 	list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
9004 		if (!all) {
9005 			if (event->state < PERF_EVENT_STATE_INACTIVE)
9006 				continue;
9007 			if (!event_filter_match(event))
9008 				continue;
9009 		}
9010 
9011 		output(event, data);
9012 	}
9013 }
9014 
9015 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
9016 {
9017 	struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
9018 	struct perf_event *event;
9019 
9020 	list_for_each_entry_rcu(event, &pel->list, sb_list) {
9021 		/*
9022 		 * Skip events that are not fully formed yet; ensure that
9023 		 * if we observe event->ctx, both event and ctx will be
9024 		 * complete enough. See perf_install_in_context().
9025 		 */
9026 		if (!smp_load_acquire(&event->ctx))
9027 			continue;
9028 
9029 		if (event->state < PERF_EVENT_STATE_INACTIVE)
9030 			continue;
9031 		if (!event_filter_match(event))
9032 			continue;
9033 		output(event, data);
9034 	}
9035 }
9036 
9037 /*
9038  * Iterate all events that need to receive side-band events.
9039  *
9040  * For new callers; ensure that account_pmu_sb_event() includes
9041  * your event, otherwise it might not get delivered.
9042  */
9043 static void
9044 perf_iterate_sb(perf_iterate_f output, void *data,
9045 	       struct perf_event_context *task_ctx)
9046 {
9047 	struct perf_event_context *ctx;
9048 
9049 	rcu_read_lock();
9050 	preempt_disable();
9051 
9052 	/*
9053 	 * If we have task_ctx != NULL we only notify the task context itself.
9054 	 * The task_ctx is set only for EXIT events before releasing task
9055 	 * context.
9056 	 */
9057 	if (task_ctx) {
9058 		perf_iterate_ctx(task_ctx, output, data, false);
9059 		goto done;
9060 	}
9061 
9062 	perf_iterate_sb_cpu(output, data);
9063 
9064 	ctx = rcu_dereference(current->perf_event_ctxp);
9065 	if (ctx)
9066 		perf_iterate_ctx(ctx, output, data, false);
9067 done:
9068 	preempt_enable();
9069 	rcu_read_unlock();
9070 }
9071 
9072 /*
9073  * Clear all file-based filters at exec, they'll have to be
9074  * re-instated when/if these objects are mmapped again.
9075  */
9076 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
9077 {
9078 	struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
9079 	struct perf_addr_filter *filter;
9080 	unsigned int restart = 0, count = 0;
9081 	unsigned long flags;
9082 
9083 	if (!has_addr_filter(event))
9084 		return;
9085 
9086 	raw_spin_lock_irqsave(&ifh->lock, flags);
9087 	list_for_each_entry(filter, &ifh->list, entry) {
9088 		if (filter->path.dentry) {
9089 			event->addr_filter_ranges[count].start = 0;
9090 			event->addr_filter_ranges[count].size = 0;
9091 			restart++;
9092 		}
9093 
9094 		count++;
9095 	}
9096 
9097 	if (restart)
9098 		event->addr_filters_gen++;
9099 	raw_spin_unlock_irqrestore(&ifh->lock, flags);
9100 
9101 	if (restart)
9102 		perf_event_stop(event, 1);
9103 }
9104 
9105 void perf_event_exec(void)
9106 {
9107 	struct perf_event_context *ctx;
9108 
9109 	ctx = perf_pin_task_context(current);
9110 	if (!ctx)
9111 		return;
9112 
9113 	perf_event_enable_on_exec(ctx);
9114 	perf_event_remove_on_exec(ctx);
9115 	scoped_guard(rcu)
9116 		perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL, true);
9117 
9118 	perf_unpin_context(ctx);
9119 	put_ctx(ctx);
9120 }
9121 
9122 struct remote_output {
9123 	struct perf_buffer	*rb;
9124 	int			err;
9125 };
9126 
9127 static void __perf_event_output_stop(struct perf_event *event, void *data)
9128 {
9129 	struct perf_event *parent = event->parent;
9130 	struct remote_output *ro = data;
9131 	struct perf_buffer *rb = ro->rb;
9132 	struct stop_event_data sd = {
9133 		.event	= event,
9134 	};
9135 
9136 	if (!has_aux(event))
9137 		return;
9138 
9139 	if (!parent)
9140 		parent = event;
9141 
9142 	/*
9143 	 * In case of inheritance, it will be the parent that links to the
9144 	 * ring-buffer, but it will be the child that's actually using it.
9145 	 *
9146 	 * We are using event::rb to determine if the event should be stopped,
9147 	 * however this may race with ring_buffer_attach() (through set_output),
9148 	 * which will make us skip the event that actually needs to be stopped.
9149 	 * So ring_buffer_attach() has to stop an aux event before re-assigning
9150 	 * its rb pointer.
9151 	 */
9152 	if (rcu_dereference(parent->rb) == rb)
9153 		ro->err = __perf_event_stop(&sd);
9154 }
9155 
9156 static int __perf_pmu_output_stop(void *info)
9157 {
9158 	struct perf_event *event = info;
9159 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
9160 	struct remote_output ro = {
9161 		.rb	= event->rb,
9162 	};
9163 
9164 	rcu_read_lock();
9165 	perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
9166 	if (cpuctx->task_ctx)
9167 		perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
9168 				   &ro, false);
9169 	rcu_read_unlock();
9170 
9171 	return ro.err;
9172 }
9173 
9174 static void perf_pmu_output_stop(struct perf_event *event)
9175 {
9176 	struct perf_event *iter;
9177 	int err, cpu;
9178 
9179 restart:
9180 	rcu_read_lock();
9181 	list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
9182 		/*
9183 		 * For per-CPU events, we need to make sure that neither they
9184 		 * nor their children are running; for cpu==-1 events it's
9185 		 * sufficient to stop the event itself if it's active, since
9186 		 * it can't have children.
9187 		 */
9188 		cpu = iter->cpu;
9189 		if (cpu == -1)
9190 			cpu = READ_ONCE(iter->oncpu);
9191 
9192 		if (cpu == -1)
9193 			continue;
9194 
9195 		err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
9196 		if (err == -EAGAIN) {
9197 			rcu_read_unlock();
9198 			goto restart;
9199 		}
9200 	}
9201 	rcu_read_unlock();
9202 }
9203 
9204 /*
9205  * task tracking -- fork/exit
9206  *
9207  * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
9208  */
9209 
9210 struct perf_task_event {
9211 	struct task_struct		*task;
9212 	struct perf_event_context	*task_ctx;
9213 
9214 	struct {
9215 		struct perf_event_header	header;
9216 
9217 		u32				pid;
9218 		u32				ppid;
9219 		u32				tid;
9220 		u32				ptid;
9221 		u64				time;
9222 	} event_id;
9223 };
9224 
9225 static int perf_event_task_match(struct perf_event *event)
9226 {
9227 	return event->attr.comm  || event->attr.mmap ||
9228 	       event->attr.mmap2 || event->attr.mmap_data ||
9229 	       event->attr.task;
9230 }
9231 
9232 static void perf_event_task_output(struct perf_event *event,
9233 				   void *data)
9234 {
9235 	struct perf_task_event *task_event = data;
9236 	struct perf_output_handle handle;
9237 	struct perf_sample_data	sample;
9238 	struct task_struct *task = task_event->task;
9239 	int ret, size = task_event->event_id.header.size;
9240 
9241 	if (!perf_event_task_match(event))
9242 		return;
9243 
9244 	perf_event_header__init_id(&task_event->event_id.header, &sample, event);
9245 
9246 	ret = perf_output_begin(&handle, &sample, event,
9247 				task_event->event_id.header.size);
9248 	if (ret)
9249 		goto out;
9250 
9251 	task_event->event_id.pid = perf_event_pid(event, task);
9252 	task_event->event_id.tid = perf_event_tid(event, task);
9253 
9254 	if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
9255 		task_event->event_id.ppid = perf_event_pid(event,
9256 							task->real_parent);
9257 		task_event->event_id.ptid = perf_event_pid(event,
9258 							task->real_parent);
9259 	} else {  /* PERF_RECORD_FORK */
9260 		task_event->event_id.ppid = perf_event_pid(event, current);
9261 		task_event->event_id.ptid = perf_event_tid(event, current);
9262 	}
9263 
9264 	task_event->event_id.time = perf_event_clock(event);
9265 
9266 	perf_output_put(&handle, task_event->event_id);
9267 
9268 	perf_event__output_id_sample(event, &handle, &sample);
9269 
9270 	perf_output_end(&handle);
9271 out:
9272 	task_event->event_id.header.size = size;
9273 }
9274 
9275 static void perf_event_task(struct task_struct *task,
9276 			      struct perf_event_context *task_ctx,
9277 			      int new)
9278 {
9279 	struct perf_task_event task_event;
9280 
9281 	if (!atomic_read(&nr_comm_events) &&
9282 	    !atomic_read(&nr_mmap_events) &&
9283 	    !atomic_read(&nr_task_events))
9284 		return;
9285 
9286 	task_event = (struct perf_task_event){
9287 		.task	  = task,
9288 		.task_ctx = task_ctx,
9289 		.event_id    = {
9290 			.header = {
9291 				.type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
9292 				.misc = 0,
9293 				.size = sizeof(task_event.event_id),
9294 			},
9295 			/* .pid  */
9296 			/* .ppid */
9297 			/* .tid  */
9298 			/* .ptid */
9299 			/* .time */
9300 		},
9301 	};
9302 
9303 	perf_iterate_sb(perf_event_task_output,
9304 		       &task_event,
9305 		       task_ctx);
9306 }
9307 
9308 /*
9309  * Allocate data for a new task when profiling system-wide
9310  * events which require PMU specific data
9311  */
9312 static void
9313 perf_event_alloc_task_data(struct task_struct *child,
9314 			   struct task_struct *parent)
9315 {
9316 	struct kmem_cache *ctx_cache = NULL;
9317 	struct perf_ctx_data *cd;
9318 
9319 	if (!refcount_read(&global_ctx_data_ref))
9320 		return;
9321 
9322 	scoped_guard (rcu) {
9323 		cd = rcu_dereference(parent->perf_ctx_data);
9324 		if (cd)
9325 			ctx_cache = cd->ctx_cache;
9326 	}
9327 
9328 	if (!ctx_cache)
9329 		return;
9330 
9331 	guard(percpu_read)(&global_ctx_data_rwsem);
9332 	scoped_guard (rcu) {
9333 		cd = rcu_dereference(child->perf_ctx_data);
9334 		if (!cd) {
9335 			/*
9336 			 * A system-wide event may be unaccount,
9337 			 * when attaching the perf_ctx_data.
9338 			 */
9339 			if (!refcount_read(&global_ctx_data_ref))
9340 				return;
9341 			goto attach;
9342 		}
9343 
9344 		if (!cd->global) {
9345 			cd->global = 1;
9346 			refcount_inc(&cd->refcount);
9347 		}
9348 	}
9349 
9350 	return;
9351 attach:
9352 	attach_task_ctx_data(child, ctx_cache, true, GFP_KERNEL);
9353 }
9354 
9355 void perf_event_fork(struct task_struct *task)
9356 {
9357 	perf_event_task(task, NULL, 1);
9358 	perf_event_namespaces(task);
9359 	perf_event_alloc_task_data(task, current);
9360 }
9361 
9362 /*
9363  * comm tracking
9364  */
9365 
9366 struct perf_comm_event {
9367 	struct task_struct	*task;
9368 	char			*comm;
9369 	int			comm_size;
9370 
9371 	struct {
9372 		struct perf_event_header	header;
9373 
9374 		u32				pid;
9375 		u32				tid;
9376 	} event_id;
9377 };
9378 
9379 static int perf_event_comm_match(struct perf_event *event)
9380 {
9381 	return event->attr.comm;
9382 }
9383 
9384 static void perf_event_comm_output(struct perf_event *event,
9385 				   void *data)
9386 {
9387 	struct perf_comm_event *comm_event = data;
9388 	struct perf_output_handle handle;
9389 	struct perf_sample_data sample;
9390 	int size = comm_event->event_id.header.size;
9391 	int ret;
9392 
9393 	if (!perf_event_comm_match(event))
9394 		return;
9395 
9396 	perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
9397 	ret = perf_output_begin(&handle, &sample, event,
9398 				comm_event->event_id.header.size);
9399 
9400 	if (ret)
9401 		goto out;
9402 
9403 	comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
9404 	comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
9405 
9406 	perf_output_put(&handle, comm_event->event_id);
9407 	__output_copy(&handle, comm_event->comm,
9408 				   comm_event->comm_size);
9409 
9410 	perf_event__output_id_sample(event, &handle, &sample);
9411 
9412 	perf_output_end(&handle);
9413 out:
9414 	comm_event->event_id.header.size = size;
9415 }
9416 
9417 static void perf_event_comm_event(struct perf_comm_event *comm_event)
9418 {
9419 	char comm[TASK_COMM_LEN];
9420 	unsigned int size;
9421 
9422 	memset(comm, 0, sizeof(comm));
9423 	strscpy(comm, comm_event->task->comm);
9424 	size = ALIGN(strlen(comm)+1, sizeof(u64));
9425 
9426 	comm_event->comm = comm;
9427 	comm_event->comm_size = size;
9428 
9429 	comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
9430 
9431 	perf_iterate_sb(perf_event_comm_output,
9432 		       comm_event,
9433 		       NULL);
9434 }
9435 
9436 void perf_event_comm(struct task_struct *task, bool exec)
9437 {
9438 	struct perf_comm_event comm_event;
9439 
9440 	if (!atomic_read(&nr_comm_events))
9441 		return;
9442 
9443 	comm_event = (struct perf_comm_event){
9444 		.task	= task,
9445 		/* .comm      */
9446 		/* .comm_size */
9447 		.event_id  = {
9448 			.header = {
9449 				.type = PERF_RECORD_COMM,
9450 				.misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
9451 				/* .size */
9452 			},
9453 			/* .pid */
9454 			/* .tid */
9455 		},
9456 	};
9457 
9458 	perf_event_comm_event(&comm_event);
9459 }
9460 
9461 /*
9462  * namespaces tracking
9463  */
9464 
9465 struct perf_namespaces_event {
9466 	struct task_struct		*task;
9467 
9468 	struct {
9469 		struct perf_event_header	header;
9470 
9471 		u32				pid;
9472 		u32				tid;
9473 		u64				nr_namespaces;
9474 		struct perf_ns_link_info	link_info[NR_NAMESPACES];
9475 	} event_id;
9476 };
9477 
9478 static int perf_event_namespaces_match(struct perf_event *event)
9479 {
9480 	return event->attr.namespaces;
9481 }
9482 
9483 static void perf_event_namespaces_output(struct perf_event *event,
9484 					 void *data)
9485 {
9486 	struct perf_namespaces_event *namespaces_event = data;
9487 	struct perf_output_handle handle;
9488 	struct perf_sample_data sample;
9489 	u16 header_size = namespaces_event->event_id.header.size;
9490 	int ret;
9491 
9492 	if (!perf_event_namespaces_match(event))
9493 		return;
9494 
9495 	perf_event_header__init_id(&namespaces_event->event_id.header,
9496 				   &sample, event);
9497 	ret = perf_output_begin(&handle, &sample, event,
9498 				namespaces_event->event_id.header.size);
9499 	if (ret)
9500 		goto out;
9501 
9502 	namespaces_event->event_id.pid = perf_event_pid(event,
9503 							namespaces_event->task);
9504 	namespaces_event->event_id.tid = perf_event_tid(event,
9505 							namespaces_event->task);
9506 
9507 	perf_output_put(&handle, namespaces_event->event_id);
9508 
9509 	perf_event__output_id_sample(event, &handle, &sample);
9510 
9511 	perf_output_end(&handle);
9512 out:
9513 	namespaces_event->event_id.header.size = header_size;
9514 }
9515 
9516 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
9517 				   struct task_struct *task,
9518 				   const struct proc_ns_operations *ns_ops)
9519 {
9520 	struct path ns_path;
9521 	struct inode *ns_inode;
9522 	int error;
9523 
9524 	error = ns_get_path(&ns_path, task, ns_ops);
9525 	if (!error) {
9526 		ns_inode = ns_path.dentry->d_inode;
9527 		ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
9528 		ns_link_info->ino = ns_inode->i_ino;
9529 		path_put(&ns_path);
9530 	}
9531 }
9532 
9533 void perf_event_namespaces(struct task_struct *task)
9534 {
9535 	struct perf_namespaces_event namespaces_event;
9536 	struct perf_ns_link_info *ns_link_info;
9537 
9538 	if (!atomic_read(&nr_namespaces_events))
9539 		return;
9540 
9541 	namespaces_event = (struct perf_namespaces_event){
9542 		.task	= task,
9543 		.event_id  = {
9544 			.header = {
9545 				.type = PERF_RECORD_NAMESPACES,
9546 				.misc = 0,
9547 				.size = sizeof(namespaces_event.event_id),
9548 			},
9549 			/* .pid */
9550 			/* .tid */
9551 			.nr_namespaces = NR_NAMESPACES,
9552 			/* .link_info[NR_NAMESPACES] */
9553 		},
9554 	};
9555 
9556 	ns_link_info = namespaces_event.event_id.link_info;
9557 
9558 	perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
9559 			       task, &mntns_operations);
9560 
9561 #ifdef CONFIG_USER_NS
9562 	perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
9563 			       task, &userns_operations);
9564 #endif
9565 #ifdef CONFIG_NET_NS
9566 	perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
9567 			       task, &netns_operations);
9568 #endif
9569 #ifdef CONFIG_UTS_NS
9570 	perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
9571 			       task, &utsns_operations);
9572 #endif
9573 #ifdef CONFIG_IPC_NS
9574 	perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
9575 			       task, &ipcns_operations);
9576 #endif
9577 #ifdef CONFIG_PID_NS
9578 	perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
9579 			       task, &pidns_operations);
9580 #endif
9581 #ifdef CONFIG_CGROUPS
9582 	perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
9583 			       task, &cgroupns_operations);
9584 #endif
9585 
9586 	perf_iterate_sb(perf_event_namespaces_output,
9587 			&namespaces_event,
9588 			NULL);
9589 }
9590 
9591 /*
9592  * cgroup tracking
9593  */
9594 #ifdef CONFIG_CGROUP_PERF
9595 
9596 struct perf_cgroup_event {
9597 	char				*path;
9598 	int				path_size;
9599 	struct {
9600 		struct perf_event_header	header;
9601 		u64				id;
9602 		char				path[];
9603 	} event_id;
9604 };
9605 
9606 static int perf_event_cgroup_match(struct perf_event *event)
9607 {
9608 	return event->attr.cgroup;
9609 }
9610 
9611 static void perf_event_cgroup_output(struct perf_event *event, void *data)
9612 {
9613 	struct perf_cgroup_event *cgroup_event = data;
9614 	struct perf_output_handle handle;
9615 	struct perf_sample_data sample;
9616 	u16 header_size = cgroup_event->event_id.header.size;
9617 	int ret;
9618 
9619 	if (!perf_event_cgroup_match(event))
9620 		return;
9621 
9622 	perf_event_header__init_id(&cgroup_event->event_id.header,
9623 				   &sample, event);
9624 	ret = perf_output_begin(&handle, &sample, event,
9625 				cgroup_event->event_id.header.size);
9626 	if (ret)
9627 		goto out;
9628 
9629 	perf_output_put(&handle, cgroup_event->event_id);
9630 	__output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
9631 
9632 	perf_event__output_id_sample(event, &handle, &sample);
9633 
9634 	perf_output_end(&handle);
9635 out:
9636 	cgroup_event->event_id.header.size = header_size;
9637 }
9638 
9639 static void perf_event_cgroup(struct cgroup *cgrp)
9640 {
9641 	struct perf_cgroup_event cgroup_event;
9642 	char path_enomem[16] = "//enomem";
9643 	char *pathname;
9644 	size_t size;
9645 
9646 	if (!atomic_read(&nr_cgroup_events))
9647 		return;
9648 
9649 	cgroup_event = (struct perf_cgroup_event){
9650 		.event_id  = {
9651 			.header = {
9652 				.type = PERF_RECORD_CGROUP,
9653 				.misc = 0,
9654 				.size = sizeof(cgroup_event.event_id),
9655 			},
9656 			.id = cgroup_id(cgrp),
9657 		},
9658 	};
9659 
9660 	pathname = kmalloc(PATH_MAX, GFP_KERNEL);
9661 	if (pathname == NULL) {
9662 		cgroup_event.path = path_enomem;
9663 	} else {
9664 		/* just to be sure to have enough space for alignment */
9665 		cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
9666 		cgroup_event.path = pathname;
9667 	}
9668 
9669 	/*
9670 	 * Since our buffer works in 8 byte units we need to align our string
9671 	 * size to a multiple of 8. However, we must guarantee the tail end is
9672 	 * zero'd out to avoid leaking random bits to userspace.
9673 	 */
9674 	size = strlen(cgroup_event.path) + 1;
9675 	while (!IS_ALIGNED(size, sizeof(u64)))
9676 		cgroup_event.path[size++] = '\0';
9677 
9678 	cgroup_event.event_id.header.size += size;
9679 	cgroup_event.path_size = size;
9680 
9681 	perf_iterate_sb(perf_event_cgroup_output,
9682 			&cgroup_event,
9683 			NULL);
9684 
9685 	kfree(pathname);
9686 }
9687 
9688 #endif
9689 
9690 /*
9691  * mmap tracking
9692  */
9693 
9694 struct perf_mmap_event {
9695 	struct vm_area_struct	*vma;
9696 
9697 	const char		*file_name;
9698 	int			file_size;
9699 	int			maj, min;
9700 	u64			ino;
9701 	u64			ino_generation;
9702 	u32			prot, flags;
9703 	u8			build_id[BUILD_ID_SIZE_MAX];
9704 	u32			build_id_size;
9705 
9706 	struct {
9707 		struct perf_event_header	header;
9708 
9709 		u32				pid;
9710 		u32				tid;
9711 		u64				start;
9712 		u64				len;
9713 		u64				pgoff;
9714 	} event_id;
9715 };
9716 
9717 static int perf_event_mmap_match(struct perf_event *event,
9718 				 void *data)
9719 {
9720 	struct perf_mmap_event *mmap_event = data;
9721 	struct vm_area_struct *vma = mmap_event->vma;
9722 	int executable = vma->vm_flags & VM_EXEC;
9723 
9724 	return (!executable && event->attr.mmap_data) ||
9725 	       (executable && (event->attr.mmap || event->attr.mmap2));
9726 }
9727 
9728 static void perf_event_mmap_output(struct perf_event *event,
9729 				   void *data)
9730 {
9731 	struct perf_mmap_event *mmap_event = data;
9732 	struct perf_output_handle handle;
9733 	struct perf_sample_data sample;
9734 	int size = mmap_event->event_id.header.size;
9735 	u32 type = mmap_event->event_id.header.type;
9736 	bool use_build_id;
9737 	int ret;
9738 
9739 	if (!perf_event_mmap_match(event, data))
9740 		return;
9741 
9742 	if (event->attr.mmap2) {
9743 		mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
9744 		mmap_event->event_id.header.size += sizeof(mmap_event->maj);
9745 		mmap_event->event_id.header.size += sizeof(mmap_event->min);
9746 		mmap_event->event_id.header.size += sizeof(mmap_event->ino);
9747 		mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
9748 		mmap_event->event_id.header.size += sizeof(mmap_event->prot);
9749 		mmap_event->event_id.header.size += sizeof(mmap_event->flags);
9750 	}
9751 
9752 	perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
9753 	ret = perf_output_begin(&handle, &sample, event,
9754 				mmap_event->event_id.header.size);
9755 	if (ret)
9756 		goto out;
9757 
9758 	mmap_event->event_id.pid = perf_event_pid(event, current);
9759 	mmap_event->event_id.tid = perf_event_tid(event, current);
9760 
9761 	use_build_id = event->attr.build_id && mmap_event->build_id_size;
9762 
9763 	if (event->attr.mmap2 && use_build_id)
9764 		mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID;
9765 
9766 	perf_output_put(&handle, mmap_event->event_id);
9767 
9768 	if (event->attr.mmap2) {
9769 		if (use_build_id) {
9770 			u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 };
9771 
9772 			__output_copy(&handle, size, 4);
9773 			__output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX);
9774 		} else {
9775 			perf_output_put(&handle, mmap_event->maj);
9776 			perf_output_put(&handle, mmap_event->min);
9777 			perf_output_put(&handle, mmap_event->ino);
9778 			perf_output_put(&handle, mmap_event->ino_generation);
9779 		}
9780 		perf_output_put(&handle, mmap_event->prot);
9781 		perf_output_put(&handle, mmap_event->flags);
9782 	}
9783 
9784 	__output_copy(&handle, mmap_event->file_name,
9785 				   mmap_event->file_size);
9786 
9787 	perf_event__output_id_sample(event, &handle, &sample);
9788 
9789 	perf_output_end(&handle);
9790 out:
9791 	mmap_event->event_id.header.size = size;
9792 	mmap_event->event_id.header.type = type;
9793 }
9794 
9795 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
9796 {
9797 	struct vm_area_struct *vma = mmap_event->vma;
9798 	struct file *file = vma->vm_file;
9799 	int maj = 0, min = 0;
9800 	u64 ino = 0, gen = 0;
9801 	u32 prot = 0, flags = 0;
9802 	unsigned int size;
9803 	char tmp[16];
9804 	char *buf = NULL;
9805 	char *name = NULL;
9806 
9807 	if (vma->vm_flags & VM_READ)
9808 		prot |= PROT_READ;
9809 	if (vma->vm_flags & VM_WRITE)
9810 		prot |= PROT_WRITE;
9811 	if (vma->vm_flags & VM_EXEC)
9812 		prot |= PROT_EXEC;
9813 
9814 	if (vma->vm_flags & VM_MAYSHARE)
9815 		flags = MAP_SHARED;
9816 	else
9817 		flags = MAP_PRIVATE;
9818 
9819 	if (vma->vm_flags & VM_LOCKED)
9820 		flags |= MAP_LOCKED;
9821 	if (is_vm_hugetlb_page(vma))
9822 		flags |= MAP_HUGETLB;
9823 
9824 	if (file) {
9825 		const struct inode *inode;
9826 		dev_t dev;
9827 
9828 		buf = kmalloc(PATH_MAX, GFP_KERNEL);
9829 		if (!buf) {
9830 			name = "//enomem";
9831 			goto cpy_name;
9832 		}
9833 		/*
9834 		 * d_path() works from the end of the rb backwards, so we
9835 		 * need to add enough zero bytes after the string to handle
9836 		 * the 64bit alignment we do later.
9837 		 */
9838 		name = d_path(file_user_path(file), buf, PATH_MAX - sizeof(u64));
9839 		if (IS_ERR(name)) {
9840 			name = "//toolong";
9841 			goto cpy_name;
9842 		}
9843 		inode = file_user_inode(vma->vm_file);
9844 		dev = inode->i_sb->s_dev;
9845 		ino = inode->i_ino;
9846 		gen = inode->i_generation;
9847 		maj = MAJOR(dev);
9848 		min = MINOR(dev);
9849 
9850 		goto got_name;
9851 	} else {
9852 		if (vma->vm_ops && vma->vm_ops->name)
9853 			name = (char *) vma->vm_ops->name(vma);
9854 		if (!name)
9855 			name = (char *)arch_vma_name(vma);
9856 		if (!name) {
9857 			if (vma_is_initial_heap(vma))
9858 				name = "[heap]";
9859 			else if (vma_is_initial_stack(vma))
9860 				name = "[stack]";
9861 			else
9862 				name = "//anon";
9863 		}
9864 	}
9865 
9866 cpy_name:
9867 	strscpy(tmp, name);
9868 	name = tmp;
9869 got_name:
9870 	/*
9871 	 * Since our buffer works in 8 byte units we need to align our string
9872 	 * size to a multiple of 8. However, we must guarantee the tail end is
9873 	 * zero'd out to avoid leaking random bits to userspace.
9874 	 */
9875 	size = strlen(name)+1;
9876 	while (!IS_ALIGNED(size, sizeof(u64)))
9877 		name[size++] = '\0';
9878 
9879 	mmap_event->file_name = name;
9880 	mmap_event->file_size = size;
9881 	mmap_event->maj = maj;
9882 	mmap_event->min = min;
9883 	mmap_event->ino = ino;
9884 	mmap_event->ino_generation = gen;
9885 	mmap_event->prot = prot;
9886 	mmap_event->flags = flags;
9887 
9888 	if (!(vma->vm_flags & VM_EXEC))
9889 		mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
9890 
9891 	mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
9892 
9893 	if (atomic_read(&nr_build_id_events))
9894 		build_id_parse_nofault(vma, mmap_event->build_id, &mmap_event->build_id_size);
9895 
9896 	perf_iterate_sb(perf_event_mmap_output,
9897 		       mmap_event,
9898 		       NULL);
9899 
9900 	kfree(buf);
9901 }
9902 
9903 /*
9904  * Check whether inode and address range match filter criteria.
9905  */
9906 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
9907 				     struct file *file, unsigned long offset,
9908 				     unsigned long size)
9909 {
9910 	/* d_inode(NULL) won't be equal to any mapped user-space file */
9911 	if (!filter->path.dentry)
9912 		return false;
9913 
9914 	if (d_inode(filter->path.dentry) != file_user_inode(file))
9915 		return false;
9916 
9917 	if (filter->offset > offset + size)
9918 		return false;
9919 
9920 	if (filter->offset + filter->size < offset)
9921 		return false;
9922 
9923 	return true;
9924 }
9925 
9926 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
9927 					struct vm_area_struct *vma,
9928 					struct perf_addr_filter_range *fr)
9929 {
9930 	unsigned long vma_size = vma->vm_end - vma->vm_start;
9931 	unsigned long off = vma_start_pgoff(vma) << PAGE_SHIFT;
9932 	struct file *file = vma->vm_file;
9933 
9934 	if (!perf_addr_filter_match(filter, file, off, vma_size))
9935 		return false;
9936 
9937 	if (filter->offset < off) {
9938 		fr->start = vma->vm_start;
9939 		fr->size = min(vma_size, filter->size - (off - filter->offset));
9940 	} else {
9941 		fr->start = vma->vm_start + filter->offset - off;
9942 		fr->size = min(vma->vm_end - fr->start, filter->size);
9943 	}
9944 
9945 	return true;
9946 }
9947 
9948 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
9949 {
9950 	struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
9951 	struct vm_area_struct *vma = data;
9952 	struct perf_addr_filter *filter;
9953 	unsigned int restart = 0, count = 0;
9954 	unsigned long flags;
9955 
9956 	if (!has_addr_filter(event))
9957 		return;
9958 
9959 	if (!vma->vm_file)
9960 		return;
9961 
9962 	raw_spin_lock_irqsave(&ifh->lock, flags);
9963 	list_for_each_entry(filter, &ifh->list, entry) {
9964 		if (perf_addr_filter_vma_adjust(filter, vma,
9965 						&event->addr_filter_ranges[count]))
9966 			restart++;
9967 
9968 		count++;
9969 	}
9970 
9971 	if (restart)
9972 		event->addr_filters_gen++;
9973 	raw_spin_unlock_irqrestore(&ifh->lock, flags);
9974 
9975 	if (restart)
9976 		perf_event_stop(event, 1);
9977 }
9978 
9979 /*
9980  * Adjust all task's events' filters to the new vma
9981  */
9982 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
9983 {
9984 	struct perf_event_context *ctx;
9985 
9986 	/*
9987 	 * Data tracing isn't supported yet and as such there is no need
9988 	 * to keep track of anything that isn't related to executable code:
9989 	 */
9990 	if (!(vma->vm_flags & VM_EXEC))
9991 		return;
9992 
9993 	rcu_read_lock();
9994 	ctx = rcu_dereference(current->perf_event_ctxp);
9995 	if (ctx)
9996 		perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
9997 	rcu_read_unlock();
9998 }
9999 
10000 void perf_event_mmap(struct vm_area_struct *vma)
10001 {
10002 	struct perf_mmap_event mmap_event;
10003 
10004 	if (!atomic_read(&nr_mmap_events))
10005 		return;
10006 
10007 	mmap_event = (struct perf_mmap_event){
10008 		.vma	= vma,
10009 		/* .file_name */
10010 		/* .file_size */
10011 		.event_id  = {
10012 			.header = {
10013 				.type = PERF_RECORD_MMAP,
10014 				.misc = PERF_RECORD_MISC_USER,
10015 				/* .size */
10016 			},
10017 			/* .pid */
10018 			/* .tid */
10019 			.start  = vma->vm_start,
10020 			.len    = vma->vm_end - vma->vm_start,
10021 			.pgoff  = (u64)vma_start_pgoff(vma) << PAGE_SHIFT,
10022 		},
10023 		/* .maj (attr_mmap2 only) */
10024 		/* .min (attr_mmap2 only) */
10025 		/* .ino (attr_mmap2 only) */
10026 		/* .ino_generation (attr_mmap2 only) */
10027 		/* .prot (attr_mmap2 only) */
10028 		/* .flags (attr_mmap2 only) */
10029 	};
10030 
10031 	perf_addr_filters_adjust(vma);
10032 	perf_event_mmap_event(&mmap_event);
10033 }
10034 
10035 void perf_event_aux_event(struct perf_event *event, unsigned long head,
10036 			  unsigned long size, u64 flags)
10037 {
10038 	struct perf_output_handle handle;
10039 	struct perf_sample_data sample;
10040 	struct perf_aux_event {
10041 		struct perf_event_header	header;
10042 		u64				offset;
10043 		u64				size;
10044 		u64				flags;
10045 	} rec = {
10046 		.header = {
10047 			.type = PERF_RECORD_AUX,
10048 			.misc = 0,
10049 			.size = sizeof(rec),
10050 		},
10051 		.offset		= head,
10052 		.size		= size,
10053 		.flags		= flags,
10054 	};
10055 	int ret;
10056 
10057 	perf_event_header__init_id(&rec.header, &sample, event);
10058 	ret = perf_output_begin(&handle, &sample, event, rec.header.size);
10059 
10060 	if (ret)
10061 		return;
10062 
10063 	perf_output_put(&handle, rec);
10064 	perf_event__output_id_sample(event, &handle, &sample);
10065 
10066 	perf_output_end(&handle);
10067 }
10068 
10069 /*
10070  * Lost/dropped samples logging
10071  */
10072 void perf_log_lost_samples(struct perf_event *event, u64 lost)
10073 {
10074 	struct perf_output_handle handle;
10075 	struct perf_sample_data sample;
10076 	int ret;
10077 
10078 	struct {
10079 		struct perf_event_header	header;
10080 		u64				lost;
10081 	} lost_samples_event = {
10082 		.header = {
10083 			.type = PERF_RECORD_LOST_SAMPLES,
10084 			.misc = 0,
10085 			.size = sizeof(lost_samples_event),
10086 		},
10087 		.lost		= lost,
10088 	};
10089 
10090 	perf_event_header__init_id(&lost_samples_event.header, &sample, event);
10091 
10092 	ret = perf_output_begin(&handle, &sample, event,
10093 				lost_samples_event.header.size);
10094 	if (ret)
10095 		return;
10096 
10097 	perf_output_put(&handle, lost_samples_event);
10098 	perf_event__output_id_sample(event, &handle, &sample);
10099 	perf_output_end(&handle);
10100 }
10101 
10102 /*
10103  * context_switch tracking
10104  */
10105 
10106 struct perf_switch_event {
10107 	struct task_struct	*task;
10108 	struct task_struct	*next_prev;
10109 
10110 	struct {
10111 		struct perf_event_header	header;
10112 		u32				next_prev_pid;
10113 		u32				next_prev_tid;
10114 	} event_id;
10115 };
10116 
10117 static int perf_event_switch_match(struct perf_event *event)
10118 {
10119 	return event->attr.context_switch;
10120 }
10121 
10122 static void perf_event_switch_output(struct perf_event *event, void *data)
10123 {
10124 	struct perf_switch_event *se = data;
10125 	struct perf_output_handle handle;
10126 	struct perf_sample_data sample;
10127 	int ret;
10128 
10129 	if (!perf_event_switch_match(event))
10130 		return;
10131 
10132 	/* Only CPU-wide events are allowed to see next/prev pid/tid */
10133 	if (event->ctx->task) {
10134 		se->event_id.header.type = PERF_RECORD_SWITCH;
10135 		se->event_id.header.size = sizeof(se->event_id.header);
10136 	} else {
10137 		se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
10138 		se->event_id.header.size = sizeof(se->event_id);
10139 		se->event_id.next_prev_pid =
10140 					perf_event_pid(event, se->next_prev);
10141 		se->event_id.next_prev_tid =
10142 					perf_event_tid(event, se->next_prev);
10143 	}
10144 
10145 	perf_event_header__init_id(&se->event_id.header, &sample, event);
10146 
10147 	ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size);
10148 	if (ret)
10149 		return;
10150 
10151 	if (event->ctx->task)
10152 		perf_output_put(&handle, se->event_id.header);
10153 	else
10154 		perf_output_put(&handle, se->event_id);
10155 
10156 	perf_event__output_id_sample(event, &handle, &sample);
10157 
10158 	perf_output_end(&handle);
10159 }
10160 
10161 static void perf_event_switch(struct task_struct *task,
10162 			      struct task_struct *next_prev, bool sched_in)
10163 {
10164 	struct perf_switch_event switch_event;
10165 
10166 	/* N.B. caller checks nr_switch_events != 0 */
10167 
10168 	switch_event = (struct perf_switch_event){
10169 		.task		= task,
10170 		.next_prev	= next_prev,
10171 		.event_id	= {
10172 			.header = {
10173 				/* .type */
10174 				.misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
10175 				/* .size */
10176 			},
10177 			/* .next_prev_pid */
10178 			/* .next_prev_tid */
10179 		},
10180 	};
10181 
10182 	if (!sched_in && task_is_runnable(task)) {
10183 		switch_event.event_id.header.misc |=
10184 				PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
10185 	}
10186 
10187 	perf_iterate_sb(perf_event_switch_output, &switch_event, NULL);
10188 }
10189 
10190 /*
10191  * IRQ throttle logging
10192  */
10193 
10194 static void perf_log_throttle(struct perf_event *event, int enable)
10195 {
10196 	struct perf_output_handle handle;
10197 	struct perf_sample_data sample;
10198 	int ret;
10199 
10200 	struct {
10201 		struct perf_event_header	header;
10202 		u64				time;
10203 		u64				id;
10204 		u64				stream_id;
10205 	} throttle_event = {
10206 		.header = {
10207 			.type = PERF_RECORD_THROTTLE,
10208 			.misc = 0,
10209 			.size = sizeof(throttle_event),
10210 		},
10211 		.time		= perf_event_clock(event),
10212 		.id		= primary_event_id(event),
10213 		.stream_id	= event->id,
10214 	};
10215 
10216 	if (enable)
10217 		throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
10218 
10219 	perf_event_header__init_id(&throttle_event.header, &sample, event);
10220 
10221 	ret = perf_output_begin(&handle, &sample, event,
10222 				throttle_event.header.size);
10223 	if (ret)
10224 		return;
10225 
10226 	perf_output_put(&handle, throttle_event);
10227 	perf_event__output_id_sample(event, &handle, &sample);
10228 	perf_output_end(&handle);
10229 }
10230 
10231 /*
10232  * ksymbol register/unregister tracking
10233  */
10234 
10235 struct perf_ksymbol_event {
10236 	const char	*name;
10237 	int		name_len;
10238 	struct {
10239 		struct perf_event_header        header;
10240 		u64				addr;
10241 		u32				len;
10242 		u16				ksym_type;
10243 		u16				flags;
10244 	} event_id;
10245 };
10246 
10247 static int perf_event_ksymbol_match(struct perf_event *event)
10248 {
10249 	return event->attr.ksymbol;
10250 }
10251 
10252 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
10253 {
10254 	struct perf_ksymbol_event *ksymbol_event = data;
10255 	struct perf_output_handle handle;
10256 	struct perf_sample_data sample;
10257 	int ret;
10258 
10259 	if (!perf_event_ksymbol_match(event))
10260 		return;
10261 
10262 	perf_event_header__init_id(&ksymbol_event->event_id.header,
10263 				   &sample, event);
10264 	ret = perf_output_begin(&handle, &sample, event,
10265 				ksymbol_event->event_id.header.size);
10266 	if (ret)
10267 		return;
10268 
10269 	perf_output_put(&handle, ksymbol_event->event_id);
10270 	__output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
10271 	perf_event__output_id_sample(event, &handle, &sample);
10272 
10273 	perf_output_end(&handle);
10274 }
10275 
10276 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
10277 			const char *sym)
10278 {
10279 	struct perf_ksymbol_event ksymbol_event;
10280 	char name[KSYM_NAME_LEN];
10281 	u16 flags = 0;
10282 	int name_len;
10283 
10284 	if (!atomic_read(&nr_ksymbol_events))
10285 		return;
10286 
10287 	if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
10288 	    ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
10289 		goto err;
10290 
10291 	strscpy(name, sym);
10292 	name_len = strlen(name) + 1;
10293 	while (!IS_ALIGNED(name_len, sizeof(u64)))
10294 		name[name_len++] = '\0';
10295 	BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
10296 
10297 	if (unregister)
10298 		flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
10299 
10300 	ksymbol_event = (struct perf_ksymbol_event){
10301 		.name = name,
10302 		.name_len = name_len,
10303 		.event_id = {
10304 			.header = {
10305 				.type = PERF_RECORD_KSYMBOL,
10306 				.size = sizeof(ksymbol_event.event_id) +
10307 					name_len,
10308 			},
10309 			.addr = addr,
10310 			.len = len,
10311 			.ksym_type = ksym_type,
10312 			.flags = flags,
10313 		},
10314 	};
10315 
10316 	perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
10317 	return;
10318 err:
10319 	WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
10320 }
10321 
10322 /*
10323  * bpf program load/unload tracking
10324  */
10325 
10326 struct perf_bpf_event {
10327 	struct bpf_prog	*prog;
10328 	struct {
10329 		struct perf_event_header        header;
10330 		u16				type;
10331 		u16				flags;
10332 		u32				id;
10333 		u8				tag[BPF_TAG_SIZE];
10334 	} event_id;
10335 };
10336 
10337 static int perf_event_bpf_match(struct perf_event *event)
10338 {
10339 	return event->attr.bpf_event;
10340 }
10341 
10342 static void perf_event_bpf_output(struct perf_event *event, void *data)
10343 {
10344 	struct perf_bpf_event *bpf_event = data;
10345 	struct perf_output_handle handle;
10346 	struct perf_sample_data sample;
10347 	int ret;
10348 
10349 	if (!perf_event_bpf_match(event))
10350 		return;
10351 
10352 	perf_event_header__init_id(&bpf_event->event_id.header,
10353 				   &sample, event);
10354 	ret = perf_output_begin(&handle, &sample, event,
10355 				bpf_event->event_id.header.size);
10356 	if (ret)
10357 		return;
10358 
10359 	perf_output_put(&handle, bpf_event->event_id);
10360 	perf_event__output_id_sample(event, &handle, &sample);
10361 
10362 	perf_output_end(&handle);
10363 }
10364 
10365 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
10366 					 enum perf_bpf_event_type type)
10367 {
10368 	bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
10369 	int i;
10370 
10371 	perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
10372 			   (u64)(unsigned long)prog->bpf_func,
10373 			   prog->jited_len, unregister,
10374 			   prog->aux->ksym.name);
10375 
10376 	for (i = 1; i < prog->aux->func_cnt; i++) {
10377 		struct bpf_prog *subprog = prog->aux->func[i];
10378 
10379 		perf_event_ksymbol(
10380 			PERF_RECORD_KSYMBOL_TYPE_BPF,
10381 			(u64)(unsigned long)subprog->bpf_func,
10382 			subprog->jited_len, unregister,
10383 			subprog->aux->ksym.name);
10384 	}
10385 }
10386 
10387 void perf_event_bpf_event(struct bpf_prog *prog,
10388 			  enum perf_bpf_event_type type,
10389 			  u16 flags)
10390 {
10391 	struct perf_bpf_event bpf_event;
10392 
10393 	switch (type) {
10394 	case PERF_BPF_EVENT_PROG_LOAD:
10395 	case PERF_BPF_EVENT_PROG_UNLOAD:
10396 		if (atomic_read(&nr_ksymbol_events))
10397 			perf_event_bpf_emit_ksymbols(prog, type);
10398 		break;
10399 	default:
10400 		return;
10401 	}
10402 
10403 	if (!atomic_read(&nr_bpf_events))
10404 		return;
10405 
10406 	bpf_event = (struct perf_bpf_event){
10407 		.prog = prog,
10408 		.event_id = {
10409 			.header = {
10410 				.type = PERF_RECORD_BPF_EVENT,
10411 				.size = sizeof(bpf_event.event_id),
10412 			},
10413 			.type = type,
10414 			.flags = flags,
10415 			.id = prog->aux->id,
10416 		},
10417 	};
10418 
10419 	BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
10420 
10421 	memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
10422 	perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
10423 }
10424 
10425 struct perf_callchain_deferred_event {
10426 	struct unwind_stacktrace *trace;
10427 	struct {
10428 		struct perf_event_header	header;
10429 		u64				cookie;
10430 		u64				nr;
10431 		u64				ips[];
10432 	} event;
10433 };
10434 
10435 static void perf_callchain_deferred_output(struct perf_event *event, void *data)
10436 {
10437 	struct perf_callchain_deferred_event *deferred_event = data;
10438 	struct perf_output_handle handle;
10439 	struct perf_sample_data sample;
10440 	int ret, size = deferred_event->event.header.size;
10441 
10442 	if (!event->attr.defer_output)
10443 		return;
10444 
10445 	/* XXX do we really need sample_id_all for this ??? */
10446 	perf_event_header__init_id(&deferred_event->event.header, &sample, event);
10447 
10448 	ret = perf_output_begin(&handle, &sample, event,
10449 				deferred_event->event.header.size);
10450 	if (ret)
10451 		goto out;
10452 
10453 	perf_output_put(&handle, deferred_event->event);
10454 	for (int i = 0; i < deferred_event->trace->nr; i++) {
10455 		u64 entry = deferred_event->trace->entries[i];
10456 		perf_output_put(&handle, entry);
10457 	}
10458 	perf_event__output_id_sample(event, &handle, &sample);
10459 
10460 	perf_output_end(&handle);
10461 out:
10462 	deferred_event->event.header.size = size;
10463 }
10464 
10465 static void perf_unwind_deferred_callback(struct unwind_work *work,
10466 					 struct unwind_stacktrace *trace, u64 cookie)
10467 {
10468 	struct perf_callchain_deferred_event deferred_event = {
10469 		.trace = trace,
10470 		.event = {
10471 			.header = {
10472 				.type = PERF_RECORD_CALLCHAIN_DEFERRED,
10473 				.misc = PERF_RECORD_MISC_USER,
10474 				.size = sizeof(deferred_event.event) +
10475 					(trace->nr * sizeof(u64)),
10476 			},
10477 			.cookie = cookie,
10478 			.nr = trace->nr,
10479 		},
10480 	};
10481 
10482 	perf_iterate_sb(perf_callchain_deferred_output, &deferred_event, NULL);
10483 }
10484 
10485 struct perf_text_poke_event {
10486 	const void		*old_bytes;
10487 	const void		*new_bytes;
10488 	size_t			pad;
10489 	u16			old_len;
10490 	u16			new_len;
10491 
10492 	struct {
10493 		struct perf_event_header	header;
10494 
10495 		u64				addr;
10496 	} event_id;
10497 };
10498 
10499 static int perf_event_text_poke_match(struct perf_event *event)
10500 {
10501 	return event->attr.text_poke;
10502 }
10503 
10504 static void perf_event_text_poke_output(struct perf_event *event, void *data)
10505 {
10506 	struct perf_text_poke_event *text_poke_event = data;
10507 	struct perf_output_handle handle;
10508 	struct perf_sample_data sample;
10509 	u64 padding = 0;
10510 	int ret;
10511 
10512 	if (!perf_event_text_poke_match(event))
10513 		return;
10514 
10515 	perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
10516 
10517 	ret = perf_output_begin(&handle, &sample, event,
10518 				text_poke_event->event_id.header.size);
10519 	if (ret)
10520 		return;
10521 
10522 	perf_output_put(&handle, text_poke_event->event_id);
10523 	perf_output_put(&handle, text_poke_event->old_len);
10524 	perf_output_put(&handle, text_poke_event->new_len);
10525 
10526 	__output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
10527 	__output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
10528 
10529 	if (text_poke_event->pad)
10530 		__output_copy(&handle, &padding, text_poke_event->pad);
10531 
10532 	perf_event__output_id_sample(event, &handle, &sample);
10533 
10534 	perf_output_end(&handle);
10535 }
10536 
10537 void perf_event_text_poke(const void *addr, const void *old_bytes,
10538 			  size_t old_len, const void *new_bytes, size_t new_len)
10539 {
10540 	struct perf_text_poke_event text_poke_event;
10541 	size_t tot, pad;
10542 
10543 	if (!atomic_read(&nr_text_poke_events))
10544 		return;
10545 
10546 	tot  = sizeof(text_poke_event.old_len) + old_len;
10547 	tot += sizeof(text_poke_event.new_len) + new_len;
10548 	pad  = ALIGN(tot, sizeof(u64)) - tot;
10549 
10550 	text_poke_event = (struct perf_text_poke_event){
10551 		.old_bytes    = old_bytes,
10552 		.new_bytes    = new_bytes,
10553 		.pad          = pad,
10554 		.old_len      = old_len,
10555 		.new_len      = new_len,
10556 		.event_id  = {
10557 			.header = {
10558 				.type = PERF_RECORD_TEXT_POKE,
10559 				.misc = PERF_RECORD_MISC_KERNEL,
10560 				.size = sizeof(text_poke_event.event_id) + tot + pad,
10561 			},
10562 			.addr = (unsigned long)addr,
10563 		},
10564 	};
10565 
10566 	perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
10567 }
10568 
10569 void perf_event_itrace_started(struct perf_event *event)
10570 {
10571 	WRITE_ONCE(event->attach_state, event->attach_state | PERF_ATTACH_ITRACE);
10572 }
10573 
10574 static void perf_log_itrace_start(struct perf_event *event)
10575 {
10576 	struct perf_output_handle handle;
10577 	struct perf_sample_data sample;
10578 	struct perf_aux_event {
10579 		struct perf_event_header        header;
10580 		u32				pid;
10581 		u32				tid;
10582 	} rec;
10583 	int ret;
10584 
10585 	if (event->parent)
10586 		event = event->parent;
10587 
10588 	if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
10589 	    event->attach_state & PERF_ATTACH_ITRACE)
10590 		return;
10591 
10592 	rec.header.type	= PERF_RECORD_ITRACE_START;
10593 	rec.header.misc	= 0;
10594 	rec.header.size	= sizeof(rec);
10595 	rec.pid	= perf_event_pid(event, current);
10596 	rec.tid	= perf_event_tid(event, current);
10597 
10598 	perf_event_header__init_id(&rec.header, &sample, event);
10599 	ret = perf_output_begin(&handle, &sample, event, rec.header.size);
10600 
10601 	if (ret)
10602 		return;
10603 
10604 	perf_output_put(&handle, rec);
10605 	perf_event__output_id_sample(event, &handle, &sample);
10606 
10607 	perf_output_end(&handle);
10608 }
10609 
10610 void perf_report_aux_output_id(struct perf_event *event, u64 hw_id)
10611 {
10612 	struct perf_output_handle handle;
10613 	struct perf_sample_data sample;
10614 	struct perf_aux_event {
10615 		struct perf_event_header        header;
10616 		u64				hw_id;
10617 	} rec;
10618 	int ret;
10619 
10620 	if (event->parent)
10621 		event = event->parent;
10622 
10623 	rec.header.type	= PERF_RECORD_AUX_OUTPUT_HW_ID;
10624 	rec.header.misc	= 0;
10625 	rec.header.size	= sizeof(rec);
10626 	rec.hw_id	= hw_id;
10627 
10628 	perf_event_header__init_id(&rec.header, &sample, event);
10629 	ret = perf_output_begin(&handle, &sample, event, rec.header.size);
10630 
10631 	if (ret)
10632 		return;
10633 
10634 	perf_output_put(&handle, rec);
10635 	perf_event__output_id_sample(event, &handle, &sample);
10636 
10637 	perf_output_end(&handle);
10638 }
10639 EXPORT_SYMBOL_GPL(perf_report_aux_output_id);
10640 
10641 static int
10642 __perf_event_account_interrupt(struct perf_event *event, int throttle)
10643 {
10644 	struct hw_perf_event *hwc = &event->hw;
10645 	int ret = 0;
10646 	u64 seq;
10647 
10648 	seq = __this_cpu_read(perf_throttled_seq);
10649 	if (seq != hwc->interrupts_seq) {
10650 		hwc->interrupts_seq = seq;
10651 		hwc->interrupts = 1;
10652 	} else {
10653 		hwc->interrupts++;
10654 	}
10655 
10656 	if (unlikely(throttle && hwc->interrupts >= max_samples_per_tick)) {
10657 		__this_cpu_inc(perf_throttled_count);
10658 		tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
10659 		perf_event_throttle_group(event);
10660 		ret = 1;
10661 	}
10662 
10663 	if (event->attr.freq) {
10664 		u64 now = perf_clock();
10665 		s64 delta = now - hwc->freq_time_stamp;
10666 
10667 		hwc->freq_time_stamp = now;
10668 
10669 		if (delta > 0 && delta < 2*TICK_NSEC)
10670 			perf_adjust_period(event, delta, hwc->last_period, true);
10671 	}
10672 
10673 	return ret;
10674 }
10675 
10676 int perf_event_account_interrupt(struct perf_event *event)
10677 {
10678 	return __perf_event_account_interrupt(event, 1);
10679 }
10680 
10681 static inline bool sample_is_allowed(struct perf_event *event, struct pt_regs *regs)
10682 {
10683 	/*
10684 	 * Due to interrupt latency (AKA "skid"), we may enter the
10685 	 * kernel before taking an overflow, even if the PMU is only
10686 	 * counting user events.
10687 	 */
10688 	if (event->attr.exclude_kernel && !user_mode(regs))
10689 		return false;
10690 
10691 	return true;
10692 }
10693 
10694 #ifdef CONFIG_BPF_SYSCALL
10695 static int bpf_overflow_handler(struct perf_event *event,
10696 				struct perf_sample_data *data,
10697 				struct pt_regs *regs)
10698 {
10699 	struct bpf_perf_event_data_kern ctx = {
10700 		.data = data,
10701 		.event = event,
10702 	};
10703 	struct bpf_prog *prog;
10704 	int ret = 0;
10705 
10706 	ctx.regs = perf_arch_bpf_user_pt_regs(regs);
10707 	if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
10708 		goto out;
10709 	rcu_read_lock();
10710 	prog = READ_ONCE(event->prog);
10711 	if (prog) {
10712 		perf_prepare_sample(data, event, regs);
10713 		ret = bpf_prog_run(prog, &ctx);
10714 	}
10715 	rcu_read_unlock();
10716 out:
10717 	__this_cpu_dec(bpf_prog_active);
10718 
10719 	return ret;
10720 }
10721 
10722 static inline int perf_event_set_bpf_handler(struct perf_event *event,
10723 					     struct bpf_prog *prog,
10724 					     u64 bpf_cookie)
10725 {
10726 	if (event->overflow_handler_context)
10727 		/* hw breakpoint or kernel counter */
10728 		return -EINVAL;
10729 
10730 	if (event->prog)
10731 		return -EEXIST;
10732 
10733 	if (prog->type != BPF_PROG_TYPE_PERF_EVENT)
10734 		return -EINVAL;
10735 
10736 	if (event->attr.precise_ip &&
10737 	    prog->call_get_stack &&
10738 	    (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) ||
10739 	     event->attr.exclude_callchain_kernel ||
10740 	     event->attr.exclude_callchain_user)) {
10741 		/*
10742 		 * On perf_event with precise_ip, calling bpf_get_stack()
10743 		 * may trigger unwinder warnings and occasional crashes.
10744 		 * bpf_get_[stack|stackid] works around this issue by using
10745 		 * callchain attached to perf_sample_data. If the
10746 		 * perf_event does not full (kernel and user) callchain
10747 		 * attached to perf_sample_data, do not allow attaching BPF
10748 		 * program that calls bpf_get_[stack|stackid].
10749 		 */
10750 		return -EPROTO;
10751 	}
10752 
10753 	event->prog = prog;
10754 	event->bpf_cookie = bpf_cookie;
10755 	return 0;
10756 }
10757 
10758 static inline void perf_event_free_bpf_handler(struct perf_event *event)
10759 {
10760 	struct bpf_prog *prog = event->prog;
10761 
10762 	if (!prog)
10763 		return;
10764 
10765 	event->prog = NULL;
10766 	bpf_prog_put(prog);
10767 }
10768 #else
10769 static inline int bpf_overflow_handler(struct perf_event *event,
10770 				       struct perf_sample_data *data,
10771 				       struct pt_regs *regs)
10772 {
10773 	return 1;
10774 }
10775 
10776 static inline int perf_event_set_bpf_handler(struct perf_event *event,
10777 					     struct bpf_prog *prog,
10778 					     u64 bpf_cookie)
10779 {
10780 	return -EOPNOTSUPP;
10781 }
10782 
10783 static inline void perf_event_free_bpf_handler(struct perf_event *event)
10784 {
10785 }
10786 #endif
10787 
10788 /*
10789  * Generic event overflow handling, sampling.
10790  */
10791 
10792 static int __perf_event_overflow(struct perf_event *event,
10793 				 int throttle, struct perf_sample_data *data,
10794 				 struct pt_regs *regs)
10795 {
10796 	int events = atomic_read(&event->event_limit);
10797 	int ret = 0;
10798 
10799 	/*
10800 	 * Non-sampling counters might still use the PMI to fold short
10801 	 * hardware counters, ignore those.
10802 	 */
10803 	if (unlikely(!is_sampling_event(event)))
10804 		return 0;
10805 
10806 	ret = __perf_event_account_interrupt(event, throttle);
10807 
10808 	if (event->attr.aux_pause)
10809 		perf_event_aux_pause(event->aux_event, true);
10810 
10811 	if (event->prog && event->prog->type == BPF_PROG_TYPE_PERF_EVENT &&
10812 	    !bpf_overflow_handler(event, data, regs))
10813 		goto out;
10814 
10815 	/*
10816 	 * XXX event_limit might not quite work as expected on inherited
10817 	 * events
10818 	 */
10819 
10820 	event->pending_kill = POLL_IN;
10821 	if (events && atomic_dec_and_test(&event->event_limit)) {
10822 		ret = 1;
10823 		event->pending_kill = POLL_HUP;
10824 		perf_event_disable_inatomic(event);
10825 		event->pmu->stop(event, 0);
10826 	}
10827 
10828 	if (event->attr.sigtrap) {
10829 		/*
10830 		 * The desired behaviour of sigtrap vs invalid samples is a bit
10831 		 * tricky; on the one hand, one should not loose the SIGTRAP if
10832 		 * it is the first event, on the other hand, we should also not
10833 		 * trigger the WARN or override the data address.
10834 		 */
10835 		bool valid_sample = sample_is_allowed(event, regs);
10836 		unsigned int pending_id = 1;
10837 		enum task_work_notify_mode notify_mode;
10838 
10839 		if (regs)
10840 			pending_id = hash32_ptr((void *)instruction_pointer(regs)) ?: 1;
10841 
10842 		notify_mode = in_nmi() ? TWA_NMI_CURRENT : TWA_RESUME;
10843 
10844 		if (!event->pending_work &&
10845 		    !task_work_add(current, &event->pending_task, notify_mode)) {
10846 			event->pending_work = pending_id;
10847 			local_inc(&event->ctx->nr_no_switch_fast);
10848 			WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount));
10849 
10850 			event->pending_addr = 0;
10851 			if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR))
10852 				event->pending_addr = data->addr;
10853 
10854 		} else if (event->attr.exclude_kernel && valid_sample) {
10855 			/*
10856 			 * Should not be able to return to user space without
10857 			 * consuming pending_work; with exceptions:
10858 			 *
10859 			 *  1. Where !exclude_kernel, events can overflow again
10860 			 *     in the kernel without returning to user space.
10861 			 *
10862 			 *  2. Events that can overflow again before the IRQ-
10863 			 *     work without user space progress (e.g. hrtimer).
10864 			 *     To approximate progress (with false negatives),
10865 			 *     check 32-bit hash of the current IP.
10866 			 */
10867 			WARN_ON_ONCE(event->pending_work != pending_id);
10868 		}
10869 	}
10870 
10871 	READ_ONCE(event->overflow_handler)(event, data, regs);
10872 
10873 	if (*perf_event_fasync(event) && event->pending_kill) {
10874 		event->pending_wakeup = 1;
10875 		irq_work_queue(&event->pending_irq);
10876 	}
10877 out:
10878 	if (event->attr.aux_resume)
10879 		perf_event_aux_pause(event->aux_event, false);
10880 
10881 	return ret;
10882 }
10883 
10884 int perf_event_overflow(struct perf_event *event,
10885 			struct perf_sample_data *data,
10886 			struct pt_regs *regs)
10887 {
10888 	/*
10889 	 * Entry point from hardware PMI, interrupts should be disabled here.
10890 	 * This serializes us against perf_event_remove_from_context() in
10891 	 * things like perf_event_release_kernel().
10892 	 */
10893 	lockdep_assert_irqs_disabled();
10894 
10895 	return __perf_event_overflow(event, 1, data, regs);
10896 }
10897 
10898 /*
10899  * Generic software event infrastructure
10900  */
10901 
10902 struct swevent_htable {
10903 	struct swevent_hlist		*swevent_hlist;
10904 	struct mutex			hlist_mutex;
10905 	int				hlist_refcount;
10906 };
10907 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
10908 
10909 /*
10910  * We directly increment event->count and keep a second value in
10911  * event->hw.period_left to count intervals. This period event
10912  * is kept in the range [-sample_period, 0] so that we can use the
10913  * sign as trigger.
10914  */
10915 
10916 u64 perf_swevent_set_period(struct perf_event *event)
10917 {
10918 	struct hw_perf_event *hwc = &event->hw;
10919 	u64 period = hwc->last_period;
10920 	u64 nr, offset;
10921 	s64 old, val;
10922 
10923 	hwc->last_period = hwc->sample_period;
10924 
10925 	old = local64_read(&hwc->period_left);
10926 	do {
10927 		val = old;
10928 		if (val < 0)
10929 			return 0;
10930 
10931 		nr = div64_u64(period + val, period);
10932 		offset = nr * period;
10933 		val -= offset;
10934 	} while (!local64_try_cmpxchg(&hwc->period_left, &old, val));
10935 
10936 	return nr;
10937 }
10938 
10939 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
10940 				    struct perf_sample_data *data,
10941 				    struct pt_regs *regs)
10942 {
10943 	struct hw_perf_event *hwc = &event->hw;
10944 	int throttle = 0;
10945 
10946 	if (!overflow)
10947 		overflow = perf_swevent_set_period(event);
10948 
10949 	if (hwc->interrupts == MAX_INTERRUPTS)
10950 		return;
10951 
10952 	for (; overflow; overflow--) {
10953 		if (__perf_event_overflow(event, throttle,
10954 					    data, regs)) {
10955 			/*
10956 			 * We inhibit the overflow from happening when
10957 			 * hwc->interrupts == MAX_INTERRUPTS.
10958 			 */
10959 			break;
10960 		}
10961 		throttle = 1;
10962 	}
10963 }
10964 
10965 static void perf_swevent_event(struct perf_event *event, u64 nr,
10966 			       struct perf_sample_data *data,
10967 			       struct pt_regs *regs)
10968 {
10969 	struct hw_perf_event *hwc = &event->hw;
10970 
10971 	/*
10972 	 * This is:
10973 	 *   - software		preempt
10974 	 *   - tracepoint	preempt
10975 	 *   -   tp_target_task	irq (ctx->lock)
10976 	 *   - uprobes		preempt/irq
10977 	 *   - kprobes		preempt/irq
10978 	 *   - hw_breakpoint	irq
10979 	 *
10980 	 * Any of these are sufficient to hold off RCU and thus ensure @event
10981 	 * exists.
10982 	 */
10983 	lockdep_assert_preemption_disabled();
10984 	local64_add(nr, &event->count);
10985 
10986 	if (!regs)
10987 		return;
10988 
10989 	if (!is_sampling_event(event))
10990 		return;
10991 
10992 	/*
10993 	 * Serialize against event_function_call() IPIs like normal overflow
10994 	 * event handling. Specifically, must not allow
10995 	 * perf_event_release_kernel() -> perf_remove_from_context() to make
10996 	 * progress and 'release' the event from under us.
10997 	 */
10998 	guard(irqsave)();
10999 	if (event->state != PERF_EVENT_STATE_ACTIVE)
11000 		return;
11001 
11002 	if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
11003 		data->period = nr;
11004 		return perf_swevent_overflow(event, 1, data, regs);
11005 	} else
11006 		data->period = event->hw.last_period;
11007 
11008 	if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
11009 		return perf_swevent_overflow(event, 1, data, regs);
11010 
11011 	if (local64_add_negative(nr, &hwc->period_left))
11012 		return;
11013 
11014 	perf_swevent_overflow(event, 0, data, regs);
11015 }
11016 
11017 int perf_exclude_event(struct perf_event *event, struct pt_regs *regs)
11018 {
11019 	if (event->hw.state & PERF_HES_STOPPED)
11020 		return 1;
11021 
11022 	if (regs) {
11023 		if (event->attr.exclude_user && user_mode(regs))
11024 			return 1;
11025 
11026 		if (event->attr.exclude_kernel && !user_mode(regs))
11027 			return 1;
11028 	}
11029 
11030 	return 0;
11031 }
11032 
11033 static int perf_swevent_match(struct perf_event *event,
11034 				enum perf_type_id type,
11035 				u32 event_id,
11036 				struct perf_sample_data *data,
11037 				struct pt_regs *regs)
11038 {
11039 	if (event->attr.type != type)
11040 		return 0;
11041 
11042 	if (event->attr.config != event_id)
11043 		return 0;
11044 
11045 	if (perf_exclude_event(event, regs))
11046 		return 0;
11047 
11048 	return 1;
11049 }
11050 
11051 static inline u64 swevent_hash(u64 type, u32 event_id)
11052 {
11053 	u64 val = event_id | (type << 32);
11054 
11055 	return hash_64(val, SWEVENT_HLIST_BITS);
11056 }
11057 
11058 static inline struct hlist_head *
11059 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
11060 {
11061 	u64 hash = swevent_hash(type, event_id);
11062 
11063 	return &hlist->heads[hash];
11064 }
11065 
11066 /* For the read side: events when they trigger */
11067 static inline struct hlist_head *
11068 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
11069 {
11070 	struct swevent_hlist *hlist;
11071 
11072 	hlist = rcu_dereference(swhash->swevent_hlist);
11073 	if (!hlist)
11074 		return NULL;
11075 
11076 	return __find_swevent_head(hlist, type, event_id);
11077 }
11078 
11079 /* For the event head insertion and removal in the hlist */
11080 static inline struct hlist_head *
11081 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
11082 {
11083 	struct swevent_hlist *hlist;
11084 	u32 event_id = event->attr.config;
11085 	u64 type = event->attr.type;
11086 
11087 	/*
11088 	 * Event scheduling is always serialized against hlist allocation
11089 	 * and release. Which makes the protected version suitable here.
11090 	 * The context lock guarantees that.
11091 	 */
11092 	hlist = rcu_dereference_protected(swhash->swevent_hlist,
11093 					  lockdep_is_held(&event->ctx->lock));
11094 	if (!hlist)
11095 		return NULL;
11096 
11097 	return __find_swevent_head(hlist, type, event_id);
11098 }
11099 
11100 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
11101 				    u64 nr,
11102 				    struct perf_sample_data *data,
11103 				    struct pt_regs *regs)
11104 {
11105 	struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
11106 	struct perf_event *event;
11107 	struct hlist_head *head;
11108 
11109 	rcu_read_lock();
11110 	head = find_swevent_head_rcu(swhash, type, event_id);
11111 	if (!head)
11112 		goto end;
11113 
11114 	hlist_for_each_entry_rcu(event, head, hlist_entry) {
11115 		if (perf_swevent_match(event, type, event_id, data, regs))
11116 			perf_swevent_event(event, nr, data, regs);
11117 	}
11118 end:
11119 	rcu_read_unlock();
11120 }
11121 
11122 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
11123 
11124 int perf_swevent_get_recursion_context(void)
11125 {
11126 	return get_recursion_context(current->perf_recursion);
11127 }
11128 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
11129 
11130 void perf_swevent_put_recursion_context(int rctx)
11131 {
11132 	put_recursion_context(current->perf_recursion, rctx);
11133 }
11134 
11135 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
11136 {
11137 	struct perf_sample_data data;
11138 
11139 	if (WARN_ON_ONCE(!regs))
11140 		return;
11141 
11142 	perf_sample_data_init(&data, addr, 0);
11143 	do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
11144 }
11145 
11146 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
11147 {
11148 	int rctx;
11149 
11150 	preempt_disable_notrace();
11151 	rctx = perf_swevent_get_recursion_context();
11152 	if (unlikely(rctx < 0))
11153 		goto fail;
11154 
11155 	___perf_sw_event(event_id, nr, regs, addr);
11156 
11157 	perf_swevent_put_recursion_context(rctx);
11158 fail:
11159 	preempt_enable_notrace();
11160 }
11161 
11162 static void perf_swevent_read(struct perf_event *event)
11163 {
11164 }
11165 
11166 static int perf_swevent_add(struct perf_event *event, int flags)
11167 {
11168 	struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
11169 	struct hw_perf_event *hwc = &event->hw;
11170 	struct hlist_head *head;
11171 
11172 	if (is_sampling_event(event)) {
11173 		hwc->last_period = hwc->sample_period;
11174 		perf_swevent_set_period(event);
11175 	}
11176 
11177 	hwc->state = !(flags & PERF_EF_START);
11178 
11179 	head = find_swevent_head(swhash, event);
11180 	if (WARN_ON_ONCE(!head))
11181 		return -EINVAL;
11182 
11183 	hlist_add_head_rcu(&event->hlist_entry, head);
11184 	perf_event_update_userpage(event);
11185 
11186 	return 0;
11187 }
11188 
11189 static void perf_swevent_del(struct perf_event *event, int flags)
11190 {
11191 	hlist_del_rcu(&event->hlist_entry);
11192 }
11193 
11194 static void perf_swevent_start(struct perf_event *event, int flags)
11195 {
11196 	event->hw.state = 0;
11197 }
11198 
11199 static void perf_swevent_stop(struct perf_event *event, int flags)
11200 {
11201 	event->hw.state = PERF_HES_STOPPED;
11202 }
11203 
11204 /* Deref the hlist from the update side */
11205 static inline struct swevent_hlist *
11206 swevent_hlist_deref(struct swevent_htable *swhash)
11207 {
11208 	return rcu_dereference_protected(swhash->swevent_hlist,
11209 					 lockdep_is_held(&swhash->hlist_mutex));
11210 }
11211 
11212 static void swevent_hlist_release(struct swevent_htable *swhash)
11213 {
11214 	struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
11215 
11216 	if (!hlist)
11217 		return;
11218 
11219 	RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
11220 	kfree_rcu(hlist, rcu_head);
11221 }
11222 
11223 static void swevent_hlist_put_cpu(int cpu)
11224 {
11225 	struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
11226 
11227 	mutex_lock(&swhash->hlist_mutex);
11228 
11229 	if (!--swhash->hlist_refcount)
11230 		swevent_hlist_release(swhash);
11231 
11232 	mutex_unlock(&swhash->hlist_mutex);
11233 }
11234 
11235 static void swevent_hlist_put(void)
11236 {
11237 	int cpu;
11238 
11239 	for_each_possible_cpu(cpu)
11240 		swevent_hlist_put_cpu(cpu);
11241 }
11242 
11243 static int swevent_hlist_get_cpu(int cpu)
11244 {
11245 	struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
11246 	int err = 0;
11247 
11248 	mutex_lock(&swhash->hlist_mutex);
11249 	if (!swevent_hlist_deref(swhash) &&
11250 	    cpumask_test_cpu(cpu, perf_online_mask)) {
11251 		struct swevent_hlist *hlist;
11252 
11253 		hlist = kzalloc_obj(*hlist);
11254 		if (!hlist) {
11255 			err = -ENOMEM;
11256 			goto exit;
11257 		}
11258 		rcu_assign_pointer(swhash->swevent_hlist, hlist);
11259 	}
11260 	swhash->hlist_refcount++;
11261 exit:
11262 	mutex_unlock(&swhash->hlist_mutex);
11263 
11264 	return err;
11265 }
11266 
11267 static int swevent_hlist_get(void)
11268 {
11269 	int err, cpu, failed_cpu;
11270 
11271 	mutex_lock(&pmus_lock);
11272 	for_each_possible_cpu(cpu) {
11273 		err = swevent_hlist_get_cpu(cpu);
11274 		if (err) {
11275 			failed_cpu = cpu;
11276 			goto fail;
11277 		}
11278 	}
11279 	mutex_unlock(&pmus_lock);
11280 	return 0;
11281 fail:
11282 	for_each_possible_cpu(cpu) {
11283 		if (cpu == failed_cpu)
11284 			break;
11285 		swevent_hlist_put_cpu(cpu);
11286 	}
11287 	mutex_unlock(&pmus_lock);
11288 	return err;
11289 }
11290 
11291 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
11292 
11293 static void sw_perf_event_destroy(struct perf_event *event)
11294 {
11295 	u64 event_id = event->attr.config;
11296 
11297 	WARN_ON(event->parent);
11298 
11299 	static_key_slow_dec(&perf_swevent_enabled[event_id]);
11300 	swevent_hlist_put();
11301 }
11302 
11303 static struct pmu perf_cpu_clock; /* fwd declaration */
11304 static struct pmu perf_task_clock;
11305 
11306 static int perf_swevent_init(struct perf_event *event)
11307 {
11308 	u64 event_id = event->attr.config;
11309 
11310 	if (event->attr.type != PERF_TYPE_SOFTWARE)
11311 		return -ENOENT;
11312 
11313 	/*
11314 	 * no branch sampling for software events
11315 	 */
11316 	if (has_branch_stack(event))
11317 		return -EOPNOTSUPP;
11318 
11319 	switch (event_id) {
11320 	case PERF_COUNT_SW_CPU_CLOCK:
11321 		event->attr.type = perf_cpu_clock.type;
11322 		return -ENOENT;
11323 	case PERF_COUNT_SW_TASK_CLOCK:
11324 		event->attr.type = perf_task_clock.type;
11325 		return -ENOENT;
11326 
11327 	default:
11328 		break;
11329 	}
11330 
11331 	if (event_id >= PERF_COUNT_SW_MAX)
11332 		return -ENOENT;
11333 
11334 	if (!event->parent) {
11335 		int err;
11336 
11337 		err = swevent_hlist_get();
11338 		if (err)
11339 			return err;
11340 
11341 		static_key_slow_inc(&perf_swevent_enabled[event_id]);
11342 		event->destroy = sw_perf_event_destroy;
11343 	}
11344 
11345 	return 0;
11346 }
11347 
11348 static struct pmu perf_swevent = {
11349 	.task_ctx_nr	= perf_sw_context,
11350 
11351 	.capabilities	= PERF_PMU_CAP_NO_NMI,
11352 
11353 	.event_init	= perf_swevent_init,
11354 	.add		= perf_swevent_add,
11355 	.del		= perf_swevent_del,
11356 	.start		= perf_swevent_start,
11357 	.stop		= perf_swevent_stop,
11358 	.read		= perf_swevent_read,
11359 };
11360 
11361 #ifdef CONFIG_EVENT_TRACING
11362 
11363 static void tp_perf_event_destroy(struct perf_event *event)
11364 {
11365 	perf_trace_destroy(event);
11366 }
11367 
11368 static int perf_tp_event_init(struct perf_event *event)
11369 {
11370 	int err;
11371 
11372 	if (event->attr.type != PERF_TYPE_TRACEPOINT)
11373 		return -ENOENT;
11374 
11375 	/*
11376 	 * no branch sampling for tracepoint events
11377 	 */
11378 	if (has_branch_stack(event))
11379 		return -EOPNOTSUPP;
11380 
11381 	err = perf_trace_init(event);
11382 	if (err)
11383 		return err;
11384 
11385 	event->destroy = tp_perf_event_destroy;
11386 
11387 	return 0;
11388 }
11389 
11390 static struct pmu perf_tracepoint = {
11391 	.task_ctx_nr	= perf_sw_context,
11392 
11393 	.event_init	= perf_tp_event_init,
11394 	.add		= perf_trace_add,
11395 	.del		= perf_trace_del,
11396 	.start		= perf_swevent_start,
11397 	.stop		= perf_swevent_stop,
11398 	.read		= perf_swevent_read,
11399 };
11400 
11401 static int perf_tp_filter_match(struct perf_event *event,
11402 				struct perf_raw_record *raw)
11403 {
11404 	void *record = raw->frag.data;
11405 
11406 	/* only top level events have filters set */
11407 	if (event->parent)
11408 		event = event->parent;
11409 
11410 	if (likely(!event->filter) || filter_match_preds(event->filter, record))
11411 		return 1;
11412 	return 0;
11413 }
11414 
11415 static int perf_tp_event_match(struct perf_event *event,
11416 				struct perf_raw_record *raw,
11417 				struct pt_regs *regs)
11418 {
11419 	if (event->hw.state & PERF_HES_STOPPED)
11420 		return 0;
11421 	/*
11422 	 * If exclude_kernel, only trace user-space tracepoints (uprobes)
11423 	 */
11424 	if (event->attr.exclude_kernel && !user_mode(regs))
11425 		return 0;
11426 
11427 	if (!perf_tp_filter_match(event, raw))
11428 		return 0;
11429 
11430 	return 1;
11431 }
11432 
11433 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
11434 			       struct trace_event_call *call, u64 count,
11435 			       struct pt_regs *regs, struct hlist_head *head,
11436 			       struct task_struct *task)
11437 {
11438 	if (bpf_prog_array_valid(call)) {
11439 		*(struct pt_regs **)raw_data = regs;
11440 		if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
11441 			perf_swevent_put_recursion_context(rctx);
11442 			return;
11443 		}
11444 	}
11445 	perf_tp_event(call->event.type, count, raw_data, size, regs, head,
11446 		      rctx, task);
11447 }
11448 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
11449 
11450 static void __perf_tp_event_target_task(u64 count, void *record,
11451 					struct pt_regs *regs,
11452 					struct perf_sample_data *data,
11453 					struct perf_raw_record *raw,
11454 					struct perf_event *event)
11455 {
11456 	struct trace_entry *entry = record;
11457 
11458 	if (event->attr.config != entry->type)
11459 		return;
11460 	/* Cannot deliver synchronous signal to other task. */
11461 	if (event->attr.sigtrap)
11462 		return;
11463 	if (perf_tp_event_match(event, raw, regs)) {
11464 		perf_sample_data_init(data, 0, 0);
11465 		perf_sample_save_raw_data(data, event, raw);
11466 		perf_swevent_event(event, count, data, regs);
11467 	}
11468 }
11469 
11470 static void perf_tp_event_target_task(u64 count, void *record,
11471 				      struct pt_regs *regs,
11472 				      struct perf_sample_data *data,
11473 				      struct perf_raw_record *raw,
11474 				      struct perf_event_context *ctx)
11475 {
11476 	unsigned int cpu = smp_processor_id();
11477 	struct pmu *pmu = &perf_tracepoint;
11478 	struct perf_event *event, *sibling;
11479 
11480 	perf_event_groups_for_cpu_pmu(event, &ctx->pinned_groups, cpu, pmu) {
11481 		__perf_tp_event_target_task(count, record, regs, data, raw, event);
11482 		for_each_sibling_event(sibling, event)
11483 			__perf_tp_event_target_task(count, record, regs, data, raw, sibling);
11484 	}
11485 
11486 	perf_event_groups_for_cpu_pmu(event, &ctx->flexible_groups, cpu, pmu) {
11487 		__perf_tp_event_target_task(count, record, regs, data, raw, event);
11488 		for_each_sibling_event(sibling, event)
11489 			__perf_tp_event_target_task(count, record, regs, data, raw, sibling);
11490 	}
11491 }
11492 
11493 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
11494 		   struct pt_regs *regs, struct hlist_head *head, int rctx,
11495 		   struct task_struct *task)
11496 {
11497 	struct perf_sample_data data;
11498 	struct perf_event *event;
11499 
11500 	/*
11501 	 * Per being a tracepoint, this runs with preemption disabled.
11502 	 */
11503 	lockdep_assert_preemption_disabled();
11504 
11505 	struct perf_raw_record raw = {
11506 		.frag = {
11507 			.size = entry_size,
11508 			.data = record,
11509 		},
11510 	};
11511 
11512 	perf_trace_buf_update(record, event_type);
11513 
11514 	hlist_for_each_entry_rcu(event, head, hlist_entry) {
11515 		if (perf_tp_event_match(event, &raw, regs)) {
11516 			/*
11517 			 * Here use the same on-stack perf_sample_data,
11518 			 * some members in data are event-specific and
11519 			 * need to be re-computed for different sweveents.
11520 			 * Re-initialize data->sample_flags safely to avoid
11521 			 * the problem that next event skips preparing data
11522 			 * because data->sample_flags is set.
11523 			 */
11524 			perf_sample_data_init(&data, 0, 0);
11525 			perf_sample_save_raw_data(&data, event, &raw);
11526 			perf_swevent_event(event, count, &data, regs);
11527 		}
11528 	}
11529 
11530 	/*
11531 	 * If we got specified a target task, also iterate its context and
11532 	 * deliver this event there too.
11533 	 */
11534 	if (task && task != current) {
11535 		struct perf_event_context *ctx;
11536 
11537 		rcu_read_lock();
11538 		ctx = rcu_dereference(task->perf_event_ctxp);
11539 		if (!ctx)
11540 			goto unlock;
11541 
11542 		raw_spin_lock(&ctx->lock);
11543 		perf_tp_event_target_task(count, record, regs, &data, &raw, ctx);
11544 		raw_spin_unlock(&ctx->lock);
11545 unlock:
11546 		rcu_read_unlock();
11547 	}
11548 
11549 	perf_swevent_put_recursion_context(rctx);
11550 }
11551 EXPORT_SYMBOL_GPL(perf_tp_event);
11552 
11553 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
11554 /*
11555  * Flags in config, used by dynamic PMU kprobe and uprobe
11556  * The flags should match following PMU_FORMAT_ATTR().
11557  *
11558  * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
11559  *                               if not set, create kprobe/uprobe
11560  *
11561  * The following values specify a reference counter (or semaphore in the
11562  * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
11563  * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
11564  *
11565  * PERF_UPROBE_REF_CTR_OFFSET_BITS	# of bits in config as th offset
11566  * PERF_UPROBE_REF_CTR_OFFSET_SHIFT	# of bits to shift left
11567  */
11568 enum perf_probe_config {
11569 	PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0,  /* [k,u]retprobe */
11570 	PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
11571 	PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
11572 };
11573 
11574 PMU_FORMAT_ATTR(retprobe, "config:0");
11575 #endif
11576 
11577 #ifdef CONFIG_KPROBE_EVENTS
11578 static struct attribute *kprobe_attrs[] = {
11579 	&format_attr_retprobe.attr,
11580 	NULL,
11581 };
11582 
11583 static struct attribute_group kprobe_format_group = {
11584 	.name = "format",
11585 	.attrs = kprobe_attrs,
11586 };
11587 
11588 static const struct attribute_group *kprobe_attr_groups[] = {
11589 	&kprobe_format_group,
11590 	NULL,
11591 };
11592 
11593 static int perf_kprobe_event_init(struct perf_event *event);
11594 static struct pmu perf_kprobe = {
11595 	.task_ctx_nr	= perf_sw_context,
11596 	.event_init	= perf_kprobe_event_init,
11597 	.add		= perf_trace_add,
11598 	.del		= perf_trace_del,
11599 	.start		= perf_swevent_start,
11600 	.stop		= perf_swevent_stop,
11601 	.read		= perf_swevent_read,
11602 	.attr_groups	= kprobe_attr_groups,
11603 };
11604 
11605 static int perf_kprobe_event_init(struct perf_event *event)
11606 {
11607 	int err;
11608 	bool is_retprobe;
11609 
11610 	if (event->attr.type != perf_kprobe.type)
11611 		return -ENOENT;
11612 
11613 	if (!perfmon_capable())
11614 		return -EACCES;
11615 
11616 	/*
11617 	 * no branch sampling for probe events
11618 	 */
11619 	if (has_branch_stack(event))
11620 		return -EOPNOTSUPP;
11621 
11622 	is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
11623 	err = perf_kprobe_init(event, is_retprobe);
11624 	if (err)
11625 		return err;
11626 
11627 	event->destroy = perf_kprobe_destroy;
11628 
11629 	return 0;
11630 }
11631 #endif /* CONFIG_KPROBE_EVENTS */
11632 
11633 #ifdef CONFIG_UPROBE_EVENTS
11634 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
11635 
11636 static struct attribute *uprobe_attrs[] = {
11637 	&format_attr_retprobe.attr,
11638 	&format_attr_ref_ctr_offset.attr,
11639 	NULL,
11640 };
11641 
11642 static struct attribute_group uprobe_format_group = {
11643 	.name = "format",
11644 	.attrs = uprobe_attrs,
11645 };
11646 
11647 static const struct attribute_group *uprobe_attr_groups[] = {
11648 	&uprobe_format_group,
11649 	NULL,
11650 };
11651 
11652 static int perf_uprobe_event_init(struct perf_event *event);
11653 static struct pmu perf_uprobe = {
11654 	.task_ctx_nr	= perf_sw_context,
11655 	.event_init	= perf_uprobe_event_init,
11656 	.add		= perf_trace_add,
11657 	.del		= perf_trace_del,
11658 	.start		= perf_swevent_start,
11659 	.stop		= perf_swevent_stop,
11660 	.read		= perf_swevent_read,
11661 	.attr_groups	= uprobe_attr_groups,
11662 };
11663 
11664 static int perf_uprobe_event_init(struct perf_event *event)
11665 {
11666 	int err;
11667 	unsigned long ref_ctr_offset;
11668 	bool is_retprobe;
11669 
11670 	if (event->attr.type != perf_uprobe.type)
11671 		return -ENOENT;
11672 
11673 	if (!capable(CAP_SYS_ADMIN))
11674 		return -EACCES;
11675 
11676 	/*
11677 	 * no branch sampling for probe events
11678 	 */
11679 	if (has_branch_stack(event))
11680 		return -EOPNOTSUPP;
11681 
11682 	is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
11683 	ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
11684 	err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
11685 	if (err)
11686 		return err;
11687 
11688 	event->destroy = perf_uprobe_destroy;
11689 
11690 	return 0;
11691 }
11692 #endif /* CONFIG_UPROBE_EVENTS */
11693 
11694 static inline void perf_tp_register(void)
11695 {
11696 	perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
11697 #ifdef CONFIG_KPROBE_EVENTS
11698 	perf_pmu_register(&perf_kprobe, "kprobe", -1);
11699 #endif
11700 #ifdef CONFIG_UPROBE_EVENTS
11701 	perf_pmu_register(&perf_uprobe, "uprobe", -1);
11702 #endif
11703 }
11704 
11705 static void perf_event_free_filter(struct perf_event *event)
11706 {
11707 	ftrace_profile_free_filter(event);
11708 }
11709 
11710 /*
11711  * returns true if the event is a tracepoint, or a kprobe/upprobe created
11712  * with perf_event_open()
11713  */
11714 static inline bool perf_event_is_tracing(struct perf_event *event)
11715 {
11716 	if (event->pmu == &perf_tracepoint)
11717 		return true;
11718 #ifdef CONFIG_KPROBE_EVENTS
11719 	if (event->pmu == &perf_kprobe)
11720 		return true;
11721 #endif
11722 #ifdef CONFIG_UPROBE_EVENTS
11723 	if (event->pmu == &perf_uprobe)
11724 		return true;
11725 #endif
11726 	return false;
11727 }
11728 
11729 static int __perf_event_set_bpf_prog(struct perf_event *event,
11730 				     struct bpf_prog *prog,
11731 				     u64 bpf_cookie)
11732 {
11733 	bool is_kprobe, is_uprobe, is_tracepoint, is_syscall_tp;
11734 
11735 	if (event->state <= PERF_EVENT_STATE_REVOKED)
11736 		return -ENODEV;
11737 
11738 	if (!perf_event_is_tracing(event))
11739 		return perf_event_set_bpf_handler(event, prog, bpf_cookie);
11740 
11741 	is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_KPROBE;
11742 	is_uprobe = event->tp_event->flags & TRACE_EVENT_FL_UPROBE;
11743 	is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
11744 	is_syscall_tp = is_syscall_trace_event(event->tp_event);
11745 	if (!is_kprobe && !is_uprobe && !is_tracepoint && !is_syscall_tp)
11746 		/* bpf programs can only be attached to u/kprobe or tracepoint */
11747 		return -EINVAL;
11748 
11749 	if (((is_kprobe || is_uprobe) && prog->type != BPF_PROG_TYPE_KPROBE) ||
11750 	    (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
11751 	    (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT))
11752 		return -EINVAL;
11753 
11754 	if (prog->type == BPF_PROG_TYPE_KPROBE && prog->sleepable && !is_uprobe)
11755 		/* only uprobe programs are allowed to be sleepable */
11756 		return -EINVAL;
11757 
11758 	if (prog->type == BPF_PROG_TYPE_TRACEPOINT && prog->sleepable) {
11759 		/*
11760 		 * Sleepable tracepoint programs can only attach to faultable
11761 		 * tracepoints. Currently only syscall tracepoints are faultable.
11762 		 */
11763 		if (!is_syscall_tp)
11764 			return -EINVAL;
11765 	}
11766 
11767 	/* Kprobe override only works for kprobes, not uprobes. */
11768 	if (prog->kprobe_override && !is_kprobe)
11769 		return -EINVAL;
11770 
11771 	/* Writing to context allowed only for uprobes. */
11772 	if (prog->aux->kprobe_write_ctx && !is_uprobe)
11773 		return -EINVAL;
11774 
11775 	if (is_tracepoint || is_syscall_tp) {
11776 		int off = trace_event_get_offsets(event->tp_event);
11777 
11778 		if (prog->aux->max_ctx_offset > off)
11779 			return -EACCES;
11780 	}
11781 
11782 	return perf_event_attach_bpf_prog(event, prog, bpf_cookie);
11783 }
11784 
11785 int perf_event_set_bpf_prog(struct perf_event *event,
11786 			    struct bpf_prog *prog,
11787 			    u64 bpf_cookie)
11788 {
11789 	struct perf_event_context *ctx;
11790 	int ret;
11791 
11792 	ctx = perf_event_ctx_lock(event);
11793 	ret = __perf_event_set_bpf_prog(event, prog, bpf_cookie);
11794 	perf_event_ctx_unlock(event, ctx);
11795 
11796 	return ret;
11797 }
11798 
11799 void perf_event_free_bpf_prog(struct perf_event *event)
11800 {
11801 	if (!event->prog)
11802 		return;
11803 
11804 	if (!perf_event_is_tracing(event)) {
11805 		perf_event_free_bpf_handler(event);
11806 		return;
11807 	}
11808 	perf_event_detach_bpf_prog(event);
11809 }
11810 
11811 #else
11812 
11813 static inline void perf_tp_register(void)
11814 {
11815 }
11816 
11817 static void perf_event_free_filter(struct perf_event *event)
11818 {
11819 }
11820 
11821 static int __perf_event_set_bpf_prog(struct perf_event *event,
11822 				     struct bpf_prog *prog,
11823 				     u64 bpf_cookie)
11824 {
11825 	return -ENOENT;
11826 }
11827 
11828 int perf_event_set_bpf_prog(struct perf_event *event,
11829 			    struct bpf_prog *prog,
11830 			    u64 bpf_cookie)
11831 {
11832 	return -ENOENT;
11833 }
11834 
11835 void perf_event_free_bpf_prog(struct perf_event *event)
11836 {
11837 }
11838 #endif /* CONFIG_EVENT_TRACING */
11839 
11840 #ifdef CONFIG_HAVE_HW_BREAKPOINT
11841 void perf_bp_event(struct perf_event *bp, void *data)
11842 {
11843 	struct perf_sample_data sample;
11844 	struct pt_regs *regs = data;
11845 
11846 	/*
11847 	 * Exception context, will have interrupts disabled.
11848 	 */
11849 	lockdep_assert_irqs_disabled();
11850 
11851 	perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
11852 
11853 	if (!bp->hw.state && !perf_exclude_event(bp, regs))
11854 		perf_swevent_event(bp, 1, &sample, regs);
11855 }
11856 #endif
11857 
11858 /*
11859  * Allocate a new address filter
11860  */
11861 static struct perf_addr_filter *
11862 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
11863 {
11864 	int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
11865 	struct perf_addr_filter *filter;
11866 
11867 	filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
11868 	if (!filter)
11869 		return NULL;
11870 
11871 	INIT_LIST_HEAD(&filter->entry);
11872 	list_add_tail(&filter->entry, filters);
11873 
11874 	return filter;
11875 }
11876 
11877 static void free_filters_list(struct list_head *filters)
11878 {
11879 	struct perf_addr_filter *filter, *iter;
11880 
11881 	list_for_each_entry_safe(filter, iter, filters, entry) {
11882 		path_put(&filter->path);
11883 		list_del(&filter->entry);
11884 		kfree(filter);
11885 	}
11886 }
11887 
11888 /*
11889  * Free existing address filters and optionally install new ones
11890  */
11891 static void perf_addr_filters_splice(struct perf_event *event,
11892 				     struct list_head *head)
11893 {
11894 	unsigned long flags;
11895 	LIST_HEAD(list);
11896 
11897 	if (!has_addr_filter(event))
11898 		return;
11899 
11900 	/* don't bother with children, they don't have their own filters */
11901 	if (event->parent)
11902 		return;
11903 
11904 	raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
11905 
11906 	list_splice_init(&event->addr_filters.list, &list);
11907 	if (head)
11908 		list_splice(head, &event->addr_filters.list);
11909 
11910 	raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
11911 
11912 	free_filters_list(&list);
11913 }
11914 
11915 static void perf_free_addr_filters(struct perf_event *event)
11916 {
11917 	/*
11918 	 * Used during free paths, there is no concurrency.
11919 	 */
11920 	if (list_empty(&event->addr_filters.list))
11921 		return;
11922 
11923 	perf_addr_filters_splice(event, NULL);
11924 }
11925 
11926 /*
11927  * Scan through mm's vmas and see if one of them matches the
11928  * @filter; if so, adjust filter's address range.
11929  * Called with mm::mmap_lock down for reading.
11930  */
11931 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
11932 				   struct mm_struct *mm,
11933 				   struct perf_addr_filter_range *fr)
11934 {
11935 	struct vm_area_struct *vma;
11936 	VMA_ITERATOR(vmi, mm, 0);
11937 
11938 	for_each_vma(vmi, vma) {
11939 		if (!vma->vm_file)
11940 			continue;
11941 
11942 		if (perf_addr_filter_vma_adjust(filter, vma, fr))
11943 			return;
11944 	}
11945 }
11946 
11947 /*
11948  * Update event's address range filters based on the
11949  * task's existing mappings, if any.
11950  */
11951 static void perf_event_addr_filters_apply(struct perf_event *event)
11952 {
11953 	struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11954 	struct task_struct *task = READ_ONCE(event->ctx->task);
11955 	struct perf_addr_filter *filter;
11956 	struct mm_struct *mm = NULL;
11957 	unsigned int count = 0;
11958 	unsigned long flags;
11959 
11960 	/*
11961 	 * We may observe TASK_TOMBSTONE, which means that the event tear-down
11962 	 * will stop on the parent's child_mutex that our caller is also holding
11963 	 */
11964 	if (task == TASK_TOMBSTONE)
11965 		return;
11966 
11967 	if (ifh->nr_file_filters) {
11968 		mm = get_task_mm(task);
11969 		if (!mm)
11970 			goto restart;
11971 
11972 		mmap_read_lock(mm);
11973 	}
11974 
11975 	raw_spin_lock_irqsave(&ifh->lock, flags);
11976 	list_for_each_entry(filter, &ifh->list, entry) {
11977 		if (filter->path.dentry) {
11978 			/*
11979 			 * Adjust base offset if the filter is associated to a
11980 			 * binary that needs to be mapped:
11981 			 */
11982 			event->addr_filter_ranges[count].start = 0;
11983 			event->addr_filter_ranges[count].size = 0;
11984 
11985 			perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
11986 		} else {
11987 			event->addr_filter_ranges[count].start = filter->offset;
11988 			event->addr_filter_ranges[count].size  = filter->size;
11989 		}
11990 
11991 		count++;
11992 	}
11993 
11994 	event->addr_filters_gen++;
11995 	raw_spin_unlock_irqrestore(&ifh->lock, flags);
11996 
11997 	if (ifh->nr_file_filters) {
11998 		mmap_read_unlock(mm);
11999 
12000 		mmput(mm);
12001 	}
12002 
12003 restart:
12004 	perf_event_stop(event, 1);
12005 }
12006 
12007 /*
12008  * Address range filtering: limiting the data to certain
12009  * instruction address ranges. Filters are ioctl()ed to us from
12010  * userspace as ascii strings.
12011  *
12012  * Filter string format:
12013  *
12014  * ACTION RANGE_SPEC
12015  * where ACTION is one of the
12016  *  * "filter": limit the trace to this region
12017  *  * "start": start tracing from this address
12018  *  * "stop": stop tracing at this address/region;
12019  * RANGE_SPEC is
12020  *  * for kernel addresses: <start address>[/<size>]
12021  *  * for object files:     <start address>[/<size>]@</path/to/object/file>
12022  *
12023  * if <size> is not specified or is zero, the range is treated as a single
12024  * address; not valid for ACTION=="filter".
12025  */
12026 enum {
12027 	IF_ACT_NONE = -1,
12028 	IF_ACT_FILTER,
12029 	IF_ACT_START,
12030 	IF_ACT_STOP,
12031 	IF_SRC_FILE,
12032 	IF_SRC_KERNEL,
12033 	IF_SRC_FILEADDR,
12034 	IF_SRC_KERNELADDR,
12035 };
12036 
12037 enum {
12038 	IF_STATE_ACTION = 0,
12039 	IF_STATE_SOURCE,
12040 	IF_STATE_END,
12041 };
12042 
12043 static const match_table_t if_tokens = {
12044 	{ IF_ACT_FILTER,	"filter" },
12045 	{ IF_ACT_START,		"start" },
12046 	{ IF_ACT_STOP,		"stop" },
12047 	{ IF_SRC_FILE,		"%u/%u@%s" },
12048 	{ IF_SRC_KERNEL,	"%u/%u" },
12049 	{ IF_SRC_FILEADDR,	"%u@%s" },
12050 	{ IF_SRC_KERNELADDR,	"%u" },
12051 	{ IF_ACT_NONE,		NULL },
12052 };
12053 
12054 /*
12055  * Address filter string parser
12056  */
12057 static int
12058 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
12059 			     struct list_head *filters)
12060 {
12061 	struct perf_addr_filter *filter = NULL;
12062 	char *start, *orig, *filename = NULL;
12063 	substring_t args[MAX_OPT_ARGS];
12064 	int state = IF_STATE_ACTION, token;
12065 	unsigned int kernel = 0;
12066 	int ret = -EINVAL;
12067 
12068 	orig = fstr = kstrdup(fstr, GFP_KERNEL);
12069 	if (!fstr)
12070 		return -ENOMEM;
12071 
12072 	while ((start = strsep(&fstr, " ,\n")) != NULL) {
12073 		static const enum perf_addr_filter_action_t actions[] = {
12074 			[IF_ACT_FILTER]	= PERF_ADDR_FILTER_ACTION_FILTER,
12075 			[IF_ACT_START]	= PERF_ADDR_FILTER_ACTION_START,
12076 			[IF_ACT_STOP]	= PERF_ADDR_FILTER_ACTION_STOP,
12077 		};
12078 		ret = -EINVAL;
12079 
12080 		if (!*start)
12081 			continue;
12082 
12083 		/* filter definition begins */
12084 		if (state == IF_STATE_ACTION) {
12085 			filter = perf_addr_filter_new(event, filters);
12086 			if (!filter)
12087 				goto fail;
12088 		}
12089 
12090 		token = match_token(start, if_tokens, args);
12091 		switch (token) {
12092 		case IF_ACT_FILTER:
12093 		case IF_ACT_START:
12094 		case IF_ACT_STOP:
12095 			if (state != IF_STATE_ACTION)
12096 				goto fail;
12097 
12098 			filter->action = actions[token];
12099 			state = IF_STATE_SOURCE;
12100 			break;
12101 
12102 		case IF_SRC_KERNELADDR:
12103 		case IF_SRC_KERNEL:
12104 			kernel = 1;
12105 			fallthrough;
12106 
12107 		case IF_SRC_FILEADDR:
12108 		case IF_SRC_FILE:
12109 			if (state != IF_STATE_SOURCE)
12110 				goto fail;
12111 
12112 			*args[0].to = 0;
12113 			ret = kstrtoul(args[0].from, 0, &filter->offset);
12114 			if (ret)
12115 				goto fail;
12116 
12117 			if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
12118 				*args[1].to = 0;
12119 				ret = kstrtoul(args[1].from, 0, &filter->size);
12120 				if (ret)
12121 					goto fail;
12122 			}
12123 
12124 			if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
12125 				int fpos = token == IF_SRC_FILE ? 2 : 1;
12126 
12127 				kfree(filename);
12128 				filename = match_strdup(&args[fpos]);
12129 				if (!filename) {
12130 					ret = -ENOMEM;
12131 					goto fail;
12132 				}
12133 			}
12134 
12135 			state = IF_STATE_END;
12136 			break;
12137 
12138 		default:
12139 			goto fail;
12140 		}
12141 
12142 		/*
12143 		 * Filter definition is fully parsed, validate and install it.
12144 		 * Make sure that it doesn't contradict itself or the event's
12145 		 * attribute.
12146 		 */
12147 		if (state == IF_STATE_END) {
12148 			ret = -EINVAL;
12149 
12150 			/*
12151 			 * ACTION "filter" must have a non-zero length region
12152 			 * specified.
12153 			 */
12154 			if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
12155 			    !filter->size)
12156 				goto fail;
12157 
12158 			if (!kernel) {
12159 				if (!filename)
12160 					goto fail;
12161 
12162 				/*
12163 				 * For now, we only support file-based filters
12164 				 * in per-task events; doing so for CPU-wide
12165 				 * events requires additional context switching
12166 				 * trickery, since same object code will be
12167 				 * mapped at different virtual addresses in
12168 				 * different processes.
12169 				 */
12170 				ret = -EOPNOTSUPP;
12171 				if (!event->ctx->task)
12172 					goto fail;
12173 
12174 				/* look up the path and grab its inode */
12175 				ret = kern_path(filename, LOOKUP_FOLLOW,
12176 						&filter->path);
12177 				if (ret)
12178 					goto fail;
12179 
12180 				ret = -EINVAL;
12181 				if (!filter->path.dentry ||
12182 				    !S_ISREG(d_inode(filter->path.dentry)
12183 					     ->i_mode))
12184 					goto fail;
12185 
12186 				event->addr_filters.nr_file_filters++;
12187 			}
12188 
12189 			/* ready to consume more filters */
12190 			kfree(filename);
12191 			filename = NULL;
12192 			state = IF_STATE_ACTION;
12193 			filter = NULL;
12194 			kernel = 0;
12195 		}
12196 	}
12197 
12198 	if (state != IF_STATE_ACTION)
12199 		goto fail;
12200 
12201 	kfree(filename);
12202 	kfree(orig);
12203 
12204 	return 0;
12205 
12206 fail:
12207 	kfree(filename);
12208 	free_filters_list(filters);
12209 	kfree(orig);
12210 
12211 	return ret;
12212 }
12213 
12214 static int
12215 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
12216 {
12217 	LIST_HEAD(filters);
12218 	int ret;
12219 
12220 	/*
12221 	 * Since this is called in perf_ioctl() path, we're already holding
12222 	 * ctx::mutex.
12223 	 */
12224 	lockdep_assert_held(&event->ctx->mutex);
12225 
12226 	if (WARN_ON_ONCE(event->parent))
12227 		return -EINVAL;
12228 
12229 	ret = perf_event_parse_addr_filter(event, filter_str, &filters);
12230 	if (ret)
12231 		goto fail_clear_files;
12232 
12233 	ret = event->pmu->addr_filters_validate(&filters);
12234 	if (ret)
12235 		goto fail_free_filters;
12236 
12237 	/* remove existing filters, if any */
12238 	perf_addr_filters_splice(event, &filters);
12239 
12240 	/* install new filters */
12241 	perf_event_for_each_child(event, perf_event_addr_filters_apply);
12242 
12243 	return ret;
12244 
12245 fail_free_filters:
12246 	free_filters_list(&filters);
12247 
12248 fail_clear_files:
12249 	event->addr_filters.nr_file_filters = 0;
12250 
12251 	return ret;
12252 }
12253 
12254 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
12255 {
12256 	int ret = -EINVAL;
12257 	char *filter_str;
12258 
12259 	filter_str = strndup_user(arg, PAGE_SIZE);
12260 	if (IS_ERR(filter_str))
12261 		return PTR_ERR(filter_str);
12262 
12263 #ifdef CONFIG_EVENT_TRACING
12264 	if (perf_event_is_tracing(event)) {
12265 		struct perf_event_context *ctx = event->ctx;
12266 
12267 		/*
12268 		 * Beware, here be dragons!!
12269 		 *
12270 		 * the tracepoint muck will deadlock against ctx->mutex, but
12271 		 * the tracepoint stuff does not actually need it. So
12272 		 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
12273 		 * already have a reference on ctx.
12274 		 *
12275 		 * This can result in event getting moved to a different ctx,
12276 		 * but that does not affect the tracepoint state.
12277 		 */
12278 		mutex_unlock(&ctx->mutex);
12279 		ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
12280 		mutex_lock(&ctx->mutex);
12281 	} else
12282 #endif
12283 	if (has_addr_filter(event))
12284 		ret = perf_event_set_addr_filter(event, filter_str);
12285 
12286 	kfree(filter_str);
12287 	return ret;
12288 }
12289 
12290 /*
12291  * hrtimer based swevent callback
12292  */
12293 
12294 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
12295 {
12296 	enum hrtimer_restart ret = HRTIMER_RESTART;
12297 	struct perf_sample_data data;
12298 	struct pt_regs *regs;
12299 	struct perf_event *event;
12300 	u64 period;
12301 
12302 	event = container_of(hrtimer, struct perf_event, hw.hrtimer);
12303 
12304 	if (event->state != PERF_EVENT_STATE_ACTIVE ||
12305 	    event->hw.state & PERF_HES_STOPPED)
12306 		return HRTIMER_NORESTART;
12307 
12308 	event->pmu->read(event);
12309 
12310 	perf_sample_data_init(&data, 0, event->hw.last_period);
12311 	regs = get_irq_regs();
12312 
12313 	if (regs && !perf_exclude_event(event, regs)) {
12314 		if (!(event->attr.exclude_idle && is_idle_task(current)))
12315 			if (perf_event_overflow(event, &data, regs))
12316 				ret = HRTIMER_NORESTART;
12317 	}
12318 
12319 	period = max_t(u64, 10000, event->hw.sample_period);
12320 	hrtimer_forward_now(hrtimer, ns_to_ktime(period));
12321 
12322 	return ret;
12323 }
12324 
12325 static void perf_swevent_start_hrtimer(struct perf_event *event)
12326 {
12327 	struct hw_perf_event *hwc = &event->hw;
12328 	s64 period;
12329 
12330 	if (!is_sampling_event(event))
12331 		return;
12332 
12333 	period = local64_read(&hwc->period_left);
12334 	if (period) {
12335 		if (period < 0)
12336 			period = 10000;
12337 
12338 		local64_set(&hwc->period_left, 0);
12339 	} else {
12340 		period = max_t(u64, 10000, hwc->sample_period);
12341 	}
12342 	hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
12343 		      HRTIMER_MODE_REL_PINNED_HARD);
12344 }
12345 
12346 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
12347 {
12348 	struct hw_perf_event *hwc = &event->hw;
12349 
12350 	/*
12351 	 * Careful: this function can be triggered in the hrtimer handler,
12352 	 * for cpu-clock events, so hrtimer_cancel() would cause a
12353 	 * deadlock.
12354 	 *
12355 	 * So use hrtimer_try_to_cancel() to try to stop the hrtimer,
12356 	 * and the cpu-clock handler also sets the PERF_HES_STOPPED flag,
12357 	 * which guarantees that perf_swevent_hrtimer() will stop the
12358 	 * hrtimer once it sees the PERF_HES_STOPPED flag.
12359 	 */
12360 	if (is_sampling_event(event) && (hwc->interrupts != MAX_INTERRUPTS)) {
12361 		ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
12362 		local64_set(&hwc->period_left, ktime_to_ns(remaining));
12363 
12364 		hrtimer_try_to_cancel(&hwc->hrtimer);
12365 	}
12366 }
12367 
12368 static void perf_swevent_destroy_hrtimer(struct perf_event *event)
12369 {
12370 	hrtimer_cancel(&event->hw.hrtimer);
12371 }
12372 
12373 static void perf_swevent_init_hrtimer(struct perf_event *event)
12374 {
12375 	struct hw_perf_event *hwc = &event->hw;
12376 
12377 	if (!is_sampling_event(event))
12378 		return;
12379 
12380 	hrtimer_setup(&hwc->hrtimer, perf_swevent_hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
12381 	event->destroy = perf_swevent_destroy_hrtimer;
12382 
12383 	/*
12384 	 * Since hrtimers have a fixed rate, we can do a static freq->period
12385 	 * mapping and avoid the whole period adjust feedback stuff.
12386 	 */
12387 	if (event->attr.freq) {
12388 		long freq = event->attr.sample_freq;
12389 
12390 		event->attr.sample_period = NSEC_PER_SEC / freq;
12391 		hwc->sample_period = event->attr.sample_period;
12392 		local64_set(&hwc->period_left, hwc->sample_period);
12393 		hwc->last_period = hwc->sample_period;
12394 		event->attr.freq = 0;
12395 	}
12396 }
12397 
12398 /*
12399  * Software event: cpu wall time clock
12400  */
12401 
12402 static void cpu_clock_event_update(struct perf_event *event)
12403 {
12404 	s64 prev;
12405 	u64 now;
12406 
12407 	now = local_clock();
12408 	prev = local64_xchg(&event->hw.prev_count, now);
12409 	local64_add(now - prev, &event->count);
12410 }
12411 
12412 static void cpu_clock_event_start(struct perf_event *event, int flags)
12413 {
12414 	event->hw.state = 0;
12415 	local64_set(&event->hw.prev_count, local_clock());
12416 	perf_swevent_start_hrtimer(event);
12417 }
12418 
12419 static void cpu_clock_event_stop(struct perf_event *event, int flags)
12420 {
12421 	event->hw.state = PERF_HES_STOPPED;
12422 	perf_swevent_cancel_hrtimer(event);
12423 	if (flags & PERF_EF_UPDATE)
12424 		cpu_clock_event_update(event);
12425 }
12426 
12427 static int cpu_clock_event_add(struct perf_event *event, int flags)
12428 {
12429 	if (flags & PERF_EF_START)
12430 		cpu_clock_event_start(event, flags);
12431 	perf_event_update_userpage(event);
12432 
12433 	return 0;
12434 }
12435 
12436 static void cpu_clock_event_del(struct perf_event *event, int flags)
12437 {
12438 	cpu_clock_event_stop(event, PERF_EF_UPDATE);
12439 }
12440 
12441 static void cpu_clock_event_read(struct perf_event *event)
12442 {
12443 	cpu_clock_event_update(event);
12444 }
12445 
12446 static int cpu_clock_event_init(struct perf_event *event)
12447 {
12448 	if (event->attr.type != perf_cpu_clock.type)
12449 		return -ENOENT;
12450 
12451 	if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
12452 		return -ENOENT;
12453 
12454 	/*
12455 	 * no branch sampling for software events
12456 	 */
12457 	if (has_branch_stack(event))
12458 		return -EOPNOTSUPP;
12459 
12460 	perf_swevent_init_hrtimer(event);
12461 
12462 	return 0;
12463 }
12464 
12465 static struct pmu perf_cpu_clock = {
12466 	.task_ctx_nr	= perf_sw_context,
12467 
12468 	.capabilities	= PERF_PMU_CAP_NO_NMI,
12469 	.dev		= PMU_NULL_DEV,
12470 
12471 	.event_init	= cpu_clock_event_init,
12472 	.add		= cpu_clock_event_add,
12473 	.del		= cpu_clock_event_del,
12474 	.start		= cpu_clock_event_start,
12475 	.stop		= cpu_clock_event_stop,
12476 	.read		= cpu_clock_event_read,
12477 };
12478 
12479 /*
12480  * Software event: task time clock
12481  */
12482 
12483 static void task_clock_event_update(struct perf_event *event, u64 now)
12484 {
12485 	u64 prev;
12486 	s64 delta;
12487 
12488 	prev = local64_xchg(&event->hw.prev_count, now);
12489 	delta = now - prev;
12490 	local64_add(delta, &event->count);
12491 }
12492 
12493 static void task_clock_event_start(struct perf_event *event, int flags)
12494 {
12495 	event->hw.state = 0;
12496 	local64_set(&event->hw.prev_count, event->ctx->time.time);
12497 	perf_swevent_start_hrtimer(event);
12498 }
12499 
12500 static void task_clock_event_stop(struct perf_event *event, int flags)
12501 {
12502 	event->hw.state = PERF_HES_STOPPED;
12503 	perf_swevent_cancel_hrtimer(event);
12504 	if (flags & PERF_EF_UPDATE)
12505 		task_clock_event_update(event, event->ctx->time.time);
12506 }
12507 
12508 static int task_clock_event_add(struct perf_event *event, int flags)
12509 {
12510 	if (flags & PERF_EF_START)
12511 		task_clock_event_start(event, flags);
12512 	perf_event_update_userpage(event);
12513 
12514 	return 0;
12515 }
12516 
12517 static void task_clock_event_del(struct perf_event *event, int flags)
12518 {
12519 	task_clock_event_stop(event, PERF_EF_UPDATE);
12520 }
12521 
12522 static void task_clock_event_read(struct perf_event *event)
12523 {
12524 	u64 now = perf_clock();
12525 	u64 delta = now - event->ctx->time.stamp;
12526 	u64 time = event->ctx->time.time + delta;
12527 
12528 	task_clock_event_update(event, time);
12529 }
12530 
12531 static int task_clock_event_init(struct perf_event *event)
12532 {
12533 	if (event->attr.type != perf_task_clock.type)
12534 		return -ENOENT;
12535 
12536 	if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
12537 		return -ENOENT;
12538 
12539 	/*
12540 	 * no branch sampling for software events
12541 	 */
12542 	if (has_branch_stack(event))
12543 		return -EOPNOTSUPP;
12544 
12545 	perf_swevent_init_hrtimer(event);
12546 
12547 	return 0;
12548 }
12549 
12550 static struct pmu perf_task_clock = {
12551 	.task_ctx_nr	= perf_sw_context,
12552 
12553 	.capabilities	= PERF_PMU_CAP_NO_NMI,
12554 	.dev		= PMU_NULL_DEV,
12555 
12556 	.event_init	= task_clock_event_init,
12557 	.add		= task_clock_event_add,
12558 	.del		= task_clock_event_del,
12559 	.start		= task_clock_event_start,
12560 	.stop		= task_clock_event_stop,
12561 	.read		= task_clock_event_read,
12562 };
12563 
12564 static void perf_pmu_nop_void(struct pmu *pmu)
12565 {
12566 }
12567 
12568 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
12569 {
12570 }
12571 
12572 static int perf_pmu_nop_int(struct pmu *pmu)
12573 {
12574 	return 0;
12575 }
12576 
12577 static int perf_event_nop_int(struct perf_event *event, u64 value)
12578 {
12579 	return 0;
12580 }
12581 
12582 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
12583 
12584 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
12585 {
12586 	__this_cpu_write(nop_txn_flags, flags);
12587 
12588 	if (flags & ~PERF_PMU_TXN_ADD)
12589 		return;
12590 
12591 	perf_pmu_disable(pmu);
12592 }
12593 
12594 static int perf_pmu_commit_txn(struct pmu *pmu)
12595 {
12596 	unsigned int flags = __this_cpu_read(nop_txn_flags);
12597 
12598 	__this_cpu_write(nop_txn_flags, 0);
12599 
12600 	if (flags & ~PERF_PMU_TXN_ADD)
12601 		return 0;
12602 
12603 	perf_pmu_enable(pmu);
12604 	return 0;
12605 }
12606 
12607 static void perf_pmu_cancel_txn(struct pmu *pmu)
12608 {
12609 	unsigned int flags =  __this_cpu_read(nop_txn_flags);
12610 
12611 	__this_cpu_write(nop_txn_flags, 0);
12612 
12613 	if (flags & ~PERF_PMU_TXN_ADD)
12614 		return;
12615 
12616 	perf_pmu_enable(pmu);
12617 }
12618 
12619 static int perf_event_idx_default(struct perf_event *event)
12620 {
12621 	return 0;
12622 }
12623 
12624 /*
12625  * Let userspace know that this PMU supports address range filtering:
12626  */
12627 static ssize_t nr_addr_filters_show(struct device *dev,
12628 				    struct device_attribute *attr,
12629 				    char *page)
12630 {
12631 	struct pmu *pmu = dev_get_drvdata(dev);
12632 
12633 	return sysfs_emit(page, "%d\n", pmu->nr_addr_filters);
12634 }
12635 DEVICE_ATTR_RO(nr_addr_filters);
12636 
12637 static struct idr pmu_idr;
12638 
12639 static ssize_t
12640 type_show(struct device *dev, struct device_attribute *attr, char *page)
12641 {
12642 	struct pmu *pmu = dev_get_drvdata(dev);
12643 
12644 	return sysfs_emit(page, "%d\n", pmu->type);
12645 }
12646 static DEVICE_ATTR_RO(type);
12647 
12648 static ssize_t
12649 perf_event_mux_interval_ms_show(struct device *dev,
12650 				struct device_attribute *attr,
12651 				char *page)
12652 {
12653 	struct pmu *pmu = dev_get_drvdata(dev);
12654 
12655 	return sysfs_emit(page, "%d\n", pmu->hrtimer_interval_ms);
12656 }
12657 
12658 static DEFINE_MUTEX(mux_interval_mutex);
12659 
12660 static ssize_t
12661 perf_event_mux_interval_ms_store(struct device *dev,
12662 				 struct device_attribute *attr,
12663 				 const char *buf, size_t count)
12664 {
12665 	struct pmu *pmu = dev_get_drvdata(dev);
12666 	int timer, cpu, ret;
12667 
12668 	ret = kstrtoint(buf, 0, &timer);
12669 	if (ret)
12670 		return ret;
12671 
12672 	if (timer < 1)
12673 		return -EINVAL;
12674 
12675 	/* same value, noting to do */
12676 	if (timer == pmu->hrtimer_interval_ms)
12677 		return count;
12678 
12679 	mutex_lock(&mux_interval_mutex);
12680 	pmu->hrtimer_interval_ms = timer;
12681 
12682 	/* update all cpuctx for this PMU */
12683 	cpus_read_lock();
12684 	for_each_online_cpu(cpu) {
12685 		struct perf_cpu_pmu_context *cpc;
12686 		cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu);
12687 		cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
12688 
12689 		cpu_function_call(cpu, perf_mux_hrtimer_restart_ipi, cpc);
12690 	}
12691 	cpus_read_unlock();
12692 	mutex_unlock(&mux_interval_mutex);
12693 
12694 	return count;
12695 }
12696 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
12697 
12698 static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu)
12699 {
12700 	switch (scope) {
12701 	case PERF_PMU_SCOPE_CORE:
12702 		return topology_sibling_cpumask(cpu);
12703 	case PERF_PMU_SCOPE_DIE:
12704 		return topology_die_cpumask(cpu);
12705 	case PERF_PMU_SCOPE_CLUSTER:
12706 		return topology_cluster_cpumask(cpu);
12707 	case PERF_PMU_SCOPE_PKG:
12708 		return topology_core_cpumask(cpu);
12709 	case PERF_PMU_SCOPE_SYS_WIDE:
12710 		return cpu_online_mask;
12711 	}
12712 
12713 	return NULL;
12714 }
12715 
12716 static inline struct cpumask *perf_scope_cpumask(unsigned int scope)
12717 {
12718 	switch (scope) {
12719 	case PERF_PMU_SCOPE_CORE:
12720 		return perf_online_core_mask;
12721 	case PERF_PMU_SCOPE_DIE:
12722 		return perf_online_die_mask;
12723 	case PERF_PMU_SCOPE_CLUSTER:
12724 		return perf_online_cluster_mask;
12725 	case PERF_PMU_SCOPE_PKG:
12726 		return perf_online_pkg_mask;
12727 	case PERF_PMU_SCOPE_SYS_WIDE:
12728 		return perf_online_sys_mask;
12729 	}
12730 
12731 	return NULL;
12732 }
12733 
12734 static ssize_t cpumask_show(struct device *dev, struct device_attribute *attr,
12735 			    char *buf)
12736 {
12737 	struct pmu *pmu = dev_get_drvdata(dev);
12738 	struct cpumask *mask = perf_scope_cpumask(pmu->scope);
12739 
12740 	if (mask)
12741 		return sysfs_emit(buf, "%*pbl\n", cpumask_pr_args(mask));
12742 	return 0;
12743 }
12744 
12745 static DEVICE_ATTR_RO(cpumask);
12746 
12747 static struct attribute *pmu_dev_attrs[] = {
12748 	&dev_attr_type.attr,
12749 	&dev_attr_perf_event_mux_interval_ms.attr,
12750 	&dev_attr_nr_addr_filters.attr,
12751 	&dev_attr_cpumask.attr,
12752 	NULL,
12753 };
12754 
12755 static umode_t pmu_dev_is_visible(struct kobject *kobj, struct attribute *a, int n)
12756 {
12757 	struct device *dev = kobj_to_dev(kobj);
12758 	struct pmu *pmu = dev_get_drvdata(dev);
12759 
12760 	if (n == 2 && !pmu->nr_addr_filters)
12761 		return 0;
12762 
12763 	/* cpumask */
12764 	if (n == 3 && pmu->scope == PERF_PMU_SCOPE_NONE)
12765 		return 0;
12766 
12767 	return a->mode;
12768 }
12769 
12770 static struct attribute_group pmu_dev_attr_group = {
12771 	.is_visible = pmu_dev_is_visible,
12772 	.attrs = pmu_dev_attrs,
12773 };
12774 
12775 static const struct attribute_group *pmu_dev_groups[] = {
12776 	&pmu_dev_attr_group,
12777 	NULL,
12778 };
12779 
12780 static int pmu_bus_running;
12781 static const struct bus_type pmu_bus = {
12782 	.name		= "event_source",
12783 	.dev_groups	= pmu_dev_groups,
12784 };
12785 
12786 static void pmu_dev_release(struct device *dev)
12787 {
12788 	kfree(dev);
12789 }
12790 
12791 static int pmu_dev_alloc(struct pmu *pmu)
12792 {
12793 	int ret = -ENOMEM;
12794 
12795 	pmu->dev = kzalloc_obj(struct device);
12796 	if (!pmu->dev)
12797 		goto out;
12798 
12799 	pmu->dev->groups = pmu->attr_groups;
12800 	device_initialize(pmu->dev);
12801 
12802 	dev_set_drvdata(pmu->dev, pmu);
12803 	pmu->dev->bus = &pmu_bus;
12804 	pmu->dev->parent = pmu->parent;
12805 	pmu->dev->release = pmu_dev_release;
12806 
12807 	ret = dev_set_name(pmu->dev, "%s", pmu->name);
12808 	if (ret)
12809 		goto free_dev;
12810 
12811 	ret = device_add(pmu->dev);
12812 	if (ret)
12813 		goto free_dev;
12814 
12815 	if (pmu->attr_update) {
12816 		ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
12817 		if (ret)
12818 			goto del_dev;
12819 	}
12820 
12821 out:
12822 	return ret;
12823 
12824 del_dev:
12825 	device_del(pmu->dev);
12826 
12827 free_dev:
12828 	put_device(pmu->dev);
12829 	pmu->dev = NULL;
12830 	goto out;
12831 }
12832 
12833 static struct lock_class_key cpuctx_mutex;
12834 static struct lock_class_key cpuctx_lock;
12835 
12836 static bool idr_cmpxchg(struct idr *idr, unsigned long id, void *old, void *new)
12837 {
12838 	void *tmp, *val = idr_find(idr, id);
12839 
12840 	if (val != old)
12841 		return false;
12842 
12843 	tmp = idr_replace(idr, new, id);
12844 	if (IS_ERR(tmp))
12845 		return false;
12846 
12847 	WARN_ON_ONCE(tmp != val);
12848 	return true;
12849 }
12850 
12851 static void perf_pmu_free(struct pmu *pmu)
12852 {
12853 	if (pmu_bus_running && pmu->dev && pmu->dev != PMU_NULL_DEV) {
12854 		if (pmu->nr_addr_filters)
12855 			device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
12856 		device_del(pmu->dev);
12857 		put_device(pmu->dev);
12858 	}
12859 
12860 	if (pmu->cpu_pmu_context) {
12861 		int cpu;
12862 
12863 		for_each_possible_cpu(cpu) {
12864 			struct perf_cpu_pmu_context *cpc;
12865 
12866 			cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu);
12867 			if (!cpc)
12868 				continue;
12869 			if (cpc->epc.embedded) {
12870 				/* refcount managed */
12871 				put_pmu_ctx(&cpc->epc);
12872 				continue;
12873 			}
12874 			kfree(cpc);
12875 		}
12876 		free_percpu(pmu->cpu_pmu_context);
12877 	}
12878 }
12879 
12880 DEFINE_FREE(pmu_unregister, struct pmu *, if (_T) perf_pmu_free(_T))
12881 
12882 int perf_pmu_register(struct pmu *_pmu, const char *name, int type)
12883 {
12884 	int cpu, max = PERF_TYPE_MAX;
12885 
12886 	struct pmu *pmu __free(pmu_unregister) = _pmu;
12887 	guard(mutex)(&pmus_lock);
12888 
12889 	if (WARN_ONCE(!name, "Can not register anonymous pmu.\n"))
12890 		return -EINVAL;
12891 
12892 	if (WARN_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE,
12893 		      "Can not register a pmu with an invalid scope.\n"))
12894 		return -EINVAL;
12895 
12896 	pmu->name = name;
12897 
12898 	if (type >= 0)
12899 		max = type;
12900 
12901 	CLASS(idr_alloc, pmu_type)(&pmu_idr, NULL, max, 0, GFP_KERNEL);
12902 	if (pmu_type.id < 0)
12903 		return pmu_type.id;
12904 
12905 	WARN_ON(type >= 0 && pmu_type.id != type);
12906 
12907 	pmu->type = pmu_type.id;
12908 	atomic_set(&pmu->exclusive_cnt, 0);
12909 
12910 	if (pmu_bus_running && !pmu->dev) {
12911 		int ret = pmu_dev_alloc(pmu);
12912 		if (ret)
12913 			return ret;
12914 	}
12915 
12916 	pmu->cpu_pmu_context = alloc_percpu(struct perf_cpu_pmu_context *);
12917 	if (!pmu->cpu_pmu_context)
12918 		return -ENOMEM;
12919 
12920 	for_each_possible_cpu(cpu) {
12921 		struct perf_cpu_pmu_context *cpc =
12922 			kmalloc_node(sizeof(struct perf_cpu_pmu_context),
12923 				     GFP_KERNEL | __GFP_ZERO,
12924 				     cpu_to_node(cpu));
12925 
12926 		if (!cpc)
12927 			return -ENOMEM;
12928 
12929 		*per_cpu_ptr(pmu->cpu_pmu_context, cpu) = cpc;
12930 		__perf_init_event_pmu_context(&cpc->epc, pmu);
12931 		__perf_mux_hrtimer_init(cpc, cpu);
12932 	}
12933 
12934 	if (!pmu->start_txn) {
12935 		if (pmu->pmu_enable) {
12936 			/*
12937 			 * If we have pmu_enable/pmu_disable calls, install
12938 			 * transaction stubs that use that to try and batch
12939 			 * hardware accesses.
12940 			 */
12941 			pmu->start_txn  = perf_pmu_start_txn;
12942 			pmu->commit_txn = perf_pmu_commit_txn;
12943 			pmu->cancel_txn = perf_pmu_cancel_txn;
12944 		} else {
12945 			pmu->start_txn  = perf_pmu_nop_txn;
12946 			pmu->commit_txn = perf_pmu_nop_int;
12947 			pmu->cancel_txn = perf_pmu_nop_void;
12948 		}
12949 	}
12950 
12951 	if (!pmu->pmu_enable) {
12952 		pmu->pmu_enable  = perf_pmu_nop_void;
12953 		pmu->pmu_disable = perf_pmu_nop_void;
12954 	}
12955 
12956 	if (!pmu->check_period)
12957 		pmu->check_period = perf_event_nop_int;
12958 
12959 	if (!pmu->event_idx)
12960 		pmu->event_idx = perf_event_idx_default;
12961 
12962 	INIT_LIST_HEAD(&pmu->events);
12963 	spin_lock_init(&pmu->events_lock);
12964 
12965 	/*
12966 	 * Now that the PMU is complete, make it visible to perf_try_init_event().
12967 	 */
12968 	if (!idr_cmpxchg(&pmu_idr, pmu->type, NULL, pmu))
12969 		return -EINVAL;
12970 	list_add_rcu(&pmu->entry, &pmus);
12971 
12972 	take_idr_id(pmu_type);
12973 	_pmu = no_free_ptr(pmu); // let it rip
12974 	return 0;
12975 }
12976 EXPORT_SYMBOL_GPL(perf_pmu_register);
12977 
12978 static void __pmu_detach_event(struct pmu *pmu, struct perf_event *event,
12979 			       struct perf_event_context *ctx)
12980 {
12981 	/*
12982 	 * De-schedule the event and mark it REVOKED.
12983 	 */
12984 	perf_event_exit_event(event, ctx, ctx->task, DETACH_REVOKE);
12985 
12986 	/*
12987 	 * All _free_event() bits that rely on event->pmu:
12988 	 *
12989 	 * Notably, perf_mmap() relies on the ordering here.
12990 	 */
12991 	scoped_guard (mutex, &event->mmap_mutex) {
12992 		WARN_ON_ONCE(pmu->event_unmapped);
12993 		/*
12994 		 * Mostly an empty lock sequence, such that perf_mmap(), which
12995 		 * relies on mmap_mutex, is sure to observe the state change.
12996 		 */
12997 	}
12998 
12999 	perf_event_free_bpf_prog(event);
13000 	perf_free_addr_filters(event);
13001 
13002 	if (event->destroy) {
13003 		event->destroy(event);
13004 		event->destroy = NULL;
13005 	}
13006 
13007 	if (event->pmu_ctx) {
13008 		put_pmu_ctx(event->pmu_ctx);
13009 		event->pmu_ctx = NULL;
13010 	}
13011 
13012 	exclusive_event_destroy(event);
13013 	module_put(pmu->module);
13014 
13015 	mediated_pmu_unaccount_event(event);
13016 	event->pmu = NULL; /* force fault instead of UAF */
13017 }
13018 
13019 static void pmu_detach_event(struct pmu *pmu, struct perf_event *event)
13020 {
13021 	struct perf_event_context *ctx;
13022 
13023 	ctx = perf_event_ctx_lock(event);
13024 	__pmu_detach_event(pmu, event, ctx);
13025 	perf_event_ctx_unlock(event, ctx);
13026 
13027 	scoped_guard (spinlock, &pmu->events_lock)
13028 		list_del(&event->pmu_list);
13029 }
13030 
13031 static struct perf_event *pmu_get_event(struct pmu *pmu)
13032 {
13033 	struct perf_event *event;
13034 
13035 	guard(spinlock)(&pmu->events_lock);
13036 	list_for_each_entry(event, &pmu->events, pmu_list) {
13037 		if (atomic_long_inc_not_zero(&event->refcount))
13038 			return event;
13039 	}
13040 
13041 	return NULL;
13042 }
13043 
13044 static bool pmu_empty(struct pmu *pmu)
13045 {
13046 	guard(spinlock)(&pmu->events_lock);
13047 	return list_empty(&pmu->events);
13048 }
13049 
13050 static void pmu_detach_events(struct pmu *pmu)
13051 {
13052 	struct perf_event *event;
13053 
13054 	for (;;) {
13055 		event = pmu_get_event(pmu);
13056 		if (!event)
13057 			break;
13058 
13059 		pmu_detach_event(pmu, event);
13060 		put_event(event);
13061 	}
13062 
13063 	/*
13064 	 * wait for pending _free_event()s
13065 	 */
13066 	wait_var_event(pmu, pmu_empty(pmu));
13067 }
13068 
13069 int perf_pmu_unregister(struct pmu *pmu)
13070 {
13071 	scoped_guard (mutex, &pmus_lock) {
13072 		if (!idr_cmpxchg(&pmu_idr, pmu->type, pmu, NULL))
13073 			return -EINVAL;
13074 
13075 		list_del_rcu(&pmu->entry);
13076 	}
13077 
13078 	/*
13079 	 * We dereference the pmu list under both SRCU and regular RCU, so
13080 	 * synchronize against both of those.
13081 	 *
13082 	 * Notably, the entirety of event creation, from perf_init_event()
13083 	 * (which will now fail, because of the above) until
13084 	 * perf_install_in_context() should be under SRCU such that
13085 	 * this synchronizes against event creation. This avoids trying to
13086 	 * detach events that are not fully formed.
13087 	 */
13088 	synchronize_srcu(&pmus_srcu);
13089 	synchronize_rcu();
13090 
13091 	if (pmu->event_unmapped && !pmu_empty(pmu)) {
13092 		/*
13093 		 * Can't force remove events when pmu::event_unmapped()
13094 		 * is used in perf_mmap_close().
13095 		 */
13096 		guard(mutex)(&pmus_lock);
13097 		idr_cmpxchg(&pmu_idr, pmu->type, NULL, pmu);
13098 		list_add_rcu(&pmu->entry, &pmus);
13099 		return -EBUSY;
13100 	}
13101 
13102 	scoped_guard (mutex, &pmus_lock)
13103 		idr_remove(&pmu_idr, pmu->type);
13104 
13105 	/*
13106 	 * PMU is removed from the pmus list, so no new events will
13107 	 * be created, now take care of the existing ones.
13108 	 */
13109 	pmu_detach_events(pmu);
13110 
13111 	/*
13112 	 * PMU is unused, make it go away.
13113 	 */
13114 	perf_pmu_free(pmu);
13115 	return 0;
13116 }
13117 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
13118 
13119 static inline bool has_extended_regs(struct perf_event *event)
13120 {
13121 	return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
13122 	       (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
13123 }
13124 
13125 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
13126 {
13127 	struct perf_event_context *ctx = NULL;
13128 	int ret;
13129 
13130 	if (!try_module_get(pmu->module))
13131 		return -ENODEV;
13132 
13133 	/*
13134 	 * A number of pmu->event_init() methods iterate the sibling_list to,
13135 	 * for example, validate if the group fits on the PMU. Therefore,
13136 	 * if this is a sibling event, acquire the ctx->mutex to protect
13137 	 * the sibling_list.
13138 	 */
13139 	if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
13140 		/*
13141 		 * This ctx->mutex can nest when we're called through
13142 		 * inheritance. See the perf_event_ctx_lock_nested() comment.
13143 		 */
13144 		ctx = perf_event_ctx_lock_nested(event->group_leader,
13145 						 SINGLE_DEPTH_NESTING);
13146 		BUG_ON(!ctx);
13147 	}
13148 
13149 	event->pmu = pmu;
13150 	ret = pmu->event_init(event);
13151 
13152 	if (ctx)
13153 		perf_event_ctx_unlock(event->group_leader, ctx);
13154 
13155 	if (ret)
13156 		goto err_pmu;
13157 
13158 	if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
13159 	    has_extended_regs(event)) {
13160 		ret = -EOPNOTSUPP;
13161 		goto err_destroy;
13162 	}
13163 
13164 	if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
13165 	    event_has_any_exclude_flag(event)) {
13166 		ret = -EINVAL;
13167 		goto err_destroy;
13168 	}
13169 
13170 	if (pmu->scope != PERF_PMU_SCOPE_NONE && event->cpu >= 0) {
13171 		const struct cpumask *cpumask;
13172 		struct cpumask *pmu_cpumask;
13173 		int cpu;
13174 
13175 		cpumask = perf_scope_cpu_topology_cpumask(pmu->scope, event->cpu);
13176 		pmu_cpumask = perf_scope_cpumask(pmu->scope);
13177 
13178 		ret = -ENODEV;
13179 		if (!pmu_cpumask || !cpumask)
13180 			goto err_destroy;
13181 
13182 		cpu = cpumask_any_and(pmu_cpumask, cpumask);
13183 		if (cpu >= nr_cpu_ids)
13184 			goto err_destroy;
13185 
13186 		event->event_caps |= PERF_EV_CAP_READ_SCOPE;
13187 	}
13188 
13189 	return 0;
13190 
13191 err_destroy:
13192 	if (event->destroy) {
13193 		event->destroy(event);
13194 		event->destroy = NULL;
13195 	}
13196 
13197 err_pmu:
13198 	event->pmu = NULL;
13199 	module_put(pmu->module);
13200 	return ret;
13201 }
13202 
13203 static struct pmu *perf_init_event(struct perf_event *event)
13204 {
13205 	bool extended_type = false;
13206 	struct pmu *pmu;
13207 	int type, ret;
13208 
13209 	guard(srcu)(&pmus_srcu); /* pmu idr/list access */
13210 
13211 	/*
13212 	 * Save original type before calling pmu->event_init() since certain
13213 	 * pmus overwrites event->attr.type to forward event to another pmu.
13214 	 */
13215 	event->orig_type = event->attr.type;
13216 
13217 	/* Try parent's PMU first: */
13218 	if (event->parent && event->parent->pmu) {
13219 		pmu = event->parent->pmu;
13220 		ret = perf_try_init_event(pmu, event);
13221 		if (!ret)
13222 			return pmu;
13223 	}
13224 
13225 	/*
13226 	 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
13227 	 * are often aliases for PERF_TYPE_RAW.
13228 	 */
13229 	type = event->attr.type;
13230 	if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE) {
13231 		type = event->attr.config >> PERF_PMU_TYPE_SHIFT;
13232 		if (!type) {
13233 			type = PERF_TYPE_RAW;
13234 		} else {
13235 			extended_type = true;
13236 			event->attr.config &= PERF_HW_EVENT_MASK;
13237 		}
13238 	}
13239 
13240 again:
13241 	scoped_guard (rcu)
13242 		pmu = idr_find(&pmu_idr, type);
13243 	if (pmu) {
13244 		if (event->attr.type != type && type != PERF_TYPE_RAW &&
13245 		    !(pmu->capabilities & PERF_PMU_CAP_EXTENDED_HW_TYPE))
13246 			return ERR_PTR(-ENOENT);
13247 
13248 		ret = perf_try_init_event(pmu, event);
13249 		if (ret == -ENOENT && event->attr.type != type && !extended_type) {
13250 			type = event->attr.type;
13251 			goto again;
13252 		}
13253 
13254 		if (ret)
13255 			return ERR_PTR(ret);
13256 
13257 		return pmu;
13258 	}
13259 
13260 	list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
13261 		ret = perf_try_init_event(pmu, event);
13262 		if (!ret)
13263 			return pmu;
13264 
13265 		if (ret != -ENOENT)
13266 			return ERR_PTR(ret);
13267 	}
13268 
13269 	return ERR_PTR(-ENOENT);
13270 }
13271 
13272 static void attach_sb_event(struct perf_event *event)
13273 {
13274 	struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
13275 
13276 	raw_spin_lock(&pel->lock);
13277 	list_add_rcu(&event->sb_list, &pel->list);
13278 	raw_spin_unlock(&pel->lock);
13279 }
13280 
13281 /*
13282  * We keep a list of all !task (and therefore per-cpu) events
13283  * that need to receive side-band records.
13284  *
13285  * This avoids having to scan all the various PMU per-cpu contexts
13286  * looking for them.
13287  */
13288 static void account_pmu_sb_event(struct perf_event *event)
13289 {
13290 	if (is_sb_event(event))
13291 		attach_sb_event(event);
13292 }
13293 
13294 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
13295 static void account_freq_event_nohz(void)
13296 {
13297 #ifdef CONFIG_NO_HZ_FULL
13298 	/* Lock so we don't race with concurrent unaccount */
13299 	spin_lock(&nr_freq_lock);
13300 	if (atomic_inc_return(&nr_freq_events) == 1)
13301 		tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
13302 	spin_unlock(&nr_freq_lock);
13303 #endif
13304 }
13305 
13306 static void account_freq_event(void)
13307 {
13308 	if (tick_nohz_full_enabled())
13309 		account_freq_event_nohz();
13310 	else
13311 		atomic_inc(&nr_freq_events);
13312 }
13313 
13314 
13315 static void account_event(struct perf_event *event)
13316 {
13317 	bool inc = false;
13318 
13319 	if (event->parent)
13320 		return;
13321 
13322 	if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
13323 		inc = true;
13324 	if (event->attr.mmap || event->attr.mmap_data)
13325 		atomic_inc(&nr_mmap_events);
13326 	if (event->attr.build_id)
13327 		atomic_inc(&nr_build_id_events);
13328 	if (event->attr.comm)
13329 		atomic_inc(&nr_comm_events);
13330 	if (event->attr.namespaces)
13331 		atomic_inc(&nr_namespaces_events);
13332 	if (event->attr.cgroup)
13333 		atomic_inc(&nr_cgroup_events);
13334 	if (event->attr.task)
13335 		atomic_inc(&nr_task_events);
13336 	if (event->attr.freq)
13337 		account_freq_event();
13338 	if (event->attr.context_switch) {
13339 		atomic_inc(&nr_switch_events);
13340 		inc = true;
13341 	}
13342 	if (has_branch_stack(event))
13343 		inc = true;
13344 	if (is_cgroup_event(event))
13345 		inc = true;
13346 	if (event->attr.ksymbol)
13347 		atomic_inc(&nr_ksymbol_events);
13348 	if (event->attr.bpf_event)
13349 		atomic_inc(&nr_bpf_events);
13350 	if (event->attr.text_poke)
13351 		atomic_inc(&nr_text_poke_events);
13352 
13353 	if (inc) {
13354 		/*
13355 		 * We need the mutex here because static_branch_enable()
13356 		 * must complete *before* the perf_sched_count increment
13357 		 * becomes visible.
13358 		 */
13359 		if (atomic_inc_not_zero(&perf_sched_count))
13360 			goto enabled;
13361 
13362 		mutex_lock(&perf_sched_mutex);
13363 		if (!atomic_read(&perf_sched_count)) {
13364 			static_branch_enable(&perf_sched_events);
13365 			/*
13366 			 * Guarantee that all CPUs observe they key change and
13367 			 * call the perf scheduling hooks before proceeding to
13368 			 * install events that need them.
13369 			 */
13370 			synchronize_rcu();
13371 		}
13372 		/*
13373 		 * Now that we have waited for the sync_sched(), allow further
13374 		 * increments to by-pass the mutex.
13375 		 */
13376 		atomic_inc(&perf_sched_count);
13377 		mutex_unlock(&perf_sched_mutex);
13378 	}
13379 enabled:
13380 
13381 	account_pmu_sb_event(event);
13382 }
13383 
13384 /*
13385  * Allocate and initialize an event structure
13386  */
13387 static struct perf_event *
13388 perf_event_alloc(struct perf_event_attr *attr, int cpu,
13389 		 struct task_struct *task,
13390 		 struct perf_event *group_leader,
13391 		 struct perf_event *parent_event,
13392 		 perf_overflow_handler_t overflow_handler,
13393 		 void *context, int cgroup_fd)
13394 {
13395 	struct pmu *pmu;
13396 	struct hw_perf_event *hwc;
13397 	long err = -EINVAL;
13398 	int node;
13399 
13400 	if ((unsigned)cpu >= nr_cpu_ids) {
13401 		if (!task || cpu != -1)
13402 			return ERR_PTR(-EINVAL);
13403 	}
13404 	if (attr->sigtrap && !task) {
13405 		/* Requires a task: avoid signalling random tasks. */
13406 		return ERR_PTR(-EINVAL);
13407 	}
13408 
13409 	node = (cpu >= 0) ? cpu_to_node(cpu) : -1;
13410 	struct perf_event *event __free(__free_event) =
13411 		kmem_cache_alloc_node(perf_event_cache, GFP_KERNEL | __GFP_ZERO, node);
13412 	if (!event)
13413 		return ERR_PTR(-ENOMEM);
13414 
13415 	/*
13416 	 * Single events are their own group leaders, with an
13417 	 * empty sibling list:
13418 	 */
13419 	if (!group_leader)
13420 		group_leader = event;
13421 
13422 	mutex_init(&event->child_mutex);
13423 	INIT_LIST_HEAD(&event->child_list);
13424 
13425 	INIT_LIST_HEAD(&event->event_entry);
13426 	INIT_LIST_HEAD(&event->sibling_list);
13427 	INIT_LIST_HEAD(&event->active_list);
13428 	init_event_group(event);
13429 	INIT_LIST_HEAD(&event->rb_entry);
13430 	INIT_LIST_HEAD(&event->active_entry);
13431 	INIT_LIST_HEAD(&event->addr_filters.list);
13432 	INIT_HLIST_NODE(&event->hlist_entry);
13433 	INIT_LIST_HEAD(&event->pmu_list);
13434 
13435 
13436 	init_waitqueue_head(&event->waitq);
13437 	init_irq_work(&event->pending_irq, perf_pending_irq);
13438 	event->pending_disable_irq = IRQ_WORK_INIT_HARD(perf_pending_disable);
13439 	init_task_work(&event->pending_task, perf_pending_task);
13440 
13441 	mutex_init(&event->mmap_mutex);
13442 	raw_spin_lock_init(&event->addr_filters.lock);
13443 
13444 	atomic_long_set(&event->refcount, 1);
13445 	event->cpu		= cpu;
13446 	event->attr		= *attr;
13447 	event->group_leader	= group_leader;
13448 	event->pmu		= NULL;
13449 	event->oncpu		= -1;
13450 
13451 	event->parent		= parent_event;
13452 
13453 	event->ns		= get_pid_ns(task_active_pid_ns(current));
13454 	event->id		= atomic64_inc_return(&perf_event_id);
13455 
13456 	event->state		= PERF_EVENT_STATE_INACTIVE;
13457 
13458 	if (parent_event)
13459 		event->event_caps = parent_event->event_caps;
13460 
13461 	if (task) {
13462 		event->attach_state = PERF_ATTACH_TASK;
13463 		/*
13464 		 * XXX pmu::event_init needs to know what task to account to
13465 		 * and we cannot use the ctx information because we need the
13466 		 * pmu before we get a ctx.
13467 		 */
13468 		event->hw.target = get_task_struct(task);
13469 	}
13470 
13471 	event->clock = &local_clock;
13472 	if (parent_event)
13473 		event->clock = parent_event->clock;
13474 
13475 	if (!overflow_handler && parent_event) {
13476 		overflow_handler = parent_event->overflow_handler;
13477 		context = parent_event->overflow_handler_context;
13478 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
13479 		if (parent_event->prog) {
13480 			struct bpf_prog *prog = parent_event->prog;
13481 
13482 			bpf_prog_inc(prog);
13483 			event->prog = prog;
13484 		}
13485 #endif
13486 	}
13487 
13488 	if (overflow_handler) {
13489 		event->overflow_handler	= overflow_handler;
13490 		event->overflow_handler_context = context;
13491 	} else if (is_write_backward(event)){
13492 		event->overflow_handler = perf_event_output_backward;
13493 		event->overflow_handler_context = NULL;
13494 	} else {
13495 		event->overflow_handler = perf_event_output_forward;
13496 		event->overflow_handler_context = NULL;
13497 	}
13498 
13499 	perf_event__state_init(event);
13500 
13501 	pmu = NULL;
13502 
13503 	hwc = &event->hw;
13504 	hwc->sample_period = attr->sample_period;
13505 	if (is_event_in_freq_mode(event))
13506 		hwc->sample_period = 1;
13507 	hwc->last_period = hwc->sample_period;
13508 
13509 	local64_set(&hwc->period_left, hwc->sample_period);
13510 
13511 	/*
13512 	 * We do not support PERF_SAMPLE_READ on inherited events unless
13513 	 * PERF_SAMPLE_TID is also selected, which allows inherited events to
13514 	 * collect per-thread samples.
13515 	 * See perf_output_read().
13516 	 */
13517 	if (has_inherit_and_sample_read(attr) && !(attr->sample_type & PERF_SAMPLE_TID))
13518 		return ERR_PTR(-EINVAL);
13519 
13520 	if (!has_branch_stack(event))
13521 		event->attr.branch_sample_type = 0;
13522 
13523 	pmu = perf_init_event(event);
13524 	if (IS_ERR(pmu))
13525 		return (void*)pmu;
13526 
13527 	/*
13528 	 * The PERF_ATTACH_TASK_DATA is set in the event_init()->hw_config().
13529 	 * The attach should be right after the perf_init_event().
13530 	 * Otherwise, the __free_event() would mistakenly detach the non-exist
13531 	 * perf_ctx_data because of the other errors between them.
13532 	 */
13533 	if (event->attach_state & PERF_ATTACH_TASK_DATA) {
13534 		err = attach_perf_ctx_data(event);
13535 		if (err)
13536 			return ERR_PTR(err);
13537 	}
13538 
13539 	/*
13540 	 * Disallow uncore-task events. Similarly, disallow uncore-cgroup
13541 	 * events (they don't make sense as the cgroup will be different
13542 	 * on other CPUs in the uncore mask).
13543 	 */
13544 	if (pmu->task_ctx_nr == perf_invalid_context && (task || cgroup_fd != -1))
13545 		return ERR_PTR(-EINVAL);
13546 
13547 	if (event->attr.aux_output &&
13548 	    (!(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT) ||
13549 	     event->attr.aux_pause || event->attr.aux_resume))
13550 		return ERR_PTR(-EOPNOTSUPP);
13551 
13552 	if (event->attr.aux_pause && event->attr.aux_resume)
13553 		return ERR_PTR(-EINVAL);
13554 
13555 	if (event->attr.aux_start_paused) {
13556 		if (!(pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE))
13557 			return ERR_PTR(-EOPNOTSUPP);
13558 		event->hw.aux_paused = 1;
13559 	}
13560 
13561 	if (cgroup_fd != -1) {
13562 		err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
13563 		if (err)
13564 			return ERR_PTR(err);
13565 	}
13566 
13567 	err = exclusive_event_init(event);
13568 	if (err)
13569 		return ERR_PTR(err);
13570 
13571 	if (has_addr_filter(event)) {
13572 		event->addr_filter_ranges = kzalloc_objs(struct perf_addr_filter_range,
13573 							 pmu->nr_addr_filters);
13574 		if (!event->addr_filter_ranges)
13575 			return ERR_PTR(-ENOMEM);
13576 
13577 		/*
13578 		 * Clone the parent's vma offsets: they are valid until exec()
13579 		 * even if the mm is not shared with the parent.
13580 		 */
13581 		if (event->parent) {
13582 			struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
13583 
13584 			raw_spin_lock_irq(&ifh->lock);
13585 			memcpy(event->addr_filter_ranges,
13586 			       event->parent->addr_filter_ranges,
13587 			       pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
13588 			raw_spin_unlock_irq(&ifh->lock);
13589 		}
13590 
13591 		/* force hw sync on the address filters */
13592 		event->addr_filters_gen = 1;
13593 	}
13594 
13595 	if (!event->parent) {
13596 		if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
13597 			err = get_callchain_buffers(attr->sample_max_stack);
13598 			if (err)
13599 				return ERR_PTR(err);
13600 			event->attach_state |= PERF_ATTACH_CALLCHAIN;
13601 		}
13602 	}
13603 
13604 	err = security_perf_event_alloc(event);
13605 	if (err)
13606 		return ERR_PTR(err);
13607 
13608 	err = mediated_pmu_account_event(event);
13609 	if (err)
13610 		return ERR_PTR(err);
13611 
13612 	/* symmetric to unaccount_event() in _free_event() */
13613 	account_event(event);
13614 
13615 	/*
13616 	 * Event creation should be under SRCU, see perf_pmu_unregister().
13617 	 */
13618 	lockdep_assert_held(&pmus_srcu);
13619 	scoped_guard (spinlock, &pmu->events_lock)
13620 		list_add(&event->pmu_list, &pmu->events);
13621 
13622 	return_ptr(event);
13623 }
13624 
13625 static int perf_copy_attr(struct perf_event_attr __user *uattr,
13626 			  struct perf_event_attr *attr)
13627 {
13628 	u32 size;
13629 	int ret;
13630 
13631 	/* Zero the full structure, so that a short copy will be nice. */
13632 	memset(attr, 0, sizeof(*attr));
13633 
13634 	ret = get_user(size, &uattr->size);
13635 	if (ret)
13636 		return ret;
13637 
13638 	/* ABI compatibility quirk: */
13639 	if (!size)
13640 		size = PERF_ATTR_SIZE_VER0;
13641 	if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
13642 		goto err_size;
13643 
13644 	ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
13645 	if (ret) {
13646 		if (ret == -E2BIG)
13647 			goto err_size;
13648 		return ret;
13649 	}
13650 
13651 	attr->size = size;
13652 
13653 	if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
13654 		return -EINVAL;
13655 
13656 	if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
13657 		return -EINVAL;
13658 
13659 	if (attr->read_format & ~(PERF_FORMAT_MAX-1))
13660 		return -EINVAL;
13661 
13662 	if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
13663 		u64 mask = attr->branch_sample_type;
13664 
13665 		/* only using defined bits */
13666 		if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
13667 			return -EINVAL;
13668 
13669 		/* at least one branch bit must be set */
13670 		if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
13671 			return -EINVAL;
13672 
13673 		/* propagate priv level, when not set for branch */
13674 		if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
13675 
13676 			/* exclude_kernel checked on syscall entry */
13677 			if (!attr->exclude_kernel)
13678 				mask |= PERF_SAMPLE_BRANCH_KERNEL;
13679 
13680 			if (!attr->exclude_user)
13681 				mask |= PERF_SAMPLE_BRANCH_USER;
13682 
13683 			if (!attr->exclude_hv)
13684 				mask |= PERF_SAMPLE_BRANCH_HV;
13685 			/*
13686 			 * adjust user setting (for HW filter setup)
13687 			 */
13688 			attr->branch_sample_type = mask;
13689 		}
13690 		/* privileged levels capture (kernel, hv): check permissions */
13691 		if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
13692 			ret = perf_allow_kernel();
13693 			if (ret)
13694 				return ret;
13695 		}
13696 	}
13697 
13698 	if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
13699 		ret = perf_reg_validate(attr->sample_regs_user);
13700 		if (ret)
13701 			return ret;
13702 	}
13703 
13704 	if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
13705 		if (!arch_perf_have_user_stack_dump())
13706 			return -ENOSYS;
13707 
13708 		/*
13709 		 * We have __u32 type for the size, but so far
13710 		 * we can only use __u16 as maximum due to the
13711 		 * __u16 sample size limit.
13712 		 */
13713 		if (attr->sample_stack_user >= USHRT_MAX)
13714 			return -EINVAL;
13715 		else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
13716 			return -EINVAL;
13717 	}
13718 
13719 	if (!attr->sample_max_stack)
13720 		attr->sample_max_stack = sysctl_perf_event_max_stack;
13721 
13722 	if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
13723 		ret = perf_reg_validate(attr->sample_regs_intr);
13724 
13725 #ifndef CONFIG_CGROUP_PERF
13726 	if (attr->sample_type & PERF_SAMPLE_CGROUP)
13727 		return -EINVAL;
13728 #endif
13729 	if ((attr->sample_type & PERF_SAMPLE_WEIGHT) &&
13730 	    (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT))
13731 		return -EINVAL;
13732 
13733 	if (!attr->inherit && attr->inherit_thread)
13734 		return -EINVAL;
13735 
13736 	if (attr->remove_on_exec && attr->enable_on_exec)
13737 		return -EINVAL;
13738 
13739 	if (attr->sigtrap && !attr->remove_on_exec)
13740 		return -EINVAL;
13741 
13742 out:
13743 	return ret;
13744 
13745 err_size:
13746 	put_user(sizeof(*attr), &uattr->size);
13747 	ret = -E2BIG;
13748 	goto out;
13749 }
13750 
13751 static void mutex_lock_double(struct mutex *a, struct mutex *b)
13752 {
13753 	if (b < a)
13754 		swap(a, b);
13755 
13756 	mutex_lock(a);
13757 	mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
13758 }
13759 
13760 static int
13761 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
13762 {
13763 	struct perf_buffer *rb = NULL;
13764 	int ret = -EINVAL;
13765 
13766 	if (!output_event) {
13767 		mutex_lock(&event->mmap_mutex);
13768 		goto set;
13769 	}
13770 
13771 	/* don't allow circular references */
13772 	if (event == output_event)
13773 		goto out;
13774 
13775 	/*
13776 	 * Don't allow cross-cpu buffers
13777 	 */
13778 	if (output_event->cpu != event->cpu)
13779 		goto out;
13780 
13781 	/*
13782 	 * If its not a per-cpu rb, it must be the same task.
13783 	 */
13784 	if (output_event->cpu == -1 && output_event->hw.target != event->hw.target)
13785 		goto out;
13786 
13787 	/*
13788 	 * Mixing clocks in the same buffer is trouble you don't need.
13789 	 */
13790 	if (output_event->clock != event->clock)
13791 		goto out;
13792 
13793 	/*
13794 	 * Either writing ring buffer from beginning or from end.
13795 	 * Mixing is not allowed.
13796 	 */
13797 	if (is_write_backward(output_event) != is_write_backward(event))
13798 		goto out;
13799 
13800 	/*
13801 	 * If both events generate aux data, they must be on the same PMU
13802 	 */
13803 	if (has_aux(event) && has_aux(output_event) &&
13804 	    event->pmu != output_event->pmu)
13805 		goto out;
13806 
13807 	/*
13808 	 * Hold both mmap_mutex to serialize against perf_mmap_close().  Since
13809 	 * output_event is already on rb->event_list, and the list iteration
13810 	 * restarts after every removal, it is guaranteed this new event is
13811 	 * observed *OR* if output_event is already removed, it's guaranteed we
13812 	 * observe !rb->mmap_count.
13813 	 */
13814 	mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex);
13815 set:
13816 	/* Can't redirect output if we've got an active mmap() */
13817 	if (refcount_read(&event->mmap_count))
13818 		goto unlock;
13819 
13820 	if (output_event) {
13821 		if (output_event->state <= PERF_EVENT_STATE_REVOKED)
13822 			goto unlock;
13823 
13824 		/* get the rb we want to redirect to */
13825 		rb = ring_buffer_get(output_event);
13826 		if (!rb)
13827 			goto unlock;
13828 
13829 		/* did we race against perf_mmap_close() */
13830 		if (!refcount_read(&rb->mmap_count)) {
13831 			ring_buffer_put(rb);
13832 			goto unlock;
13833 		}
13834 	}
13835 
13836 	ring_buffer_attach(event, rb);
13837 
13838 	ret = 0;
13839 unlock:
13840 	mutex_unlock(&event->mmap_mutex);
13841 	if (output_event)
13842 		mutex_unlock(&output_event->mmap_mutex);
13843 
13844 out:
13845 	return ret;
13846 }
13847 
13848 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
13849 {
13850 	bool nmi_safe = false;
13851 
13852 	switch (clk_id) {
13853 	case CLOCK_MONOTONIC:
13854 		event->clock = &ktime_get_mono_fast_ns;
13855 		nmi_safe = true;
13856 		break;
13857 
13858 	case CLOCK_MONOTONIC_RAW:
13859 		event->clock = &ktime_get_raw_fast_ns;
13860 		nmi_safe = true;
13861 		break;
13862 
13863 	case CLOCK_REALTIME:
13864 		event->clock = &ktime_get_real_ns;
13865 		break;
13866 
13867 	case CLOCK_BOOTTIME:
13868 		event->clock = &ktime_get_boottime_ns;
13869 		break;
13870 
13871 	case CLOCK_TAI:
13872 		event->clock = &ktime_get_clocktai_ns;
13873 		break;
13874 
13875 	default:
13876 		return -EINVAL;
13877 	}
13878 
13879 	if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
13880 		return -EINVAL;
13881 
13882 	return 0;
13883 }
13884 
13885 static bool
13886 perf_check_permission(struct perf_event_attr *attr, struct task_struct *task)
13887 {
13888 	unsigned int ptrace_mode = PTRACE_MODE_READ_REALCREDS;
13889 	bool is_capable = perfmon_capable();
13890 
13891 	if (attr->sigtrap) {
13892 		/*
13893 		 * perf_event_attr::sigtrap sends signals to the other task.
13894 		 * Require the current task to also have CAP_KILL.
13895 		 */
13896 		rcu_read_lock();
13897 		is_capable &= ns_capable(__task_cred(task)->user_ns, CAP_KILL);
13898 		rcu_read_unlock();
13899 
13900 		/*
13901 		 * If the required capabilities aren't available, checks for
13902 		 * ptrace permissions: upgrade to ATTACH, since sending signals
13903 		 * can effectively change the target task.
13904 		 */
13905 		ptrace_mode = PTRACE_MODE_ATTACH_REALCREDS;
13906 	}
13907 
13908 	/*
13909 	 * Preserve ptrace permission check for backwards compatibility. The
13910 	 * ptrace check also includes checks that the current task and other
13911 	 * task have matching uids, and is therefore not done here explicitly.
13912 	 */
13913 	return is_capable || ptrace_may_access(task, ptrace_mode);
13914 }
13915 
13916 /**
13917  * sys_perf_event_open - open a performance event, associate it to a task/cpu
13918  *
13919  * @attr_uptr:	event_id type attributes for monitoring/sampling
13920  * @pid:		target pid
13921  * @cpu:		target cpu
13922  * @group_fd:		group leader event fd
13923  * @flags:		perf event open flags
13924  */
13925 SYSCALL_DEFINE5(perf_event_open,
13926 		struct perf_event_attr __user *, attr_uptr,
13927 		pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
13928 {
13929 	struct perf_event *group_leader = NULL, *output_event = NULL;
13930 	struct perf_event_pmu_context *pmu_ctx;
13931 	struct perf_event *event, *sibling;
13932 	struct perf_event_attr attr;
13933 	struct perf_event_context *ctx;
13934 	struct file *event_file = NULL;
13935 	struct task_struct *task = NULL;
13936 	struct pmu *pmu;
13937 	int event_fd;
13938 	int move_group = 0;
13939 	int err;
13940 	int f_flags = O_RDWR;
13941 	int cgroup_fd = -1;
13942 
13943 	/* for future expandability... */
13944 	if (flags & ~PERF_FLAG_ALL)
13945 		return -EINVAL;
13946 
13947 	err = perf_copy_attr(attr_uptr, &attr);
13948 	if (err)
13949 		return err;
13950 
13951 	/* Do we allow access to perf_event_open(2) ? */
13952 	err = security_perf_event_open(PERF_SECURITY_OPEN);
13953 	if (err)
13954 		return err;
13955 
13956 	if (!attr.exclude_kernel ||
13957 	    ((attr.sample_type & PERF_SAMPLE_CALLCHAIN) &&
13958 	     !attr.exclude_callchain_kernel)) {
13959 		err = perf_allow_kernel();
13960 		if (err)
13961 			return err;
13962 	}
13963 
13964 	if (attr.namespaces) {
13965 		if (!perfmon_capable())
13966 			return -EACCES;
13967 	}
13968 
13969 	if (attr.freq) {
13970 		if (attr.sample_freq > sysctl_perf_event_sample_rate)
13971 			return -EINVAL;
13972 	} else {
13973 		if (attr.sample_period & (1ULL << 63))
13974 			return -EINVAL;
13975 	}
13976 
13977 	/* Only privileged users can get physical addresses */
13978 	if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
13979 		err = perf_allow_kernel();
13980 		if (err)
13981 			return err;
13982 	}
13983 
13984 	/* REGS_INTR can leak data, lockdown must prevent this */
13985 	if (attr.sample_type & PERF_SAMPLE_REGS_INTR) {
13986 		err = security_locked_down(LOCKDOWN_PERF);
13987 		if (err)
13988 			return err;
13989 	}
13990 
13991 	/*
13992 	 * In cgroup mode, the pid argument is used to pass the fd
13993 	 * opened to the cgroup directory in cgroupfs. The cpu argument
13994 	 * designates the cpu on which to monitor threads from that
13995 	 * cgroup.
13996 	 */
13997 	if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
13998 		return -EINVAL;
13999 
14000 	if (flags & PERF_FLAG_FD_CLOEXEC)
14001 		f_flags |= O_CLOEXEC;
14002 
14003 	event_fd = get_unused_fd_flags(f_flags);
14004 	if (event_fd < 0)
14005 		return event_fd;
14006 
14007 	/*
14008 	 * Event creation should be under SRCU, see perf_pmu_unregister().
14009 	 */
14010 	guard(srcu)(&pmus_srcu);
14011 
14012 	CLASS(fd, group)(group_fd);     // group_fd == -1 => empty
14013 	if (group_fd != -1) {
14014 		if (!is_perf_file(group)) {
14015 			err = -EBADF;
14016 			goto err_fd;
14017 		}
14018 		group_leader = fd_file(group)->private_data;
14019 		if (group_leader->state <= PERF_EVENT_STATE_EXIT) {
14020 			err = -ENODEV;
14021 			goto err_fd;
14022 		}
14023 		if (flags & PERF_FLAG_FD_OUTPUT)
14024 			output_event = group_leader;
14025 		if (flags & PERF_FLAG_FD_NO_GROUP)
14026 			group_leader = NULL;
14027 	}
14028 
14029 	if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
14030 		task = find_lively_task_by_vpid(pid);
14031 		if (IS_ERR(task)) {
14032 			err = PTR_ERR(task);
14033 			goto err_fd;
14034 		}
14035 	}
14036 
14037 	if (task && group_leader &&
14038 	    group_leader->attr.inherit != attr.inherit) {
14039 		err = -EINVAL;
14040 		goto err_task;
14041 	}
14042 
14043 	if (flags & PERF_FLAG_PID_CGROUP)
14044 		cgroup_fd = pid;
14045 
14046 	event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
14047 				 NULL, NULL, cgroup_fd);
14048 	if (IS_ERR(event)) {
14049 		err = PTR_ERR(event);
14050 		goto err_task;
14051 	}
14052 
14053 	if (is_sampling_event(event)) {
14054 		if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
14055 			err = -EOPNOTSUPP;
14056 			goto err_alloc;
14057 		}
14058 	}
14059 
14060 	/*
14061 	 * Special case software events and allow them to be part of
14062 	 * any hardware group.
14063 	 */
14064 	pmu = event->pmu;
14065 
14066 	if (attr.use_clockid) {
14067 		err = perf_event_set_clock(event, attr.clockid);
14068 		if (err)
14069 			goto err_alloc;
14070 	}
14071 
14072 	if (pmu->task_ctx_nr == perf_sw_context)
14073 		event->event_caps |= PERF_EV_CAP_SOFTWARE;
14074 
14075 	if (task) {
14076 		err = down_read_interruptible(&task->signal->exec_update_lock);
14077 		if (err)
14078 			goto err_alloc;
14079 
14080 		/*
14081 		 * We must hold exec_update_lock across this and any potential
14082 		 * perf_install_in_context() call for this new event to
14083 		 * serialize against exec() altering our credentials (and the
14084 		 * perf_event_exit_task() that could imply).
14085 		 */
14086 		err = -EACCES;
14087 		if (!perf_check_permission(&attr, task))
14088 			goto err_cred;
14089 	}
14090 
14091 	/*
14092 	 * Get the target context (task or percpu):
14093 	 */
14094 	ctx = find_get_context(task, event);
14095 	if (IS_ERR(ctx)) {
14096 		err = PTR_ERR(ctx);
14097 		goto err_cred;
14098 	}
14099 
14100 	mutex_lock(&ctx->mutex);
14101 
14102 	if (ctx->task == TASK_TOMBSTONE) {
14103 		err = -ESRCH;
14104 		goto err_locked;
14105 	}
14106 
14107 	if (!task) {
14108 		/*
14109 		 * Check if the @cpu we're creating an event for is online.
14110 		 *
14111 		 * We use the perf_cpu_context::ctx::mutex to serialize against
14112 		 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
14113 		 */
14114 		struct perf_cpu_context *cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
14115 
14116 		if (!cpuctx->online) {
14117 			err = -ENODEV;
14118 			goto err_locked;
14119 		}
14120 	}
14121 
14122 	if (group_leader) {
14123 		err = -EINVAL;
14124 
14125 		/*
14126 		 * Do not allow a recursive hierarchy (this new sibling
14127 		 * becoming part of another group-sibling):
14128 		 */
14129 		if (group_leader->group_leader != group_leader)
14130 			goto err_locked;
14131 
14132 		/* All events in a group should have the same clock */
14133 		if (group_leader->clock != event->clock)
14134 			goto err_locked;
14135 
14136 		/*
14137 		 * Make sure we're both events for the same CPU;
14138 		 * grouping events for different CPUs is broken; since
14139 		 * you can never concurrently schedule them anyhow.
14140 		 */
14141 		if (group_leader->cpu != event->cpu)
14142 			goto err_locked;
14143 
14144 		/*
14145 		 * Make sure we're both on the same context; either task or cpu.
14146 		 */
14147 		if (group_leader->ctx != ctx)
14148 			goto err_locked;
14149 
14150 		/* Recheck under ctx::mutex to serialize against remove-on-exec. */
14151 		if (group_leader->state <= PERF_EVENT_STATE_EXIT) {
14152 			err = -ENODEV;
14153 			goto err_locked;
14154 		}
14155 
14156 		/*
14157 		 * Only a group leader can be exclusive or pinned
14158 		 */
14159 		if (attr.exclusive || attr.pinned)
14160 			goto err_locked;
14161 
14162 		if (is_software_event(event) &&
14163 		    !in_software_context(group_leader)) {
14164 			/*
14165 			 * If the event is a sw event, but the group_leader
14166 			 * is on hw context.
14167 			 *
14168 			 * Allow the addition of software events to hw
14169 			 * groups, this is safe because software events
14170 			 * never fail to schedule.
14171 			 *
14172 			 * Note the comment that goes with struct
14173 			 * perf_event_pmu_context.
14174 			 */
14175 			pmu = group_leader->pmu_ctx->pmu;
14176 		} else if (!is_software_event(event)) {
14177 			if (is_software_event(group_leader) &&
14178 			    (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
14179 				/*
14180 				 * In case the group is a pure software group, and we
14181 				 * try to add a hardware event, move the whole group to
14182 				 * the hardware context.
14183 				 */
14184 				move_group = 1;
14185 			}
14186 
14187 			/* Don't allow group of multiple hw events from different pmus */
14188 			if (!in_software_context(group_leader) &&
14189 			    group_leader->pmu_ctx->pmu != pmu)
14190 				goto err_locked;
14191 		}
14192 	}
14193 
14194 	/*
14195 	 * Now that we're certain of the pmu; find the pmu_ctx.
14196 	 */
14197 	pmu_ctx = find_get_pmu_context(pmu, ctx, event);
14198 	if (IS_ERR(pmu_ctx)) {
14199 		err = PTR_ERR(pmu_ctx);
14200 		goto err_locked;
14201 	}
14202 	event->pmu_ctx = pmu_ctx;
14203 
14204 	if (output_event) {
14205 		err = perf_event_set_output(event, output_event);
14206 		if (err)
14207 			goto err_context;
14208 	}
14209 
14210 	if (!perf_event_validate_size(event)) {
14211 		err = -E2BIG;
14212 		goto err_context;
14213 	}
14214 
14215 	if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
14216 		err = -EINVAL;
14217 		goto err_context;
14218 	}
14219 
14220 	/*
14221 	 * Must be under the same ctx::mutex as perf_install_in_context(),
14222 	 * because we need to serialize with concurrent event creation.
14223 	 */
14224 	if (!exclusive_event_installable(event, ctx)) {
14225 		err = -EBUSY;
14226 		goto err_context;
14227 	}
14228 
14229 	WARN_ON_ONCE(ctx->parent_ctx);
14230 
14231 	event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags);
14232 	if (IS_ERR(event_file)) {
14233 		err = PTR_ERR(event_file);
14234 		event_file = NULL;
14235 		goto err_context;
14236 	}
14237 
14238 	/*
14239 	 * This is the point on no return; we cannot fail hereafter. This is
14240 	 * where we start modifying current state.
14241 	 */
14242 
14243 	if (move_group) {
14244 		perf_remove_from_context(group_leader, 0);
14245 		put_pmu_ctx(group_leader->pmu_ctx);
14246 
14247 		for_each_sibling_event(sibling, group_leader) {
14248 			perf_remove_from_context(sibling, 0);
14249 			put_pmu_ctx(sibling->pmu_ctx);
14250 		}
14251 
14252 		/*
14253 		 * Install the group siblings before the group leader.
14254 		 *
14255 		 * Because a group leader will try and install the entire group
14256 		 * (through the sibling list, which is still in-tact), we can
14257 		 * end up with siblings installed in the wrong context.
14258 		 *
14259 		 * By installing siblings first we NO-OP because they're not
14260 		 * reachable through the group lists.
14261 		 */
14262 		for_each_sibling_event(sibling, group_leader) {
14263 			sibling->pmu_ctx = pmu_ctx;
14264 			get_pmu_ctx(pmu_ctx);
14265 			perf_event__state_init(sibling);
14266 			perf_install_in_context(ctx, sibling, sibling->cpu);
14267 		}
14268 
14269 		/*
14270 		 * Removing from the context ends up with disabled
14271 		 * event. What we want here is event in the initial
14272 		 * startup state, ready to be add into new context.
14273 		 */
14274 		group_leader->pmu_ctx = pmu_ctx;
14275 		get_pmu_ctx(pmu_ctx);
14276 		perf_event__state_init(group_leader);
14277 		perf_install_in_context(ctx, group_leader, group_leader->cpu);
14278 	}
14279 
14280 	/*
14281 	 * Precalculate sample_data sizes; do while holding ctx::mutex such
14282 	 * that we're serialized against further additions and before
14283 	 * perf_install_in_context() which is the point the event is active and
14284 	 * can use these values.
14285 	 */
14286 	perf_event__header_size(event);
14287 	perf_event__id_header_size(event);
14288 
14289 	event->owner = current;
14290 
14291 	perf_install_in_context(ctx, event, event->cpu);
14292 	perf_unpin_context(ctx);
14293 
14294 	mutex_unlock(&ctx->mutex);
14295 
14296 	if (task) {
14297 		up_read(&task->signal->exec_update_lock);
14298 		put_task_struct(task);
14299 	}
14300 
14301 	mutex_lock(&current->perf_event_mutex);
14302 	list_add_tail(&event->owner_entry, &current->perf_event_list);
14303 	mutex_unlock(&current->perf_event_mutex);
14304 
14305 	/*
14306 	 * File reference in group guarantees that group_leader has been
14307 	 * kept alive until we place the new event on the sibling_list.
14308 	 * This ensures destruction of the group leader will find
14309 	 * the pointer to itself in perf_group_detach().
14310 	 */
14311 	fd_install(event_fd, event_file);
14312 	return event_fd;
14313 
14314 err_context:
14315 	put_pmu_ctx(event->pmu_ctx);
14316 	event->pmu_ctx = NULL; /* _free_event() */
14317 err_locked:
14318 	mutex_unlock(&ctx->mutex);
14319 	perf_unpin_context(ctx);
14320 	put_ctx(ctx);
14321 err_cred:
14322 	if (task)
14323 		up_read(&task->signal->exec_update_lock);
14324 err_alloc:
14325 	put_event(event);
14326 err_task:
14327 	if (task)
14328 		put_task_struct(task);
14329 err_fd:
14330 	put_unused_fd(event_fd);
14331 	return err;
14332 }
14333 
14334 /**
14335  * perf_event_create_kernel_counter
14336  *
14337  * @attr: attributes of the counter to create
14338  * @cpu: cpu in which the counter is bound
14339  * @task: task to profile (NULL for percpu)
14340  * @overflow_handler: callback to trigger when we hit the event
14341  * @context: context data could be used in overflow_handler callback
14342  */
14343 struct perf_event *
14344 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
14345 				 struct task_struct *task,
14346 				 perf_overflow_handler_t overflow_handler,
14347 				 void *context)
14348 {
14349 	struct perf_event_pmu_context *pmu_ctx;
14350 	struct perf_event_context *ctx;
14351 	struct perf_event *event;
14352 	struct pmu *pmu;
14353 	int err;
14354 
14355 	/*
14356 	 * Grouping is not supported for kernel events, neither is 'AUX',
14357 	 * make sure the caller's intentions are adjusted.
14358 	 */
14359 	if (attr->aux_output || attr->aux_action)
14360 		return ERR_PTR(-EINVAL);
14361 
14362 	/*
14363 	 * Event creation should be under SRCU, see perf_pmu_unregister().
14364 	 */
14365 	guard(srcu)(&pmus_srcu);
14366 
14367 	event = perf_event_alloc(attr, cpu, task, NULL, NULL,
14368 				 overflow_handler, context, -1);
14369 	if (IS_ERR(event)) {
14370 		err = PTR_ERR(event);
14371 		goto err;
14372 	}
14373 
14374 	/* Mark owner so we could distinguish it from user events. */
14375 	event->owner = TASK_TOMBSTONE;
14376 	pmu = event->pmu;
14377 
14378 	if (pmu->task_ctx_nr == perf_sw_context)
14379 		event->event_caps |= PERF_EV_CAP_SOFTWARE;
14380 
14381 	/*
14382 	 * Get the target context (task or percpu):
14383 	 */
14384 	ctx = find_get_context(task, event);
14385 	if (IS_ERR(ctx)) {
14386 		err = PTR_ERR(ctx);
14387 		goto err_alloc;
14388 	}
14389 
14390 	WARN_ON_ONCE(ctx->parent_ctx);
14391 	mutex_lock(&ctx->mutex);
14392 	if (ctx->task == TASK_TOMBSTONE) {
14393 		err = -ESRCH;
14394 		goto err_unlock;
14395 	}
14396 
14397 	pmu_ctx = find_get_pmu_context(pmu, ctx, event);
14398 	if (IS_ERR(pmu_ctx)) {
14399 		err = PTR_ERR(pmu_ctx);
14400 		goto err_unlock;
14401 	}
14402 	event->pmu_ctx = pmu_ctx;
14403 
14404 	if (!task) {
14405 		/*
14406 		 * Check if the @cpu we're creating an event for is online.
14407 		 *
14408 		 * We use the perf_cpu_context::ctx::mutex to serialize against
14409 		 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
14410 		 */
14411 		struct perf_cpu_context *cpuctx =
14412 			container_of(ctx, struct perf_cpu_context, ctx);
14413 		if (!cpuctx->online) {
14414 			err = -ENODEV;
14415 			goto err_pmu_ctx;
14416 		}
14417 	}
14418 
14419 	if (!exclusive_event_installable(event, ctx)) {
14420 		err = -EBUSY;
14421 		goto err_pmu_ctx;
14422 	}
14423 
14424 	perf_install_in_context(ctx, event, event->cpu);
14425 	perf_unpin_context(ctx);
14426 	mutex_unlock(&ctx->mutex);
14427 
14428 	return event;
14429 
14430 err_pmu_ctx:
14431 	put_pmu_ctx(pmu_ctx);
14432 	event->pmu_ctx = NULL; /* _free_event() */
14433 err_unlock:
14434 	mutex_unlock(&ctx->mutex);
14435 	perf_unpin_context(ctx);
14436 	put_ctx(ctx);
14437 err_alloc:
14438 	put_event(event);
14439 err:
14440 	return ERR_PTR(err);
14441 }
14442 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
14443 
14444 static void __perf_pmu_remove(struct perf_event_context *ctx,
14445 			      int cpu, struct pmu *pmu,
14446 			      struct perf_event_groups *groups,
14447 			      struct list_head *events)
14448 {
14449 	struct perf_event *event, *sibling;
14450 
14451 	perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) {
14452 		perf_remove_from_context(event, 0);
14453 		put_pmu_ctx(event->pmu_ctx);
14454 		list_add(&event->migrate_entry, events);
14455 
14456 		for_each_sibling_event(sibling, event) {
14457 			perf_remove_from_context(sibling, 0);
14458 			put_pmu_ctx(sibling->pmu_ctx);
14459 			list_add(&sibling->migrate_entry, events);
14460 		}
14461 	}
14462 }
14463 
14464 static void __perf_pmu_install_event(struct pmu *pmu,
14465 				     struct perf_event_context *ctx,
14466 				     int cpu, struct perf_event *event)
14467 {
14468 	struct perf_event_pmu_context *epc;
14469 	struct perf_event_context *old_ctx = event->ctx;
14470 
14471 	get_ctx(ctx); /* normally find_get_context() */
14472 
14473 	event->cpu = cpu;
14474 	epc = find_get_pmu_context(pmu, ctx, event);
14475 	event->pmu_ctx = epc;
14476 
14477 	if (event->state >= PERF_EVENT_STATE_OFF)
14478 		event->state = PERF_EVENT_STATE_INACTIVE;
14479 	perf_install_in_context(ctx, event, cpu);
14480 
14481 	/*
14482 	 * Now that event->ctx is updated and visible, put the old ctx.
14483 	 */
14484 	put_ctx(old_ctx);
14485 }
14486 
14487 static void __perf_pmu_install(struct perf_event_context *ctx,
14488 			       int cpu, struct pmu *pmu, struct list_head *events)
14489 {
14490 	struct perf_event *event, *tmp;
14491 
14492 	/*
14493 	 * Re-instate events in 2 passes.
14494 	 *
14495 	 * Skip over group leaders and only install siblings on this first
14496 	 * pass, siblings will not get enabled without a leader, however a
14497 	 * leader will enable its siblings, even if those are still on the old
14498 	 * context.
14499 	 */
14500 	list_for_each_entry_safe(event, tmp, events, migrate_entry) {
14501 		if (event->group_leader == event)
14502 			continue;
14503 
14504 		list_del(&event->migrate_entry);
14505 		__perf_pmu_install_event(pmu, ctx, cpu, event);
14506 	}
14507 
14508 	/*
14509 	 * Once all the siblings are setup properly, install the group leaders
14510 	 * to make it go.
14511 	 */
14512 	list_for_each_entry_safe(event, tmp, events, migrate_entry) {
14513 		list_del(&event->migrate_entry);
14514 		__perf_pmu_install_event(pmu, ctx, cpu, event);
14515 	}
14516 }
14517 
14518 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
14519 {
14520 	struct perf_event_context *src_ctx, *dst_ctx;
14521 	LIST_HEAD(events);
14522 
14523 	/*
14524 	 * Since per-cpu context is persistent, no need to grab an extra
14525 	 * reference.
14526 	 */
14527 	src_ctx = &per_cpu_ptr(&perf_cpu_context, src_cpu)->ctx;
14528 	dst_ctx = &per_cpu_ptr(&perf_cpu_context, dst_cpu)->ctx;
14529 
14530 	/*
14531 	 * See perf_event_ctx_lock() for comments on the details
14532 	 * of swizzling perf_event::ctx.
14533 	 */
14534 	mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
14535 
14536 	__perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->pinned_groups, &events);
14537 	__perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->flexible_groups, &events);
14538 
14539 	if (!list_empty(&events)) {
14540 		/*
14541 		 * Wait for the events to quiesce before re-instating them.
14542 		 */
14543 		synchronize_rcu();
14544 
14545 		__perf_pmu_install(dst_ctx, dst_cpu, pmu, &events);
14546 	}
14547 
14548 	mutex_unlock(&dst_ctx->mutex);
14549 	mutex_unlock(&src_ctx->mutex);
14550 }
14551 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
14552 
14553 static void sync_child_event(struct perf_event *child_event,
14554 			     struct task_struct *task)
14555 {
14556 	struct perf_event *parent_event = child_event->parent;
14557 	u64 child_val;
14558 
14559 	if (child_event->attr.inherit_stat) {
14560 		if (task && task != TASK_TOMBSTONE)
14561 			perf_event_read_event(child_event, task);
14562 	}
14563 
14564 	child_val = perf_event_count(child_event, false);
14565 
14566 	/*
14567 	 * Add back the child's count to the parent's count:
14568 	 */
14569 	atomic64_add(child_val, &parent_event->child_count);
14570 	atomic64_add(child_event->total_time_enabled,
14571 		     &parent_event->child_total_time_enabled);
14572 	atomic64_add(child_event->total_time_running,
14573 		     &parent_event->child_total_time_running);
14574 }
14575 
14576 static void
14577 perf_event_exit_event(struct perf_event *event,
14578 		      struct perf_event_context *ctx,
14579 		      struct task_struct *task,
14580 		      unsigned long detach_flags)
14581 {
14582 	struct perf_event *parent_event = event->parent;
14583 	unsigned int attach_state;
14584 
14585 	detach_flags |= DETACH_EXIT;
14586 
14587 	if (parent_event) {
14588 		/*
14589 		 * Do not destroy the 'original' grouping; because of the
14590 		 * context switch optimization the original events could've
14591 		 * ended up in a random child task.
14592 		 *
14593 		 * If we were to destroy the original group, all group related
14594 		 * operations would cease to function properly after this
14595 		 * random child dies.
14596 		 *
14597 		 * Do destroy all inherited groups, we don't care about those
14598 		 * and being thorough is better.
14599 		 */
14600 		detach_flags |= DETACH_GROUP | DETACH_CHILD;
14601 		mutex_lock(&parent_event->child_mutex);
14602 		/* PERF_ATTACH_ITRACE might be set concurrently */
14603 		attach_state = READ_ONCE(event->attach_state);
14604 
14605 		if (attach_state & PERF_ATTACH_CHILD)
14606 			sync_child_event(event, task);
14607 	}
14608 
14609 	if (detach_flags & DETACH_REVOKE)
14610 		detach_flags |= DETACH_GROUP;
14611 
14612 	perf_remove_from_context(event, detach_flags);
14613 	/*
14614 	 * Child events can be freed.
14615 	 */
14616 	if (parent_event) {
14617 		mutex_unlock(&parent_event->child_mutex);
14618 
14619 		/*
14620 		 * Match the refcount initialization. Make sure it doesn't happen
14621 		 * twice if pmu_detach_event() calls it on an already exited task.
14622 		 */
14623 		if (attach_state & PERF_ATTACH_CHILD) {
14624 			/*
14625 			 * Kick perf_poll() for is_event_hup();
14626 			 */
14627 			perf_event_wakeup(parent_event);
14628 			/*
14629 			 * pmu_detach_event() will have an extra refcount.
14630 			 * perf_pending_task() might have one too.
14631 			 */
14632 			put_event(event);
14633 		}
14634 
14635 		return;
14636 	}
14637 
14638 	/*
14639 	 * Parent events are governed by their filedesc, retain them.
14640 	 */
14641 	perf_event_wakeup(event);
14642 }
14643 
14644 static void perf_event_exit_task_context(struct task_struct *task, bool exit)
14645 {
14646 	struct perf_event_context *ctx, *clone_ctx = NULL;
14647 	struct perf_event *child_event, *next;
14648 
14649 	ctx = perf_pin_task_context(task);
14650 	if (!ctx)
14651 		return;
14652 
14653 	/*
14654 	 * In order to reduce the amount of tricky in ctx tear-down, we hold
14655 	 * ctx::mutex over the entire thing. This serializes against almost
14656 	 * everything that wants to access the ctx.
14657 	 *
14658 	 * The exception is sys_perf_event_open() /
14659 	 * perf_event_create_kernel_count() which does find_get_context()
14660 	 * without ctx::mutex (it cannot because of the move_group double mutex
14661 	 * lock thing). See the comments in perf_install_in_context().
14662 	 */
14663 	mutex_lock(&ctx->mutex);
14664 
14665 	/*
14666 	 * In a single ctx::lock section, de-schedule the events and detach the
14667 	 * context from the task such that we cannot ever get it scheduled back
14668 	 * in.
14669 	 */
14670 	raw_spin_lock_irq(&ctx->lock);
14671 	if (exit)
14672 		task_ctx_sched_out(ctx, NULL, EVENT_ALL);
14673 
14674 	/*
14675 	 * Now that the context is inactive, destroy the task <-> ctx relation
14676 	 * and mark the context dead.
14677 	 */
14678 	RCU_INIT_POINTER(task->perf_event_ctxp, NULL);
14679 	put_ctx(ctx); /* cannot be last */
14680 	WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
14681 	put_task_struct(task); /* cannot be last */
14682 
14683 	clone_ctx = unclone_ctx(ctx);
14684 	raw_spin_unlock_irq(&ctx->lock);
14685 
14686 	if (clone_ctx)
14687 		put_ctx(clone_ctx);
14688 
14689 	/*
14690 	 * Report the task dead after unscheduling the events so that we
14691 	 * won't get any samples after PERF_RECORD_EXIT. We can however still
14692 	 * get a few PERF_RECORD_READ events.
14693 	 */
14694 	if (exit)
14695 		perf_event_task(task, ctx, 0);
14696 
14697 	list_for_each_entry_safe(child_event, next, &ctx->event_list, event_entry)
14698 		perf_event_exit_event(child_event, ctx, exit ? task : NULL, 0);
14699 
14700 	mutex_unlock(&ctx->mutex);
14701 
14702 	if (!exit) {
14703 		/*
14704 		 * perf_event_release_kernel() could still have a reference on
14705 		 * this context. In that case we must wait for these events to
14706 		 * have been freed (in particular all their references to this
14707 		 * task must've been dropped).
14708 		 *
14709 		 * Without this copy_process() will unconditionally free this
14710 		 * task (irrespective of its reference count) and
14711 		 * _free_event()'s put_task_struct(event->hw.target) will be a
14712 		 * use-after-free.
14713 		 *
14714 		 * Wait for all events to drop their context reference.
14715 		 */
14716 		wait_var_event(&ctx->refcount,
14717 			       refcount_read(&ctx->refcount) == 1);
14718 	}
14719 	put_ctx(ctx);
14720 }
14721 
14722 /*
14723  * When a task exits, feed back event values to parent events.
14724  *
14725  * Can be called with exec_update_lock held when called from
14726  * setup_new_exec().
14727  */
14728 void perf_event_exit_task(struct task_struct *task)
14729 {
14730 	struct perf_event *event, *tmp;
14731 
14732 	WARN_ON_ONCE(task != current);
14733 
14734 	mutex_lock(&task->perf_event_mutex);
14735 	list_for_each_entry_safe(event, tmp, &task->perf_event_list,
14736 				 owner_entry) {
14737 		list_del_init(&event->owner_entry);
14738 
14739 		/*
14740 		 * Ensure the list deletion is visible before we clear
14741 		 * the owner, closes a race against perf_release() where
14742 		 * we need to serialize on the owner->perf_event_mutex.
14743 		 */
14744 		smp_store_release(&event->owner, NULL);
14745 	}
14746 	mutex_unlock(&task->perf_event_mutex);
14747 
14748 	perf_event_exit_task_context(task, true);
14749 
14750 	/*
14751 	 * The perf_event_exit_task_context calls perf_event_task
14752 	 * with task's task_ctx, which generates EXIT events for
14753 	 * task contexts and sets task->perf_event_ctxp[] to NULL.
14754 	 * At this point we need to send EXIT events to cpu contexts.
14755 	 */
14756 	perf_event_task(task, NULL, 0);
14757 
14758 	/*
14759 	 * Detach the perf_ctx_data for the system-wide event.
14760 	 *
14761 	 * Done without holding global_ctx_data_rwsem; typically
14762 	 * attach_global_ctx_data() will skip over this task, but otherwise
14763 	 * attach_task_ctx_data() will observe PF_EXITING.
14764 	 */
14765 	detach_task_ctx_data(task);
14766 }
14767 
14768 /*
14769  * Free a context as created by inheritance by perf_event_init_task() below,
14770  * used by fork() in case of fail.
14771  *
14772  * Even though the task has never lived, the context and events have been
14773  * exposed through the child_list, so we must take care tearing it all down.
14774  */
14775 void perf_event_free_task(struct task_struct *task)
14776 {
14777 	perf_event_exit_task_context(task, false);
14778 }
14779 
14780 void perf_event_delayed_put(struct task_struct *task)
14781 {
14782 	WARN_ON_ONCE(task->perf_event_ctxp);
14783 }
14784 
14785 struct file *perf_event_get(unsigned int fd)
14786 {
14787 	struct file *file = fget(fd);
14788 	if (!file)
14789 		return ERR_PTR(-EBADF);
14790 
14791 	if (file->f_op != &perf_fops) {
14792 		fput(file);
14793 		return ERR_PTR(-EBADF);
14794 	}
14795 
14796 	return file;
14797 }
14798 
14799 const struct perf_event *perf_get_event(struct file *file)
14800 {
14801 	if (file->f_op != &perf_fops)
14802 		return ERR_PTR(-EINVAL);
14803 
14804 	return file->private_data;
14805 }
14806 
14807 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
14808 {
14809 	if (!event)
14810 		return ERR_PTR(-EINVAL);
14811 
14812 	return &event->attr;
14813 }
14814 
14815 int perf_allow_kernel(void)
14816 {
14817 	if (sysctl_perf_event_paranoid > 1 && !perfmon_capable())
14818 		return -EACCES;
14819 
14820 	return security_perf_event_open(PERF_SECURITY_KERNEL);
14821 }
14822 EXPORT_SYMBOL_GPL(perf_allow_kernel);
14823 
14824 int perf_allow_cpu(void)
14825 {
14826 	if (sysctl_perf_event_paranoid > 0 && !perfmon_capable())
14827 		return -EACCES;
14828 
14829 	return security_perf_event_open(PERF_SECURITY_CPU);
14830 }
14831 EXPORT_SYMBOL_GPL(perf_allow_cpu);
14832 
14833 int perf_allow_tracepoint(void)
14834 {
14835 	if (sysctl_perf_event_paranoid > -1 && !perfmon_capable())
14836 		return -EPERM;
14837 
14838 	return security_perf_event_open(PERF_SECURITY_TRACEPOINT);
14839 }
14840 EXPORT_SYMBOL_GPL(perf_allow_tracepoint);
14841 
14842 /*
14843  * Inherit an event from parent task to child task.
14844  *
14845  * Returns:
14846  *  - valid pointer on success
14847  *  - NULL for orphaned events
14848  *  - IS_ERR() on error
14849  */
14850 static struct perf_event *
14851 inherit_event(struct perf_event *parent_event,
14852 	      struct task_struct *parent,
14853 	      struct perf_event_context *parent_ctx,
14854 	      struct task_struct *child,
14855 	      struct perf_event *group_leader,
14856 	      struct perf_event_context *child_ctx)
14857 {
14858 	enum perf_event_state parent_state = parent_event->state;
14859 	struct perf_event_pmu_context *pmu_ctx;
14860 	struct perf_event *child_event;
14861 	unsigned long flags;
14862 
14863 	/*
14864 	 * Instead of creating recursive hierarchies of events,
14865 	 * we link inherited events back to the original parent,
14866 	 * which has a filp for sure, which we use as the reference
14867 	 * count:
14868 	 */
14869 	if (parent_event->parent)
14870 		parent_event = parent_event->parent;
14871 
14872 	if (parent_event->state <= PERF_EVENT_STATE_REVOKED)
14873 		return NULL;
14874 
14875 	/*
14876 	 * Event creation should be under SRCU, see perf_pmu_unregister().
14877 	 */
14878 	guard(srcu)(&pmus_srcu);
14879 
14880 	child_event = perf_event_alloc(&parent_event->attr,
14881 					   parent_event->cpu,
14882 					   child,
14883 					   group_leader, parent_event,
14884 					   NULL, NULL, -1);
14885 	if (IS_ERR(child_event))
14886 		return child_event;
14887 
14888 	get_ctx(child_ctx);
14889 	child_event->ctx = child_ctx;
14890 
14891 	pmu_ctx = find_get_pmu_context(parent_event->pmu_ctx->pmu, child_ctx, child_event);
14892 	if (IS_ERR(pmu_ctx)) {
14893 		free_event(child_event);
14894 		return ERR_CAST(pmu_ctx);
14895 	}
14896 	child_event->pmu_ctx = pmu_ctx;
14897 
14898 	/*
14899 	 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
14900 	 * must be under the same lock in order to serialize against
14901 	 * perf_event_release_kernel(), such that either we must observe
14902 	 * is_orphaned_event() or they will observe us on the child_list.
14903 	 */
14904 	mutex_lock(&parent_event->child_mutex);
14905 	if (is_orphaned_event(parent_event) ||
14906 	    !atomic_long_inc_not_zero(&parent_event->refcount)) {
14907 		mutex_unlock(&parent_event->child_mutex);
14908 		free_event(child_event);
14909 		return NULL;
14910 	}
14911 
14912 	/*
14913 	 * Make the child state follow the state of the parent event,
14914 	 * not its attr.disabled bit.  We hold the parent's mutex,
14915 	 * so we won't race with perf_event_{en, dis}able_family.
14916 	 */
14917 	if (parent_state >= PERF_EVENT_STATE_INACTIVE)
14918 		child_event->state = PERF_EVENT_STATE_INACTIVE;
14919 	else
14920 		child_event->state = PERF_EVENT_STATE_OFF;
14921 
14922 	if (parent_event->attr.freq) {
14923 		u64 sample_period = parent_event->hw.sample_period;
14924 		struct hw_perf_event *hwc = &child_event->hw;
14925 
14926 		hwc->sample_period = sample_period;
14927 		hwc->last_period   = sample_period;
14928 
14929 		local64_set(&hwc->period_left, sample_period);
14930 	}
14931 
14932 	child_event->overflow_handler = parent_event->overflow_handler;
14933 	child_event->overflow_handler_context
14934 		= parent_event->overflow_handler_context;
14935 
14936 	/*
14937 	 * Precalculate sample_data sizes
14938 	 */
14939 	perf_event__header_size(child_event);
14940 	perf_event__id_header_size(child_event);
14941 
14942 	/*
14943 	 * Link it up in the child's context:
14944 	 */
14945 	raw_spin_lock_irqsave(&child_ctx->lock, flags);
14946 	add_event_to_ctx(child_event, child_ctx);
14947 	child_event->attach_state |= PERF_ATTACH_CHILD;
14948 	raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
14949 
14950 	/*
14951 	 * Link this into the parent event's child list
14952 	 */
14953 	list_add_tail(&child_event->child_list, &parent_event->child_list);
14954 	mutex_unlock(&parent_event->child_mutex);
14955 
14956 	return child_event;
14957 }
14958 
14959 /*
14960  * Inherits an event group.
14961  *
14962  * This will quietly suppress orphaned events; !inherit_event() is not an error.
14963  * This matches with perf_event_release_kernel() removing all child events.
14964  *
14965  * Returns:
14966  *  - 0 on success
14967  *  - <0 on error
14968  */
14969 static int inherit_group(struct perf_event *parent_event,
14970 	      struct task_struct *parent,
14971 	      struct perf_event_context *parent_ctx,
14972 	      struct task_struct *child,
14973 	      struct perf_event_context *child_ctx)
14974 {
14975 	struct perf_event *leader;
14976 	struct perf_event *sub;
14977 	struct perf_event *child_ctr;
14978 
14979 	leader = inherit_event(parent_event, parent, parent_ctx,
14980 				 child, NULL, child_ctx);
14981 	if (IS_ERR(leader))
14982 		return PTR_ERR(leader);
14983 	/*
14984 	 * @leader can be NULL here because of is_orphaned_event(). In this
14985 	 * case inherit_event() will create individual events, similar to what
14986 	 * perf_group_detach() would do anyway.
14987 	 */
14988 	for_each_sibling_event(sub, parent_event) {
14989 		child_ctr = inherit_event(sub, parent, parent_ctx,
14990 					    child, leader, child_ctx);
14991 		if (IS_ERR(child_ctr))
14992 			return PTR_ERR(child_ctr);
14993 
14994 		if (sub->aux_event == parent_event && child_ctr &&
14995 		    !perf_get_aux_event(child_ctr, leader))
14996 			return -EINVAL;
14997 	}
14998 	if (leader)
14999 		leader->group_generation = parent_event->group_generation;
15000 	return 0;
15001 }
15002 
15003 /*
15004  * Creates the child task context and tries to inherit the event-group.
15005  *
15006  * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
15007  * inherited_all set when we 'fail' to inherit an orphaned event; this is
15008  * consistent with perf_event_release_kernel() removing all child events.
15009  *
15010  * Returns:
15011  *  - 0 on success
15012  *  - <0 on error
15013  */
15014 static int
15015 inherit_task_group(struct perf_event *event, struct task_struct *parent,
15016 		   struct perf_event_context *parent_ctx,
15017 		   struct task_struct *child,
15018 		   u64 clone_flags, int *inherited_all)
15019 {
15020 	struct perf_event_context *child_ctx;
15021 	int ret;
15022 
15023 	if (!event->attr.inherit ||
15024 	    (event->attr.inherit_thread && !(clone_flags & CLONE_THREAD)) ||
15025 	    /* Do not inherit if sigtrap and signal handlers were cleared. */
15026 	    (event->attr.sigtrap && (clone_flags & CLONE_CLEAR_SIGHAND))) {
15027 		*inherited_all = 0;
15028 		return 0;
15029 	}
15030 
15031 	child_ctx = child->perf_event_ctxp;
15032 	if (!child_ctx) {
15033 		/*
15034 		 * This is executed from the parent task context, so
15035 		 * inherit events that have been marked for cloning.
15036 		 * First allocate and initialize a context for the
15037 		 * child.
15038 		 */
15039 		child_ctx = alloc_perf_context(child);
15040 		if (!child_ctx)
15041 			return -ENOMEM;
15042 
15043 		child->perf_event_ctxp = child_ctx;
15044 	}
15045 
15046 	ret = inherit_group(event, parent, parent_ctx, child, child_ctx);
15047 	if (ret)
15048 		*inherited_all = 0;
15049 
15050 	return ret;
15051 }
15052 
15053 /*
15054  * Initialize the perf_event context in task_struct
15055  */
15056 static int perf_event_init_context(struct task_struct *child, u64 clone_flags)
15057 {
15058 	struct perf_event_context *child_ctx, *parent_ctx;
15059 	struct perf_event_context *cloned_ctx;
15060 	struct perf_event *event;
15061 	struct task_struct *parent = current;
15062 	int inherited_all = 1;
15063 	unsigned long flags;
15064 	int ret = 0;
15065 
15066 	if (likely(!parent->perf_event_ctxp))
15067 		return 0;
15068 
15069 	/*
15070 	 * If the parent's context is a clone, pin it so it won't get
15071 	 * swapped under us.
15072 	 */
15073 	parent_ctx = perf_pin_task_context(parent);
15074 	if (!parent_ctx)
15075 		return 0;
15076 
15077 	/*
15078 	 * No need to check if parent_ctx != NULL here; since we saw
15079 	 * it non-NULL earlier, the only reason for it to become NULL
15080 	 * is if we exit, and since we're currently in the middle of
15081 	 * a fork we can't be exiting at the same time.
15082 	 */
15083 
15084 	/*
15085 	 * Lock the parent list. No need to lock the child - not PID
15086 	 * hashed yet and not running, so nobody can access it.
15087 	 */
15088 	mutex_lock(&parent_ctx->mutex);
15089 
15090 	/*
15091 	 * We dont have to disable NMIs - we are only looking at
15092 	 * the list, not manipulating it:
15093 	 */
15094 	perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
15095 		ret = inherit_task_group(event, parent, parent_ctx,
15096 					 child, clone_flags, &inherited_all);
15097 		if (ret)
15098 			goto out_unlock;
15099 	}
15100 
15101 	/*
15102 	 * We can't hold ctx->lock when iterating the ->flexible_group list due
15103 	 * to allocations, but we need to prevent rotation because
15104 	 * rotate_ctx() will change the list from interrupt context.
15105 	 */
15106 	raw_spin_lock_irqsave(&parent_ctx->lock, flags);
15107 	parent_ctx->rotate_disable = 1;
15108 	raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
15109 
15110 	perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
15111 		ret = inherit_task_group(event, parent, parent_ctx,
15112 					 child, clone_flags, &inherited_all);
15113 		if (ret)
15114 			goto out_unlock;
15115 	}
15116 
15117 	raw_spin_lock_irqsave(&parent_ctx->lock, flags);
15118 	parent_ctx->rotate_disable = 0;
15119 
15120 	child_ctx = child->perf_event_ctxp;
15121 
15122 	if (child_ctx && inherited_all) {
15123 		/*
15124 		 * Mark the child context as a clone of the parent
15125 		 * context, or of whatever the parent is a clone of.
15126 		 *
15127 		 * Note that if the parent is a clone, the holding of
15128 		 * parent_ctx->lock avoids it from being uncloned.
15129 		 */
15130 		cloned_ctx = parent_ctx->parent_ctx;
15131 		if (cloned_ctx) {
15132 			child_ctx->parent_ctx = cloned_ctx;
15133 			child_ctx->parent_gen = parent_ctx->parent_gen;
15134 		} else {
15135 			child_ctx->parent_ctx = parent_ctx;
15136 			child_ctx->parent_gen = parent_ctx->generation;
15137 		}
15138 		get_ctx(child_ctx->parent_ctx);
15139 	}
15140 
15141 	raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
15142 out_unlock:
15143 	mutex_unlock(&parent_ctx->mutex);
15144 
15145 	perf_unpin_context(parent_ctx);
15146 	put_ctx(parent_ctx);
15147 
15148 	return ret;
15149 }
15150 
15151 /*
15152  * Initialize the perf_event context in task_struct
15153  */
15154 int perf_event_init_task(struct task_struct *child, u64 clone_flags)
15155 {
15156 	int ret;
15157 
15158 	memset(child->perf_recursion, 0, sizeof(child->perf_recursion));
15159 	child->perf_event_ctxp = NULL;
15160 	mutex_init(&child->perf_event_mutex);
15161 	INIT_LIST_HEAD(&child->perf_event_list);
15162 	child->perf_ctx_data = NULL;
15163 
15164 	ret = perf_event_init_context(child, clone_flags);
15165 	if (ret) {
15166 		perf_event_free_task(child);
15167 		return ret;
15168 	}
15169 
15170 	return 0;
15171 }
15172 
15173 static void __init perf_event_init_all_cpus(void)
15174 {
15175 	struct swevent_htable *swhash;
15176 	struct perf_cpu_context *cpuctx;
15177 	int cpu;
15178 
15179 	zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
15180 	zalloc_cpumask_var(&perf_online_core_mask, GFP_KERNEL);
15181 	zalloc_cpumask_var(&perf_online_die_mask, GFP_KERNEL);
15182 	zalloc_cpumask_var(&perf_online_cluster_mask, GFP_KERNEL);
15183 	zalloc_cpumask_var(&perf_online_pkg_mask, GFP_KERNEL);
15184 	zalloc_cpumask_var(&perf_online_sys_mask, GFP_KERNEL);
15185 
15186 
15187 	for_each_possible_cpu(cpu) {
15188 		swhash = &per_cpu(swevent_htable, cpu);
15189 		mutex_init(&swhash->hlist_mutex);
15190 
15191 		INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
15192 		raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
15193 
15194 		INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
15195 
15196 		cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
15197 		__perf_event_init_context(&cpuctx->ctx);
15198 		lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
15199 		lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
15200 		cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
15201 		cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
15202 		cpuctx->heap = cpuctx->heap_default;
15203 	}
15204 }
15205 
15206 static void perf_swevent_init_cpu(unsigned int cpu)
15207 {
15208 	struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
15209 
15210 	mutex_lock(&swhash->hlist_mutex);
15211 	if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
15212 		struct swevent_hlist *hlist;
15213 
15214 		hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
15215 		WARN_ON(!hlist);
15216 		rcu_assign_pointer(swhash->swevent_hlist, hlist);
15217 	}
15218 	mutex_unlock(&swhash->hlist_mutex);
15219 }
15220 
15221 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
15222 static void __perf_event_exit_context(void *__info)
15223 {
15224 	struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
15225 	struct perf_event_context *ctx = __info;
15226 	struct perf_event *event;
15227 
15228 	raw_spin_lock(&ctx->lock);
15229 	ctx_sched_out(ctx, NULL, EVENT_TIME);
15230 	list_for_each_entry(event, &ctx->event_list, event_entry)
15231 		__perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
15232 	raw_spin_unlock(&ctx->lock);
15233 }
15234 
15235 static void perf_event_clear_cpumask(unsigned int cpu)
15236 {
15237 	int target[PERF_PMU_MAX_SCOPE];
15238 	unsigned int scope;
15239 	struct pmu *pmu;
15240 
15241 	cpumask_clear_cpu(cpu, perf_online_mask);
15242 
15243 	for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) {
15244 		const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu);
15245 		struct cpumask *pmu_cpumask = perf_scope_cpumask(scope);
15246 
15247 		target[scope] = -1;
15248 		if (WARN_ON_ONCE(!pmu_cpumask || !cpumask))
15249 			continue;
15250 
15251 		if (!cpumask_test_and_clear_cpu(cpu, pmu_cpumask))
15252 			continue;
15253 		target[scope] = cpumask_any_but(cpumask, cpu);
15254 		if (target[scope] < nr_cpu_ids)
15255 			cpumask_set_cpu(target[scope], pmu_cpumask);
15256 	}
15257 
15258 	/* migrate */
15259 	list_for_each_entry(pmu, &pmus, entry) {
15260 		if (pmu->scope == PERF_PMU_SCOPE_NONE ||
15261 		    WARN_ON_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE))
15262 			continue;
15263 
15264 		if (target[pmu->scope] >= 0 && target[pmu->scope] < nr_cpu_ids)
15265 			perf_pmu_migrate_context(pmu, cpu, target[pmu->scope]);
15266 	}
15267 }
15268 
15269 static void perf_event_exit_cpu_context(int cpu)
15270 {
15271 	struct perf_cpu_context *cpuctx;
15272 	struct perf_event_context *ctx;
15273 
15274 	// XXX simplify cpuctx->online
15275 	mutex_lock(&pmus_lock);
15276 	/*
15277 	 * Clear the cpumasks, and migrate to other CPUs if possible.
15278 	 * Must be invoked before the __perf_event_exit_context.
15279 	 */
15280 	perf_event_clear_cpumask(cpu);
15281 	cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
15282 	ctx = &cpuctx->ctx;
15283 
15284 	mutex_lock(&ctx->mutex);
15285 	if (ctx->nr_events)
15286 		smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
15287 	cpuctx->online = 0;
15288 	mutex_unlock(&ctx->mutex);
15289 	mutex_unlock(&pmus_lock);
15290 }
15291 #else
15292 
15293 static void perf_event_exit_cpu_context(int cpu) { }
15294 
15295 #endif
15296 
15297 static void perf_event_setup_cpumask(unsigned int cpu)
15298 {
15299 	struct cpumask *pmu_cpumask;
15300 	unsigned int scope;
15301 
15302 	/*
15303 	 * Early boot stage, the cpumask hasn't been set yet.
15304 	 * The perf_online_<domain>_masks includes the first CPU of each domain.
15305 	 * Always unconditionally set the boot CPU for the perf_online_<domain>_masks.
15306 	 */
15307 	if (cpumask_empty(perf_online_mask)) {
15308 		for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) {
15309 			pmu_cpumask = perf_scope_cpumask(scope);
15310 			if (WARN_ON_ONCE(!pmu_cpumask))
15311 				continue;
15312 			cpumask_set_cpu(cpu, pmu_cpumask);
15313 		}
15314 		goto end;
15315 	}
15316 
15317 	for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) {
15318 		const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu);
15319 
15320 		pmu_cpumask = perf_scope_cpumask(scope);
15321 
15322 		if (WARN_ON_ONCE(!pmu_cpumask || !cpumask))
15323 			continue;
15324 
15325 		if (!cpumask_empty(cpumask) &&
15326 		    cpumask_any_and(pmu_cpumask, cpumask) >= nr_cpu_ids)
15327 			cpumask_set_cpu(cpu, pmu_cpumask);
15328 	}
15329 end:
15330 	cpumask_set_cpu(cpu, perf_online_mask);
15331 }
15332 
15333 int perf_event_init_cpu(unsigned int cpu)
15334 {
15335 	struct perf_cpu_context *cpuctx;
15336 	struct perf_event_context *ctx;
15337 
15338 	perf_swevent_init_cpu(cpu);
15339 
15340 	mutex_lock(&pmus_lock);
15341 	perf_event_setup_cpumask(cpu);
15342 	cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
15343 	ctx = &cpuctx->ctx;
15344 
15345 	mutex_lock(&ctx->mutex);
15346 	cpuctx->online = 1;
15347 	mutex_unlock(&ctx->mutex);
15348 	mutex_unlock(&pmus_lock);
15349 
15350 	return 0;
15351 }
15352 
15353 int perf_event_exit_cpu(unsigned int cpu)
15354 {
15355 	perf_event_exit_cpu_context(cpu);
15356 	return 0;
15357 }
15358 
15359 static int
15360 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
15361 {
15362 	int cpu;
15363 
15364 	for_each_online_cpu(cpu)
15365 		perf_event_exit_cpu(cpu);
15366 
15367 	return NOTIFY_OK;
15368 }
15369 
15370 /*
15371  * Run the perf reboot notifier at the very last possible moment so that
15372  * the generic watchdog code runs as long as possible.
15373  */
15374 static struct notifier_block perf_reboot_notifier = {
15375 	.notifier_call = perf_reboot,
15376 	.priority = INT_MIN,
15377 };
15378 
15379 void __init perf_event_init(void)
15380 {
15381 	int ret;
15382 
15383 	idr_init(&pmu_idr);
15384 
15385 	unwind_deferred_init(&perf_unwind_work,
15386 			     perf_unwind_deferred_callback);
15387 
15388 	perf_event_init_all_cpus();
15389 	init_srcu_struct(&pmus_srcu);
15390 	perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
15391 	perf_pmu_register(&perf_cpu_clock, "cpu_clock", -1);
15392 	perf_pmu_register(&perf_task_clock, "task_clock", -1);
15393 	perf_tp_register();
15394 	perf_event_init_cpu(smp_processor_id());
15395 	register_reboot_notifier(&perf_reboot_notifier);
15396 
15397 	ret = init_hw_breakpoint();
15398 	WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
15399 
15400 	perf_event_cache = KMEM_CACHE(perf_event, SLAB_PANIC);
15401 
15402 	/*
15403 	 * Build time assertion that we keep the data_head at the intended
15404 	 * location.  IOW, validation we got the __reserved[] size right.
15405 	 */
15406 	BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
15407 		     != 1024);
15408 }
15409 
15410 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
15411 			      char *page)
15412 {
15413 	struct perf_pmu_events_attr *pmu_attr =
15414 		container_of(attr, struct perf_pmu_events_attr, attr);
15415 
15416 	if (pmu_attr->event_str)
15417 		return sprintf(page, "%s\n", pmu_attr->event_str);
15418 
15419 	return 0;
15420 }
15421 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
15422 
15423 static int __init perf_event_sysfs_init(void)
15424 {
15425 	struct pmu *pmu;
15426 	int ret;
15427 
15428 	mutex_lock(&pmus_lock);
15429 
15430 	ret = bus_register(&pmu_bus);
15431 	if (ret)
15432 		goto unlock;
15433 
15434 	list_for_each_entry(pmu, &pmus, entry) {
15435 		if (pmu->dev)
15436 			continue;
15437 
15438 		ret = pmu_dev_alloc(pmu);
15439 		WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
15440 	}
15441 	pmu_bus_running = 1;
15442 	ret = 0;
15443 
15444 unlock:
15445 	mutex_unlock(&pmus_lock);
15446 
15447 	return ret;
15448 }
15449 device_initcall(perf_event_sysfs_init);
15450 
15451 #ifdef CONFIG_CGROUP_PERF
15452 static struct cgroup_subsys_state *
15453 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
15454 {
15455 	struct perf_cgroup *jc;
15456 
15457 	jc = kzalloc_obj(*jc);
15458 	if (!jc)
15459 		return ERR_PTR(-ENOMEM);
15460 
15461 	jc->info = alloc_percpu(struct perf_cgroup_info);
15462 	if (!jc->info) {
15463 		kfree(jc);
15464 		return ERR_PTR(-ENOMEM);
15465 	}
15466 
15467 	return &jc->css;
15468 }
15469 
15470 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
15471 {
15472 	struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
15473 
15474 	free_percpu(jc->info);
15475 	kfree(jc);
15476 }
15477 
15478 static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
15479 {
15480 	perf_event_cgroup(css->cgroup);
15481 	return 0;
15482 }
15483 
15484 static int __perf_cgroup_move(void *info)
15485 {
15486 	struct task_struct *task = info;
15487 
15488 	preempt_disable();
15489 	perf_cgroup_switch(task);
15490 	preempt_enable();
15491 
15492 	return 0;
15493 }
15494 
15495 static void perf_cgroup_attach(struct cgroup_taskset *tset)
15496 {
15497 	struct task_struct *task;
15498 	struct cgroup_subsys_state *css;
15499 
15500 	cgroup_taskset_for_each(task, css, tset)
15501 		task_function_call(task, __perf_cgroup_move, task);
15502 }
15503 
15504 struct cgroup_subsys perf_event_cgrp_subsys = {
15505 	.css_alloc	= perf_cgroup_css_alloc,
15506 	.css_free	= perf_cgroup_css_free,
15507 	.css_online	= perf_cgroup_css_online,
15508 	.attach		= perf_cgroup_attach,
15509 	/*
15510 	 * Implicitly enable on dfl hierarchy so that perf events can
15511 	 * always be filtered by cgroup2 path as long as perf_event
15512 	 * controller is not mounted on a legacy hierarchy.
15513 	 */
15514 	.implicit_on_dfl = true,
15515 	.threaded	= true,
15516 };
15517 #endif /* CONFIG_CGROUP_PERF */
15518 
15519 DEFINE_STATIC_CALL_RET0(perf_snapshot_branch_stack, perf_snapshot_branch_stack_t);
15520