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