xref: /freebsd/sys/kern/kern_kcov.c (revision 5bb3134a8c21cb87b30e135ef168483f0333dabb)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (C) 2018 The FreeBSD Foundation. All rights reserved.
5  * Copyright (C) 2018, 2019 Andrew Turner
6  *
7  * This software was developed by Mitchell Horne under sponsorship of
8  * the FreeBSD Foundation.
9  *
10  * This software was developed by SRI International and the University of
11  * Cambridge Computer Laboratory under DARPA/AFRL contract FA8750-10-C-0237
12  * ("CTSRD"), as part of the DARPA CRASH research programme.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  * $FreeBSD$
36  */
37 
38 /* Interceptors are required for KMSAN. */
39 #if defined(KASAN) || defined(KCSAN)
40 #define	SAN_RUNTIME
41 #endif
42 
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/conf.h>
49 #include <sys/eventhandler.h>
50 #include <sys/kcov.h>
51 #include <sys/kernel.h>
52 #include <sys/limits.h>
53 #include <sys/lock.h>
54 #include <sys/malloc.h>
55 #include <sys/mman.h>
56 #include <sys/mutex.h>
57 #include <sys/proc.h>
58 #include <sys/rwlock.h>
59 #include <sys/sysctl.h>
60 
61 #include <vm/vm.h>
62 #include <vm/pmap.h>
63 #include <vm/vm_extern.h>
64 #include <vm/vm_object.h>
65 #include <vm/vm_page.h>
66 #include <vm/vm_pager.h>
67 #include <vm/vm_param.h>
68 
69 MALLOC_DEFINE(M_KCOV_INFO, "kcovinfo", "KCOV info type");
70 
71 #define	KCOV_ELEMENT_SIZE	sizeof(uint64_t)
72 
73 /*
74  * To know what the code can safely perform at any point in time we use a
75  * state machine. In the normal case the state transitions are:
76  *
77  * OPEN -> READY -> RUNNING -> DYING
78  *  |       | ^        |        ^ ^
79  *  |       | +--------+        | |
80  *  |       +-------------------+ |
81  *  +-----------------------------+
82  *
83  * The states are:
84  *  OPEN:   The kcov fd has been opened, but no buffer is available to store
85  *          coverage data.
86  *  READY:  The buffer to store coverage data has been allocated. Userspace
87  *          can set this by using ioctl(fd, KIOSETBUFSIZE, entries);. When
88  *          this has been set the buffer can be written to by the kernel,
89  *          and mmaped by userspace.
90  * RUNNING: The coverage probes are able to store coverage data in the buffer.
91  *          This is entered with ioctl(fd, KIOENABLE, mode);. The READY state
92  *          can be exited by ioctl(fd, KIODISABLE); or exiting the thread to
93  *          return to the READY state to allow tracing to be reused, or by
94  *          closing the kcov fd to enter the DYING state.
95  * DYING:   The fd has been closed. All states can enter into this state when
96  *          userspace closes the kcov fd.
97  *
98  * We need to be careful when moving into and out of the RUNNING state. As
99  * an interrupt may happen while this is happening the ordering of memory
100  * operations is important so struct kcov_info is valid for the tracing
101  * functions.
102  *
103  * When moving into the RUNNING state prior stores to struct kcov_info need
104  * to be observed before the state is set. This allows for interrupts that
105  * may call into one of the coverage functions to fire at any point while
106  * being enabled and see a consistent struct kcov_info.
107  *
108  * When moving out of the RUNNING state any later stores to struct kcov_info
109  * need to be observed after the state is set. As with entering this is to
110  * present a consistent struct kcov_info to interrupts.
111  */
112 typedef enum {
113 	KCOV_STATE_INVALID,
114 	KCOV_STATE_OPEN,	/* The device is open, but with no buffer */
115 	KCOV_STATE_READY,	/* The buffer has been allocated */
116 	KCOV_STATE_RUNNING,	/* Recording trace data */
117 	KCOV_STATE_DYING,	/* The fd was closed */
118 } kcov_state_t;
119 
120 /*
121  * (l) Set while holding the kcov_lock mutex and not in the RUNNING state.
122  * (o) Only set once while in the OPEN state. Cleaned up while in the DYING
123  *     state, and with no thread associated with the struct kcov_info.
124  * (s) Set atomically to enter or exit the RUNNING state, non-atomically
125  *     otherwise. See above for a description of the other constraints while
126  *     moving into or out of the RUNNING state.
127  */
128 struct kcov_info {
129 	struct thread	*thread;	/* (l) */
130 	vm_object_t	bufobj;		/* (o) */
131 	vm_offset_t	kvaddr;		/* (o) */
132 	size_t		entries;	/* (o) */
133 	size_t		bufsize;	/* (o) */
134 	kcov_state_t	state;		/* (s) */
135 	int		mode;		/* (l) */
136 };
137 
138 /* Prototypes */
139 static d_open_t		kcov_open;
140 static d_close_t	kcov_close;
141 static d_mmap_single_t	kcov_mmap_single;
142 static d_ioctl_t	kcov_ioctl;
143 
144 static int  kcov_alloc(struct kcov_info *info, size_t entries);
145 static void kcov_free(struct kcov_info *info);
146 static void kcov_init(const void *unused);
147 
148 static struct cdevsw kcov_cdevsw = {
149 	.d_version =	D_VERSION,
150 	.d_open =	kcov_open,
151 	.d_close =	kcov_close,
152 	.d_mmap_single = kcov_mmap_single,
153 	.d_ioctl =	kcov_ioctl,
154 	.d_name =	"kcov",
155 };
156 
157 SYSCTL_NODE(_kern, OID_AUTO, kcov, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
158     "Kernel coverage");
159 
160 static u_int kcov_max_entries = KCOV_MAXENTRIES;
161 SYSCTL_UINT(_kern_kcov, OID_AUTO, max_entries, CTLFLAG_RW,
162     &kcov_max_entries, 0,
163     "Maximum number of entries in the kcov buffer");
164 
165 static struct mtx kcov_lock;
166 static int active_count;
167 
168 static struct kcov_info * __nosanitizeaddress __nosanitizememory
169 get_kinfo(struct thread *td)
170 {
171 	struct kcov_info *info;
172 
173 	/* We might have a NULL thread when releasing the secondary CPUs */
174 	if (td == NULL)
175 		return (NULL);
176 
177 	/*
178 	 * We are in an interrupt, stop tracing as it is not explicitly
179 	 * part of a syscall.
180 	 */
181 	if (td->td_intr_nesting_level > 0 || td->td_intr_frame != NULL)
182 		return (NULL);
183 
184 	/*
185 	 * If info is NULL or the state is not running we are not tracing.
186 	 */
187 	info = td->td_kcov_info;
188 	if (info == NULL ||
189 	    atomic_load_acq_int(&info->state) != KCOV_STATE_RUNNING)
190 		return (NULL);
191 
192 	return (info);
193 }
194 
195 static void __nosanitizeaddress __nosanitizememory
196 trace_pc(uintptr_t ret)
197 {
198 	struct thread *td;
199 	struct kcov_info *info;
200 	uint64_t *buf, index;
201 
202 	td = curthread;
203 	info = get_kinfo(td);
204 	if (info == NULL)
205 		return;
206 
207 	/*
208 	 * Check we are in the PC-trace mode.
209 	 */
210 	if (info->mode != KCOV_MODE_TRACE_PC)
211 		return;
212 
213 	KASSERT(info->kvaddr != 0,
214 	    ("__sanitizer_cov_trace_pc: NULL buf while running"));
215 
216 	buf = (uint64_t *)info->kvaddr;
217 
218 	/* The first entry of the buffer holds the index */
219 	index = buf[0];
220 	if (index + 2 > info->entries)
221 		return;
222 
223 	buf[index + 1] = ret;
224 	buf[0] = index + 1;
225 }
226 
227 static bool __nosanitizeaddress __nosanitizememory
228 trace_cmp(uint64_t type, uint64_t arg1, uint64_t arg2, uint64_t ret)
229 {
230 	struct thread *td;
231 	struct kcov_info *info;
232 	uint64_t *buf, index;
233 
234 	td = curthread;
235 	info = get_kinfo(td);
236 	if (info == NULL)
237 		return (false);
238 
239 	/*
240 	 * Check we are in the comparison-trace mode.
241 	 */
242 	if (info->mode != KCOV_MODE_TRACE_CMP)
243 		return (false);
244 
245 	KASSERT(info->kvaddr != 0,
246 	    ("__sanitizer_cov_trace_pc: NULL buf while running"));
247 
248 	buf = (uint64_t *)info->kvaddr;
249 
250 	/* The first entry of the buffer holds the index */
251 	index = buf[0];
252 
253 	/* Check we have space to store all elements */
254 	if (index * 4 + 4 + 1 > info->entries)
255 		return (false);
256 
257 	while (1) {
258 		buf[index * 4 + 1] = type;
259 		buf[index * 4 + 2] = arg1;
260 		buf[index * 4 + 3] = arg2;
261 		buf[index * 4 + 4] = ret;
262 
263 		if (atomic_cmpset_64(&buf[0], index, index + 1))
264 			break;
265 		buf[0] = index;
266 	}
267 
268 	return (true);
269 }
270 
271 /*
272  * The fd is being closed, cleanup everything we can.
273  */
274 static void
275 kcov_mmap_cleanup(void *arg)
276 {
277 	struct kcov_info *info = arg;
278 	struct thread *thread;
279 
280 	mtx_lock_spin(&kcov_lock);
281 	/*
282 	 * Move to KCOV_STATE_DYING to stop adding new entries.
283 	 *
284 	 * If the thread is running we need to wait until thread exit to
285 	 * clean up as it may currently be adding a new entry. If this is
286 	 * the case being in KCOV_STATE_DYING will signal that the buffer
287 	 * needs to be cleaned up.
288 	 */
289 	atomic_store_int(&info->state, KCOV_STATE_DYING);
290 	atomic_thread_fence_seq_cst();
291 	thread = info->thread;
292 	mtx_unlock_spin(&kcov_lock);
293 
294 	if (thread != NULL)
295 		return;
296 
297 	/*
298 	 * We can safely clean up the info struct as it is in the
299 	 * KCOV_STATE_DYING state with no thread associated.
300 	 *
301 	 * The KCOV_STATE_DYING stops new threads from using it.
302 	 * The lack of a thread means nothing is currently using the buffers.
303 	 */
304 	kcov_free(info);
305 }
306 
307 static int
308 kcov_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
309 {
310 	struct kcov_info *info;
311 	int error;
312 
313 	info = malloc(sizeof(struct kcov_info), M_KCOV_INFO, M_ZERO | M_WAITOK);
314 	info->state = KCOV_STATE_OPEN;
315 	info->thread = NULL;
316 	info->mode = -1;
317 
318 	if ((error = devfs_set_cdevpriv(info, kcov_mmap_cleanup)) != 0)
319 		kcov_mmap_cleanup(info);
320 
321 	return (error);
322 }
323 
324 static int
325 kcov_close(struct cdev *dev, int fflag, int devtype, struct thread *td)
326 {
327 	struct kcov_info *info;
328 	int error;
329 
330 	if ((error = devfs_get_cdevpriv((void **)&info)) != 0)
331 		return (error);
332 
333 	KASSERT(info != NULL, ("kcov_close with no kcov_info structure"));
334 
335 	/* Trying to close, but haven't disabled */
336 	if (info->state == KCOV_STATE_RUNNING)
337 		return (EBUSY);
338 
339 	return (0);
340 }
341 
342 static int
343 kcov_mmap_single(struct cdev *dev, vm_ooffset_t *offset, vm_size_t size,
344     struct vm_object **object, int nprot)
345 {
346 	struct kcov_info *info;
347 	int error;
348 
349 	if ((nprot & (PROT_EXEC | PROT_READ | PROT_WRITE)) !=
350 	    (PROT_READ | PROT_WRITE))
351 		return (EINVAL);
352 
353 	if ((error = devfs_get_cdevpriv((void **)&info)) != 0)
354 		return (error);
355 
356 	if (info->kvaddr == 0 || size / KCOV_ELEMENT_SIZE != info->entries)
357 		return (EINVAL);
358 
359 	vm_object_reference(info->bufobj);
360 	*offset = 0;
361 	*object = info->bufobj;
362 	return (0);
363 }
364 
365 static int
366 kcov_alloc(struct kcov_info *info, size_t entries)
367 {
368 	size_t n, pages;
369 	vm_page_t m;
370 
371 	KASSERT(info->kvaddr == 0, ("kcov_alloc: Already have a buffer"));
372 	KASSERT(info->state == KCOV_STATE_OPEN,
373 	    ("kcov_alloc: Not in open state (%x)", info->state));
374 
375 	if (entries < 2 || entries > kcov_max_entries)
376 		return (EINVAL);
377 
378 	/* Align to page size so mmap can't access other kernel memory */
379 	info->bufsize = roundup2(entries * KCOV_ELEMENT_SIZE, PAGE_SIZE);
380 	pages = info->bufsize / PAGE_SIZE;
381 
382 	if ((info->kvaddr = kva_alloc(info->bufsize)) == 0)
383 		return (ENOMEM);
384 
385 	info->bufobj = vm_pager_allocate(OBJT_PHYS, 0, info->bufsize,
386 	    PROT_READ | PROT_WRITE, 0, curthread->td_ucred);
387 
388 	VM_OBJECT_WLOCK(info->bufobj);
389 	for (n = 0; n < pages; n++) {
390 		m = vm_page_grab(info->bufobj, n,
391 		    VM_ALLOC_ZERO | VM_ALLOC_WIRED);
392 		vm_page_valid(m);
393 		vm_page_xunbusy(m);
394 		pmap_qenter(info->kvaddr + n * PAGE_SIZE, &m, 1);
395 	}
396 	VM_OBJECT_WUNLOCK(info->bufobj);
397 
398 	info->entries = entries;
399 
400 	return (0);
401 }
402 
403 static void
404 kcov_free(struct kcov_info *info)
405 {
406 	vm_page_t m;
407 	size_t i;
408 
409 	if (info->kvaddr != 0) {
410 		pmap_qremove(info->kvaddr, info->bufsize / PAGE_SIZE);
411 		kva_free(info->kvaddr, info->bufsize);
412 	}
413 	if (info->bufobj != NULL) {
414 		VM_OBJECT_WLOCK(info->bufobj);
415 		m = vm_page_lookup(info->bufobj, 0);
416 		for (i = 0; i < info->bufsize / PAGE_SIZE; i++) {
417 			vm_page_unwire_noq(m);
418 			m = vm_page_next(m);
419 		}
420 		VM_OBJECT_WUNLOCK(info->bufobj);
421 		vm_object_deallocate(info->bufobj);
422 	}
423 	free(info, M_KCOV_INFO);
424 }
425 
426 static int
427 kcov_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag __unused,
428     struct thread *td)
429 {
430 	struct kcov_info *info;
431 	int mode, error;
432 
433 	if ((error = devfs_get_cdevpriv((void **)&info)) != 0)
434 		return (error);
435 
436 	if (cmd == KIOSETBUFSIZE) {
437 		/*
438 		 * Set the size of the coverage buffer. Should be called
439 		 * before enabling coverage collection for that thread.
440 		 */
441 		if (info->state != KCOV_STATE_OPEN) {
442 			return (EBUSY);
443 		}
444 		error = kcov_alloc(info, *(u_int *)data);
445 		if (error == 0)
446 			info->state = KCOV_STATE_READY;
447 		return (error);
448 	}
449 
450 	mtx_lock_spin(&kcov_lock);
451 	switch (cmd) {
452 	case KIOENABLE:
453 		if (info->state != KCOV_STATE_READY) {
454 			error = EBUSY;
455 			break;
456 		}
457 		if (td->td_kcov_info != NULL) {
458 			error = EINVAL;
459 			break;
460 		}
461 		mode = *(int *)data;
462 		if (mode != KCOV_MODE_TRACE_PC && mode != KCOV_MODE_TRACE_CMP) {
463 			error = EINVAL;
464 			break;
465 		}
466 
467 		/* Lets hope nobody opens this 2 billion times */
468 		KASSERT(active_count < INT_MAX,
469 		    ("%s: Open too many times", __func__));
470 		active_count++;
471 		if (active_count == 1) {
472 			cov_register_pc(&trace_pc);
473 			cov_register_cmp(&trace_cmp);
474 		}
475 
476 		KASSERT(info->thread == NULL,
477 		    ("Enabling kcov when already enabled"));
478 		info->thread = td;
479 		info->mode = mode;
480 		/*
481 		 * Ensure the mode has been set before starting coverage
482 		 * tracing.
483 		 */
484 		atomic_store_rel_int(&info->state, KCOV_STATE_RUNNING);
485 		td->td_kcov_info = info;
486 		break;
487 	case KIODISABLE:
488 		/* Only the currently enabled thread may disable itself */
489 		if (info->state != KCOV_STATE_RUNNING ||
490 		    info != td->td_kcov_info) {
491 			error = EINVAL;
492 			break;
493 		}
494 		KASSERT(active_count > 0, ("%s: Open count is zero", __func__));
495 		active_count--;
496 		if (active_count == 0) {
497 			cov_unregister_pc();
498 			cov_unregister_cmp();
499 		}
500 
501 		td->td_kcov_info = NULL;
502 		atomic_store_int(&info->state, KCOV_STATE_READY);
503 		/*
504 		 * Ensure we have exited the READY state before clearing the
505 		 * rest of the info struct.
506 		 */
507 		atomic_thread_fence_rel();
508 		info->mode = -1;
509 		info->thread = NULL;
510 		break;
511 	default:
512 		error = EINVAL;
513 		break;
514 	}
515 	mtx_unlock_spin(&kcov_lock);
516 
517 	return (error);
518 }
519 
520 static void
521 kcov_thread_dtor(void *arg __unused, struct thread *td)
522 {
523 	struct kcov_info *info;
524 
525 	info = td->td_kcov_info;
526 	if (info == NULL)
527 		return;
528 
529 	mtx_lock_spin(&kcov_lock);
530 	KASSERT(active_count > 0, ("%s: Open count is zero", __func__));
531 	active_count--;
532 	if (active_count == 0) {
533 		cov_unregister_pc();
534 		cov_unregister_cmp();
535 	}
536 	td->td_kcov_info = NULL;
537 	if (info->state != KCOV_STATE_DYING) {
538 		/*
539 		 * The kcov file is still open. Mark it as unused and
540 		 * wait for it to be closed before cleaning up.
541 		 */
542 		atomic_store_int(&info->state, KCOV_STATE_READY);
543 		atomic_thread_fence_seq_cst();
544 		/* This info struct is unused */
545 		info->thread = NULL;
546 		mtx_unlock_spin(&kcov_lock);
547 		return;
548 	}
549 	mtx_unlock_spin(&kcov_lock);
550 
551 	/*
552 	 * We can safely clean up the info struct as it is in the
553 	 * KCOV_STATE_DYING state where the info struct is associated with
554 	 * the current thread that's about to exit.
555 	 *
556 	 * The KCOV_STATE_DYING stops new threads from using it.
557 	 * It also stops the current thread from trying to use the info struct.
558 	 */
559 	kcov_free(info);
560 }
561 
562 static void
563 kcov_init(const void *unused)
564 {
565 	struct make_dev_args args;
566 	struct cdev *dev;
567 
568 	mtx_init(&kcov_lock, "kcov lock", NULL, MTX_SPIN);
569 
570 	make_dev_args_init(&args);
571 	args.mda_devsw = &kcov_cdevsw;
572 	args.mda_uid = UID_ROOT;
573 	args.mda_gid = GID_WHEEL;
574 	args.mda_mode = 0600;
575 	if (make_dev_s(&args, &dev, "kcov") != 0) {
576 		printf("%s", "Failed to create kcov device");
577 		return;
578 	}
579 
580 	EVENTHANDLER_REGISTER(thread_dtor, kcov_thread_dtor, NULL,
581 	    EVENTHANDLER_PRI_ANY);
582 }
583 
584 SYSINIT(kcovdev, SI_SUB_LAST, SI_ORDER_ANY, kcov_init, NULL);
585