xref: /linux/kernel/kcov.c (revision 1b78070aaef63512688aebfbc82365ef9d6660f1)
1 // SPDX-License-Identifier: GPL-2.0
2 #define pr_fmt(fmt) "kcov: " fmt
3 
4 #define DISABLE_BRANCH_PROFILING
5 #include <linux/atomic.h>
6 #include <linux/compiler.h>
7 #include <linux/errno.h>
8 #include <linux/export.h>
9 #include <linux/types.h>
10 #include <linux/file.h>
11 #include <linux/fs.h>
12 #include <linux/hashtable.h>
13 #include <linux/init.h>
14 #include <linux/jiffies.h>
15 #include <linux/kmsan-checks.h>
16 #include <linux/mm.h>
17 #include <linux/preempt.h>
18 #include <linux/printk.h>
19 #include <linux/sched.h>
20 #include <linux/slab.h>
21 #include <linux/spinlock.h>
22 #include <linux/vmalloc.h>
23 #include <linux/debugfs.h>
24 #include <linux/uaccess.h>
25 #include <linux/kcov.h>
26 #include <linux/refcount.h>
27 #include <linux/log2.h>
28 #include <asm/setup.h>
29 
30 #define kcov_debug(fmt, ...) pr_debug("%s: " fmt, __func__, ##__VA_ARGS__)
31 
32 /* Number of 64-bit words written per one comparison: */
33 #define KCOV_WORDS_PER_CMP 4
34 
35 /*
36  * kcov descriptor (one per opened debugfs file).
37  * State transitions of the descriptor:
38  *  - initial state after open()
39  *  - then there must be a single ioctl(KCOV_INIT_TRACE) call
40  *  - then, mmap() call (several calls are allowed but not useful)
41  *  - then, ioctl(KCOV_ENABLE, arg), where arg is
42  *	KCOV_TRACE_PC - to trace only the PCs
43  *	or
44  *	KCOV_TRACE_CMP - to trace only the comparison operands
45  *  - then, ioctl(KCOV_DISABLE) to disable the task.
46  * Enabling/disabling ioctls can be repeated (only one task a time allowed).
47  */
48 struct kcov {
49 	/*
50 	 * Reference counter. We keep one for:
51 	 *  - opened file descriptor
52 	 *  - task with enabled coverage (we can't unwire it from another task)
53 	 *  - each code section for remote coverage collection
54 	 */
55 	refcount_t		refcount;
56 	/* The lock protects mode, size, area and t. */
57 	spinlock_t		lock;
58 	enum kcov_mode		mode __guarded_by(&lock);
59 	/* Size of arena (in long's). */
60 	unsigned int		size __guarded_by(&lock);
61 	/* Coverage buffer shared with user space. */
62 	void			*area __guarded_by(&lock);
63 	/* Task for which we collect coverage, or NULL. */
64 	struct task_struct	*t __guarded_by(&lock);
65 	/* Collecting coverage from remote (background) threads. */
66 	bool			remote;
67 	/* Size of remote area (in long's). */
68 	unsigned int		remote_size;
69 	/*
70 	 * Sequence is incremented each time kcov is reenabled, used by
71 	 * kcov_remote_stop(), see the comment there.
72 	 */
73 	int			sequence;
74 };
75 
76 struct kcov_remote_area {
77 	struct list_head	list;
78 	unsigned int		size;
79 };
80 
81 struct kcov_remote {
82 	u64			handle;
83 	struct kcov		*kcov;
84 	struct hlist_node	hnode;
85 };
86 
87 static DEFINE_SPINLOCK(kcov_remote_lock);
88 static DEFINE_HASHTABLE(kcov_remote_map, 4);
89 static struct list_head kcov_remote_areas[2] = {
90 	LIST_HEAD_INIT(kcov_remote_areas[0]), LIST_HEAD_INIT(kcov_remote_areas[1])
91 };
92 
93 struct kcov_percpu_data {
94 	local_lock_t		lock;
95 };
96 
97 static DEFINE_PER_CPU(struct kcov_percpu_data, kcov_percpu_data) = {
98 	.lock = INIT_LOCAL_LOCK(lock),
99 };
100 
101 /* Must be called with kcov_remote_lock locked. */
102 static struct kcov_remote *kcov_remote_find(u64 handle)
103 {
104 	struct kcov_remote *remote;
105 
106 	hash_for_each_possible(kcov_remote_map, remote, hnode, handle) {
107 		if (remote->handle == handle)
108 			return remote;
109 	}
110 	return NULL;
111 }
112 
113 /* Must be called with kcov_remote_lock locked. */
114 static struct kcov_remote *kcov_remote_add(struct kcov *kcov, u64 handle)
115 {
116 	struct kcov_remote *remote;
117 
118 	if (kcov_remote_find(handle))
119 		return ERR_PTR(-EEXIST);
120 	remote = kmalloc_obj(*remote, GFP_ATOMIC);
121 	if (!remote)
122 		return ERR_PTR(-ENOMEM);
123 	remote->handle = handle;
124 	remote->kcov = kcov;
125 	hash_add(kcov_remote_map, &remote->hnode, handle);
126 	return remote;
127 }
128 
129 /* Must be called with kcov_remote_lock locked. */
130 static struct kcov_remote_area *kcov_remote_area_get(unsigned int size, bool irq)
131 {
132 	struct kcov_remote_area *area;
133 	struct list_head *pos;
134 	struct list_head *list = &kcov_remote_areas[irq];
135 
136 	list_for_each(pos, list) {
137 		area = list_entry(pos, struct kcov_remote_area, list);
138 		if (area->size == size) {
139 			list_del(&area->list);
140 			return area;
141 		}
142 	}
143 	return NULL;
144 }
145 
146 /* Must be called with kcov_remote_lock locked. */
147 static void kcov_remote_area_put(struct kcov_remote_area *area,
148 				 unsigned int size, bool irq)
149 {
150 	INIT_LIST_HEAD(&area->list);
151 	area->size = size;
152 	list_add(&area->list, &kcov_remote_areas[irq]);
153 	/*
154 	 * KMSAN doesn't instrument this file, so it may not know area->list
155 	 * is initialized. Unpoison it explicitly to avoid reports in
156 	 * kcov_remote_area_get().
157 	 */
158 	kmsan_unpoison_memory(&area->list, sizeof(area->list));
159 }
160 
161 /*
162  * Unlike in_serving_softirq(), this function returns false when called during
163  * a hardirq or an NMI that happened in the softirq context.
164  */
165 static __always_inline bool in_softirq_really(void)
166 {
167 	return in_serving_softirq() && !in_hardirq() && !in_nmi();
168 }
169 
170 static notrace bool check_kcov_mode(enum kcov_mode needed_mode, struct task_struct *t)
171 {
172 	unsigned int mode;
173 
174 	/*
175 	 * We are interested in code coverage as a function of a syscall inputs,
176 	 * so we ignore code executed in interrupts, unless we are in a remote
177 	 * coverage collection section in a softirq.
178 	 */
179 	if (!in_task() && !(in_softirq_really() && t->kcov_softirq))
180 		return false;
181 	mode = READ_ONCE(t->kcov_mode);
182 	/*
183 	 * There is some code that runs in interrupts but for which
184 	 * in_interrupt() returns false (e.g. preempt_schedule_irq()).
185 	 * READ_ONCE()/barrier() effectively provides load-acquire wrt
186 	 * interrupts, there are paired barrier()/WRITE_ONCE() in
187 	 * kcov_start().
188 	 */
189 	barrier();
190 	return mode == needed_mode;
191 }
192 
193 static notrace unsigned long canonicalize_ip(unsigned long ip)
194 {
195 #ifdef CONFIG_RANDOMIZE_BASE
196 	ip -= kaslr_offset();
197 #endif
198 	return ip;
199 }
200 
201 /*
202  * Entry point from instrumented code.
203  * This is called once per basic-block/edge.
204  */
205 void notrace __sanitizer_cov_trace_pc(void)
206 {
207 	struct task_struct *t;
208 	unsigned long *area;
209 	unsigned long ip = canonicalize_ip(_RET_IP_);
210 	unsigned long pos;
211 
212 	t = current;
213 	if (!check_kcov_mode(KCOV_MODE_TRACE_PC, t))
214 		return;
215 
216 	area = t->kcov_area;
217 	/* The first 64-bit word is the number of subsequent PCs. */
218 	pos = READ_ONCE(area[0]) + 1;
219 	if (likely(pos < t->kcov_size)) {
220 		/* Previously we write pc before updating pos. However, some
221 		 * early interrupt code could bypass check_kcov_mode() check
222 		 * and invoke __sanitizer_cov_trace_pc(). If such interrupt is
223 		 * raised between writing pc and updating pos, the pc could be
224 		 * overitten by the recursive __sanitizer_cov_trace_pc().
225 		 * Update pos before writing pc to avoid such interleaving.
226 		 */
227 		WRITE_ONCE(area[0], pos);
228 		barrier();
229 		area[pos] = ip;
230 	}
231 }
232 EXPORT_SYMBOL(__sanitizer_cov_trace_pc);
233 
234 #ifdef CONFIG_KCOV_ENABLE_COMPARISONS
235 static void notrace write_comp_data(u64 type, u64 arg1, u64 arg2, u64 ip)
236 {
237 	struct task_struct *t;
238 	u64 *area;
239 	u64 count, start_index, end_pos, max_pos;
240 
241 	t = current;
242 	if (!check_kcov_mode(KCOV_MODE_TRACE_CMP, t))
243 		return;
244 
245 	ip = canonicalize_ip(ip);
246 
247 	/*
248 	 * We write all comparison arguments and types as u64.
249 	 * The buffer was allocated for t->kcov_size unsigned longs.
250 	 */
251 	area = (u64 *)t->kcov_area;
252 	max_pos = t->kcov_size * sizeof(unsigned long);
253 
254 	count = READ_ONCE(area[0]);
255 
256 	/* Every record is KCOV_WORDS_PER_CMP 64-bit words. */
257 	start_index = 1 + count * KCOV_WORDS_PER_CMP;
258 	end_pos = (start_index + KCOV_WORDS_PER_CMP) * sizeof(u64);
259 	if (likely(end_pos <= max_pos)) {
260 		/* See comment in __sanitizer_cov_trace_pc(). */
261 		WRITE_ONCE(area[0], count + 1);
262 		barrier();
263 		area[start_index] = type;
264 		area[start_index + 1] = arg1;
265 		area[start_index + 2] = arg2;
266 		area[start_index + 3] = ip;
267 	}
268 }
269 
270 void notrace __sanitizer_cov_trace_cmp1(u8 arg1, u8 arg2)
271 {
272 	write_comp_data(KCOV_CMP_SIZE(0), arg1, arg2, _RET_IP_);
273 }
274 EXPORT_SYMBOL(__sanitizer_cov_trace_cmp1);
275 
276 void notrace __sanitizer_cov_trace_cmp2(u16 arg1, u16 arg2)
277 {
278 	write_comp_data(KCOV_CMP_SIZE(1), arg1, arg2, _RET_IP_);
279 }
280 EXPORT_SYMBOL(__sanitizer_cov_trace_cmp2);
281 
282 void notrace __sanitizer_cov_trace_cmp4(u32 arg1, u32 arg2)
283 {
284 	write_comp_data(KCOV_CMP_SIZE(2), arg1, arg2, _RET_IP_);
285 }
286 EXPORT_SYMBOL(__sanitizer_cov_trace_cmp4);
287 
288 void notrace __sanitizer_cov_trace_cmp8(kcov_u64 arg1, kcov_u64 arg2)
289 {
290 	write_comp_data(KCOV_CMP_SIZE(3), arg1, arg2, _RET_IP_);
291 }
292 EXPORT_SYMBOL(__sanitizer_cov_trace_cmp8);
293 
294 void notrace __sanitizer_cov_trace_const_cmp1(u8 arg1, u8 arg2)
295 {
296 	write_comp_data(KCOV_CMP_SIZE(0) | KCOV_CMP_CONST, arg1, arg2,
297 			_RET_IP_);
298 }
299 EXPORT_SYMBOL(__sanitizer_cov_trace_const_cmp1);
300 
301 void notrace __sanitizer_cov_trace_const_cmp2(u16 arg1, u16 arg2)
302 {
303 	write_comp_data(KCOV_CMP_SIZE(1) | KCOV_CMP_CONST, arg1, arg2,
304 			_RET_IP_);
305 }
306 EXPORT_SYMBOL(__sanitizer_cov_trace_const_cmp2);
307 
308 void notrace __sanitizer_cov_trace_const_cmp4(u32 arg1, u32 arg2)
309 {
310 	write_comp_data(KCOV_CMP_SIZE(2) | KCOV_CMP_CONST, arg1, arg2,
311 			_RET_IP_);
312 }
313 EXPORT_SYMBOL(__sanitizer_cov_trace_const_cmp4);
314 
315 void notrace __sanitizer_cov_trace_const_cmp8(kcov_u64 arg1, kcov_u64 arg2)
316 {
317 	write_comp_data(KCOV_CMP_SIZE(3) | KCOV_CMP_CONST, arg1, arg2,
318 			_RET_IP_);
319 }
320 EXPORT_SYMBOL(__sanitizer_cov_trace_const_cmp8);
321 
322 void notrace __sanitizer_cov_trace_switch(kcov_u64 val, void *arg)
323 {
324 	u64 i;
325 	u64 *cases = arg;
326 	u64 count = cases[0];
327 	u64 size = cases[1];
328 	u64 type = KCOV_CMP_CONST;
329 
330 	switch (size) {
331 	case 8:
332 		type |= KCOV_CMP_SIZE(0);
333 		break;
334 	case 16:
335 		type |= KCOV_CMP_SIZE(1);
336 		break;
337 	case 32:
338 		type |= KCOV_CMP_SIZE(2);
339 		break;
340 	case 64:
341 		type |= KCOV_CMP_SIZE(3);
342 		break;
343 	default:
344 		return;
345 	}
346 	for (i = 0; i < count; i++)
347 		write_comp_data(type, cases[i + 2], val, _RET_IP_);
348 }
349 EXPORT_SYMBOL(__sanitizer_cov_trace_switch);
350 #endif /* ifdef CONFIG_KCOV_ENABLE_COMPARISONS */
351 
352 static void kcov_start(struct task_struct *t, struct kcov *kcov,
353 			unsigned int size, void *area, enum kcov_mode mode,
354 			int sequence)
355 {
356 	kcov_debug("t = %px, size = %u, area = %px\n", t, size, area);
357 	t->kcov = kcov;
358 	/* Cache in task struct for performance. */
359 	t->kcov_size = size;
360 	t->kcov_area = area;
361 	t->kcov_sequence = sequence;
362 	/* See comment in check_kcov_mode(). */
363 	barrier();
364 	WRITE_ONCE(t->kcov_mode, mode);
365 }
366 
367 /* operates on coverage-generator-owned fields */
368 static void kcov_stop(struct task_struct *t)
369 {
370 	WRITE_ONCE(t->kcov_mode, KCOV_MODE_DISABLED);
371 	barrier();
372 	t->kcov = NULL;
373 	t->kcov_size = 0;
374 	t->kcov_area = NULL;
375 }
376 
377 /* operates on coverage-generator-owned fields */
378 static void kcov_task_reset(struct task_struct *t)
379 {
380 	kcov_stop(t);
381 	t->kcov_sequence = 0;
382 }
383 
384 void kcov_task_init(struct task_struct *t)
385 {
386 	kcov_task_reset(t);
387 	t->kcov_remote = NULL;
388 	t->kcov_handle = current->kcov_handle;
389 	t->kcov_softirq = 0;
390 	t->kcov_saved_mode = 0;
391 	t->kcov_saved_size = 0;
392 	t->kcov_saved_area = NULL;
393 	t->kcov_saved_kcov = NULL;
394 	t->kcov_saved_sequence = 0;
395 }
396 
397 static void kcov_reset(struct kcov *kcov)
398 	__must_hold(&kcov->lock)
399 {
400 	kcov->t = NULL;
401 	kcov->mode = KCOV_MODE_INIT;
402 	kcov->remote = false;
403 	kcov->remote_size = 0;
404 	kcov->sequence++;
405 }
406 
407 static void kcov_remote_reset(struct kcov *kcov)
408 	__must_hold(&kcov->lock)
409 {
410 	int bkt;
411 	struct kcov_remote *remote;
412 	struct hlist_node *tmp;
413 	unsigned long flags;
414 
415 	spin_lock_irqsave(&kcov_remote_lock, flags);
416 	hash_for_each_safe(kcov_remote_map, bkt, tmp, remote, hnode) {
417 		if (remote->kcov != kcov)
418 			continue;
419 		hash_del(&remote->hnode);
420 		kfree(remote);
421 	}
422 	/* Do reset before unlock to prevent races with kcov_remote_start(). */
423 	kcov_reset(kcov);
424 	spin_unlock_irqrestore(&kcov_remote_lock, flags);
425 }
426 
427 static void kcov_disable(struct task_struct *t, struct kcov *kcov)
428 	__must_hold(&kcov->lock)
429 {
430 	if (kcov->remote) {
431 		t->kcov_handle = 0;
432 		t->kcov_remote = NULL;
433 		kcov_remote_reset(kcov);
434 	} else {
435 		kcov_task_reset(t);
436 		kcov_reset(kcov);
437 	}
438 }
439 
440 static void kcov_get(struct kcov *kcov)
441 {
442 	refcount_inc(&kcov->refcount);
443 }
444 
445 static void kcov_put(struct kcov *kcov)
446 {
447 	if (refcount_dec_and_test(&kcov->refcount)) {
448 		/* Context-safety: no references left, object being destroyed. */
449 		context_unsafe(
450 			kcov_remote_reset(kcov);
451 			vfree(kcov->area);
452 		);
453 		kfree(kcov);
454 	}
455 }
456 
457 void kcov_task_exit(struct task_struct *t)
458 {
459 	struct kcov *kcov;
460 	unsigned long flags;
461 
462 	kcov = t->kcov;
463 	if (kcov) {
464 		spin_lock_irqsave(&kcov->lock, flags);
465 		kcov_debug("t = %px, kcov->t = %px\n", t, kcov->t);
466 		/*
467 		 * This could be a remote task between kcov_remote_start() and
468 		 * kcov_remote_stop().
469 		 * In this case we should print a warning right away, since a
470 		 * task shouldn't be exiting when it's in a kcov coverage
471 		 * collection section.
472 		 *
473 		 * Otherwise, this should be a task that created a local
474 		 * kcov instance and hasn't called KCOV_DISABLE.
475 		 * Make sure that t->kcov->t is consistent.
476 		 */
477 		if (WARN_ON(kcov->remote) || WARN_ON(kcov->t != t)) {
478 			spin_unlock_irqrestore(&kcov->lock, flags);
479 			return;
480 		}
481 		/* Just to not leave dangling references behind. */
482 		kcov_disable(t, kcov);
483 		spin_unlock_irqrestore(&kcov->lock, flags);
484 		kcov_put(kcov);
485 	}
486 	kcov = t->kcov_remote;
487 	if (kcov) {
488 		spin_lock_irqsave(&kcov->lock, flags);
489 		kcov_debug("t = %px, kcov->t = %px\n", t, kcov->t);
490 		/*
491 		 * This is a KCOV_REMOTE_ENABLE device, and the task is the
492 		 * user task which has requested remote coverage collection.
493 		 * Make sure that t->kcov->t is consistent.
494 		 */
495 		if (WARN_ON(!kcov->remote) || WARN_ON(kcov->t != t)) {
496 			spin_unlock_irqrestore(&kcov->lock, flags);
497 			return;
498 		}
499 		/* Just to not leave dangling references behind. */
500 		kcov_disable(t, kcov);
501 		spin_unlock_irqrestore(&kcov->lock, flags);
502 		kcov_put(kcov);
503 	}
504 }
505 
506 static int kcov_mmap(struct file *filep, struct vm_area_struct *vma)
507 {
508 	int res = 0;
509 	struct kcov *kcov = vma->vm_file->private_data;
510 	unsigned long size, off;
511 	struct page *page;
512 	unsigned long flags;
513 	void *area;
514 
515 	spin_lock_irqsave(&kcov->lock, flags);
516 	size = kcov->size * sizeof(unsigned long);
517 	if (kcov->area == NULL || vma_start_pgoff(vma) ||
518 	    vma->vm_end - vma->vm_start != size) {
519 		res = -EINVAL;
520 		goto exit;
521 	}
522 	area = kcov->area;
523 	spin_unlock_irqrestore(&kcov->lock, flags);
524 	vm_flags_set(vma, VM_DONTEXPAND);
525 	for (off = 0; off < size; off += PAGE_SIZE) {
526 		page = vmalloc_to_page(area + off);
527 		res = vm_insert_page(vma, vma->vm_start + off, page);
528 		if (res) {
529 			pr_warn_once("kcov: vm_insert_page() failed\n");
530 			return res;
531 		}
532 	}
533 	return 0;
534 exit:
535 	spin_unlock_irqrestore(&kcov->lock, flags);
536 	return res;
537 }
538 
539 static int kcov_open(struct inode *inode, struct file *filep)
540 {
541 	struct kcov *kcov;
542 
543 	kcov = kzalloc_obj(*kcov);
544 	if (!kcov)
545 		return -ENOMEM;
546 	guard(spinlock_init)(&kcov->lock);
547 	kcov->mode = KCOV_MODE_DISABLED;
548 	kcov->sequence = 1;
549 	refcount_set(&kcov->refcount, 1);
550 	filep->private_data = kcov;
551 	return nonseekable_open(inode, filep);
552 }
553 
554 static int kcov_close(struct inode *inode, struct file *filep)
555 {
556 	kcov_put(filep->private_data);
557 	return 0;
558 }
559 
560 static int kcov_get_mode(unsigned long arg)
561 {
562 	if (arg == KCOV_TRACE_PC)
563 		return KCOV_MODE_TRACE_PC;
564 	else if (arg == KCOV_TRACE_CMP)
565 #ifdef CONFIG_KCOV_ENABLE_COMPARISONS
566 		return KCOV_MODE_TRACE_CMP;
567 #else
568 		return -ENOTSUPP;
569 #endif
570 	else
571 		return -EINVAL;
572 }
573 
574 /*
575  * Fault in a lazily-faulted vmalloc area before it can be used by
576  * __sanitizer_cov_trace_pc(), to avoid recursion issues if any code on the
577  * vmalloc fault handling path is instrumented.
578  */
579 static void kcov_fault_in_area(struct kcov *kcov)
580 	__must_hold(&kcov->lock)
581 {
582 	unsigned long stride = PAGE_SIZE / sizeof(unsigned long);
583 	unsigned long *area = kcov->area;
584 	unsigned long offset;
585 
586 	for (offset = 0; offset < kcov->size; offset += stride)
587 		READ_ONCE(area[offset]);
588 }
589 
590 static inline bool kcov_check_handle(u64 handle, bool common_valid,
591 				bool uncommon_valid, bool zero_valid)
592 {
593 	if (handle & ~(KCOV_SUBSYSTEM_MASK | KCOV_INSTANCE_MASK))
594 		return false;
595 	switch (handle & KCOV_SUBSYSTEM_MASK) {
596 	case KCOV_SUBSYSTEM_COMMON:
597 		return (handle & KCOV_INSTANCE_MASK) ?
598 			common_valid : zero_valid;
599 	case KCOV_SUBSYSTEM_USB:
600 		return uncommon_valid;
601 	default:
602 		return false;
603 	}
604 	return false;
605 }
606 
607 static int kcov_ioctl_locked(struct kcov *kcov, unsigned int cmd,
608 			     unsigned long arg)
609 	__must_hold(&kcov->lock)
610 {
611 	struct task_struct *t;
612 	unsigned long flags, unused;
613 	int mode, i;
614 	struct kcov_remote_arg *remote_arg;
615 	struct kcov_remote *remote;
616 
617 	switch (cmd) {
618 	case KCOV_ENABLE:
619 		/*
620 		 * Enable coverage for the current task.
621 		 * At this point user must have been enabled trace mode,
622 		 * and mmapped the file. Coverage collection is disabled only
623 		 * at task exit or voluntary by KCOV_DISABLE. After that it can
624 		 * be enabled for another task.
625 		 */
626 		if (kcov->mode != KCOV_MODE_INIT || !kcov->area)
627 			return -EINVAL;
628 		t = current;
629 		if (kcov->t != NULL || t->kcov != NULL)
630 			return -EBUSY;
631 		mode = kcov_get_mode(arg);
632 		if (mode < 0)
633 			return mode;
634 		kcov_fault_in_area(kcov);
635 		kcov->mode = mode;
636 		kcov_start(t, kcov, kcov->size, kcov->area, kcov->mode,
637 				kcov->sequence);
638 		kcov->t = t;
639 		/* Put either in kcov_task_exit() or in KCOV_DISABLE. */
640 		kcov_get(kcov);
641 		return 0;
642 	case KCOV_DISABLE:
643 		/* Disable coverage for the current task. */
644 		unused = arg;
645 		t = current;
646 		if (unused != 0 || (kcov != t->kcov && kcov != t->kcov_remote))
647 			return -EINVAL;
648 		if (WARN_ON(kcov->t != t))
649 			return -EINVAL;
650 		kcov_disable(t, kcov);
651 		kcov_put(kcov);
652 		return 0;
653 	case KCOV_REMOTE_ENABLE:
654 		if (kcov->mode != KCOV_MODE_INIT || !kcov->area)
655 			return -EINVAL;
656 		t = current;
657 		if (kcov->t != NULL || t->kcov_remote != NULL)
658 			return -EBUSY;
659 		remote_arg = (struct kcov_remote_arg *)arg;
660 		mode = kcov_get_mode(remote_arg->trace_mode);
661 		if (mode < 0)
662 			return mode;
663 		if ((unsigned long)remote_arg->area_size >
664 		    LONG_MAX / sizeof(unsigned long))
665 			return -EINVAL;
666 		kcov->mode = mode;
667 		t->kcov_remote = kcov;
668 		kcov->t = t;
669 		kcov->remote = true;
670 		kcov->remote_size = remote_arg->area_size;
671 		spin_lock_irqsave(&kcov_remote_lock, flags);
672 		for (i = 0; i < remote_arg->num_handles; i++) {
673 			if (!kcov_check_handle(remote_arg->handles[i],
674 						false, true, false)) {
675 				spin_unlock_irqrestore(&kcov_remote_lock,
676 							flags);
677 				kcov_disable(t, kcov);
678 				return -EINVAL;
679 			}
680 			remote = kcov_remote_add(kcov, remote_arg->handles[i]);
681 			if (IS_ERR(remote)) {
682 				spin_unlock_irqrestore(&kcov_remote_lock,
683 							flags);
684 				kcov_disable(t, kcov);
685 				return PTR_ERR(remote);
686 			}
687 		}
688 		if (remote_arg->common_handle) {
689 			if (!kcov_check_handle(remote_arg->common_handle,
690 						true, false, false)) {
691 				spin_unlock_irqrestore(&kcov_remote_lock,
692 							flags);
693 				kcov_disable(t, kcov);
694 				return -EINVAL;
695 			}
696 			remote = kcov_remote_add(kcov,
697 					remote_arg->common_handle);
698 			if (IS_ERR(remote)) {
699 				spin_unlock_irqrestore(&kcov_remote_lock,
700 							flags);
701 				kcov_disable(t, kcov);
702 				return PTR_ERR(remote);
703 			}
704 			t->kcov_handle = remote_arg->common_handle;
705 		}
706 		spin_unlock_irqrestore(&kcov_remote_lock, flags);
707 		/* Put either in kcov_task_exit() or in KCOV_DISABLE. */
708 		kcov_get(kcov);
709 		return 0;
710 	default:
711 		return -ENOTTY;
712 	}
713 }
714 
715 static long kcov_ioctl(struct file *filep, unsigned int cmd, unsigned long arg)
716 {
717 	struct kcov *kcov;
718 	int res;
719 	struct kcov_remote_arg *remote_arg = NULL;
720 	unsigned int remote_num_handles;
721 	unsigned long remote_arg_size;
722 	unsigned long size, flags;
723 	void *area;
724 
725 	kcov = filep->private_data;
726 	switch (cmd) {
727 	case KCOV_INIT_TRACE:
728 		/*
729 		 * Enable kcov in trace mode and setup buffer size.
730 		 * Must happen before anything else.
731 		 *
732 		 * First check the size argument - it must be at least 2
733 		 * to hold the current position and one PC.
734 		 */
735 		size = arg;
736 		if (size < 2 || size > INT_MAX / sizeof(unsigned long))
737 			return -EINVAL;
738 		area = vmalloc_user(size * sizeof(unsigned long));
739 		if (area == NULL)
740 			return -ENOMEM;
741 		spin_lock_irqsave(&kcov->lock, flags);
742 		if (kcov->mode != KCOV_MODE_DISABLED) {
743 			spin_unlock_irqrestore(&kcov->lock, flags);
744 			vfree(area);
745 			return -EBUSY;
746 		}
747 		kcov->area = area;
748 		kcov->size = size;
749 		kcov->mode = KCOV_MODE_INIT;
750 		spin_unlock_irqrestore(&kcov->lock, flags);
751 		return 0;
752 	case KCOV_REMOTE_ENABLE:
753 		if (get_user(remote_num_handles, (unsigned __user *)(arg +
754 				offsetof(struct kcov_remote_arg, num_handles))))
755 			return -EFAULT;
756 		if (remote_num_handles > KCOV_REMOTE_MAX_HANDLES)
757 			return -EINVAL;
758 		remote_arg_size = struct_size(remote_arg, handles,
759 					remote_num_handles);
760 		remote_arg = memdup_user((void __user *)arg, remote_arg_size);
761 		if (IS_ERR(remote_arg))
762 			return PTR_ERR(remote_arg);
763 		if (remote_arg->num_handles != remote_num_handles) {
764 			kfree(remote_arg);
765 			return -EINVAL;
766 		}
767 		arg = (unsigned long)remote_arg;
768 		fallthrough;
769 	default:
770 		/*
771 		 * All other commands can be normally executed under a spin lock, so we
772 		 * obtain and release it here in order to simplify kcov_ioctl_locked().
773 		 */
774 		spin_lock_irqsave(&kcov->lock, flags);
775 		res = kcov_ioctl_locked(kcov, cmd, arg);
776 		spin_unlock_irqrestore(&kcov->lock, flags);
777 		kfree(remote_arg);
778 		return res;
779 	}
780 }
781 
782 static const struct file_operations kcov_fops = {
783 	.open		= kcov_open,
784 	.unlocked_ioctl	= kcov_ioctl,
785 	.compat_ioctl	= kcov_ioctl,
786 	.mmap		= kcov_mmap,
787 	.release        = kcov_close,
788 };
789 
790 /*
791  * kcov_remote_start() and kcov_remote_stop() can be used to annotate a section
792  * of code in a kernel background thread or in a softirq to allow kcov to be
793  * used to collect coverage from that part of code.
794  *
795  * The handle argument of kcov_remote_start() identifies a code section that is
796  * used for coverage collection. A userspace process passes this handle to
797  * KCOV_REMOTE_ENABLE ioctl to make the used kcov device start collecting
798  * coverage for the code section identified by this handle.
799  *
800  * The usage of these annotations in the kernel code is different depending on
801  * the type of the kernel thread whose code is being annotated.
802  *
803  * For global kernel threads that are spawned in a limited number of instances
804  * (e.g. one USB hub_event() worker thread is spawned per USB HCD) and for
805  * softirqs, each instance must be assigned a unique 4-byte instance id. The
806  * instance id is then combined with a 1-byte subsystem id to get a handle via
807  * kcov_remote_handle(subsystem_id, instance_id).
808  *
809  * For local kernel threads that are spawned from system calls handler when a
810  * user interacts with some kernel interface (e.g. vhost workers), a handle is
811  * passed from a userspace process as the common_handle field of the
812  * kcov_remote_arg struct (note, that the user must generate a handle by using
813  * kcov_remote_handle() with KCOV_SUBSYSTEM_COMMON as the subsystem id and an
814  * arbitrary 4-byte non-zero number as the instance id). This common handle
815  * then gets saved into the task_struct of the process that issued the
816  * KCOV_REMOTE_ENABLE ioctl. When this process issues system calls that spawn
817  * kernel threads, the common handle must be retrieved via kcov_common_handle()
818  * and passed to the spawned threads via custom annotations. Those kernel
819  * threads must in turn be annotated with kcov_remote_start(common_handle) and
820  * kcov_remote_stop(). All of the threads that are spawned by the same process
821  * obtain the same handle, hence the name "common".
822  *
823  * See Documentation/dev-tools/kcov.rst for more details.
824  *
825  * Internally, kcov_remote_start() looks up the kcov device associated with the
826  * provided handle, allocates an area for coverage collection, and saves the
827  * pointers to kcov and area into the current task_struct to allow coverage to
828  * be collected via __sanitizer_cov_trace_pc().
829  * In turns kcov_remote_stop() clears those pointers from task_struct to stop
830  * collecting coverage and copies all collected coverage into the kcov area.
831  */
832 
833 static inline bool kcov_mode_enabled(unsigned int mode)
834 {
835 	return (mode & ~KCOV_IN_CTXSW) != KCOV_MODE_DISABLED;
836 }
837 
838 static void kcov_remote_softirq_start(struct task_struct *t)
839 	__must_hold(&kcov_percpu_data.lock)
840 {
841 	unsigned int mode;
842 
843 	mode = READ_ONCE(t->kcov_mode);
844 	barrier();
845 	if (kcov_mode_enabled(mode)) {
846 		t->kcov_saved_mode = mode;
847 		t->kcov_saved_size = t->kcov_size;
848 		t->kcov_saved_area = t->kcov_area;
849 		t->kcov_saved_sequence = t->kcov_sequence;
850 		t->kcov_saved_kcov = t->kcov;
851 		kcov_stop(t);
852 	}
853 }
854 
855 static void kcov_remote_softirq_stop(struct task_struct *t)
856 	__must_hold(&kcov_percpu_data.lock)
857 {
858 	if (t->kcov_saved_kcov) {
859 		kcov_start(t, t->kcov_saved_kcov, t->kcov_saved_size,
860 			   t->kcov_saved_area, t->kcov_saved_mode,
861 			   t->kcov_saved_sequence);
862 		t->kcov_saved_mode = 0;
863 		t->kcov_saved_size = 0;
864 		t->kcov_saved_area = NULL;
865 		t->kcov_saved_sequence = 0;
866 		t->kcov_saved_kcov = NULL;
867 	}
868 }
869 
870 void kcov_remote_start(u64 handle)
871 {
872 	struct task_struct *t = current;
873 	struct kcov_remote *remote;
874 	struct kcov *kcov;
875 	unsigned int mode;
876 	void *area;
877 	unsigned int size;
878 	int sequence;
879 	unsigned long flags;
880 
881 	if (WARN_ON(!kcov_check_handle(handle, true, true, true)))
882 		return;
883 	if (!in_task() && !in_softirq_really())
884 		return;
885 
886 	local_lock_irqsave(&kcov_percpu_data.lock, flags);
887 
888 	/*
889 	 * Check that kcov_remote_start() is not called twice in background
890 	 * threads nor called by user tasks (with enabled kcov).
891 	 */
892 	mode = READ_ONCE(t->kcov_mode);
893 	if (WARN_ON(in_task() && kcov_mode_enabled(mode))) {
894 		local_unlock_irqrestore(&kcov_percpu_data.lock, flags);
895 		return;
896 	}
897 	/*
898 	 * Check that kcov_remote_start() is not called twice in softirqs.
899 	 * Note, that kcov_remote_start() can be called from a softirq that
900 	 * happened while collecting coverage from a background thread.
901 	 */
902 	if (WARN_ON(in_serving_softirq() && t->kcov_softirq)) {
903 		local_unlock_irqrestore(&kcov_percpu_data.lock, flags);
904 		return;
905 	}
906 
907 	spin_lock(&kcov_remote_lock);
908 	remote = kcov_remote_find(handle);
909 	if (!remote) {
910 		spin_unlock(&kcov_remote_lock);
911 		local_unlock_irqrestore(&kcov_percpu_data.lock, flags);
912 		return;
913 	}
914 	kcov_debug("handle = %llx, context: %s\n", handle,
915 			in_task() ? "task" : "softirq");
916 	kcov = remote->kcov;
917 	/* Put in kcov_remote_stop(). */
918 	kcov_get(kcov);
919 	/*
920 	 * Read kcov fields before unlocking kcov_remote_lock to prevent races
921 	 * with KCOV_DISABLE and kcov_remote_reset(); cannot acquire kcov->lock
922 	 * here, because it might lead to deadlock given kcov_remote_lock is
923 	 * acquired _after_ kcov->lock elsewhere.
924 	 */
925 	mode = context_unsafe(kcov->mode);
926 	sequence = kcov->sequence;
927 	if (in_task()) {
928 		size = kcov->remote_size;
929 		area = kcov_remote_area_get(size, false);
930 	} else {
931 		size = CONFIG_KCOV_IRQ_AREA_SIZE;
932 		area = kcov_remote_area_get(size, true);
933 	}
934 	spin_unlock(&kcov_remote_lock);
935 
936 	/* Allocate new buffer if we can sleep. */
937 	if (!area) {
938 		local_unlock_irqrestore(&kcov_percpu_data.lock, flags);
939 		area = in_task() ? vmalloc(size * sizeof(unsigned long)) : NULL;
940 		if (!area) {
941 			kcov_put(kcov);
942 			return;
943 		}
944 		local_lock_irqsave(&kcov_percpu_data.lock, flags);
945 	}
946 
947 	/* Reset coverage size. */
948 	*(u64 *)area = 0;
949 
950 	if (in_serving_softirq()) {
951 		kcov_remote_softirq_start(t);
952 		t->kcov_softirq = 1;
953 	}
954 	kcov_start(t, kcov, size, area, mode, sequence);
955 
956 	local_unlock_irqrestore(&kcov_percpu_data.lock, flags);
957 
958 }
959 EXPORT_SYMBOL(kcov_remote_start);
960 
961 static void kcov_move_area(enum kcov_mode mode, void *dst_area,
962 				unsigned int dst_area_size, void *src_area)
963 {
964 	u64 word_size = sizeof(unsigned long);
965 	u64 count_size, entry_size_log;
966 	u64 dst_len, src_len;
967 	void *dst_entries, *src_entries;
968 	u64 dst_occupied, dst_free, bytes_to_move, entries_moved;
969 
970 	kcov_debug("%px %u <= %px %lu\n",
971 		dst_area, dst_area_size, src_area, *(unsigned long *)src_area);
972 
973 	switch (mode) {
974 	case KCOV_MODE_TRACE_PC:
975 		dst_len = READ_ONCE(*(unsigned long *)dst_area);
976 		src_len = *(unsigned long *)src_area;
977 		count_size = sizeof(unsigned long);
978 		entry_size_log = __ilog2_u64(sizeof(unsigned long));
979 		break;
980 	case KCOV_MODE_TRACE_CMP:
981 		dst_len = READ_ONCE(*(u64 *)dst_area);
982 		src_len = *(u64 *)src_area;
983 		count_size = sizeof(u64);
984 		BUILD_BUG_ON(!is_power_of_2(KCOV_WORDS_PER_CMP));
985 		entry_size_log = __ilog2_u64(sizeof(u64) * KCOV_WORDS_PER_CMP);
986 		break;
987 	default:
988 		WARN_ON(1);
989 		return;
990 	}
991 
992 	/* As arm can't divide u64 integers use log of entry size. */
993 	if (dst_len > ((dst_area_size * word_size - count_size) >>
994 				entry_size_log))
995 		return;
996 	dst_occupied = count_size + (dst_len << entry_size_log);
997 	dst_free = dst_area_size * word_size - dst_occupied;
998 	bytes_to_move = min(dst_free, src_len << entry_size_log);
999 	dst_entries = dst_area + dst_occupied;
1000 	src_entries = src_area + count_size;
1001 	memcpy(dst_entries, src_entries, bytes_to_move);
1002 	entries_moved = bytes_to_move >> entry_size_log;
1003 
1004 	/*
1005 	 * A write memory barrier is required here, to ensure
1006 	 * that the writes from the memcpy() are visible before
1007 	 * the count is updated. Without this, it is possible for
1008 	 * a user to observe a new count value but stale
1009 	 * coverage data.
1010 	 */
1011 	smp_wmb();
1012 
1013 	switch (mode) {
1014 	case KCOV_MODE_TRACE_PC:
1015 		WRITE_ONCE(*(unsigned long *)dst_area, dst_len + entries_moved);
1016 		break;
1017 	case KCOV_MODE_TRACE_CMP:
1018 		WRITE_ONCE(*(u64 *)dst_area, dst_len + entries_moved);
1019 		break;
1020 	default:
1021 		break;
1022 	}
1023 }
1024 
1025 /* See the comment before kcov_remote_start() for usage details. */
1026 void kcov_remote_stop(void)
1027 {
1028 	struct task_struct *t = current;
1029 	struct kcov *kcov;
1030 	unsigned int mode;
1031 	void *area;
1032 	unsigned int size;
1033 	int sequence;
1034 	unsigned long flags;
1035 
1036 	if (!in_task() && !in_softirq_really())
1037 		return;
1038 
1039 	local_lock_irqsave(&kcov_percpu_data.lock, flags);
1040 
1041 	mode = READ_ONCE(t->kcov_mode);
1042 	barrier();
1043 	if (!kcov_mode_enabled(mode)) {
1044 		local_unlock_irqrestore(&kcov_percpu_data.lock, flags);
1045 		return;
1046 	}
1047 	/*
1048 	 * When in softirq, check if the corresponding kcov_remote_start()
1049 	 * actually found the remote handle and started collecting coverage.
1050 	 */
1051 	if (in_serving_softirq() && !t->kcov_softirq) {
1052 		local_unlock_irqrestore(&kcov_percpu_data.lock, flags);
1053 		return;
1054 	}
1055 	/* Make sure that kcov_softirq is only set when in softirq. */
1056 	if (WARN_ON(!in_serving_softirq() && t->kcov_softirq)) {
1057 		local_unlock_irqrestore(&kcov_percpu_data.lock, flags);
1058 		return;
1059 	}
1060 
1061 	kcov = t->kcov;
1062 	area = t->kcov_area;
1063 	size = t->kcov_size;
1064 	sequence = t->kcov_sequence;
1065 
1066 	kcov_stop(t);
1067 	if (in_serving_softirq()) {
1068 		t->kcov_softirq = 0;
1069 		kcov_remote_softirq_stop(t);
1070 	}
1071 
1072 	spin_lock(&kcov->lock);
1073 	/*
1074 	 * KCOV_DISABLE could have been called between kcov_remote_start()
1075 	 * and kcov_remote_stop(), hence the sequence check.
1076 	 */
1077 	if (sequence == kcov->sequence && kcov->remote)
1078 		kcov_move_area(kcov->mode, kcov->area, kcov->size, area);
1079 	spin_unlock(&kcov->lock);
1080 
1081 	spin_lock(&kcov_remote_lock);
1082 	kcov_remote_area_put(area, size, !in_task());
1083 	spin_unlock(&kcov_remote_lock);
1084 
1085 	local_unlock_irqrestore(&kcov_percpu_data.lock, flags);
1086 
1087 	/* Get in kcov_remote_start(). */
1088 	kcov_put(kcov);
1089 }
1090 EXPORT_SYMBOL(kcov_remote_stop);
1091 
1092 /* See the comment before kcov_remote_start() for usage details. */
1093 struct kcov_common_handle_id kcov_common_handle(void)
1094 {
1095 	if (!in_task())
1096 		return (struct kcov_common_handle_id){ .val = 0 };
1097 	return (struct kcov_common_handle_id){ .val = current->kcov_handle };
1098 }
1099 EXPORT_SYMBOL(kcov_common_handle);
1100 
1101 #ifdef CONFIG_KCOV_SELFTEST
1102 static void __init selftest(void)
1103 {
1104 	unsigned long start;
1105 
1106 	pr_err("running self test\n");
1107 	/*
1108 	 * Test that interrupts don't produce spurious coverage.
1109 	 * The coverage callback filters out interrupt code, but only
1110 	 * after the handler updates preempt count. Some code periodically
1111 	 * leaks out of that section and leads to spurious coverage.
1112 	 * It's hard to call the actual interrupt handler directly,
1113 	 * so we just loop here for a bit waiting for a timer interrupt.
1114 	 * We set kcov_mode to enable tracing, but don't setup the area,
1115 	 * so any attempt to trace will crash. Note: we must not call any
1116 	 * potentially traced functions in this region.
1117 	 */
1118 	start = jiffies;
1119 	WRITE_ONCE(current->kcov_mode, KCOV_MODE_TRACE_PC);
1120 	while ((jiffies - start) * MSEC_PER_SEC / HZ < 300)
1121 		;
1122 	WRITE_ONCE(current->kcov_mode, 0);
1123 	pr_err("done running self test\n");
1124 }
1125 #endif
1126 
1127 static int __init kcov_init(void)
1128 {
1129 	int cpu = num_possible_cpus();
1130 
1131 #ifdef CONFIG_PREEMPT_RT
1132 	/* Allocate some extra buffers in order to prepare for softirq preemption. */
1133 	cpu = cpu >= 4 ? cpu * 2 : cpu + 4;
1134 #endif
1135 	while (cpu--) {
1136 		void *area = vmalloc(CONFIG_KCOV_IRQ_AREA_SIZE * sizeof(unsigned long));
1137 		unsigned long flags;
1138 
1139 		if (!area)
1140 			return -ENOMEM;
1141 		spin_lock_irqsave(&kcov_remote_lock, flags);
1142 		kcov_remote_area_put(area, CONFIG_KCOV_IRQ_AREA_SIZE, true);
1143 		spin_unlock_irqrestore(&kcov_remote_lock, flags);
1144 	}
1145 
1146 	/*
1147 	 * The kcov debugfs file won't ever get removed and thus,
1148 	 * there is no need to protect it against removal races. The
1149 	 * use of debugfs_create_file_unsafe() is actually safe here.
1150 	 */
1151 	debugfs_create_file_unsafe("kcov", 0600, NULL, NULL, &kcov_fops);
1152 
1153 #ifdef CONFIG_KCOV_SELFTEST
1154 	selftest();
1155 #endif
1156 
1157 	return 0;
1158 }
1159 
1160 device_initcall(kcov_init);
1161