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