Module 3 · Lesson 67 of 77

Tradeoffs, review and the write-up

Weigh correctness, performance and simplicity for each design decision, review a partner's kernel diff with specific comments, act on review of your own, and write a short retrospective.

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

Ubuntu 24.04 in WSL2 or a VM with git, make, the riscv64 GNU toolchain and QEMU 8.2 (qemu-system-misc, ipxe-qemu for the net branch), your project branch and a partner's branch to review; no board is required

Your place in the module
By the end you can 4 objectives
  • Compare two designs for the same xv6 feature on correctness, measured performance and simplicity, and justify the choice
  • Review a kernel diff and write comments that name the line, the failure and a fix
  • Turn a review comment on your own code into a tested commit and merge it
  • Write a retrospective of what worked, what failed and what you would change, backed by numbers
Video coming soonTradeoffs, review and the write-up
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Building and testing incrementally
  • 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
01

Correctness, performance, simplicity

4 min read

The last lesson built and tested the feature; this lesson finishes it. It weighs correctness, performance and simplicity for each decision, gives and receives specific code review feedback, and writes a short retrospective of what worked and what you would change.

The running example makes the trade concrete because both designs exist and both were measured. The stock allocator on the lock branch has one free list and one lock, kmem.lock. The per-CPU version has NCPU lists, one lock each, and steals when its own list is empty. Under the same QEMU setup with four harts:

One big lock Per-CPU lists
kalloctest test1 kmem spins #test-and-set 107239 #test-and-set 0 on all four locks
test1 verdict test1 FAIL test1 OK
leak tests test2 to test4 OK OK
usertests -q passes ALL TESTS PASSED
new code none push_off around cpuid, steal loop
failure modes contention only wrong CPU's list if cpuid is read with interrupts on

Read the table in priority order.

Correctness first. Both designs pass the leak tests and the full suite, so both are correct as far as the tests can tell. That "as far as" matters, because tests only exercise the interleavings that happened to occur. The per-CPU version depends on an argument no test checks directly. cpuid() reads the hart number from tp, and its comment in proc.c says it "Must be called with interrupts disabled". Without push_off(), a timer interrupt can move the thread to another hart between reading the id and using it. In our design that is harmless, because every list is still taken under its own lock: the page just lands on another CPU's list. But the argument is fragile. A tempting stretch goal is to skip the lock on "my own" list, since no other CPU should touch it; the moment you do that, a stale id becomes a real race, two harts editing one list without a lock, and it would almost never fail in a test. Correctness here comes from reasoning written down in the design doc, not from a green run.

Performance second, and measured. The spin count dropped from 107239 to 0. That is a real number from the lock branch's statistics, and it is the only kind of performance claim worth making. "It should be faster" is a guess; "test-and-set spins on kmem fell from 107239 to 0 in kalloctest test1, four harts, QEMU 8.2.2" is evidence. Also be honest about what the number does not show: the busiest locks in both runs were proc and virtio_disk, not kmem, so a program that rarely allocates would see no difference.

Simplicity third. The stock kernel/kalloc.c is 82 lines and obviously right. The per-CPU version adds an array, push_off/pop_off pairs and a steal loop that must never hold two kmem locks at once. That complexity is justified only because the measurement shows a gain under contention. When two designs are both correct and the faster one's gain is too small to measure, pick the simpler one.

The same three questions settle smaller decisions inside a project. Should e1000_transmit reclaim finished buffers in the interrupt handler or lazily when a slot comes round? Lazy is simpler and correct; interrupt-time reclaim frees memory sooner but adds a path to get wrong. Should the UDP port table have one lock (netlock) or one per port? One lock is simpler; per-port locks help only if many harts receive on different ports at once, which nothing in the lab measures. In both cases the simpler choice wins until a number says otherwise.

Judging a design decisionCorrect?tests plusreasoningFaster?measured,withconditionsSimplest?of thedesignsleftChoose andrecord whyExit from step 1: noreject, whatever its speedCorrect?tests plusreasoningFaster?measured,withconditionsExit from step 1: noreject, whatever its speedSimplest?of thedesignsleftChoose andrecord why
The order in which a design decision is judged
02

Reviewing a diff, and being reviewed

3 min read

Review the diff, not the person, and review it against the design doc. Read the doc first, then git diff base..branch, then build and run the tests yourself; a review that never ran the code only checks spelling. Useful comments have three parts: where (file and line), what goes wrong (an input or interleaving and its result), and what to do (a concrete change or a question that forces a decision). "This looks racy" is not actionable. "e1000.c line 117: if a second frame arrives while net_rx runs, ..." is.

Here is a review worked through on the net lab solution from M3-S09B3, with the test run for real. The proposed change looks like extra safety, with the reasoning "the ring is shared, so the receive loop should hold the lock too":

c
 static void
 e1000_recv(void)
 {
+  acquire(&e1000_lock);          // reviewed version: lock the whole loop
   while(1){
     ...
     regs[E1000_RDT] = i;       // hand the slot back to the card
     net_rx(buf, len);          // net_rx (or its callees) frees buf
   }
+  release(&e1000_lock);
 }

The review comment:

e1000.c, e1000_recv: the new acquire is held across net_rx. For an ARP frame, net_rx calls arp_rx, which calls e1000_transmit, which does acquire(&e1000_lock) on the same hart. xv6 spinlocks are not reentrant, so acquire sees holding(lk) and panics. Suggest: drop the lock from the receive loop; only the interrupt handler touches the RX ring, and the PLIC does not deliver IRQ 33 again until plic_complete. If you keep a lock, release it before calling net_rx. Please run nettest grade with nettest.py grade to confirm.

The author's job is not to argue but to run it. With the change applied, the xv6 console showed:

bash
$ nettest grade
txone: sending one packet
arp_rx: received an ARP packet
panic: acquire

The fix is to revert the two added lines, in a commit whose message records why, for example "e1000_recv: do not hold e1000_lock across net_rx (arp_rx transmits; spinlocks are not reentrant)". Without the lock, nettest grade printed every OK again. Two lessons in one comment: the reviewer named the exact call chain instead of a vague worry, and the author answered with a test result instead of an opinion.

When you are the author, every comment gets one of three answers: a commit that fixes it, a test that shows it is not a problem, or a reason you are not changing it that the reviewer can accept or escalate. Do not silently ignore a comment and do not "fix" one by changing something unrelated. Keep each fix in its own commit so the reviewer can re-read just that change; the Linux kernel's patch guide asks for the same thing for the same reason.

A review comment becomes a merged fixAuthorReviewerTestsgit diffbase..branchwhere, what fails,fixnettest gradepanic: acquirefix in its owncommitall OK, merge1. Author → Reviewergit diff base..branch2. Reviewer → Authorwhere, what fails, fix3. Author → Testsnettest grade4. Tests → Authorpanic: acquire5. Author → Reviewerfix in its own commit6. Tests → Authorall OK, merge
One review comment from diff to merged fix
03

The write-up: a short retrospective

3 min read

A retrospective is one to two pages, written within a day of finishing while you still remember the dead ends. Use five headings:

Step by stepFive headings for a project retrospective
  1. What I built. The feature in two sentences and the command that shows it, with its real output.

  2. How I know it works. The tests you ran, with their final lines: your own test, the lab test, usertests -q.

  3. What the numbers say. Baseline against feature, measured the same way, with the conditions.

  4. What failed. Bugs you hit, how long each took, and the evidence that found it.

  5. What I would do differently. Concrete changes to the design or the process, not "start earlier".

For the per-CPU allocator, a real entry under "What failed" reads: "The first slice (per-CPU lists, no stealing) could never pass: kinit frees every page on hart 0, so other CPUs start empty. I found it by reading kinit, not by running it; stealing moved into the minimal deliverable." Under "What the numbers say": "kalloctest test1, four harts, QEMU 8.2.2: kmem test-and-set spins 107239 before, 0 after; proc and virtio_disk remain the most contended locks." Under "What I would do differently": "Spread free pages across CPUs in kinit so stealing is rare from the start, and add a steal counter before tuning anything."

Write it for a specific reader: the student who will extend your project next term, or you in six months. That reader has the code and the diff, so do not retell them. They lack exactly what is not in the code: the alternatives you tried and dropped, the bug that cost a day and the evidence that finally exposed it, the measurement conditions, and the parts you know are weak. A paragraph on a dead end you abandoned is often the most useful part of the document, because it is the one thing nobody can recover from git log.

Two rules keep a write-up honest. Every number has its conditions next to it (which test, how many harts, which QEMU), because a number without conditions cannot be checked. And the failures section is not optional: a retrospective that reports only successes teaches the next reader nothing they could not get from the diff.

The project is built, reviewed and written up. The next session is about showing it: a live demo, explaining each design decision, and the rubric it will be judged by.

Key takeaways

  • Correctness comes first, then measured performance, then simplicity; a faster design that is not provably correct is not a choice
  • Per-CPU free lists cut kmem test-and-set spins in kalloctest test1 from 107239 to 0, at the cost of stealing logic and push_off around cpuid
  • Holding e1000_lock across net_rx looks safer but panics with acquire, because arp_rx transmits and xv6 spinlocks are not reentrant
Reflect
  1. Explain to a colleague, in two sentences: compare two designs for the same xv6 feature on correctness, measured performance and simplicity, and justify the choice
  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