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