Skip to content

Testing

ebenali edited this page Dec 3, 2026 · 13 revisions

Testing

Part VI of the system development guide.

aiBSD follows NetBSD's three layers:

  1. Compile coverage — build.sh builds, including ALL kernels, for every port that enables the code.
  2. Unit tests — ATF tests in src/tests, installed in /usr/tests, run with atf-run or kyua. Kernel code is tested in a rump kernel: the real kernel sources, linked into a user process.
  3. System tests — boot a freshly built image and run the installed test suite in it (what NetBSD's anita automates).

Compile testing while code does not build yet

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-kernel

The 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.

Unit tests in a rump kernel

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, .PATH to the sources, .include "${RUMPTOP}/Makefile.rump"). Add a source file here when it gets tests.

  • An ATF C program linked with -Wl,--whole-archive against it and ${LIBRUMPBASE}. It calls rump_init() and rump_schedule(), then the kernel functions under their rump names: rump prefixes kernel symbols with rumpns_, 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_SUBDIRS in the parent Makefile, the program and directory in distrib/sets/lists/tests/mi, the .debug file in debug/mi, the directories in etc/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.

A rump kernel on the build host

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.sh tool (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 empty SHLIB_LDSTARTFILE, SHLIB_LDENDFILE and DPLIBC (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 on sys/endian.h; it is not needed — librump and librumpuser are.
  • Our tests. The rumpmake wrapper it produces builds the private test library (tests/dev/drm/liblinux) with the host compiler; a small host program calls rump_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 every rump_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 dev VM

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.

Device tests

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.

Rump pitfalls

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_NCPU before rump_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, pserialize and even kthread_create wait 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; test curlwp->l_nopreempt instead (what kpreempt_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.
  • curlwp may be cached. The __thread flavour of rump's curlwp is __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 with rump_lwproc_rfork()/rump_lwproc_switch(). Ask rump_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.

Writing stress tests

  • 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 -a on 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, and cacheattr_tester + t_cacheattr). Repeat loops in the VM run detached (nohup sh loop.sh > log &) and are checked afterwards together with uptime: a panic reboots the VM, and a loop driven over SSH then just hangs. vmstat -e counters 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.

Host-side harnesses

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.

What each kind of test finds

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 past ULONG_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_load under xa_lock, as drm_minor_acquire does) or as a callback asserting a lock it runs without (fence-array callbacks run under the member's lock, not the array's). LOCKDEBUG kernels 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 in librumpuser).
  • 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.

Running the system tests

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.

Still to set up

  • 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.

Clone this wiki locally