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