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