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