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