
Recall first from Choosing and scoping your project
- The 2025 MIT lab repository has nine lab branches: util, syscall, pgtbl, traps, cow, net, lock, fs and mmap
- Stock xv6-riscv already allocates heap pages lazily through sbrklazy and vmfault, so a lazy-allocation project must go beyond it
- In the per-CPU allocator project every free page starts on CPU 0's list, because kinit runs only on hart 0, so stealing from other CPUs belongs in the minimal deliverable
One test at a time, with usertests as the net
4 min readThe last lesson produced a design doc; this lesson executes it. It covers branch-per-feature git commits, getting one test passing before the next with usertests as a regression net, and matching panic, backtrace, GDB and printk to the symptom at hand.
xv6 ships with the regression net already built. user/usertests.c is about 3,600 lines of tests that hammer every system call, the file system, memory and processes. On the stock tree it takes about a minute under QEMU in quick mode. This is the start and end of a real run on commit fa2ddcb:
$ usertests -q
usertests starting
test copyin: OK
test copyout: OK
test copyinstr1: OK
...
test lazy_sbrk: OK
test partial_write: OK
test unlinkcwd: OK
ALL TESTS PASSED
That run printed 69 OK lines. Ask for anything else and the program prints its options: Usage: usertests [-c] [-C] [-q] [testname]. -q runs only the quick tests; with no option it also runs the slow ones; a test name runs just that test, which is the fastest way to re-check one failure; -c repeats the whole suite until a failure and -C repeats it regardless. Two lines matter beyond OK. A failing test prints FAILED and the run ends with SOME TESTS FAILED. And around every pass, usertests counts free pages with countfree() and prints FAILED -- lost some free pages if fewer remain afterwards, so a leak fails the suite even when every individual test passed.
The feature's own test tells you whether you are moving forward; usertests tells you whether you broke something on the way. Use both after every step, in that order. For the per-CPU allocator from the last lesson, the steps and what each run showed:
Baseline. On the unmodified
lockbranch,kalloctestprintedtest1 FAILwithlock: kmem: #test-and-set 107239 #acquire() 433058, thentest2 OK. Record this before you change anything.Array of lists, no stealing. Build only. Reading
kinitalready told you this slice cannot pass, so do not commit it as "working".Add stealing.
kalloctestprintedtest1 OKwith fourkmemlocks each showing#test-and-set 0, thentest2 OK,test3 OKandtest4 OK.Regression net.
usertests -qon the same kernel printedALL TESTS PASSED, about 150 seconds after the command (the lock branch boots four harts and adds lock statistics).Commit, then start the first stretch goal from a green tree.
Notice the order inside each step: the narrow test first, because it is fast and tells you whether the step did what you meant, then the full suite, because it is slow and tells you what you broke. Never start the next step with a red suite. If usertests fails after step 3, the bug is in step 3's diff, which is a few dozen lines. If you wait until step 5 to run it, the bug is somewhere in everything.
Branch per feature, commits that build
2 min readDo the project on its own branch, cut from the tree that passed usertests before you began. On the lab repository that tree is the lab branch itself:
git switch lock # the starting point, tests already run
git switch -c percpu-kalloc # all project work lives here
# ... edit kernel/kalloc.c for one step ...
make qemu # run kalloctest, then usertests -q
git add kernel/kalloc.c
git commit -m "kalloc: steal a page from another CPU when the local list is empty"
Three rules make the history useful later.
Every commit builds and passes. The xv6 Makefile compiles with -Werror, so a warning breaks the build; fix it before committing. A commit that does not boot is a trap for git bisect and for your reviewer.
One idea per commit. "Add per-CPU lists" and "steal on empty" are two commits; "fix typo in comment, also change the lock order" is two commits that were squeezed into one. Small commits make the review in the next lesson possible and make reverting one idea cheap.
The message says why. The diff already says what changed. "Steal a page from another CPU when the local list is empty" tells a reader the reason; "update kalloc.c" tells them nothing.
The payoff comes when a test that passed last week fails today. git bisect does a binary search through the commits between a good one and a bad one. You mark the ends with git bisect good followed by a known-good commit hash and git bisect bad, build and test the commit it checks out, mark it, and repeat; with 16 commits in between it needs at most 4 test runs to name the first bad commit. It only works if every commit builds, which is the first rule again. When you are done, git diff lock..percpu-kalloc shows the whole feature as one diff, ready for review.
Matching the debugger to the symptom
5 min read| Symptom | Evidence you have | First tool |
|---|---|---|
panic: ... on the console |
the message, a frozen machine | grep the message, then GDB bt |
usertrap(): unexpected scause |
cause, sepc, stval |
kernel/kernel.asm or addr2line on sepc |
scause=... sepc=... stval=... from kerneltrap |
a kernel fault address | GDB at that sepc |
| hang, no output | a CPU spinning or sleeping forever | GDB: interrupt, info threads, bt |
| wrong value or wrong order | nothing on the console | a targeted printk |
Panic messages first. In the stock tree panic() in kernel/printk.c prints panic: and its string, then spins forever, so the machine freezes with the message on screen. Every message is a literal string you can grep: acquire and release come from spinlock.c, kfree from kalloc.c, freewalk: leaf and mappages: remap from vm.c, sched locks from proc.c. The string names the check that failed, which is usually one step away from the bug.
User faults. When a user program touches a bad address, usertrap prints usertrap(): unexpected scause 0x... with the process id, then sepc (the faulting instruction) and stval (the bad address), and kills the process. Look up sepc in the program's .asm file under user/ to find the line. We tried it with a small program that writes through a null pointer:
$ nulltest w
usertrap(): unexpected scause 0xf pid=4
sepc=0xe stval=0x0
scause 15 is a store page fault, stval 0 is the address, and user/nulltest.asm shows e: 00f02023 sw a5,0(zero) at offset 0xe. The same program reading through the null pointer did not fault at all and printed a value: xv6 links user programs at address 0, so address 0 holds the program's own code, readable but not writable. A null read in xv6 is a silent wrong value, not a crash.
GDB for everything that stops or hangs. make qemu-gdb starts QEMU paused and waiting on TCP port 25000 plus your user id modulo 5000 (the Makefile's GDBPORT); gdb-multiarch with the generated .gdbinit connects to it. break panic then continue stops at the moment of any panic with the whole stack intact, and bt shows how you got there. For a hang, press Ctrl-C in GDB, run info threads to see what each hart is doing, and bt on each. The stock tree has no kernel backtrace() function; the traps lab adds one that walks frame pointers, and until you have it GDB's bt is your backtrace.
printk for wrong values. Note the name: in this tree the kernel's print function is printk, not printf (the lab branches still call it printf). A printk at the exact place a value is computed is the right tool when nothing crashes but the answer is wrong. Keep them few and targeted, print the values that test your hypothesis (not "got here"), guard them with a counter so a hot path does not flood the console, and remove them before you commit.
The next session's lesson on bugs walks one panic from first symptom to fix with exactly these tools.
Going deeperMeasuring against baseline, and making the test reproducible
A performance feature needs a number before and after, measured the same way. The lock branch instruments every spinlock: acquire counts how many times it is called and how many test-and-set spins it needed, and kalloctest reads the totals through the statistics system call. On the same QEMU setup, the baseline printed lock: kmem: #test-and-set 107239 #acquire() 433058 for test1, and the per-CPU version printed four kmem lines, the busiest #test-and-set 0 #acquire() 125511, with tot= 0. That is the measurement to quote, not "it feels faster". Keep the conditions fixed (same CPUS, same QEMU, nothing else running) and run each side more than once, because QEMU timing varies with the host.
Then make the check runnable by anyone with one command. Add the test program to UPROGS so it is in fs.img, and add a Makefile target that boots xv6, runs it, and fails unless it prints its success line. We added this to the stock Makefile together with $U/_alloctest in UPROGS:
# run alloctest in a fresh xv6 and fail if it does not print OK
check-alloc: fs.img $K/kernel
(sleep 8; echo alloctest; sleep 15) | timeout 30 $(MAKE) -s qemu > alloc.out 2>&1 || true
grep -q "alloctest: .*OK" alloc.out && echo "check-alloc: PASS" || (echo "check-alloc: FAIL"; exit 1)
make check-alloc printed check-alloc: PASS and exited with status 0. The recipe lines must start with a tab. The sleeps are crude (a slow machine needs longer), which is why the lab repositories use a Python grading library that waits for the prompt instead; for a project, a target like this is enough for a reviewer to reproduce your result.
With the feature built and green, the next lesson weighs what it cost: correctness against performance and simplicity, a review of the diff by someone else, and a written account of what you learned.
Key takeaways
- usertests -q ran 69 tests on stock xv6-riscv and printed ALL TESTS PASSED about a minute after boot under QEMU
- usertests compares free pages before and after and prints FAILED -- lost some free pages when memory leaks
- In the stock tree the kernel prints with printk, panic prints panic: and the message, and usertrap reports unexpected scause with sepc and stval
Reflect
- Explain to a colleague, in two sentences: run usertests in quick, single-test and continuous modes and read its pass and leak lines
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Sourcexv6-riscv user/usertests.c
- Sourcexv6-riscv kernel/printk.c
- Man pagegit-bisect(1) man page
- DocumentationDebugging with GDB
Official documentation first. Links checked when the lesson was published.