Repository navigation
Testing
Part VI of the system development guide.
aiBSD follows NetBSD's three layers:
-
Compile coverage —
build.shbuilds, includingALLkernels, for every port that enables the code. -
Unit tests — ATF tests in
src/tests, installed in/usr/tests, run withatf-runorkyua. Kernel code is tested in a rump kernel: the real kernel sources, linked into a user process. -
System tests — boot a freshly built image and run the installed
test suite in it (what NetBSD's
anitaautomates).
sys/external/bsd/drm2/tools/probe is a temporary, local-only aid
(listed in .git/info/exclude): it syntax-checks DRM source files with
the compile flags of a real configured kernel and ranks the first
error of each failing file.
cd sys/external/bsd/drm2
tools/probe $TOOLS $OBJ/drm-probe-kernel
tools/probe -l files.txt -o logs/ $TOOLS $OBJ/drm-probe-kernelThe kernel build directory comes from configuring GENERIC minus the
DRM drivers (recipe in the script's header), since config(8) fails on
driver lists not yet converted. Read the first-error ranking, not
the total error count: a single unknown token in a header produces
hundreds of follow-on errors, and the total rises as files get further.
Delete the probe once DRM builds through the normal kernel build.
Also compile every compat-layer source after changing compat headers
(tools/probe -l with the file lines of linux/files.drmkms_linux):
header changes made for new code can break code that already worked.
Pattern (modelled on tests/dev/usb/t_hid):
-
A private rump library built from the kernel sources under test (
tests/dev/drm/liblinux/Makefile:LIBISPRIVATE=yes,.PATHto the sources,.include "${RUMPTOP}/Makefile.rump"). Add a source file here when it gets tests. -
An ATF C program linked with
-Wl,--whole-archiveagainst it and${LIBRUMPBASE}. It callsrump_init()andrump_schedule(), then the kernel functions under their rump names: rump prefixes kernel symbols withrumpns_, so the test maps them first:#define linux_rb_insert_color rumpns_linux_rb_insert_color #include <linux/rbtree.h>
Inline functions and macros from kernel headers then work in the test as is.
-
Register the test:
TESTS_SUBDIRSin the parent Makefile, the program and directory indistrib/sets/lists/tests/mi, the.debugfile indebug/mi, the directories inetc/mtree/NetBSD.dist.tests.
Kernel headers stay in the kernel. Most compat headers include
kernel-only headers (<lib/libkern/libkern.h>, ...), so ATF code
cannot include them. Put the test logic in the private rump library
instead: a kernel-side file (tests/dev/drm/liblinux/*_test.c) with
one function per test case returning NULL on success or a failure
message, listed in liblinux/drm_linux_tests.h, which declares them
under their plain names in the kernel and their rumpns_ names for
the ATF side. The ATF program then only calls them and reports, as in
t_linux_xarray. (t_linux_rbtree includes its few self-contained
headers directly; new tests should use the kernel-side pattern.)
tests/dev/drm/t_linux_rbtree checks the red-black tree, augmented
tree and interval tree code with randomized operations, verifying the
red-black invariants, parent links, ordering, iterators, cached
subtree maxima and leftmost nodes after every step, and comparing
interval queries against brute force.
Rump kernels are portable: NetBSD's kernel code runs in an ordinary
process of another OS, on top of librumpuser (threads, memory,
clocks from the host). For the compat layer this is the fastest loop
there is: the drm2 tests run on a Linux build host in about 0.3 s, in
plain processes, with gdb and AddressSanitizer available.
-
Building. The old
buildrump.shtool (rumpkernel project, last changed 2017) still works with current sources given a few make variables:NOGCCERROR=yes(newer host compilers warn about code the tree has not been cleaned up for), and emptySHLIB_LDSTARTFILE,SHLIB_LDENDFILEandDPLIBC(NetBSD's makefiles otherwise expect NetBSD's C startup files and libc in the staging area). Its third stage (librumpclient, for remote system calls) fails onsys/endian.h; it is not needed —librumpandlibrumpuserare. -
Our tests. The
rumpmakewrapper it produces builds the private test library (tests/dev/drm/liblinux) with the host compiler; a small host program callsrump_init(), then each test function (rumpns_drm_linux_test_*) in a child process of its own, as ATF does, so a crash fails one test only. On Linux, include<sys/types.h>and<stdint.h>before<rump/rump.h>. -
AddressSanitizer on the host program intercepts
malloc, which rump's kernel allocator ends up in, and so watches kernel memory. It found a heap overflow in everyrump_init()within a minute. - It complements, not replaces, the NetBSD runs: it is a host NetBSD never targets, so it finds different problems — and misses some.
The second fast loop runs the tests on NetBSD itself without building
an image each time. A persistent VM runs an image built from the
tree once (a variant of the test image whose test list is empty, so it
stays up), with sshd and a root key. A script then rebuilds just the
test programs, copies them in and runs them with atf-run | atf-report
(the image has no kyua), or single cases directly (./t_prog case):
about two seconds per cycle. Reinstall the image only after changes
outside the tests (libc, the rump libraries).
Image-build details: the extra-files mechanism of the image build
cannot create directories (ship files under /etc and move them from
rc.local); images built one after another reuse the work directory,
so give every image variant the same file list and vary only the
contents; and after a reinstall the DHCP server keeps the old lease
too — take the newest one for the VM's MAC address.
Not everything can run in a rump kernel: a DRM driver needs the real
kernel's file, mmap and module machinery. tests/dev/drm/t_vgem
tests a DRM device from user space on the running kernel (vgem, which
needs no hardware): buffer mapping and export, implicit fences seen
through poll(2), PRIME sharing with another DRM device, and the
dma-buf and sync file ioctls (CPU-access brackets that wait for a
fence, fences exported to and imported from sync files, merging).
tests/dev/drm/t_vkms does the same for a display (vkms): a mode set
and vblanks at the refresh rate, page-flip events, and an atomic
commit through the writeback connector whose captured frame must equal
the scanned-out one pixel for pixel — an end-to-end check of mode
setting, composition and fences with no GPU.
Such tests skip when the device is absent (no module loaded), so a
machine without it doesn't report a failure. A skip is silent,
though: on a test image meant to have the device, a broken driver
would look like a missing one. So a test image that builds the
devices in (pseudo-device vgem, pseudo-device vkms: the CI image
has no modules) sets the ATF configuration variable
drm_devices_required, and the tests then fail instead of skipping:
kyua -v test_suites.NetBSD.drm_devices_required=yes test
atf-run -v drm_devices_required=yes
The same reasoning covers modules. An image built with MKKMOD=no
and its drivers compiled in never loads a module, so nothing that
breaks module files or the loader (a tool that rewrites .kmods, the
module build's flags, modinfo and dependencies) can fail its tests.
Two checks close that gap: a build-time check over every .kmod
that no defined symbol lives in a relocation, symbol-table or
string-table section, and a test on an image with modules that loads a
few real ones (the DTrace set, a GPU driver) and checks they work.
The tests build against the DRM uapi
headers in dist/include/uapi (with -D__user= and two stand-in
Linux headers in tests/dev/drm/uapi), not libdrm.
Things that are true of a rump kernel and not of the real one; each can make a test fail or hang:
-
Two virtual CPUs by default, set with
RUMP_NCPUbeforerump_init()(the drm test programs ask for 8). Virtual CPUs are only scheduling slots; more than the host has is fine. -
No preemption. A thread keeps its virtual CPU until it blocks.
Threads that spin (stress-test readers) starve the others — including
the per-CPU cross-call threads that RCU grace periods,
pserializeand evenkthread_createwait for.preempt()/yield()do not help: the scheduler hands the CPU straight back. Sleep briefly (kpause(..., 1, ...)) every so often. -
kpreempt_disabled()always returns true; testcurlwp->l_nopreemptinstead (whatkpreempt_disable()counts on every kernel). -
Spin mutexes are host mutexes, so held spin mutexes are not
counted; use
kpreempt_disable()to create atomic context in a test. -
curlwpmay be cached. The__threadflavour of rump'scurlwpis__attribute__((const)), so the compiler may reuse an earlier value within a function. Harmless in a real kernel (a thread's lwp never changes); wrong in a test that switches lwps withrump_lwproc_rfork()/rump_lwproc_switch(). Askrump_lwproc_curlwp()instead. -
The calling host thread runs on an implicit lwp, which
rump_lwproc_curlwp()reports as NULL and which cannot be switched back to; run tests that create processes in a kthread.
- Make bugs visible. Test objects carry a liveness magic cleared on release, and a global count of live objects must be zero at the end: a reader holding a released object, or a leaked or doubly dropped reference, then fails the test instead of passing by luck.
- Make sure the threads overlap. A writer that finishes in 13 ms while readers sleep a 10 ms tick tests little; let writers run until every reader has done a minimum number of passes (with a cap).
-
Swap needs real memory pressure. To test that pages go to swap
and come back, a test module can hold free pages
(
uvm_pagealloc()in a loop, pausing when it fails) until the page daemon has paged out the object under test -- checked by the object's pages no longer being resident -- then free them all. Deactivating the object's pages first (pgo_put(..., PGO_DEACTIVATE)) makes them the first candidates. The VM needs swap (swapctl -aon a file). -
Kernel code that rump cannot run (pmap, page tables): a test
kernel module exposing sysctl nodes, driven by an ATF program that
loads it (
tests/modules/x86_pte_tester+t_x86_pte, andcacheattr_tester+t_cacheattr). Repeat loops in the VM run detached (nohup sh loop.sh > log &) and are checked afterwards together withuptime: a panic reboots the VM, and a loop driven over SSH then just hangs.vmstat -ecounters show progress. - Run them on both systems. Rump on Linux and NetBSD differ in timing and clock granularity; a race can pass hundreds of runs on one and fail a few times in a thousand on the other.
- Run them hundreds of times. A bug that fails one run in 75 is invisible to a single run.
- Fork per test in host harnesses, and give hanging runs a timeout; attach gdb to a hung run and look at every thread.
For pure algorithms, a quicker loop is compiling the kernel sources on
the build host with tiny stand-ins for the few NetBSD headers they
include, under AddressSanitizer and UBSan.
A harness kept outside the tree does this for linux_rbtree.c
(candidate to move into the tree). It is not a substitute for the rump test, which
runs in the real kernel environment, but it gives results in seconds.
Gotcha: put only the headers under test on the host include path —
the host's libc includes <linux/limits.h> and would pick up the
compat version.
Different techniques catch different classes of bug; a compat API is covered when each class has a test that could see it.
-
Reimplementing against the Linux semantics (reading Linux's
documentation and callers, not the old code) finds wrong contracts:
an inverted predicate (
str_has_prefix), an interval query that misses intervals starting before the range, an off-by-one at an inclusive maximum or a wrap pastULONG_MAX(xa_find_after), a replaced entry removing the new node instead of the old (xa_store), 64-bit identifiers truncated to 32 bits. -
Locking contracts — which lock a caller already holds — show up
as recursion on a spin mutex (
xa_loadunderxa_lock, asdrm_minor_acquiredoes) or as a callback asserting a lock it runs without (fence-array callbacks run under the member's lock, not the array's).LOCKDEBUGkernels and assertions on every lock assumption make these fail at once rather than deadlock later. - Randomized comparison with a simple model (operations on the real structure and on an obviously-correct one, then compare) finds invariant violations: an augmented red-black tree whose cached value goes stale on erase.
-
Postcondition checks — memory returned zeroed, inside the DMA
mask, mapped where claimed — find arithmetic and plumbing errors,
such as a host macro silently changed by a compat redefinition
(see
PAGE_MASK). -
Stress loops run hundreds of times find races that one run never
shows: references dropped twice, use after free (in rump itself:
kthread_join()reading a freed lwp), counters updated under two different locks. With AddressSanitizer, also plain memory errors (a heap overflow inlibrumpuser). - The same test on another kernel (rump on Linux, then NetBSD) changes timing and clock granularity: a one-tick timeout that reports time left, a pointer published after it is announced, a wakeup of a task that already exited.
- Kernel stress loops for pmap work find hardware-coherence bugs: stale TLB entries after page-table changes (see Page tables, TLBs and memory types).
-
Loading the real modules (a test module that depends on
drmkms_linux) checks module linkage — link sets, unresolved symbols — which no compile test sees.
A local script builds the distribution and sets, the test kernel's
set and a live image whose rc.local runs the requested test
directories when /etc/aibsd-autotest exists, printing results
between AIBSD-AUTOTEST markers on the serial console and powering
off. It writes the image over a dedicated, disposable VM's disk —
it refuses any VM not marked as such, so a VM used for interactive
work is never wiped — boots it, and reads the results from the
serial log. A run takes about a minute after the build. This is the
final check before pushing; day to day, use the two fast loops above.
Build the test programs in their object directories (nbmake obj
first): built in place, their .o, .d, .depend and binaries land
next to the Makefiles and are easily committed by accident.
- Cross-port compile coverage: amd64 and i386 GENERIC and ALL, evbarm GENERIC and GENERIC64.
- Rump tests for wait queues and
ww_mutex. - Moving the host harness for rump into the tree.
aiBSD system development guide
Tutorial
II — Building
III — The kernel
- Kernel basics
- Booting and kernel modules
- Threads, processes, tasks
- Devices and drivers
- Files, descriptors, device nodes
- PCI
- Virtual memory
- Memory and DMA
- Page tables, TLBs, memory types
- Firmware
- State and events
- The console
- Power management
IV — Linux compat layer
V — DRM
VI — Testing
VII — Upstreams
Appendices