2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (C) 2018 The FreeBSD Foundation. All rights reserved.
5 * Copyright (C) 2018, 2019 Andrew Turner
7 * This software was developed by Mitchell Horne under sponsorship of
8 * the FreeBSD Foundation.
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.
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
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.
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
38 /* Interceptors are required for KMSAN. */
39 #if defined(KASAN) || defined(KCSAN)
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
46 #include <sys/param.h>
47 #include <sys/systm.h>
49 #include <sys/eventhandler.h>
51 #include <sys/kernel.h>
52 #include <sys/limits.h>
54 #include <sys/malloc.h>
56 #include <sys/mutex.h>
58 #include <sys/rwlock.h>
59 #include <sys/sysctl.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>
69 MALLOC_DEFINE(M_KCOV_INFO, "kcovinfo", "KCOV info type");
71 #define KCOV_ELEMENT_SIZE sizeof(uint64_t)
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:
77 * OPEN -> READY -> RUNNING -> DYING
80 * | +-------------------+ |
81 * +-----------------------------+
84 * OPEN: The kcov fd has been opened, but no buffer is available to store
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.
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
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.
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.
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 */
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.
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) */
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;
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);
148 static struct cdevsw kcov_cdevsw = {
149 .d_version = D_VERSION,
151 .d_close = kcov_close,
152 .d_mmap_single = kcov_mmap_single,
153 .d_ioctl = kcov_ioctl,
157 SYSCTL_NODE(_kern, OID_AUTO, kcov, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
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");
165 static struct mtx kcov_lock;
166 static int active_count;
168 static struct kcov_info * __nosanitizeaddress __nosanitizememory
169 get_kinfo(struct thread *td)
171 struct kcov_info *info;
173 /* We might have a NULL thread when releasing the secondary CPUs */
178 * We are in an interrupt, stop tracing as it is not explicitly
181 if (td->td_intr_nesting_level > 0 || td->td_intr_frame != NULL)
185 * If info is NULL or the state is not running we are not tracing.
187 info = td->td_kcov_info;
189 atomic_load_acq_int(&info->state) != KCOV_STATE_RUNNING)
195 static void __nosanitizeaddress __nosanitizememory
196 trace_pc(uintptr_t ret)
199 struct kcov_info *info;
200 uint64_t *buf, index;
203 info = get_kinfo(td);
208 * Check we are in the PC-trace mode.
210 if (info->mode != KCOV_MODE_TRACE_PC)
213 KASSERT(info->kvaddr != 0, ("%s: NULL buf while running", __func__));
215 buf = (uint64_t *)info->kvaddr;
217 /* The first entry of the buffer holds the index */
219 if (index + 2 > info->entries)
222 buf[index + 1] = ret;
226 static bool __nosanitizeaddress __nosanitizememory
227 trace_cmp(uint64_t type, uint64_t arg1, uint64_t arg2, uint64_t ret)
230 struct kcov_info *info;
231 uint64_t *buf, index;
234 info = get_kinfo(td);
239 * Check we are in the comparison-trace mode.
241 if (info->mode != KCOV_MODE_TRACE_CMP)
244 KASSERT(info->kvaddr != 0, ("%s: NULL buf while running", __func__));
246 buf = (uint64_t *)info->kvaddr;
248 /* The first entry of the buffer holds the index */
251 /* Check we have space to store all elements */
252 if (index * 4 + 4 + 1 > info->entries)
256 buf[index * 4 + 1] = type;
257 buf[index * 4 + 2] = arg1;
258 buf[index * 4 + 3] = arg2;
259 buf[index * 4 + 4] = ret;
261 if (atomic_cmpset_64(&buf[0], index, index + 1))
270 * The fd is being closed, cleanup everything we can.
273 kcov_mmap_cleanup(void *arg)
275 struct kcov_info *info = arg;
276 struct thread *thread;
278 mtx_lock_spin(&kcov_lock);
280 * Move to KCOV_STATE_DYING to stop adding new entries.
282 * If the thread is running we need to wait until thread exit to
283 * clean up as it may currently be adding a new entry. If this is
284 * the case being in KCOV_STATE_DYING will signal that the buffer
285 * needs to be cleaned up.
287 atomic_store_int(&info->state, KCOV_STATE_DYING);
288 atomic_thread_fence_seq_cst();
289 thread = info->thread;
290 mtx_unlock_spin(&kcov_lock);
296 * We can safely clean up the info struct as it is in the
297 * KCOV_STATE_DYING state with no thread associated.
299 * The KCOV_STATE_DYING stops new threads from using it.
300 * The lack of a thread means nothing is currently using the buffers.
306 kcov_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
308 struct kcov_info *info;
311 info = malloc(sizeof(struct kcov_info), M_KCOV_INFO, M_ZERO | M_WAITOK);
312 info->state = KCOV_STATE_OPEN;
316 if ((error = devfs_set_cdevpriv(info, kcov_mmap_cleanup)) != 0)
317 kcov_mmap_cleanup(info);
323 kcov_close(struct cdev *dev, int fflag, int devtype, struct thread *td)
325 struct kcov_info *info;
328 if ((error = devfs_get_cdevpriv((void **)&info)) != 0)
331 KASSERT(info != NULL, ("kcov_close with no kcov_info structure"));
333 /* Trying to close, but haven't disabled */
334 if (info->state == KCOV_STATE_RUNNING)
341 kcov_mmap_single(struct cdev *dev, vm_ooffset_t *offset, vm_size_t size,
342 struct vm_object **object, int nprot)
344 struct kcov_info *info;
347 if ((nprot & (PROT_EXEC | PROT_READ | PROT_WRITE)) !=
348 (PROT_READ | PROT_WRITE))
351 if ((error = devfs_get_cdevpriv((void **)&info)) != 0)
354 if (info->kvaddr == 0 || size / KCOV_ELEMENT_SIZE != info->entries)
357 vm_object_reference(info->bufobj);
359 *object = info->bufobj;
364 kcov_alloc(struct kcov_info *info, size_t entries)
369 KASSERT(info->kvaddr == 0, ("kcov_alloc: Already have a buffer"));
370 KASSERT(info->state == KCOV_STATE_OPEN,
371 ("kcov_alloc: Not in open state (%x)", info->state));
373 if (entries < 2 || entries > kcov_max_entries)
376 /* Align to page size so mmap can't access other kernel memory */
377 info->bufsize = roundup2(entries * KCOV_ELEMENT_SIZE, PAGE_SIZE);
378 pages = info->bufsize / PAGE_SIZE;
380 if ((info->kvaddr = kva_alloc(info->bufsize)) == 0)
383 info->bufobj = vm_pager_allocate(OBJT_PHYS, 0, info->bufsize,
384 PROT_READ | PROT_WRITE, 0, curthread->td_ucred);
386 VM_OBJECT_WLOCK(info->bufobj);
387 for (n = 0; n < pages; n++) {
388 m = vm_page_grab(info->bufobj, n,
389 VM_ALLOC_ZERO | VM_ALLOC_WIRED);
392 pmap_qenter(info->kvaddr + n * PAGE_SIZE, &m, 1);
394 VM_OBJECT_WUNLOCK(info->bufobj);
396 info->entries = entries;
402 kcov_free(struct kcov_info *info)
407 if (info->kvaddr != 0) {
408 pmap_qremove(info->kvaddr, info->bufsize / PAGE_SIZE);
409 kva_free(info->kvaddr, info->bufsize);
411 if (info->bufobj != NULL) {
412 VM_OBJECT_WLOCK(info->bufobj);
413 m = vm_page_lookup(info->bufobj, 0);
414 for (i = 0; i < info->bufsize / PAGE_SIZE; i++) {
415 vm_page_unwire_noq(m);
418 VM_OBJECT_WUNLOCK(info->bufobj);
419 vm_object_deallocate(info->bufobj);
421 free(info, M_KCOV_INFO);
425 kcov_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag __unused,
428 struct kcov_info *info;
431 if ((error = devfs_get_cdevpriv((void **)&info)) != 0)
434 if (cmd == KIOSETBUFSIZE) {
436 * Set the size of the coverage buffer. Should be called
437 * before enabling coverage collection for that thread.
439 if (info->state != KCOV_STATE_OPEN) {
442 error = kcov_alloc(info, *(u_int *)data);
444 info->state = KCOV_STATE_READY;
448 mtx_lock_spin(&kcov_lock);
451 if (info->state != KCOV_STATE_READY) {
455 if (td->td_kcov_info != NULL) {
460 if (mode != KCOV_MODE_TRACE_PC && mode != KCOV_MODE_TRACE_CMP) {
465 /* Lets hope nobody opens this 2 billion times */
466 KASSERT(active_count < INT_MAX,
467 ("%s: Open too many times", __func__));
469 if (active_count == 1) {
470 cov_register_pc(&trace_pc);
471 cov_register_cmp(&trace_cmp);
474 KASSERT(info->thread == NULL,
475 ("Enabling kcov when already enabled"));
479 * Ensure the mode has been set before starting coverage
482 atomic_store_rel_int(&info->state, KCOV_STATE_RUNNING);
483 td->td_kcov_info = info;
486 /* Only the currently enabled thread may disable itself */
487 if (info->state != KCOV_STATE_RUNNING ||
488 info != td->td_kcov_info) {
492 KASSERT(active_count > 0, ("%s: Open count is zero", __func__));
494 if (active_count == 0) {
496 cov_unregister_cmp();
499 td->td_kcov_info = NULL;
500 atomic_store_int(&info->state, KCOV_STATE_READY);
502 * Ensure we have exited the READY state before clearing the
503 * rest of the info struct.
505 atomic_thread_fence_rel();
513 mtx_unlock_spin(&kcov_lock);
519 kcov_thread_dtor(void *arg __unused, struct thread *td)
521 struct kcov_info *info;
523 info = td->td_kcov_info;
527 mtx_lock_spin(&kcov_lock);
528 KASSERT(active_count > 0, ("%s: Open count is zero", __func__));
530 if (active_count == 0) {
532 cov_unregister_cmp();
534 td->td_kcov_info = NULL;
535 if (info->state != KCOV_STATE_DYING) {
537 * The kcov file is still open. Mark it as unused and
538 * wait for it to be closed before cleaning up.
540 atomic_store_int(&info->state, KCOV_STATE_READY);
541 atomic_thread_fence_seq_cst();
542 /* This info struct is unused */
544 mtx_unlock_spin(&kcov_lock);
547 mtx_unlock_spin(&kcov_lock);
550 * We can safely clean up the info struct as it is in the
551 * KCOV_STATE_DYING state where the info struct is associated with
552 * the current thread that's about to exit.
554 * The KCOV_STATE_DYING stops new threads from using it.
555 * It also stops the current thread from trying to use the info struct.
561 kcov_init(const void *unused)
563 struct make_dev_args args;
566 mtx_init(&kcov_lock, "kcov lock", NULL, MTX_SPIN);
568 make_dev_args_init(&args);
569 args.mda_devsw = &kcov_cdevsw;
570 args.mda_uid = UID_ROOT;
571 args.mda_gid = GID_WHEEL;
572 args.mda_mode = 0600;
573 if (make_dev_s(&args, &dev, "kcov") != 0) {
574 printf("%s", "Failed to create kcov device");
578 EVENTHANDLER_REGISTER(thread_dtor, kcov_thread_dtor, NULL,
579 EVENTHANDLER_PRI_ANY);
582 SYSINIT(kcovdev, SI_SUB_LAST, SI_ORDER_ANY, kcov_init, NULL);