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