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