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