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