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