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