Module 3 · Lesson 69 of 77

Bugs, debugging and review feedback

Recognise the four common xv6 bug classes by their symptoms, run a reproduce, hypothesise and confirm cycle in GDB, and turn a review comment into a tested diff.

  • Beginner to advanced
  • 8 min read
  • 85 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM with git, make, the riscv64 GNU toolchain, QEMU 8.2 (qemu-system-misc) and gdb-multiarch, and the stock xv6-riscv tree; no board is required

Your place in the module
By the end you can 4 objectives
  • Name the symptom and the first check for page-table leaks, lock-order violations, reference-count mistakes and off-by-one block indexing
  • Reproduce a kernel bug on demand and narrow it with a GDB backtrace and targeted prints until one hypothesis remains
  • Confirm a hypothesis by predicting a value and reading it in GDB before changing any code
  • Turn a reviewer's comment into a small diff, rerun the tests and answer a hostile why-not-just-X question
Video coming soonBugs, debugging and review feedback
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from The demo and the rubric
  • A demo shows the feature first, the evidence second and the code third, and every output on screen comes from the build being demonstrated
  • A design decision is explained as what you chose, what you rejected and the number or code fact that decided it
  • Robustness means usertests -q prints ALL TESTS PASSED and the leak checks pass on the final build, not on an earlier one
01

Four bug classes and how they show up

3 min read

The rubric from the last lesson sets the bar; this lesson meets it on the hardest part. It recaps the common bug classes, walks a live reproduce-hypothesis-confirm cycle in GDB and printk, and incorporates a reviewer's comment as a concrete diff.

Four classes account for most of the bugs in the projects of this studio. Each has a symptom you can recognise and a first check that splits it from the others.

Page-table leaks. A process's page table is a tree of pages. Freeing it is two steps: uvmunmap removes and frees the leaf mappings, then freewalk frees the table pages and panics if it still finds a valid leaf. That check is in kernel/vm.c:

c
    } else if (pte & PTE_V) {
      panic("freewalk: leaf");
    }

So panic: freewalk: leaf means some mapping was never unmapped, typically one your project added (a mapped file region, an extra shared page) that exit or exec does not know about. The quieter form is leaked physical pages: no panic, but usertests prints FAILED -- lost some free pages at the end. First check: list every place your feature calls mappages and find the matching uvmunmap on every exit path.

Lock-order violations and double acquires. Taking a spinlock the same hart already holds panics at once with panic: acquire, because acquire in spinlock.c checks holding(lk). Two harts taking two locks in opposite orders does not panic: both spin forever and the console goes silent. First check for a hang: GDB, info threads, bt on each; two threads inside acquire holding each other's lock is the signature. Returning to user space with a lock held is a special case of the double acquire, and it is the bug the next section chases.

Reference-count mistakes. With copy-on-write or shared mappings, one physical page has several users and must be freed only when the count reaches zero. Freeing early makes a use-after-free: kfree fills the page with the byte 1 and kalloc fills a reused page with 5 (both junk fills are in kalloc.c), so a process reading 0x01010101 or 0x05050505 where its data should be is reading a freed or reused page. Freeing late, or never, leaks pages. First check: print the count at every increment and decrement for one page and look for a path that skips one.

Off-by-one in block indexing. An inode has NDIRECT (12) direct block numbers and one indirect block, in uint addrs[NDIRECT + 1]; bmap treats any block number below NDIRECT as direct. Compare with less-than-or-equal by mistake and block 12 of a file is read from addrs[12], which holds the indirect block's number, so file data overwrites the indirect block and later blocks point to garbage. The symptom appears only for files larger than 12 blocks, which is why the large-file tests catch it and small tests do not. First check: test the exact boundary sizes, 12 and 13 blocks, and the last block a file can have.

Bug classes and their signsUsual symptomFirst checkPage-table leakfreewalk:leaf, lostpageseverymappages hasan uvmunmapLock order ordouble acquirepanic:acquire, orsilent hangGDB bt onevery threadRefcount mistake0x01 or 0x05junk, lostpagesprint countchanges forone pageBlock indexoff-by-onecorruptionpast 12blockstest sizes12, 13 andmax
Bug classes, their symptoms and the first check for each
02

Reproduce, hypothesise, confirm: a live walkthrough

4 min read

Here is a real session on the stock tree. A project added locking to sys_getpid in kernel/sysproc.c with an early return, and a test program pidtest that prints getpid() twice. We built it and ran the cycle exactly as you would.

Reproduce. Boot and run the program. It fails the same way every time, which makes it the easy kind:

bash
$ pidtest
panic: acquire

Not one line of pidtest's output appeared, so the failure happens during or right after its first system call. The message says a hart tried to acquire a lock it already held.

Hypothesis 1: some lock is taken twice. Which one, and where? A panic message does not say which lock. A backtrace does. Start make qemu-gdb, connect gdb-multiarch to port 25000 (uid 0 in our image), and stop at the panic. (We ran GDB in batch mode; the (gdb) prompts are added here and a few lines, such as the last frame in user space, are trimmed.)

bash
(gdb) break panic
(gdb) continue
Thread 2 hit Breakpoint 1, panic (s=s@entry=0x80007048 "acquire") at kernel/printk.c:139
(gdb) bt
#0  panic (s=s@entry=0x80007048 "acquire") at kernel/printk.c:139
#1  0x0000000080000c10 in acquire (lk=lk@entry=0x80012a28 <proc+720>) at kernel/spinlock.c:26
#2  0x0000000080002152 in killed (p=p@entry=0x80012a28 <proc+720>) at kernel/proc.c:637
#3  0x0000000080002644 in usertrap () at kernel/trap.c:81

The lock is proc+720, the lock of one entry in the process table, and it was being taken by killed(), called from usertrap at trap.c line 81. That line is the killed(p) check usertrap makes after a system call returns. So the process's own p->lock was already held when its system call finished.

Hypothesis 2: a system call returned while holding p->lock. Which call, and was it this hart? Make predictions that would be true if this hypothesis holds: the lock's locked field is 1, its cpu field points to this hart's struct cpu, and the trapframe's a7, which carried the system call number into the kernel, names the call that just ran. Read them, without changing any code:

bash
(gdb) frame 2
(gdb) print p->pid
$1 = 3
(gdb) print p->name
$2 = "pidtest\000\000\000\000\000\000\000\000"
(gdb) print p->lock
$3 = {locked = 1, name = 0x80007178 "proc", cpu = 0x800123d8 <cpus+128>}
(gdb) print p->trapframe->a7
$4 = 11
(gdb) print mycpu()->noff
$5 = 2

Every prediction holds. cpus+128 is cpus[1] (a struct cpu is 128 bytes), the hart GDB calls thread 2, the one that panicked. noff is 2: one push_off from the lock still held, one from the acquire that panicked. And a7 is 11, which kernel/syscall.h defines as SYS_getpid. The hypothesis is confirmed and narrowed to one function. Reading it now takes seconds:

c
uint64
sys_getpid(void)
{
  struct proc *p = myproc();
  acquire(&p->lock);
  int pid = p->pid;
  if(pid > 2)
    return pid;          // BUG: this path keeps p->lock
  release(&p->lock);
  return pid;
}

The early return skips the release for every process with a pid above 2, which is every program you start from the shell. init (pid 1) and sh (pid 2) would never have shown the bug, which is a reminder to test from more than one process.

When nothing crashes and GDB has nothing to stop on, the same cycle works with a targeted printk instead (the stock kernel's print function): print exactly the value your hypothesis predicts, at the place it is computed, and compare. Here printk("getpid: pid %d holding %d\n", pid, holding(&p->lock)); just before each return would have shown holding 1 on the early path. Either way, the rule is the same: no code changes until a prediction has been checked.

03

Turning a review comment into a diff

4 min read

The first fix is the obvious one, releasing on every path. As a diff against the buggy commit:

bash
--- a/kernel/sysproc.c
+++ b/kernel/sysproc.c
@@ -22,8 +22,6 @@ sys_getpid(void)
   struct proc *p = myproc();
   acquire(&p->lock);
   int pid = p->pid;
-  if(pid > 2)
-    return pid;          // BUG: this path keeps p->lock
   release(&p->lock);
   return pid;
 }

After rebuilding, the program ran to the end:

bash
$ pidtest
pidtest: pid 3
pidtest: pid again 3

Then the reviewer read the diff and left one comment: "sysproc.c, sys_getpid: why take p->lock at all? p->pid is set in allocproc before the process can run and does not change while it runs, and the stock code reads it without the lock. The lock adds a way to fail and protects nothing here. Suggest restoring return myproc()->pid;." That comment has the three parts from the review lesson: where, what is wrong, what to do. It also cites the code, so the author can check the claim instead of taking it on trust: in the stock tree sys_getpid is exactly return myproc()->pid;.

The author's answer is a second small commit that applies the suggestion, and a reply that quotes evidence from the new build: the pidtest output and the last line of usertests -q, which on the stock sys_getpid is ALL TESTS PASSED. Two commits, not one squashed change, so the history shows both the bug fix and the simplification and the reviewer can re-read just the second.

From panic to merged fixReproducepanic:acquirebtkilled,usertrapConfirma7 = 11,getpidCommit 1release onall pathsReviewcommentlock notneededCommit 2return myproc()->pidReproducepanic:acquirebtkilled,usertrapConfirma7 = 11,getpidCommit 1release onall pathsReviewcommentlock notneededCommit 2return myproc()->pid
From panic to merged fix: the two commits and what proved each
Going deeperDefending an implementation: answering why not just X

In a tough review the hardest questions start with "why not just". They are fair: X is usually simpler, and the burden is on the more complex design. Answer with the same shape as a design decision, choice, alternative, evidence, and add the case where X fails.

"Why not just make acquire reentrant, so taking a lock twice is allowed?" Because the panic is the only thing that caught this bug at the point of failure. A reentrant lock would have let sys_getpid return holding p->lock silently; the next process to need that lock (the scheduler, wait, kill) would hang with no message. xv6's acquire panics on purpose.

"Why not just use one big lock for the whole allocator?" Because kalloctest measured 107239 spins on it in test1, and 0 with per-CPU locks. If your workload does not allocate under contention, the big lock is the right answer, and you should say so.

"Why not just disable interrupts instead of locking?" Because push_off stops interrupts on one hart only; the other harts keep running and can touch the same data. Interrupts off is necessary around cpuid(), not sufficient for shared state.

When you have no evidence, say that and offer the measurement that would settle it. "I have not measured that" ends an argument better than a guess, which a reviewer will test.

The next lesson asks whether the fixed project is sound under pressure: running the whole suite repeatedly, checking for leaks and deadlocks, and naming honestly what is still missing.

Key takeaways

  • A syscall that returns while holding p->lock panics at once with panic: acquire, because usertrap calls killed(), which acquires p->lock again
  • In GDB the panicking frame's p->trapframe->a7 holds the number of the system call that just ran, which named SYS_getpid (11) in our run
  • freewalk: leaf, panic: acquire, a silent hang and data corruption point to page-table leaks, double acquires, lock-order cycles and refcount or indexing bugs
Reflect
  1. Explain to a colleague, in two sentences: name the symptom and the first check for page-table leaks, lock-order violations, reference-count mistakes and off-by-one block indexing
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. 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

Find your next step

↑ ↓ to move · Enter to open · Esc to close