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