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