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