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