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