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