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