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