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