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