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