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