Chris Low-level systems developer

C / RISC-V / FIRMWARE / OS INTERNALS

Chris Dillinger, freelance RISC-V and OS kernel systems programmerI help firmware teams and hardware startupsship reliable low-level C, covering bare-metalbring-up and crash fixes.

Focused, fixed-scope work with small diffs, explicit tradeoffs, and a test trail your team can reproduce.

See the projects

WHO THIS IS FOR

    01 / PROJECTS

    Projects and labs.

    Density

    j / k move, / searches

    Loading projects…

    COMPLETE RECORD

    BLOG / ALL POSTS

    Blog

    Short notes on C, RISC-V, and systems internals.

    LATEST

    The Fence That Names Only Its Top

    ISA

    The claim is the PMP TOR addressing rule as this machine shows it: in TOR mode each entry's region runs from the previous pmpaddr to its own, so pmpaddr1 = 0x20000c00 ends the denied region at 0x80003000 and pmpaddr0 = 0x20000800 ends the allowed region at 0x80002000. The run shows each side directly: the load at 0x80001fff completed with no trap and returned the 0x5a sentinel, and the load at 0x80002000 trapped once with mcause 0x5, mepc 0x80000272, and mtval 0x80002000.

    MICROARCH

    No claim depends on how any core implements the TOR match. QEMU serves as a functional executor only; no pipeline or execution-unit behavior is asserted or measured, and the honest limit states the result is emulator-observed, not silicon-proved.

    FIRMWARE

    No firmware service takes part in the claim. The binary runs in M-mode on bare QEMU with no SBI or firmware calls; the behavior under test is the PMP TOR addressing rule itself.

    KERNEL

    No kernel code runs in the claim. The binary is a bare-metal M-mode program with no supervisor, no scheduler, and no system call path; the fence is a hardware PMP entry, not an operating system service.

    ALGORITHM

    The claim is one fixed addressing rule with boundary probes, not a computation proved against an independent oracle. The results are shown as the consequence the TOR rule forces, not as a verified algorithm.

    A fence usually names both of its edges: the bottom where protection starts and the top where it ends. A PMP entry in TOR mode names only the top. The bottom comes from the entry below it. pmpaddr1 holds the top of its region; the region starts where pmpaddr0 ends. Entry 0 has no entry below it, so its region starts at address 0.

    Measured on QEMU 8.2.2, bare metal in M-mode. The program wrote pmpaddr0 = 0x20000800 and pmpaddr1 = 0x20000c00, then pmpcfg0 = 0x880f: entry 0 TOR with R=W=X=1, entry 1 locked TOR with R=W=X=0. Entry 0 covers [0x0, 0x80002000) and entry 1 covers [0x80002000, 0x80003000), a 4 KiB scratch buffer. A load of the last allowed byte at 0x80001fff completed with no trap and returned the 0x5a sentinel written before programming. A load of the first denied byte at 0x80002000 trapped once, mcause 0x5, mepc 0x80000272, the faulting load itself, mtval 0x80002000. The same boundary, probed three times, gave the same verdict every time. RESULT: PASS. [1]

    The programming, two addresses and one config word:

    csrw pmpaddr0, s1  # s1 = 0x20000800: entry 0 ends at 0x80002000
    csrw pmpaddr1, s2  # s2 = 0x20000c00: entry 1 ends at 0x80003000
    csrw pmpcfg0, s0   # s0 = 0x880f: entry 0 TOR allow, entry 1 locked TOR deny

    Why entry 1 is locked. An unlocked PMP entry does not restrict M-mode at all, and this program runs in M-mode, so an unlocked deny entry would have let both probes through and proved nothing. The lock bit is what makes the fence bind the most privileged mode. The program verified the lock instead of assuming it: after programming, a write of zero to pmpcfg0 left entry 1 at 0x88 while entry 0 cleared to 0x00, and the boundary probes ran after that clear, so the denial came from the locked entry alone. [1]

    The bench habit: when you fence a buffer with TOR, program the bottom into the entry below and the top into the fencing entry, then probe the last byte below the boundary and the first byte inside it. If the inside probe passes, check the lock bit before doubting the fence: an unlocked entry never binds M-mode, and a fence that only binds lower modes is a fence with a hole at the top.

    One sentence to carry away: in TOR mode a PMP entry names only the top of its fence, the entry below names the bottom, and the lock bit is what makes the fence bind machine mode.

    Blueprint-style diagram of the PMP TOR fence in three panels: THE RULE shows pmpaddr names only the top, the region runs from the previous pmpaddr to its own, and entry 0 starts at address 0; BELOW THE LINE: READS shows a load at 0x80001fff completing with no trap and returning the 0x5a sentinel; ON THE LINE: TRAPS shows a load at 0x80002000 trapping with mcause 0x5, mepc 0x80000272, and mtval 0x80002000
    Below the boundary the byte reads. On the boundary the load traps. The entry below names the bottom.
    Diagram: hand-built by Chris Dillinger for this post

    Sources

    1. 01
      src/pmp-tor: module PROOF.md and the QEMU runChris Dillinger

      The QEMU 8.2.2 run behind the post, run firsthand for this post from the module's prebuilt ELF: pmpaddr0 0x20000800, pmpaddr1 0x20000c00, pmpcfg0 0x880f (entry 0 TOR allow, entry 1 locked TOR deny); pmpcfg0 readback 0x880f, after clear attempt 0x8800 (entry 1 byte 0x88 locked, entry 0 byte cleared); lbu at 0x80001fff seen 0, byte 0x5a; lbu at 0x80002000 seen 1, mcause 0x5, mepc 0x80000272, mtval 0x80002000; three runs identical apart from the timeout PID; RESULT: PASS.

    The Bit That Lets Machine Mode Read as User Mode

    ISA

    The claim is the mstatus.MPRV access rule as this machine shows it: with MPRV set and MPP=U, an M-mode load from a deny-all PMP page traps as a load access fault with mepc at the probe site, and with MPRV clear, or with MPP=M, the same load returns the canary. The run shows each side directly: phase A returned 0xc0ffee1234567890 with zero traps, phase B trapped once with mcause 0x5 at 0x800005ee and mtval 0x80002000, and phase C returned the canary again.

    MICROARCH

    No claim depends on how any core implements the MPRV check. QEMU serves as a functional executor only; no pipeline or execution-unit behavior is asserted or measured, and the honest limit states the result is emulator-observed, not silicon-proved.

    FIRMWARE

    No firmware service takes part in the claim. The binary runs in M-mode on bare QEMU with no SBI or firmware calls; the behavior under test is the mstatus MPRV bit's own access rule.

    KERNEL

    No kernel code runs in the claim. The binary is a bare-metal M-mode program with no supervisor, no scheduler, and no system call path; the U-mode check is a privilege field in mstatus, not a guest operating system.

    ALGORITHM

    The claim is one fixed switch and one fixed probe load with trap comparisons, not a computation proved against an independent oracle. The results are shown as the consequence the MPRV rule forces, not as a verified algorithm.

    A machine-mode monitor that wants to check a guest's pointer has a problem: its own loads bypass the protections the guest lives under. M-mode ignores unlocked PMP entries, so a load from a page the guest cannot touch still succeeds for the monitor. One bit in mstatus closes that gap. MPRV, bit 17, makes M-mode loads and stores take the privilege level in MPP instead of M-mode, so the monitor's load is checked exactly as the guest's would be.

    Measured on QEMU 8.2.2, bare metal in M-mode. The program fenced a 4 KiB page at 0x80002000 with one unlocked PMP entry, R=W=X=0, then ran the same load three ways. MPRV clear, MPP=U: the load returned the canary 0xc0ffee1234567890, zero traps. MPRV set, MPP=U: the same load trapped once, mcause 0x5, mepc 0x800005ee, the probe site itself, mtval 0x80002000, and the destination kept its poison value 0xbadc0de0badc0de0. MPRV set, MPP=M: the load returned the canary again, zero new traps. 20 checks, 0 mismatches. RESULT: PASS. [1]

    The probe, three ways:

    csrc mstatus, t1  # t1 = MPP mask: MPP=U, the guest's mode
    csrs mstatus, t0  # t0 = 1<<17: MPRV set
    ld s3, 0(s2)      # s2 = 0x80002000: traps, mcause 0x5
    csrc mstatus, t0  # MPRV clear: machine-mode checks again

    Why the handler clears the bit first. While MPRV is set with MPP=U, the trap handler's own stack saves are checked as U-mode accesses too, so a handler that saves registers before clearing the bit faults on its own first store. This module's entry stashes t0 in mscratch, then clears MPRV with csrc before the first sd. CSR accesses touch no data memory, so that sequence is safe while the bit is still set. The bit changes the rules for every explicit load and store, including the handler's own. [1]

    The bench habit: when a monitor reads memory on a guest's behalf, set MPRV and MPP to the guest's mode first, and let the hardware refuse what the guest could not touch. A load that traps under MPRV is a pointer the guest could not have used either, and a load that returns is one the guest could have made itself. Never read guest memory with machine-mode privilege and assume the result means the guest could have read it.

    One sentence to carry away: one bit lets machine mode borrow the guest's permissions for a single load, and a trap under that bit means the guest could not have made the load either.

    Blueprint-style diagram of the mstatus.MPRV switch in three panels: THE SWITCH shows MPRV bit 17 and MPP bits 11-12, set means loads check as MPP and clear means M-mode checks again; SET, MPP=U: ONE TRAP shows a load from 0x80002000 trapping with mcause 0x5 at 0x800005ee, mtval 0x80002000, and the destination keeping the poison value 0xbadc0de0badc0de0; CLEAR OR MPP=M: CANARY shows the same load returning 0xc0ffee1234567890 with 20 checks and 0 mismatches
    MPRV set, MPP=U: the load traps. MPRV clear, or MPP=M: the same load returns the canary.
    Diagram: hand-built by Chris Dillinger for this post

    Sources

    1. 01
      src/mstatus-mprv-load: module PROOF.md and the QEMU runChris Dillinger

      The QEMU 8.2.2 run behind the post, re-run firsthand for this post: boot mstatus 0xa00000000, pmpcfg0 0x08 over 4 KiB at 0x80002000; phase A (MPRV=0, MPP=U) value 0xc0ffee1234567890, traps 0; phase B (MPRV=1, MPP=U) new traps 1, cause 0x5, mepc 0x800005ee, mtval 0x80002000, destination kept 0xbadc0de0badc0de0; phase C (MPRV=1, MPP=M) value 0xc0ffee1234567890, new traps 0; phase D value 0xc0ffee1234567890; 20 checks, 0 mismatches; checksum 0xcaa47691de34383c; RESULT: PASS.

    The Bit That Traps the Page Table

    ISA

    The claim is the mstatus.TVM access rule as this machine shows it: with TVM set, an S-mode satp write, satp read, and sfence.vma each trap as illegal instruction with mepc at the exact probe site, and with TVM clear the identical pad takes no trap but the closing ecall. The run shows each side directly: mstatus read back 0xa00100000 with the bit set, three mcause 0x2 traps at 0x800002cc, 0x800002d0, and 0x800002e0, and one ecall trap in each phase.

    MICROARCH

    No claim depends on how any core implements the TVM trap. QEMU serves as a functional executor only; no pipeline or execution-unit behavior is asserted or measured, and the honest limit states the result is emulator-observed, not silicon-proved.

    FIRMWARE

    No firmware service takes part in the claim. The binary runs in M-mode on bare QEMU with no SBI or firmware calls; the behavior under test is the mstatus TVM bit's own gating rule.

    KERNEL

    No kernel code runs in the claim. The binary is a bare-metal M-mode program with no supervisor, no scheduler, and no system call path; the hypervisor use is named as the reason for the switch, not as a behavior this run measures.

    ALGORITHM

    The claim is one fixed switch and one fixed probe pad with trap comparisons, not a computation proved against an independent oracle. The results are shown as the consequence the TVM rule forces, not as a verified algorithm.

    One bit in mstatus decides whether supervisor mode may touch virtual-memory control. TVM, bit 20, is the trap switch: set it, and three ordinary S-mode operations trap to M-mode instead of running. Clear it, and the same three operations run normally. The bit lives in M-mode only. S-mode cannot read it or change it; sstatus carries no TVM bit. It can only feel the effect.

    Measured on QEMU 8.2.2, bare metal in M-mode. The program set TVM with one csrs and read mstatus back as 0xa00100000, bit 20 set and nothing else disturbed. An S-mode pad then tried three operations: write satp, read satp, execute sfence.vma. All three trapped as illegal instruction, mcause 0x2, with mepc at the exact probe site each time: 0x800002cc, 0x800002d0, 0x800002e0. A closing ecall made the fourth trap, mcause 0x9. The trapped satp write had no effect: satp still read 0 from M-mode. With TVM clear, the identical pad took one trap only, the closing ecall, and the satp write stuck. 19 checks, 0 mismatches. RESULT: PASS. [1]

    The three traps, side by side:

    csrs mstatus, t0  # t0 = 1 << 20: TVM set, bit 20
    # S-mode csrw satp, zero: trap, mcause 0x2, mepc 0x800002cc
    # S-mode csrr t1, satp: trap, mcause 0x2, mepc 0x800002d0
    # S-mode sfence.vma: trap, mcause 0x2, mepc 0x800002e0

    Why the read matters. The first guess was that only the write traps, and the first run proved that guess wrong: the S-mode satp read trapped too, at 0x800002d0, with the same illegal-instruction cause. The specification covers attempts to read or write satp, and this hart follows the letter of it. A hypervisor that sets TVM to trap a guest's page-table changes must therefore handle the read as well as the write, or the guest's innocent read of satp dies in a trap it never expected. [1]

    The bench habit: when you install a trap-and-emulate switch, probe every operation the switch gates, not just the one you named it for. Here the switch is called a write trap in shorthand, and the read was the operation that actually surprised. A pad that tries the read, the write, and the fence, with the switch set and clear, turns a one-line gloss into a measured rule.

    One sentence to carry away: one bit makes the page-table register untouchable from S-mode, and the read traps just like the write.

    Blueprint-style diagram of the mstatus.TVM trap switch in three panels: THE SWITCH shows mstatus 0xa00000000 at boot and 0xa00100000 after csrs with bit 20 set; SET: THREE TRAPS shows csrw satp trapping with mcause 0x2 at 0x800002cc, csrr satp trapping at 0x800002d0, and sfence.vma trapping at 0x800002e0; CLEAR: NO TRAPS shows the same pad taking one trap only, the closing ecall, with 19 checks and 0 mismatches
    TVM set: the satp write, the satp read, and sfence.vma all trap. TVM clear: the same pad takes no trap but the closing ecall.
    Diagram: hand-built by Chris Dillinger for this post

    Sources

    1. 01
      src/mstatus-tvm-trap: module PROOF.md and the QEMU runChris Dillinger

      The QEMU 8.2.2 run behind the post, re-run firsthand for this post: mstatus at boot 0xa00000000, after TVM set 0xa00100000; phase 1 traps 4: mcause 0x2 at 0x800002cc (satp write), 0x2 at 0x800002d0 (satp read), 0x2 at 0x800002e0 (sfence.vma), 0x9 at 0x800002e4 (ecall); satp after phase 1 0x0; phase 2 new traps 1, ecall only, satp readback 0x0; 19 checks, 0 mismatches; RESULT: PASS.

    The Table That Only Jumps for Interrupts

    ISA

    The claim is the mtvec vectored dispatch rule as this machine shows it: a timer interrupt with code 7 lands at base plus 28, and a U-mode ecall with code 8 lands at the base itself. The run shows each side directly: mtvec read back 0x80000201, the timer landing recorded from the entry 7 stub at 0x8000021c, and both ecall landings recorded from the base stub at 0x80000200.

    MICROARCH

    No claim depends on how any core implements trap dispatch. QEMU serves as a functional executor only; no pipeline or execution-unit behavior is asserted or measured, and the honest limit states the result is emulator-observed, not silicon-proved.

    FIRMWARE

    No firmware service takes part in the claim. The binary runs in M-mode on bare QEMU with no SBI or firmware calls; the behavior under test is the mtvec CSR's own dispatch rule.

    KERNEL

    No kernel code runs in the claim. The binary is a bare-metal M-mode program with no supervisor, no scheduler, and no system call path; the U-mode ecall is the test's own payload, handled by the M-mode handler, not a kernel service.

    ALGORITHM

    The claim is one fixed vector table and two fixed trap probes with landing comparisons, not a computation proved against an independent oracle. The results are shown as the consequence the dispatch rule forces, not as a verified algorithm.

    A vectored trap table promises a shortcut. Set one register, mtvec, to a table base plus mode 1, and each trap jumps straight to its own stub, with no compare chain in the handler to sort out which trap arrived. The table is indexed by trap cause: entry 7 for cause 7, entry 8 for cause 8, each stub four bytes apart.

    Measured on QEMU 8.2.2, bare metal in M-mode. The program wrote mtvec as 0x80000201 and read it back unchanged: base 0x80000200, mode 1, vectored. A control window before any trigger produced zero traps. Two U-mode ecalls, mcause 8 both times, both landed at 0x80000200, the base itself, not at base plus 32. One machine timer interrupt, mcause 0x8000000000000007, landed at 0x8000021c, base plus 28, exactly entry 7. The handler disarmed the source by writing all-ones to mtimecmp, and a quiet window after it produced no second delivery: the timer count stayed 1. RESULT: PASS. [1]

    The two landings, side by side:

    csrw mtvec, t0  # t0 = 0x80000201: base, mode 1
    # timer, code 7: lands at base + 28 (0x8000021c)
    # ecall, code 8: lands at base (0x80000200), not + 32

    Why the split matters. On this machine, vectored dispatch vectors interrupts and leaves synchronous exceptions at the base. That is the behavior the run shows, and it is not the whole specification: the privileged specification vectors synchronous exceptions in vectored mode too, so hardware built to the letter of the spec may send the ecall to base plus 32 after all. The landing is therefore a property to measure on the target, not a fact to assume from the mode bit. [1]

    The bench habit: when you install a vectored table, provoke one interrupt and one exception and record the stub address that actually ran for each. If the exception lands at the base, put the shared exception entry there and do not leave entry 8 empty on the assumption that the hardware will use it. A table with an empty entry 8 is a trap that lands nowhere you tested.

    One sentence to carry away: a vectored table jumps for interrupts, and for everything else it still starts at the base, at least on the machine you measured.

    Blueprint-style diagram of mtvec vectored dispatch in three panels: THE TABLE shows mtvec 0x80000201 with base 0x80000200 and mode 1, entry 7 at base plus 28 and entry 8 at base plus 32; INTERRUPT JUMPS shows the timer interrupt with code 7 landing at 0x8000021c; EXCEPTION STAYS shows the U-mode ecall with code 8 landing at the base 0x80000200, not at base plus 32
    Vectored dispatch on this machine: the timer interrupt lands at entry 7, base plus 28, while the U-mode ecall lands at the base itself, not at entry 8.
    Diagram: hand-built by Chris Dillinger for this post

    Sources

    1. 01
      src/mtvec-vectored: module PROOF.md and the QEMU runChris Dillinger

      The QEMU 8.2.2 run behind the post, re-run firsthand for this post: mtvec written 0x80000201, read back 0x80000201; table base 0x80000200, entry 7 at 0x8000021c, entry 8 at 0x80000220; control traps 0; two U-mode ecalls, mcause 0x8, landings 0x80000200 both times; timer count 1, mcause 0x8000000000000007, landing 0x8000021c; mtimecmp after handler 0xffffffffffffffff; count after quiet window 1; RESULT: PASS.

    The Bit You Cannot Set

    ISA

    The claim is the mstatus SD summary rule as this machine shows it: SD reads 1 exactly when FS reads Dirty, and a forced write to bit 63 reads back 0. The run shows each side directly: FS Initial read back with SD 0, one fadd.d moved FS to Dirty with SD 1, FS Clean returned SD to 0, and the forced bit-63 write left SD 0 with FS unchanged.

    MICROARCH

    No claim depends on how any core implements the SD summary. QEMU serves as a functional executor only; no pipeline or execution-unit behavior is asserted or measured, and the honest limit states the result is emulator-observed, not silicon-proved.

    FIRMWARE

    No firmware service takes part in the claim. The binary runs in M-mode on bare QEMU with no SBI or firmware calls; the behavior under test is the mstatus CSR's own summary rule.

    KERNEL

    No kernel code runs in the claim. The binary is a bare-metal M-mode program with no supervisor, no scheduler, and no system call path; the SD readback is a CSR operation, not a kernel mechanism.

    ALGORITHM

    The claim is one fixed sequence of FS writes, one floating point addition, and register readbacks, not a computation proved against an independent oracle. The results are shown as the consequence the SD summary rule forces, not as a verified algorithm.

    Most status bits are switches: write 1 to set, write 0 to clear, and read back what you wrote. mstatus bit 63, SD, is not a switch. It is a summary, a single bit that reports whether the floating point state is dirty, and the only way to move it is to change the state it summarizes.

    Measured on QEMU 8.2.2, bare metal in M-mode. At boot, mstatus read 0xa00000000, FS Off, SD 0. Writing FS Initial gave 0xa00004000, SD still 0: the floating point unit was enabled but not dirty. One fadd.d, 1.5 plus 2.25, left f0 holding 0x400e000000000000 (3.75) and mstatus at 0x8000000a00006000, FS Dirty, SD 1. Writing FS Clean gave 0xa00002000, SD back to 0. Forcing bit 63 with csrs left mstatus at 0xa00002000, SD still 0, FS unchanged. Restoring the boot word returned 0xa00000000 exactly. Fifteen checks, zero mismatches, traps 0, checksum 0xcd8421132251ca67, RESULT: PASS. [1]

    The four moves, and what SD did after each:

    csrs mstatus, t0  # FS = Initial: SD reads 0
    fadd.d f0, f1, f2  # 1.5 + 2.25: FS = Dirty, SD reads 1
    csrs mstatus, t1  # t1 = bit 63: SD still reads 0
    # writing FS = Clean drops SD back to 0

    Why the forced write cannot stick. SD is defined as a summary of FS, not as a bit of its own: it reads 1 exactly when FS reads Dirty. A write to bit 63 therefore has nothing to change, and the readback shows the state FS is actually in, not the value software offered. A stored copy would disagree the moment the state changed, so the architecture does not store one.

    The bench habit: never test SD by writing it. Test it by dirtying the state and by cleaning it: write FS Initial, execute one floating point operation, read SD, write FS Clean, read SD again. If the first read is not 0, the unit was already dirty before your test. If the forced write sticks, your test is reading a stored bit, not a summary, and every conclusion drawn from it is suspect.

    One sentence to carry away: a summary bit answers a question about state, and it is not a place to store an answer.

    Blueprint-style diagram of the mstatus SD summary bit in three panels: THE SUMMARY shows mstatus bit 63 named SD above the FS field at bits 14 and 13; DIRTY MAKES IT 1 shows FS Initial with SD 0, then fadd.d on 1.5 and 2.25 giving 3.75 with FS Dirty and SD 1; NO WRITE MOVES IT shows a forced write to bit 63 reading back SD 0 and FS Clean reading back SD 0
    SD reads 1 exactly when FS is Dirty: Initial leaves it 0, one fadd.d sets it, a forced write to bit 63 leaves it 0, and Clean drops it back to 0.
    Diagram: hand-built by Chris Dillinger for this post

    Sources

    1. 01
      src/mstatus-sd-summary: module PROOF.md and the QEMU runChris Dillinger

      The QEMU 8.2.2 run behind the post, re-run firsthand for this post: boot mstatus 0xa00000000, FS Off, SD 0; FS Initial 0xa00004000, SD 0; after fadd.d mstatus 0x8000000a00006000, FS Dirty, SD 1, f0 bits 0x400e000000000000; FS Clean 0xa00002000, SD 0; forced bit-63 write read back 0xa00002000, SD 0, FS unchanged; restore 0xa00000000; traps 0; 15 checks, 0 mismatches, checksum 0xcd8421132251ca67; RESULT: PASS.

    The Region Described by Trailing Ones

    ISA

    The claim is the PMP NAPOT encoding and matching rule as this machine shows it: one pmpaddr value names a base and a size through its trailing ones, and the matching rule refuses the inside edges while passing one word outside on either side. The run shows each side directly: pmpaddr0 = 0x200009ff read back exactly, loads at 0x80002000 and 0x80002ffc trapping with mcause 0x5, and loads at 0x80001ffc and 0x80003000 passing.

    MICROARCH

    No claim depends on how any core implements PMP matching. QEMU serves as a functional executor only; no pipeline or execution-unit behavior is asserted or measured, and the honest limit states the result is emulator-observed, not silicon-proved.

    FIRMWARE

    No firmware service takes part in the claim. The binary runs in M-mode on bare QEMU with no SBI or firmware calls; the behavior under test is the PMP CSRs own encoding and matching rule.

    KERNEL

    No kernel code runs in the claim. The binary is a bare-metal M-mode program with no supervisor, no scheduler, and no system call path; the S-mode view of the probes comes from MPRV set by the M-mode program itself, not from a supervisor running.

    ALGORITHM

    The claim is one fixed encoding and a fixed set of boundary probes with trap and value comparisons, not a computation proved against an independent oracle. The results are shown as the consequence the NAPOT rule forces, not as a verified algorithm.

    Fencing a scratch buffer usually means checking every access by hand, or trusting a range you never tested. RISC-V physical memory protection gives a shorter way: one PMP entry can fence a whole region, and the fence is described by a single register value whose tail of trailing ones names the size.

    Measured on QEMU 8.2.2, bare metal in M-mode. The program wrote pmpaddr0 = 0x200009ff and pmpcfg0 = 0x1f18, fencing 4 KiB at 0x80002000. Loads at the first word inside, 0x80002000, and the last word inside, 0x80002ffc, each trapped with mcause 0x5, and a store at 0x80002000 trapped with mcause 0x7. Loads one word below, at 0x80001ffc, and one word above, at 0x80003000, passed with their canary values, and stores at both outside addresses round-tripped. RESULT: PASS. [1]

    The encoding, and how to read it back:

    csrw pmpaddr0, t0  # t0 = 0x200009ff: 4 KiB at 0x80002000
    csrw pmpaddr1, t1  # t1 = 0x200007ff: 16 KiB allow entry
    csrw pmpcfg0, t2   # t2 = 0x1f18: entry 0 deny, entry 1 allow
    # 9 trailing ones in 0x200009ff means 2^(9+3) = 4096 bytes

    Why there are two entries, not one. An unlocked PMP entry does not restrict M-mode at all, so the probes ran as S-mode accesses, with mstatus.MPRV set and MPP = S. And an S-mode access that matches no entry is denied whenever any entry is programmed, so entry 1, a 16 KiB allow entry at 0x80000000, covers the outside addresses. Inside the deny region, entry 0 wins because the lowest matching entry decides. Without entry 1, the outside probes would have trapped for the wrong reason, and the test would have proved nothing about the edge.

    The readback alone would not prove the fence. Reading pmpaddr0 back as 0x200009ff proves the register took the value; only the boundary probes prove what the value matches. The first and last words inside trap, one word outside on either side passes, and mtval names the faulting address in each trap, 0x80002000 for the low edge. That is the whole test: program the value, then touch both edges and one word past each.

    The bench habit: when you fence a buffer with PMP, program the deny entry and an allow entry for everything else, then probe the first word, the last word, and one word past each edge. If an outside probe traps, check whether it matched the fence or merely matched nothing; the two failures look identical from the trap alone.

    One sentence to carry away: count the trailing ones in a NAPOT pmpaddr value and you know the size of the region it fences, and two probes on either side of each edge tell you whether the fence sits where you think it does.

    Blueprint-style diagram of the PMP NAPOT fence in three panels: THE ENCODING shows pmpaddr0 = 0x200009ff with 9 trailing ones meaning 4096 bytes and pmpcfg0 = 0x1f18; INSIDE TRAPS shows loads at 0x80002000 and 0x80002ffc trapping with mcause 0x5 and a store at 0x80002000 trapping with mcause 0x7; OUTSIDE PASSES shows loads at 0x80001ffc and 0x80003000 passing with canary values and stores below and above round-tripping
    One value fences the region: pmpaddr0 = 0x200009ff, 9 trailing ones, 4 KiB at 0x80002000, with both inside edges trapping and one word outside passing on either side.
    Diagram: hand-built by Chris Dillinger for this post

    Sources

    1. 01
      src/pmp-napot-match: module PROOF.md and the QEMU runChris Dillinger

      The QEMU 8.2.2 run behind the post, re-run firsthand for this post: pmpaddr0 = 0x200009ff, pmpaddr1 = 0x200007ff, pmpcfg0 = 0x1f18; loads at 0x80002000 and 0x80002ffc trapped with mcause 0x5, a store at 0x80002000 trapped with mcause 0x7; loads at 0x80001ffc and 0x80003000 passed, stores below and above round-tripped; quiet window showed no new traps; RESULT: PASS.

    The Counter You Can Rebase

    ISA

    The claim is the mcycle write and readback rule as this machine shows it: a csrw to mcycle takes effect, the next csrr returns the written value plus the ticks that passed, and later reads keep rising from that base. The run shows each side directly: written 0x100000000, read back 0x100002940, then four strictly increasing samples, all above the base.

    MICROARCH

    No claim depends on how any core implements its cycle counter. QEMU serves as a functional executor only; no pipeline or execution-unit behavior is asserted or measured, and the honest limit states the result is emulator-observed, not silicon-proved.

    FIRMWARE

    No firmware service takes part in the claim. The binary runs in M-mode on bare QEMU with no SBI or firmware calls; the behavior under test is the mcycle CSR's own write and readback.

    KERNEL

    No kernel code runs in the claim. The binary is a bare-metal M-mode program with no supervisor, no scheduler, and no system call path; the write and readback are CSR operations, not a kernel mechanism.

    ALGORITHM

    The claim is one fixed write and readback sequence with sample comparisons, not a computation proved against an independent oracle. The results are shown as the consequence the CSR write forces, not as a verified algorithm.

    Timing a section of code usually starts the same way: read a counter, save a large number, and subtract it at the end. The subtraction is easy to get wrong, and the saved baseline is one more value to carry through the code. There is a shorter way, if the counter itself accepts a write: put the counter where you want it first, then read it.

    Measured on QEMU 8.2.2, bare metal in M-mode. Two baseline reads came back 0x17798beddac and then 0x17798bf0377, a delta of 9675, so the counter was live before anything was written. The program then wrote 0x100000000 to mcycle with csrw and read it back at once: 0x100002940, a delta of 10560 ticks. Four further samples followed, 0x10012c7da, 0x1001570a7, 0x10016c47f, and 0x10018182a, each strictly larger than the last and every one above the written base. RESULT: PASS. [1]

    The witness, the write and what it returned:

    csrw mcycle, t0  # t0 = 0x100000000: rebase the counter
    csrr t1, mcycle  # t1 = 0x100002940: 10560 ticks later
    # later reads are already deltas from your base

    Why the readback matters more than the write. mcycle is a WARL register, which means the specification only requires a write followed by a read to return the written value filtered through the implementation's behavior. On some machine the write might not stick, and code that assumes it did would time everything against a base that never moved. The module does not assume: it reads back at once and requires the readback to sit within 100000 ticks above the written value. A readback below the written value would make the unsigned delta wrap to a huge number and fail the bound, with the actual values printed. Trust the readback, not the write.

    The bench habit: in an M-mode timing harness, write a known base before the section under test and read the counter after it. The reading is already a delta from the base you chose, with no baseline saved and no subtraction to get wrong. On this machine the base was 0x100000000 and the first readback was only 10560 ticks past it, so the cost of the write itself is visible in the numbers, not hidden in a baseline.

    One sentence to carry away: a counter you can write is a counter you can start at a round number, and a timing run that starts at a known base needs no baseline at all.

    Blueprint-style diagram of the mcycle write and readback in three panels: BASELINE shows two reads 0x17798beddac then 0x17798bf0377 with delta 9675; WRITE AND READ BACK shows csrw mcycle with 0x100000000 read back as 0x100002940 with delta 10560; STILL ADVANCING shows four samples 0x10012c7da, 0x1001570a7, 0x10016c47f, 0x10018182a, each larger than the last
    The counter took the base: written 0x100000000, read back 0x100002940, and four later samples kept rising from that base.
    Diagram: hand-built by Chris Dillinger for this post

    Sources

    1. 01
      src/mcycle-write: module PROOF.md and the QEMU runChris Dillinger

      The QEMU 8.2.2 run behind the post, re-run firsthand for this post: baseline reads 0x17798beddac then 0x17798bf0377 with delta 9675; written 0x100000000, read back 0x100002940 with delta 10560; four further samples 0x10012c7da, 0x1001570a7, 0x10016c47f, 0x10018182a, strictly increasing and all above the written base; RESULT: PASS.

    The Instruction That Reads Its Own Address

    ISA

    The claim is the unprivileged auipc rule: rd receives pc plus the 20-bit immediate shifted left 12, so the low 12 bits stay zero. The run shows both sides directly: auipc rd, 0 returned the auipc's own address 0x800001d2, and auipc rd, 0x12345 returned 0x923451f4, its pc plus 0x12345000.

    MICROARCH

    No claim depends on how any core implements auipc. QEMU serves as a functional executor only; no pipeline or execution-unit behavior is asserted or measured, and the honest limit states the result is emulator-observed, not silicon-proved.

    FIRMWARE

    No firmware service takes part in the claim. The binary runs in M-mode on bare QEMU with no SBI or firmware calls; the behavior under test is the auipc instruction's own pc rule.

    KERNEL

    The pair is the addressing idiom kernels are written against: xv6 entry opens with la sp, stack0, which assembles to auipc, so the kernel's first stack address is computed from the live pc rather than baked in. The module verifies the same pc rule on bare metal in M-mode.

    ALGORITHM

    The claim is one fixed instruction semantic exercised as three fixed checks with register readback, not a computation proved against an independent oracle. The results are shown as the consequence the auipc rule forces, not as a verified algorithm.

    A program that can run from any address has a problem: it does not know where it is. The program counter holds the answer, but the program counter is not one of the 32 registers, and no instruction takes it as a source operand. You cannot move it into a register the ordinary way. One instruction can.

    Measured on QEMU 8.2.2, bare metal in M-mode. auipc rd, 0 returned 0x800001d2, the address of the auipc itself, confirmed against the disassembly. auipc rd, 0x12345, sitting at 0x800001f4, returned 0x923451f4, its pc plus 0x12345000: the 20-bit immediate lands in the upper 20 bits and the low 12 stay zero. The auipc and ld pair then loaded 0x123456789abcdef0 from a marker through a link-time offset from the live pc, with the load address named nowhere in the instruction stream. Three checks, zero mismatches. [1]

    The witness, the instruction and what it returned:

    auipc s0, 0        # s0 = pc: the address of this instruction
    auipc s0, 0x12345  # s0 = pc + 0x12345000
    auipc t0, 0        # pair: ld s0, 314(t0) reaches marker
    # marker loaded: 0x123456789abcdef0, address named nowhere

    Why one instruction matters. auipc is the anchor for everything position independent. A constant, a string, a table: the code does not need to know where it was loaded, it only needs the distance from here to there, and auipc turns here into a register. The linker fills in that distance at link time, and at run time the same two instructions reach the target wherever the code runs, because the offset is measured from the live pc, not from an assumed load address.

    That is the first address xv6 builds. The kernel entry opens with la sp, stack0, which assembles to auipc sp, 0x8 at 0x80000000: the stack pointer comes from the pc, not from a baked-in constant. [2]

    The bench habit: whenever a value must be reached without assuming where the code was loaded, anchor on auipc first and let the linker fill in the offset. Never hardcode an address the linker can compute as a distance.

    One sentence to carry away: auipc is the one instruction that reads the program counter, and a program that knows where it stands never needs to be told where it was put.

    Blueprint-style diagram of the auipc pc rule in three panels: NO WAY IN shows the program counter is not a register and no instruction takes it as an operand; AUIPC RD, 0 shows auipc at 0x800001d2 returning 0x800001d2, its own address; THE PAIR REACHES shows auipc plus ld loading 0x123456789abcdef0 from marker with the load address named nowhere
    One instruction reads the program counter: auipc rd, 0 returned its own address, auipc rd, 0x12345 added 0x12345000 to its pc, and the pair loaded the marker through a link-time offset.
    Diagram: hand-built by Chris Dillinger for this post

    Sources

    1. 01
      src/auipc-pcread: module PROOF.md and the QEMU runChris Dillinger

      The QEMU 8.2.2 run behind the post: auipc rd, 0 returning 0x800001d2, the address of the auipc itself from the disassembly; auipc rd, 0x12345 at 0x800001f4 returning 0x923451f4, its pc plus 0x12345000; the auipc and ld pair loading 0x123456789abcdef0 from marker through a link-time offset, with the load address named nowhere in the instruction stream. 3 checks, 0 mismatches, re-run firsthand for this post with the same output.

    2. 02
      kernel/entry.S: _entry opens with la sp, stack0Chris Dillinger

      xv6 _entry opens with la sp, stack0, which the build disassembly shows as auipc sp, 0x8 at 0x80000000: the kernel's first stack address is computed from the live pc, not baked in as a constant.

    The Gate That Holds the Interrupt

    ISA

    The claim is the privileged-architecture delivery rule: an interrupt is taken only when its pending bit is set, its enable bit is set, and the global gate is open. The run shows each side directly: with mie.MTIE set and mstatus.MIE clear, mip.MTIP read 1 and traps stayed 0 through 100,000 ticks, and with MIE set, exactly one trap arrived with mcause 0x8000000000000007.

    MICROARCH

    No claim depends on how any core implements interrupt delivery. QEMU serves as a functional executor only; no pipeline or execution-unit behavior is asserted or measured, and the honest limit states the result is emulator-observed, not silicon-proved.

    FIRMWARE

    No firmware service takes part in the claim. The binary runs in M-mode on bare QEMU with no SBI or firmware calls; the behavior under test is the MIE gate itself.

    KERNEL

    The gate is the critical-section idiom kernels are written against: close one global enable around the critical section instead of disturbing per-source enables, and reopen it on exit. xv6's intr_off clears sstatus.SIE and intr_on sets it again, the supervisor form of the same gate, and the module verifies the machine form on mstatus.MIE.

    ALGORITHM

    The claim is one fixed delivery rule exercised as a single gated window with pending-bit and trap-count readbacks, not a computation proved against an independent oracle. The results are shown as the consequence the delivery rule forces, not as a verified algorithm.

    A timer fires in the middle of a critical section. You cannot take the interrupt yet, and you cannot afford to lose it either. Two different bits decide what happens, and they are not the same decision. One says this source is allowed to interrupt. The other says the hart is taking interrupts at all.

    Measured on QEMU 8.2.2, bare metal in M-mode. The program enabled only the machine timer interrupt, mie.MTIE set and mstatus.MIE clear, then armed the CLINT timer. The timer fired and went pending, mip.MTIP read 1, and through a gated window of 100,000 mtime ticks no trap arrived: traps during the window were 0. Opening the gate with one instruction delivered exactly one trap, mcause 0x8000000000000007. Fourteen checks, zero mismatches, and the run printed the same checksum the module records, 0xddb82db8ae1a497d. [1]

    The witness, the gate and what it held:

    csrci mstatus, 8    # MIE clear: gate shut, enables untouched
    # timer fires: mip.MTIP = 1, traps = 0
    csrsi mstatus, 8    # MIE set: gate opens
    # one trap: mcause = 0x8000000000000007

    Why the gate is not the enable. mie.MTIE answers one question, whether this source may interrupt. mstatus.MIE answers another, whether the hart is taking interrupts at all. Closing MIE holds delivery for every enabled source at once, and it disturbs no per-source enable: when the gate reopened, the timer interrupt that had waited through the gated window arrived without anything being re-armed. The pending bit is the memory. mip.MTIP stayed 1 through the whole gated window, so nothing was lost while the gate was shut. The handler still has one job before it returns: disarm the source, here by writing all-ones to mtimecmp, because the timer is level-triggered and mret restores MIE, so an armed source would fire again at once. The run proves the disarm too: after the handler, mtimecmp read all-ones, mip.MTIP read 0, and through a quiet window of another 100,000 ticks the trap count stayed 1. [1]

    That is the same gate xv6 closes in supervisor mode. xv6's intr_off clears sstatus.SIE, and intr_on sets it again, so kernel critical sections shut one global gate instead of saving and restoring every per-source enable. [2] The machine-level run proves the mechanism the supervisor-level idiom relies on: a pending interrupt waits at a shut gate instead of being lost. [1]

    The bench habit: open and close a critical section with the gate, not with the per-source enables. Clear MIE on entry, set it on exit, and never return from a handler with the source still armed.

    One sentence to carry away: mie says which interrupts may fire, MIE says whether any of them get through, and a pending interrupt waits at a shut gate instead of being lost.

    Blueprint-style diagram of the mstatus.MIE gate in three panels: GATE SHUT shows mie.MTIE set and MIE clear with the timer pending and traps at 0; GATE OPENS shows csrsi mstatus, 8 delivering one trap; DISARM, QUIET shows mtimecmp set to all-ones with the trap count staying 1
    The gate held the interrupt: pending through 100,000 gated ticks, exactly one trap when the gate opened, and quiet after the handler disarmed the source.
    Diagram: hand-built by Chris Dillinger for this post

    Sources

    1. 01
      src/mie-toggle: module PROOF.md and the QEMU runChris Dillinger

      The QEMU 8.2.2 run behind the post: only mie.MTIE enabled with mstatus.MIE clear, the timer armed, mip.MTIP reading 1 with 0 traps through a gated window of 100,000 mtime ticks, csrsi mstatus, 8 opening the gate, exactly one trap with mcause 0x8000000000000007, the handler disarming with mtimecmp all-ones and mip.MTIP 0, and the trap count staying 1 through a quiet window of 100,000 ticks. 14 checks, 0 mismatches, checksum 0xddb82db8ae1a497d, re-run firsthand for this post with the same verdict.

    2. 02
      kernel/riscv.h: intr_on and intr_offChris Dillinger

      xv6 intr_on sets sstatus.SIE and intr_off clears it, the supervisor form of the same global gate: one bit opens or closes delivery without touching per-source enables.

    The Swap That Needs No Spare Register

    ISA

    The claim is the Zicsr csrrw rule: one instruction writes rd with the old CSR value and writes rs1 into the CSR, so the two values exchange with no third register spent. The run shows both sides directly: the swap returned the boot value 0x0 and the readback showed the sentinel 0xa5a55a5a5a5a5a5, then the restore swap returned the sentinel and the final readback was 0x0 again.

    MICROARCH

    No claim depends on how any core implements a CSR swap. QEMU serves as a functional executor only; no pipeline or execution-unit behavior is asserted or measured, and the honest limit states the result is emulator-observed, not silicon-proved.

    FIRMWARE

    No firmware service takes part in the claim. The binary runs in M-mode on bare QEMU with no SBI or firmware calls; the behavior under test is the csrrw instruction's own exchange semantic.

    KERNEL

    The exchange is the trap-entry idiom kernels are written against: at trap entry no general-purpose register is free, so xv6's uservec opens with csrrw a0, sscratch, a0, putting the trapframe address in a0 and the user's a0 in sscratch. The module verifies the same exchange on mscratch in M-mode, which is the mechanism the idiom relies on.

    ALGORITHM

    The claim is one fixed instruction semantic exercised as a single sentinel round trip with register and CSR readback, not a computation proved against an independent oracle. The results are shown as the consequence the csrrw rule forces, not as a verified algorithm.

    A trap lands and every register belongs to the interrupted code. The handler must save all 32 registers before it can use any of them, but storing to memory needs an address, and an address needs a register. There is no register to spare, and no place to put one down first. That is the trap-entry problem, and one instruction solves it.

    Measured on QEMU 8.2.2, bare metal in M-mode. The program swapped a sentinel into mscratch, then swapped the boot value back. The first swap returned the boot value, 0x0, and the readback showed the sentinel, 0xa5a55a5a5a5a5a5. The restoring swap returned the sentinel, and the final readback was 0x0 again. Five checks, zero failures, no traps, and the run printed the same checksum the module records, 0xd2dc5b584cb8669. [1]

    The witness, the one instruction and what it returned:

    csrrw a0, sscratch, a0  # exchange, not read then write
    # before: a0 = user value, sscratch = trapframe
    # after:  a0 = trapframe, sscratch = user value

    Why one instruction matters. A read followed by a write is two steps with a gap between them: the read puts the old value in a register, and until the write lands, the exchange is half done and a register is spent holding the copy. csrrw has no gap and spends no register. The destination register receives the old CSR value at the same moment the CSR receives the register's value, so neither value is ever homeless, and nothing needs a third place to sit. The swap is the whole operation, not two operations stapled together.

    That is exactly the door xv6 walks through. Before a process runs in user space, the kernel writes the address of its trapframe into sscratch. When a trap lands, uservec opens with csrrw a0, sscratch, a0: a0 now holds the trapframe address, sscratch now holds the user's a0, and the handler stores every register into the trapframe through a0, including the user's a0, read back from sscratch. [2] The module behind this post proves the same exchange on mscratch in M-mode, because that is the CSR a bare-metal M-mode program can touch; the instruction is the same, only the scratch register changes. [1]

    The bench habit: whenever a trap entry or a context switch needs a register before it has anywhere to save one, park the pointer in a scratch CSR ahead of time and open with the swap. One instruction buys the first free register, and the value it displaced is already safe in the CSR, waiting to be stored with the rest.

    One sentence to carry away: csrrw does not read a CSR and then write it, it exchanges with it, and the exchange is what frees the first register.

    Blueprint-style diagram of the csrrw swap in three panels: NO FREE REGISTER shows all 32 registers holding user values with nowhere to save; THE SWAP shows csrrw a0, sscratch, a0 giving a0 the trapframe address and sscratch the user's a0; NOW SAVE shows all 32 registers stored through a0 with nothing lost
    One swap freed the first register: csrrw returned the boot value 0x0, the readback showed the sentinel, and the restore returned the sentinel with 0x0 back in place.
    Diagram: hand-built by Chris Dillinger for this post

    Sources

    1. 01
      src/mscratch-csrrw: module PROOF.md and the QEMU runChris Dillinger

      The QEMU 8.2.2 run behind the post: csrrw on mscratch in M-mode, a sentinel swapped in and the boot value swapped back, the swap returning the boot value 0x0, the readback showing the sentinel 0xa5a55a5a5a5a5a5, the restore returning the sentinel, and the final readback 0x0. 5 checks, 0 failures, 0 traps, checksum 0xd2dc5b584cb8669, re-run firsthand for this post with the same verdict.

    2. 02
      L Internal: xv6 trap internals lecture notesMIT 6.S081

      uservec starts with csrrw a0, sscratch, a0: the swap saves user a0 in sscratch and gives a0 the trapframe address, so the handler can save the remaining registers. The kernel set sscratch to the trapframe address before entering user space.

    The Mask That Won't Fit in Twelve Bits

    ISA

    The claim is the I-type immediate rule: the immediate is 12 bits, sign-extended, so its range is -2048 to 2047 and the largest positive mask it can spell is 2047, or 0x7FF. The run shows it directly: the assembler refuses andi with 0xfff and with 0x800, andi with 2047 loses bit 11 on 0x12345abc, 0xfff, and 0xffff, and the shift pair matches a loaded 4095 constant on all four inputs.

    MICROARCH

    No claim depends on how any core implements immediate AND. QEMU serves as a functional executor only; no pipeline or execution-unit behavior is asserted or measured, and the honest limit states the result is emulator-observed, not silicon-proved.

    FIRMWARE

    No firmware service takes part in the claim. The binary runs in M-mode on bare QEMU with no SBI or firmware calls; the behavior under test is the andi immediate encoding itself.

    KERNEL

    No kernel is involved at any step. The test binary runs on bare QEMU with no operating system; no system call or kernel data structure appears in the argument.

    ALGORITHM

    The claim is one fixed instruction semantic exercised as four fixed inputs with register readback, not a computation proved against an independent oracle. The four results are shown as the consequence the immediate rule forces, not as a verified algorithm.

    You have a value in a register and you want its low 12 bits, a packed field, a page offset, a tag. The line that writes itself is andi t0, s0, 0xfff: AND the register with twelve ones, keep the field, throw the rest away. It reads exactly like the mask it means. It does not assemble.

    Measured on QEMU 8.2.2, bare metal in M-mode. The program ran three ways of masking for four inputs: andi with 2047, the shift pair slli 52 then srli 52, and and against 4095 loaded with li. The shift pair and the loaded constant agreed on every input. The andi column agreed only where bit 11 was clear, and lost bit 11 everywhere else. Four inputs, zero mismatches between the two true 0xFFF masks, two runs identical. [1]

    The witness, the refused line and the two that work:

    andi t0, s0, 0xfff   # illegal operands: 4095 is out of range
    andi t0, s0, 2047    # keeps the low 11 bits, no more
    slli t0, s0, 52      # the compiler's dodge for x & 0xFFF
    srli t0, t0, 52      # low 12 bits back down, zero-filled
    # v = 0x12345abc: andi 2047 -> 0x2bc, shift pair -> 0xabc

    Why the assembler says no. The immediate in an I-type instruction is 12 bits, and it is sign-extended, so it runs from -2048 to 2047. A mask is a positive number, so the largest mask you can write as an andi immediate is 2047, which is 0x7FF, eleven ones. 0xFFF is 4095, one past the top of the range, and 0x800 is 2048, also past it, so the assembler refuses both. The sign extension is not a detail here; it is the whole limit, because bit 11 of the immediate is the sign bit, not a mask bit you can set freely.

    The numbers show the cost of settling for 2047. For 0x12345abc the andi column gave 0x2bc and the true mask gave 0xabc: the field's top bit, bit 11, silently dropped. For 0xfff the columns gave 0x7ff and 0xfff, and for 0xffff the same split. For 0x1000 all three gave 0, because bit 12 is outside both masks. Settling for the smaller mask does not error; it quietly reads a narrower field. [1]

    The compiler already knows the dodge. Given x & 0xFFFUL in C at -O2, GCC 13.2.0 for rv64imac did not emit an andi at all. It emitted slli a0, a0, 52 then srli a0, a0, 52: shift left to throw away everything above bit 11, shift right to bring the twelve bits back down, zero-filled. [1]

    The bench habit: when a mask in hand-written assembly needs bit 11 or higher, do not reach for andi. Write the shift pair, or load the constant and use and. If the assembler accepts your andi mask, it fits; if it refuses it, the refusal is the specification telling you the range, not a quirk to work around with a different spelling of the same immediate.

    One sentence to carry away: an andi immediate is a signed 12-bit number, so the widest low mask it can spell is 0x7FF, and 0xFFF has to be built, not written.

    Blueprint-style diagram of the andi immediate limit in three panels: THE MASK THAT FITS shows andi t0, s0, 2047 with v equal to 0x12345abc giving t0 equal to 0x2bc; THE MASK THAT DOES NOT shows andi t0, s0, 0xfff refused as illegal operands because 4095 is out of range; THE WAY AROUND shows slli t0, s0, 52 then srli t0, t0, 52 giving t0 equal to 0xabc
    andi with 2047 gave 0x2bc, the assembler refused 0xFFF, and the shift pair gave 0xabc: the widest low mask an andi immediate can spell is 0x7FF.
    Diagram: hand-built by Chris Dillinger for this post

    Sources

    1. 01
      src/andi-mask12: module PROOF.md and the QEMU runChris Dillinger

      The QEMU 8.2.2 run behind the post: andi with 2047, the slli 52 and srli 52 pair, and and against a loaded 4095 for four inputs on bare metal in M-mode, the shift pair and the loaded constant agreeing on all four and the andi column losing bit 11 where it was set. 6 checks, 0 mismatches, two runs identical. The assembler rejection log and the GCC 13.2.0 shift-pair output for x and 0xFFFUL are in the same module's bench-logs.

    The Add That Sign-Extends the Word

    ISA

    The claim is the unprivileged specification's addiw rule: it adds the sign-extended immediate to the low word, keeps only the low 32 bits of the sum, then sign-extends the result to 64 bits. With immediate 0 the addition does nothing, so the instruction is a pure sign extension, and the run shows it directly: the 0x80000001 word gives 0xffffffff80000001, the 0xffffffff word gives 0xffffffffffffffff, and dirty upper bits never survive.

    MICROARCH

    No claim depends on how any core implements word arithmetic. QEMU serves as a functional executor only; no pipeline or execution-unit behavior is asserted or measured, and the honest limit states the result is emulator-observed, not silicon-proved.

    FIRMWARE

    No firmware service takes part in the claim. The binary runs in M-mode on bare QEMU with no SBI or firmware calls; the behavior under test is the addiw instruction's own word semantic.

    KERNEL

    No kernel is involved at any step. The test binary runs on bare QEMU with no operating system; no system call or kernel data structure appears in the argument.

    ALGORITHM

    The claim is one fixed instruction semantic exercised as five fixed inputs with register readback, not a computation proved against an independent oracle. The five results are shown as the consequence the addiw rule forces, not as a verified algorithm.

    A 32-bit value living in a 64-bit register can carry junk upstairs. Take 0x0000000180000001. Its low word is 0x80000001, which as a signed 32-bit number means negative 2,147,483,647. But the register as a whole has bit 32 set too, so as a 64-bit number it is a large positive value, not that negative number at all. The word and the register disagree, and any code that trusts the register gets the wrong sign.

    Measured on QEMU 8.2.2, bare metal in M-mode. The program ran addiw with immediate 0 and addi with immediate 0 on five inputs. The addiw column matched the sign extension of the low word every time, and the addi column matched the input every time. Five addiw checks, zero mismatches, two runs identical. [1]

    The witness, the one instruction and three of its answers:

    addiw t0, s0, 0   # sext.w: keep the low word, sign-extend it
    # s0 = 0x0000000080000001  -> t0 = 0xffffffff80000001
    # s0 = 0x000000007fffffff  -> t0 = 0x000000007fffffff
    # s0 = 0x00000000ffffffff  -> t0 = 0xffffffffffffffff
    Blueprint-style diagram of the addiw sign extension in three panels: HAND IT 0x80000001 shows addiw t0, s0, 0 with s0 equal to 0x0000000080000001 giving t0 equal to 0xffffffff80000001; HAND IT 0x7fffffff shows s0 equal to 0x000000007fffffff giving t0 unchanged; HAND IT LOW ALL ONES shows s0 equal to 0x00000000ffffffff giving t0 equal to 0xffffffffffffffff because the low word means -1
    0x80000001 gained ones upstairs, 0x7fffffff stayed put, and 0xffffffff became -1: addiw with 0 is sext.w, five checks, zero mismatches.
    Diagram: hand-built by Chris Dillinger for this post

    Why addiw and not addi. The addi instruction works on all 64 bits, so adding 0 changes nothing, and the junk upstairs survives. The addiw instruction works on 32 bits: it adds the immediate to the low word, keeps only the low 32 bits of that sum, then sign-extends the result back to 64 bits. With an immediate of 0, the addition does nothing, and what is left is pure narrowing plus sign extension. The 0 is just the excuse; the narrowing is the trick.

    The other two inputs close the loop. The dirty-upper-bits input 0x0000000180000001 also came out 0xffffffff80000001, because addiw never looks above bit 31. And the already extended 0xffffffff80000001 came out unchanged, so running sext.w twice is harmless: the second pass is a no-op. [1]

    The disassembly gives the idiom its short name. The loop test is one instruction, and objdump prints it as sext.w a0, s0 at 0x80000222: sext.w is the assembler's name for exactly addiw rd, rs, 0. Writing sext.w in your own assembly says what you mean, and the reader never has to wonder why you are adding zero. The addi side of the loop prints as mv, the assembler's name for addi with immediate 0, which is why that column never moved. [1]

    The bench habit: whenever a value reaches you as a 32-bit int but sits in a 64-bit register, and you cannot prove the upper bits are clean, one sext.w settles it. After that instruction the register and the word agree, and a comparison, a sign test, or a widening conversion reads the number the word actually names.

    One sentence to carry away: addiw with 0 is not an addition at all, it is a sign extension wearing an addition's clothes.

    Sources

    1. 01
      src/addiw-sextw: module PROOF.md and the QEMU runChris Dillinger

      The QEMU 8.2.2 run behind the post: addiw with immediate 0 and addi with immediate 0 for five inputs on bare metal in M-mode, the addiw column matching the sign extension of the low word in all five cases and the addi column matching the input in all five. 5 checks, 0 mismatches, two runs identical. The disassembly confirms the loop test as sext.w a0, s0 at 0x80000222, the assembler's name for addiw a0, s0, 0, and the addi side as mv, the assembler's name for addi with immediate 0.

    The Comparison That Tests for Zero

    ISA

    The claim is the unprivileged specification's sltiu rule: it writes 1 when rs1 is smaller than the sign-extended immediate under an unsigned comparison, else 0. With the immediate 1, only rs1 equal to zero qualifies, and the run shows it directly: 0 gave 1, and 1, 2, 5, and all ones gave 0.

    MICROARCH

    No claim depends on how any core implements set-less-than-immediate. QEMU serves as a functional executor only; no pipeline or execution-unit behavior is asserted or measured, and the honest limit states the result is emulator-observed, not silicon-proved.

    FIRMWARE

    No firmware service takes part in the claim. The binary runs in M-mode on bare QEMU with no SBI or firmware calls; the behavior under test is the sltiu instruction's own comparison semantic.

    KERNEL

    No kernel is involved at any step. The test binary runs on bare QEMU with no operating system; no system call or kernel data structure appears in the argument.

    ALGORITHM

    The claim is one fixed instruction semantic exercised as five fixed inputs with register readback, not a computation proved against an independent oracle. The five results are shown as the consequence the sltiu rule forces, not as a verified algorithm.

    Testing for zero usually means a branch: compare, then jump. RISC-V has a branchless way. The instruction sltiu compares its input against an immediate as an unsigned number and writes 1 when the input is smaller, else 0. Compare against 1, and only one unsigned value qualifies: zero itself.

    Measured on QEMU 8.2.2, bare metal in M-mode. The program ran sltiu against 1 for five inputs. Zero returned 1. One, two, and five returned 0. All ones, the 64-bit value 0xffffffffffffffff, returned 0. Five checks, zero mismatches, two runs identical. [1]

    The witness, the zero test itself:

    sltiu a2, a1, 1   # a2 = 1 exactly when a1 == 0
    # a1 = 0                    -> a2 = 1
    # a1 = 5                    -> a2 = 0
    # a1 = 0xffffffffffffffff  -> a2 = 0
    Blueprint-style diagram of the sltiu zero test in three panels: HAND IT ZERO shows sltiu a2, a1, 1 with a1 equal to 0 giving a2 equal to 1; HAND IT FIVE shows a1 equal to 5 giving a2 equal to 0; HAND IT ALL ONES shows a1 equal to 0xffffffffffffffff giving a2 equal to 0 because the compare is unsigned
    Zero gave 1, five gave 0, and all ones gave 0: sltiu against 1 is a zero test, five checks, zero mismatches.
    Diagram: hand-built by Chris Dillinger for this post

    The all-ones result is the point of the unsigned compare. Read as a signed number, all ones is negative one, and negative one is below 1. But sltiu reads it unsigned, where it is the largest possible value, far above 1, so it returns 0. The signed twin, slti, would have answered 1 for that input. Picking the wrong twin turns a zero test into a test for zero or negative. [1]

    The disassembly gives the idiom its short name. The loop kept the test as one instruction, and objdump prints it as seqz a0, s0 at 0x80000218: seqz is the assembler's name for exactly sltiu rd, rs, 1. Writing seqz in your own assembly says the same thing, and says it more plainly. [1]

    The bench habit: when you need a 0-or-1 flag that says whether a value is zero, and you do not want a branch, sltiu against 1 is the one instruction. The flag it writes can feed an add, a mask, or a count without ever jumping.

    One sentence to carry away: sltiu against 1 is a zero test, because zero is the only unsigned value below 1.

    Sources

    1. 01
      src/sltiu-zero-test: module PROOF.md and the QEMU runChris Dillinger

      The QEMU 8.2.2 run behind the post: sltiu against 1 for five inputs on bare metal in M-mode, 0 giving 1 and 1, 2, 5, and 0xffffffffffffffff giving 0. 5 checks, 0 mismatches, two runs identical. The disassembly confirms the loop test as seqz a0, s0 at 0x80000218, the assembler's name for sltiu a0, s0, 1.

    The Jump That Always Lands Even

    ISA

    The claim is the unprivileged specification's jalr target rule: the target is rs1 plus the sign-extended 12-bit immediate, with the least-significant bit set to zero. The run shows it directly: jalr handed the odd address 0x800001f3 ran the block at the even label 0x800001f2 and returned through t2.

    MICROARCH

    No claim depends on how any core implements indirect jumps. QEMU serves as a functional executor only; no pipeline, return-stack, or predictor behavior is asserted or measured, and the honest limit states the result is emulator-observed, not silicon-proved.

    FIRMWARE

    No firmware service takes part in the claim. The binary runs in M-mode on bare QEMU with no SBI or firmware calls; the behavior under test is the jalr instruction's own target semantic.

    KERNEL

    No kernel is involved at any step. The test binary runs on bare QEMU with no operating system; no system call or kernel data structure appears in the argument.

    ALGORITHM

    The claim is one fixed instruction semantic exercised as a single odd-target jump with register readback, not a computation proved against an independent oracle. The landing and return are shown as the consequence the jalr rule forces, not as a verified algorithm.

    A function pointer with its low bit set looks broken. On RISC-V it is not. The indirect jump instruction, jalr, clears bit 0 of its target before it jumps, so a pointer that ends in 1 still lands on the even address next door. The manual says this clearing is deliberate: it lets the low bit of a function pointer store auxiliary information, a tag, instead of an address bit.

    Measured on QEMU 8.2.2, bare metal in M-mode. The label block sat at 0x800001f2. Adding 1 made the jump target 0x800001f3, odd on purpose. The jalr to that odd address ran the block at 0x800001f2 anyway, the block stored 1 into a flag, and the jump back through the link register returned to the caller. Four checks, zero mismatches, three runs byte-identical. [1]

    The witness, the jump and its return:

    la t0, 1f
    addi t0, t0, 1
    jalr t2, 0(t0)
    1: li t1, 1
       sw t1, 0(landed)
       jalr x0, 0(t2)
    Blueprint-style diagram of the jalr odd-target experiment in three panels: HAND IT AN ODD ADDRESS shows the label at 0x800001f2 with the jump target made odd at 0x800001f3; IT LANDS EVEN shows jalr clearing bit 0 and the label block running at 0x800001f2; AND IT COMES BACK shows the return through t2 with landed equal to 1
    Handed 0x800001f3, jalr landed on 0x800001f2, ran the block, and returned: landed 1, four checks, zero mismatches.
    Diagram: hand-built by Chris Dillinger for this post

    The disassembly confirms the jump the source describes: jalr t2, s0 at 0x800001ec, where s0 was formed as the label address plus 1, and the label block at 0x800001f2 ends with a return through t2. Nothing in the run depended on the compiler tidying the odd address away first: the odd value was formed in a register at run time, inside volatile asm, and handed to jalr as its base. [1]

    The unprivileged manual states the rule plainly: the target address is obtained by adding the sign-extended 12-bit immediate to rs1, then setting the least-significant bit of the result to zero, and the address of the following instruction goes to the link register. The return instruction itself is just this rule with the link register as base: ret is jalr x0, 0(x1). [1] [2]

    The bench habit, in both directions. If you tag a function pointer's low bit, or you receive one from code that does, you do not need to clear the bit before an indirect call: jalr clears it for you. And the reverse is a trap of its own: do not use bit 0 to tell two targets apart. Two pointers that differ only in bit 0 jump to the same place, so a tag bit read back from a pointer is not an address bit, and a comparison that treats it as one will lie.

    One measured boundary, stated honestly: these are emulator results, not silicon, and this build had the compressed extension, so a two-byte-aligned target was enough. Without the compressed extension, a target must be four-byte aligned or the jump raises an instruction-address-misaligned exception. The clearing only forgives bit 0; it does not forgive a genuinely misaligned target on a machine without compressed instructions. [1] [2]

    One sentence to carry away: jalr never jumps to an odd address, it jumps to the even address next door, and a set low bit on a function pointer is a tag, not a bug.

    Sources

    1. 01
      src/jalr-clears-bit0: module PROOF.md and the QEMU runChris Dillinger

      The QEMU 8.2.2 run behind the post: the label block at 0x800001f2, the odd jump target 0x800001f3 formed at run time in volatile asm, jalr landing on 0x800001f2, the block storing 1 into landed, and the return through t2. 4 checks, 0 mismatches, byte-identical across three runs, md5 27d8e494ce968d8ba1bdd193ad9bc41c. The disassembly confirmed jalr t2, s0 at 0x800001ec with s0 equal to the label address plus 1, and the label block returning with jr t2.

    2. 02
      RISC-V ISA Manual, unprivileged architecture (JALR target rule)RISC-V International

      The jalr rule, read from the pinned release. The target address is obtained by adding the sign-extended 12-bit I-immediate to rs1, then setting the least-significant bit of the result to zero. Clearing that bit lets the low bit of function pointers store auxiliary information. Without the compressed extension, a target not aligned to a four-byte boundary raises an instruction-address-misaligned exception.

    The Rounding Mode Written Into the Instruction

    ISA

    The claim is the unprivileged specification's floating-point rounding rule: a value of 111 in the instruction's rm field selects the dynamic rounding mode held in fcsr.frm, and every other rm value names its own mode. The run shows both halves: a static-RNE divide ignores frm under RDN and RUP alike, while the dynamic control under RUP diverges by one ulp.

    MICROARCH

    No claim depends on how any core implements floating-point rounding. QEMU serves as a functional executor only; no pipeline, latency, or rounding-unit behavior is asserted or measured, and the honest limit states the result is emulator-observed, not silicon-proved.

    FIRMWARE

    No firmware service takes part in the claim. The binary runs in M-mode on bare QEMU with no SBI or firmware calls; the behavior under test is the floating-point instruction's own rounding semantic.

    KERNEL

    No kernel is involved at any step. The test binary runs on bare QEMU with no operating system; no system call or kernel data structure appears in the argument.

    ALGORITHM

    The claim is one fixed instruction semantic exercised as four fixed divides with register readback, not a computation proved against an independent oracle. The static-then-dynamic contrast is shown as the consequence the rounding rule forces, not as a verified algorithm.

    A floating-point divide gets its rounding mode from two places: the instruction itself, or the fcsr register. Most code leaves the choice to fcsr.frm and never thinks about it again. But the instruction carries its own rm field, and when that field names a mode, the register does not get a vote.

    Measured on QEMU 8.2.2, dividing 1.0 by 3.0 in double precision. With fcsr.frm set to RDN, round toward negative infinity, the static-RNE divide returned 0x3FD5555555555555, and frm still read back RDN afterward. Under frm set to RUP, round toward positive infinity, the same static-RNE divide returned the same 0x3FD5555555555555, and frm still read back RUP. The instruction's mode won twice, and the register came back untouched both times. [1]

    The witness, the static divide and its dynamic control:

    fdiv.d fa0, fa0, fa1, rne   # static RNE, rm field 000
    # under frm=RDN: q=0x3FD5555555555555, frm still RDN
    # under frm=RUP: q=0x3FD5555555555555, frm still RUP
    fdiv.d fa0, fa0, fa1        # dynamic, rm field 111
    # under frm=RUP: q=0x3FD5555555555556, one ulp higher
    Blueprint-style diagram of the static rounding mode experiment in three panels: FRM SAYS RDN shows fcsr.frm set to RDN while the instruction says RNE; THE INSTRUCTION WINS shows the static-RNE divide returning 0x3FD5555555555555 with frm still reading RDN; THE CONTROL DIVERGES shows the dynamic divide under frm RUP returning 0x3FD5555555555556, one ulp higher
    The static mode in the instruction beat frm twice and left frm untouched, while the dynamic control under RUP moved one ulp.
    Diagram: hand-built by Chris Dillinger for this post

    The control is what makes the override real. The same divide with the rounding operand omitted encodes rm 111, dynamic, so it follows frm. Under frm set to RUP, that dynamic divide returned 0x3FD5555555555556, one ulp above the static result. The rounding path is live; the static agreement is not a dead rounding unit ignoring the mode. All four divides showed fflags NX only, the inexact flag, as 1.0/3.0 is inexact with no other exception. Nineteen checks, zero mismatches, three runs byte-identical, checksum 0xaaf26cfb83385742. [1]

    The unprivileged manual states the rule plainly: a value of 111 in the instruction's rm field selects the dynamic rounding mode held in frm. Every other value names its own mode: RNE is 000, RDN is 010, RUP is 011. The operands here traveled as raw bit patterns in integer registers and were moved into floating-point registers with fmv.d.x inside volatile asm, so the compiler could not constant-fold the divides; every division executed on the hart. [1] [2]

    The bench habit: when one computation needs a specific rounding, a correctly rounded constant or a directed-rounding bound, and the rest of the program runs under a global frm, write the mode into that one instruction instead of saving frm, setting it, dividing, and restoring it. The save, set, and restore dance disappears, and a forgotten restore cannot leak the temporary mode into later arithmetic.

    One measured boundary, stated honestly: these are emulator results, not silicon. And the static mode leaves frm untouched, which is the point, but it also means code that reads frm afterward learns nothing about how that divide rounded. The rounding decision lives in the instruction stream, so it is visible only in the disassembly. [1]

    One sentence to carry away: the rounding mode you write into the instruction beats the rounding mode in the register, and leaves the register exactly as it found it.

    Sources

    1. 01
      src/frm-dynamic-vs-static: module PROOF.md and the QEMU runChris Dillinger

      The QEMU 8.2.2 run behind the post: fdiv.d 1.0/3.0 with a static RNE encoding under frm=RDN returned 0x3FD5555555555555 with frm still RDN, and under frm=RUP returned the same 0x3FD5555555555555 with frm still RUP. The dynamic control under frm=RUP returned 0x3FD5555555555556. All four divides showed fflags NX only; traps 0; 19 checks, 0 mismatches, byte-identical across three runs, checksum 0xaaf26cfb83385742; the post's own rebuild and rerun on the build VM reproduced the PASS and the checksum in three runs. The disassembly confirmed the static encoding (rm bits 14:12 = 000) and the dynamic encoding (rm bits 14:12 = 111).

    2. 02
      RISC-V ISA Manual, unprivileged architecture (F extension, rounding modes)RISC-V International

      The rounding rule, read from the pinned release. A value of 111 in the instruction's rm field selects the dynamic rounding mode held in frm. RNE is 000, RDN is 010, RUP is 011. The manual's rounding-mode table gives the same encodings for the instruction rm field and the frm register, with 111 meaning dynamic only in the instruction field.

    The Store That Kills the Reservation

    ISA

    The claim is the unprivileged specification's LR/SC contract, sections 13.2 and 13.3: a failed store-conditional writes nothing to memory and reports nonzero in rd, and a store between the lr and the sc breaks the constrained loop. The run shows both halves: the intervening sw makes sc.w report rd=1 and store nothing, while the control pair with nothing between succeeds.

    MICROARCH

    No claim depends on how any core implements reservations. QEMU serves as a functional executor only; no reservation-set geometry, pipeline, or timing behavior is asserted or measured, and the honest limit states the result is emulator-observed, not silicon-proved.

    FIRMWARE

    No firmware service takes part in the claim. The binary runs in M-mode on bare QEMU with no SBI or firmware calls; the behavior under test is the atomic instructions' own contract.

    KERNEL

    No kernel is involved at any step. The test binary runs on bare QEMU with no operating system; the lock-free pattern is shown as a userspace mechanism, and no system call or kernel data structure appears in the argument.

    ALGORITHM

    The claim is one fixed instruction semantic exercised as a three-instruction sequence with register and memory readback, not a computation proved against an independent oracle. The kill-then-report contrast is shown as the consequence the contract forces, not as a verified algorithm.

    A lock-free retry loop is three instructions wide. lr.w reads the word and registers a reservation on it. You compute the new value. sc.w writes it only if the reservation is still valid. The question the whole pattern hangs on is what counts as breaking the reservation.

    Here is one answer, measured on QEMU 8.2.2. One aligned word, cell_a, holding 0xAAAA0000. The sequence runs as one volatile asm block so the compiler cannot reorder it: lr.w t1, 0(a3), then an ordinary sw of 0xBBBB1111 to the same address, then sc.w s2, a4, 0(a3) attempting 0xCCCC2222. The run printed rd = 1: the store-conditional reported failure. Memory held 0xBBBB1111, the intervening store's value. The failed store-conditional had stored nothing: 0xCCCC2222 never landed. [1]

    The witness, three instructions and their aftermath:

    lr.w t1, 0(a3)        # reserve cell_a, holding 0xAAAA0000
    sw   a5, 0(a3)        # 0xBBBB1111 lands between
    sc.w s2, a4, 0(a3)    # rd=1: reservation gone, nothing stored
    Blueprint-style diagram of the reservation-invalidation experiment in three panels: THE WINDOW OPENS shows lr.w arming the reservation on cell_a holding 0xAAAA0000; THE STORE LANDS BETWEEN shows an ordinary sw writing 0xBBBB1111 to the same address with the reservation dead; THE SC REPORTS shows sc.w attempting 0xCCCC2222 returning rd=1 with nothing stored, cell_a holding 0xBBBB1111
    One ordinary store between the load-reserved and the store-conditional killed the reservation: rd=1, and the failed store-conditional stored nothing.
    Diagram: hand-built by Chris Dillinger for this post

    The control rules out the alternative. A second word, cell_b, ran lr.w immediately followed by sc.w with nothing between: rd = 0, and cell_b read back 0xEEEE4444. The reservation mechanism works here; the failure in the first test belongs to the intervening store. The disassembly confirmed the emitted order is lr.w / sw / sc.w, so no reordering is in play either. Six checks, zero mismatches, three runs byte-identical. [1]

    The unprivileged manual states the contract in section 13.2: if the store-conditional succeeds, it writes the word to memory and writes zero to rd; if it fails, it writes nothing to memory and writes a nonzero value to rd. Failure code 1 encodes an unspecified failure, and portable software should only assume the failure code will be nonzero. [2]

    The bench habit has two parts. First, check rd and retry from the load-reserved, never from the store-conditional: executing an sc, success or failure, invalidates the reservation the hart holds, so re-issuing the sc alone can never succeed. [2] Second, keep the window empty. The constrained LR/SC loop in section 13.3 forbids loads, stores, backward jumps, and several other instruction types between the lr and the sc; a store in the window breaks the eventual-success guarantee. The experiment's intervening sw is exactly that forbidden store, and on this QEMU build the reservation died for it. [1] [2]

    One measured boundary, stated honestly: these are emulator results, not silicon. The spec mandates failure for stores from another hart and for a second sc in the window, but it does not mandate that an ordinary same-hart store kills the reservation. The run proves the observable outcome on QEMU 8.2.2, not the internal mechanism behind it. [1]

    One sentence to carry away: between your load-reserved and your store-conditional there is room for exactly nothing, and a failed store-conditional tells you so in rd without touching memory.

    Sources

    1. 01
      src/lrsc-store-invalidate: module PROOF.md and the firsthand runChris Dillinger

      The firsthand QEMU 8.2.2 run behind the post: cell_a held 0xAAAA0000; lr.w, an intervening sw of 0xBBBB1111, then sc.w attempting 0xCCCC2222 on the same address. rd printed 1 (failure), cell_a read back 0xBBBB1111 (the intervening store), and 0xCCCC2222 never landed. Control: lr.w then sc.w on cell_b with nothing between, rd 0, cell_b 0xEEEE4444. 6 checks, 0 mismatches, byte-identical across three runs, checksum 0xa61fb63cece6cebc; the post's own rebuild and rerun on the build VM reproduced the PASS and the checksum. The disassembly confirmed the emitted order lr.w / sw / sc.w in one volatile asm block.

    2. 02
      RISC-V ISA Manual, unprivileged architecture (LR/SC, sections 13.2 and 13.3)RISC-V International

      The contract, read from the pinned release. Section 13.2: 'If the SC.W succeeds, the instruction writes the word in rs2 to memory, and it writes zero to rd. If the SC.W fails, the instruction does not write to memory, and it writes a nonzero value to rd'; 'The failure code with value 1 encodes an unspecified failure. Other failure codes are reserved at this time. Portable software should only assume the failure code will be non-zero'; 'Regardless of success or failure, executing an SC.W instruction invalidates any reservation held by this hart'; 'An SC must fail if there is another SC (to any address) between the LR and the SC in program order.' Section 13.3: the constrained LR/SC loop's dynamic code between the LR and SC can only contain base I instructions excluding loads, stores, backward jumps, taken backward branches, JALR, FENCE, and SYSTEM instructions.

    The Page Table Edit That Changed Nothing

    ISA

    The claim is the privileged specification's SFENCE.VMA contract: the fence orders prior page-table stores before the hart's subsequent implicit translation reads, and invalidates the address-translation cache. The run shows both faces on one hart: the PTE rewrite with no fence reads stale, the same load after sfence.vma reads fresh.

    MICROARCH

    No claim depends on how any core implements its translation cache. QEMU serves as a functional executor only; no cache geometry, pipeline, or timing behavior is asserted or measured, and the stale phase is the architecture-permitted behavior the fence exists to order.

    FIRMWARE

    No firmware service takes part in the claim. The binary runs in M-mode on bare QEMU with no SBI or firmware calls; the fence is executed directly by the test's own M-mode code.

    KERNEL

    No kernel takes part at any step. The binary runs on bare QEMU with no operating system; the S-mode phases are a test payload, and no system call or kernel data structure appears in the argument.

    ALGORITHM

    The claim is one fixed ordering semantic exercised as three fixed phases with readback, not a computation proved against an independent oracle. The stale-then-fresh contrast is shown as the consequence the fence contract forces, not as a verified algorithm.

    One virtual address, 0x40000000. A hand-built Sv39 page table maps it to a physical page holding the canary 0xaaaaaaaaaaaaaaaa. A supervisor-mode program loads the word and gets 0xaaaaaaaaaaaaaaaa back. That walk does something invisible too: the hart caches the translation, 0x40000000 goes to the canary-A page, in its address-translation cache. [1]

    Now machine mode rewrites the leaf page-table entry in memory, repointing the address at a second page holding 0xbbbbbbbbbbbbbbbb. The PTE readback proves the write landed: 0x200010c7 before, 0x20000cc7 after. No fence is issued. The supervisor program loads the address again and gets 0xaaaaaaaaaaaaaaaa. The edit changed nothing the hart could see. The cache still holds the old walk, and the architecture permits the hart to keep using it. [1]

    The three phases, reduced to their witness:

    pte:    0x200010c7 -> 0x20000cc7   # the rewrite landed in memory
    phaseB: readback 0xaaaaaaaaaaaaaaaa # stale: no fence issued
    phaseC: readback 0xbbbbbbbbbbbbbbbb # fresh: after sfence.vma
    Blueprint-style diagram of the sfence.vma remap experiment in three phases: phase A loads 0xaaaaaaaaaaaaaaaa from virtual address 0x40000000 and the hart caches the translation; M-mode rewrites the leaf PTE from 0x200010c7 to 0x20000cc7 with no fence and the next load still returns 0xaaaaaaaaaaaaaaaa, stale; after one sfence.vma the same load returns 0xbbbbbbbbbbbbbbbb, fresh
    The PTE rewrite landed in memory (the readback proved it) but the hart kept its cached translation until one sfence.vma forced a fresh walk.
    Diagram: hand-built by Chris Dillinger for this post

    Then machine mode executes one sfence.vma. The same load now returns 0xbbbbbbbbbbbbbbbb. Note what the fence did not do: it did not move the write. The write was already in memory before the fence ran. The fence invalidated the hart's cached translation, so the next load walked the table again and found the new leaf. The privileged manual, section 12.2.1, states the contract: the fence guarantees that previous stores already visible to the hart are ordered before its subsequent implicit reads of the memory-management data structures, and it invalidates entries in the address-translation cache. [1] [2]

    The bench habit: after every page-table edit, a map, an unmap, a permission change, issue sfence.vma before the address is used again. One boundary from the manual: the fence orders only the local hart, so every hart that may hold the entry needs its own fence, which is why operating systems do TLB shootdowns with interprocessor interrupts. [2] One boundary measured: the manual explicitly permits over-fencing, an implementation may ignore the address in rs1 and flush everything. The sibling run on QEMU 8.2.2 confirmed it: a scoped sfence.vma naming one address freshened both test addresses. Scoping is a performance hint, not a correctness tool you can verify on every implementation. [3]

    One sentence to carry away: the PTE rewrite lands in memory; only sfence.vma lands it in the hart.

    Sources

    1. 01
      src/sfence-vma-remap: module PROOF.md and the firsthand runChris Dillinger

      The firsthand QEMU 8.2.2 run behind the post: TEST_VA 0x40000000 mapped to the canary-A page; M-mode rewrote the leaf PTE, readback 0x200010c7 to 0x20000cc7, with no fence; the S-mode load returned stale 0xaaaaaaaaaaaaaaaa; after one sfence.vma the same load returned fresh 0xbbbbbbbbbbbbbbbb. 39 checks, 0 mismatches, byte-identical across runs; the post's own rebuild and rerun on the build VM reproduced the PASS and the checksum.

    2. 02
      RISC-V ISA Manual, privileged architecture (SFENCE.VMA, section 12.2.1)RISC-V International

      The fence contract, read from the pinned release, section 12.2.1: executing SFENCE.VMA guarantees that previous stores already visible to the hart are ordered before subsequent implicit references to the memory-management data structures, and the instruction invalidates entries in the address-translation cache. The same section states the fence orders only the local hart and that over-fencing is always legal.

    3. 03
      src/sfence-vma-rs1-scoped: module PROOF.mdChris Dillinger

      The sibling run behind the post's stated limit: sfence.vma with rs1 naming one address freshened both test addresses on QEMU 8.2.2, so the scoped form behaved as a full invalidation; 60 checks, 0 mismatches. The manual's over-fencing note predicts exactly this latitude.

    The Borrow That Betrays the Zero

    ISA

    No instruction-set claim is made. The guarantee is C unsigned arithmetic: subtraction wraps modulo 2^64 and each byte borrows exactly as the language defines, so the identity holds on any target with two's-complement integers. No instruction, CSR, or privilege behavior is asserted or measured.

    MICROARCH

    No claim depends on how any core implements anything. The verdicts are differential equalities between the mask and a per-byte reference loop that hold regardless of pipeline or cache behavior; no timing, throughput, or implementation detail is asserted.

    FIRMWARE

    No boot code, machine-mode service, or privilege handoff takes part. The test compiles the identity as an ordinary C function and runs it as a userspace program; no firmware call enters the computation, so nothing firmware does can move the result.

    KERNEL

    No kernel is involved at any step. The program makes no system call and no kernel data structure appears in the argument; the scanner use case is ordinary string handling, and kernel behavior cannot move any verdict.

    ALGORITHM

    The claim is an arithmetic identity proved against an independent oracle: the mask is nonzero exactly when a zero byte is present, checked exhaustively over all 16,777,216 24-bit inputs plus 65,536 16-bit and 2 million random 64-bit words against a per-byte reference loop, with zero mismatches. The phantom-borrow boundary is measured the same way: 1001 counting overcounts in 10,065,536 differential inputs.

    A strlen loop checks one byte at a time: is this the terminator, is this the terminator. Eight checks for eight bytes. There is a way to ask all eight bytes at once, and the whole trick is a subtraction.

    Take the word 0x4200. Its lowest byte is 0x00, the byte you are hunting. Subtract 0x0101, which takes 0x01 off each of the two low bytes. The low byte computes 0x00 minus 0x01. That borrows, wraps to 0xFF, and the borrow sets the byte's top bit. The byte above computes 0x42 minus 0x01 minus the incoming borrow, landing at 0x40 with its top bit quiet. The zero byte just announced itself through its top bit.

    A nonzero byte cannot fake this. Subtract 0x01 from 0x05 and you get 0x04: no borrow, top bit unchanged. Subtract 0x01 from 0xFF and the top bit stays on, but that is what the second half of the expression is for. AND the result with ~x, the bitwise inverse of the original word: a byte that already had its top bit set has a zero in ~x at that position, so the AND clears it. Only a top bit that the subtraction itself set survives, and the subtraction sets it by borrowing out of a zero byte. [1]

    The whole test, for all eight bytes at once:

    uint64_t has_zero_byte(uint64_t x) {
        return (x - 0x0101010101010101ULL) & ~x & 0x8080808080808080ULL;
    }
    Blueprint-style diagram of the zero-byte borrow mechanism: a 0x00 byte shown as eight zero bits becomes eight one bits after subtracting 0x01, with the top bit lit amber, while a 0x42 byte becomes 0x40 with its top bit quiet; below, the full expression (x - 0x0101010101010101) & ~x & 0x8080808080808080 with the verdict that a nonzero mask means a zero byte lives in the word
    The borrow is the signal: 0x00 minus 0x01 wraps to 0xFF and flips the top bit on, while a nonzero byte subtracts cleanly. One 64-bit subtraction asks all eight bytes at once.
    Diagram: hand-built by Chris Dillinger for this post

    I ran this over every 24-bit input, all 16,777,216 of them, against a byte-by-byte reference loop: the mask fired exactly when a zero byte was present, with zero misses, and a zero mask always meant no zero byte. That is the direction a scanner needs. A word-at-a-time strlen walks the string in 8-byte steps; when the mask is zero the whole word is clean and it moves on, and only when the mask fires does it drop to the byte loop to find where. [1]

    One measured boundary, not an assumption: the mask names the word, not the byte. A borrow out of a zero byte can spill into the byte above it. With x = 0x0100, byte 0 is 0x00 and byte 1 is 0x01, and the borrow turns byte 1 into 0xFF, setting its top bit too: a phantom. The lab behind this post measured 1001 such overcounts in 10,065,536 differential inputs when the identity was used for counting. So never count the mask's bits as zero positions. Use it as the tripwire, then let the byte loop do the locating. [1]

    The bench habit: when you scan for a sentinel byte, test the word first and read the bytes only on a hit.

    One sentence to carry away: one subtraction asks eight bytes whether any of them is zero, and a zero mask is proof that none are.

    Sources

    1. 01
      lab/93-swar-zero-count: module source and firsthand PROOF.mdChris Dillinger

      The verification behind the post: the zero-byte detection identity, the measured 1001 counting overcounts in 10,065,536 differential inputs that bound the naive identity to existence testing, and the guarded 16-bit lane construction that counts exactly. The post's own firsthand run (exhaustive 24-bit sweep, 16,777,216 inputs, zero mismatches between the mask and a per-byte reference) re-verified the existence direction on the build VM.

    The Trap You Plant on Purpose

    ISA

    The claim is the breakpoint trap contract from the unprivileged specification: executing ebreak raises a precise trap with mcause 3 and mepc holding the breakpoint's address, in both the 4-byte and the compressed 2-byte encodings. The run fires one of each and reads back the identical trap shape, with the resume landing 4 bytes past the ebreak and 2 bytes past the c.ebreak.

    MICROARCH

    No claim depends on how any core implements anything. No cache, pipeline, or timing behavior is asserted or measured; QEMU serves as a functional executor only, and the breakpoint contract is complete from the unprivileged specification and the run.

    FIRMWARE

    No firmware service takes part in the claim. The binary runs in M-mode on bare QEMU with no SBI or firmware calls; the behavior under test is the trap hardware's own contract.

    KERNEL

    No kernel is involved at any step. The test binary runs on bare QEMU with no operating system, and no system interface appears in the argument.

    ALGORITHM

    The claim is two fixed trap semantics exercised as two planted tripwires with register readback, not a computation proved against an independent oracle. The plant-it-on-the-can't-happen-path habit is shown as the consequence the contract forces, not as a verified algorithm.

    Every bare-metal program has a path that should never execute: the default case the hardware manual says is impossible, the error return that cannot happen. The usual treatment is an empty infinite loop, and when the impossible happens you get silence. The hart spins, and nothing tells you which loop it died in. There is a one-instruction alternative: plant a breakpoint on the path and let the hardware report the exact address.

    The instruction is ebreak. Section 2.8 of the unprivileged manual says it plainly: EBREAK is used to return control to a debugging environment, and it was designed for a debugger to make execution stop and fall back into the debugger. When the hart executes it, it traps with mcause 3, the breakpoint code, and mepc holds the address of the ebreak itself. A run on QEMU 8.2.2 executed one ebreak at 0x800002fe: the handler recorded mcause 0x3 and mepc 0x800002fe, the word at that address read back 0x00100073, the ebreak encoding, and execution resumed 4 bytes later at 0x80000302. [1] [2]

    The trap record, reduced to its witness:

    tripwire: ebreak at 0x800002fe          # encoding 0x00100073
    trap:     mcause=0x3  mepc=0x800002fe   # the hardware names the PC
    resume:   0x80000302                    # 4 bytes past the tripwire
    Blueprint-style diagram of the planted-breakpoint contract: a 4-BYTE EBREAK box with tripwire at 0x800002fe, encoding 0x00100073, mcause 0x3 and mepc 0x800002fe, and a 2-BYTE C.EBREAK box with tripwire at 0x80000320, encoding 0x9002, mcause 0x3 and mepc 0x80000320; both arrows converge on the C spelling __builtin_trap(), which compiles to the 2-byte c.ebreak at -O2
    The same breakpoint trap in two encodings: the 4-byte ebreak and the 2-byte compressed c.ebreak. Both trap with mcause 3; mepc names the planted instruction in each case.
    Diagram: hand-built by Chris Dillinger for this post

    There are two spellings, and the length is the part that bites. The compressed form, c.ebreak, is two bytes, encoding 0x9002. The same run fired it at 0x80000320: mcause 0x3 again, mepc 0x80000320, the halfword at that address 0x9002, resume 2 bytes later at 0x80000322. A handler that steps over the tripwire must skip the right length for the form planted, 4 for ebreak, 2 for c.ebreak, or it resumes in the middle of the next instruction. [1]

    The C spelling is the one you will actually plant. The manual notes that EBREAK is used by the standard GCC compiler to mark code paths that should not be executed, and the current spelling of that is __builtin_trap(): compiled at -O2 it emits the compressed c.ebreak, a single 0x9002 sitting in .text.unlikely. So the can't-happen path in C is one builtin call, and the trap still arrives with mcause 3 and mepc naming it. Thirteen checks across the run, zero mismatches. [1] [2]

    The bench habit. On a can't-happen path, plant __builtin_trap() instead of an empty loop. When the impossible happens, your trap handler reads mepc and you know the exact address that died, instead of hunting every parked loop in the binary. One stated limit: this names where the hart stopped, not why. The why is still your bug to find. [2]

    One sentence to carry away: a planted breakpoint turns a silent hang into a trap that names its own address.

    Sources

    1. 01
      src/ebreak-tripwire: module PROOF.md and the firsthand runChris Dillinger

      The firsthand QEMU run behind the post: one 4-byte ebreak at 0x800002fe and one 2-byte c.ebreak at 0x80000320, each trapped with mcause 0x3 and mepc equal to the tripwire address; the word at the first mepc read 0x00100073 and the halfword at the second 0x9002; resumes landed 4 and 2 bytes past. Thirteen checks, zero mismatches, QEMU 8.2.2, three identical runs. The PROOF also records that __builtin_trap() compiled at -O2 emits the single 0x9002 c.ebreak in .text.unlikely.

    2. 02
      RISC-V ISA Manual, unprivileged architecture (EBREAK, section 2.8; C.EBREAK, C-extension chapter)RISC-V International

      The breakpoint contract, read from the pinned release, section 2.8: 'The EBREAK instruction is used to return control to a debugging environment.' And the planting license: 'EBREAK was primarily designed to be used by a debugger to cause execution to stop and fall back into the debugger. EBREAK is also used by the standard GCC compiler to mark code paths that should not be executed.' The C-extension chapter: 'Debuggers can use the C.EBREAK instruction, which expands to ebreak, to cause control to be transferred back to the debugging environment.'

    The Register That Names the Bad Address

    ISA

    The claim is the privileged specification's mtval contract: on an access fault, a nonzero mtval holds the faulting virtual address. The run traps once on a load and once on a store at the same unmapped address and reads back the identical mtval both times, proving the witness behaves the same for both access types.

    MICROARCH

    No claim depends on how any core implements anything. No cache, pipeline, or timing behavior is asserted or measured; QEMU serves as a functional executor only, and the mtval contract is complete from the privileged specification and the run.

    FIRMWARE

    No firmware service takes part in the claim. The binary runs in M-mode on bare QEMU with no SBI or firmware calls; the behavior under test is the trap hardware's own contract.

    KERNEL

    No kernel is involved at any step. The test binary runs on bare QEMU with no operating system, and no system interface appears in the argument.

    ALGORITHM

    The claim is one fixed trap semantic exercised as two fixed faulting accesses with readback, not a computation proved against an independent oracle. The read-mtval-first habit is shown as the consequence the contract forces, not as a verified algorithm.

    Two traps, one address. A bare-metal program loads a word from the unmapped address 0xffffffffc0000000 with lw a0, 0(a1), and the hart traps with mcause 0x5, a load access fault. It then stores to the same address with sw a0, 0(a1): mcause 0x7, a store access fault. The handler reads mtval on each trap, and the UART printed 0xffffffffc0000000 both times. Two different traps, two different cause codes, one identical witness. [1]

    The mechanism is one register the hardware fills on the way into the trap. The privileged manual, section 3.1.16, says that when a trap is taken into M-mode, mtval is either set to zero or written with exception-specific information to assist software in handling the trap. Then the sentence that matters: if mtval is written with a nonzero value when an access-fault exception occurs on a load or store, then mtval will contain the faulting virtual address. The platform decides whether it reports or writes zero; the contract is about what a nonzero value means, not a promise that every hart reports. [1] [2]

    The two trap records, reduced to their witness:

    load trap:  mcause=0x5  mtval=0xffffffffc0000000   # lw a0,0(a1) at 0x80000322
    store trap: mcause=0x7  mtval=0xffffffffc0000000   # sw a0,0(a1) at 0x8000036a
    Blueprint-style diagram of mtval on access faults: a LOAD TRAP box with mcause 0x5 and a STORE TRAP box with mcause 0x7, both showing mtval = 0xffffffffc0000000; two arrows converge on the one address both traps named, labeled unmapped on the QEMU virt board
    Two traps, two mcause codes, one identical witness. Both the load fault and the store fault reported the same mtval.
    Diagram: hand-built by Chris Dillinger for this post

    The run behind it. A bare-metal M-mode program on QEMU 8.2.2 issued one load and one store at the unmapped address and recorded the mcause/mepc/mtval triple for each trap. Both mtval values came back 0xffffffffc0000000, equal to the address in the register and equal to each other. The disassembly shows the real instructions: the lw encoding 0x0005a503 at 0x80000322, the sw encoding 0x00a5a023 at 0x8000036a, each mepc matching its faulting address exactly. Nineteen checks, zero mismatches, and the machine exited clean. [1]

    The bench habit. In your access-fault handler, read mtval first, before you decode anything. A nonzero value names the exact address that faulted; mcause tells you whether it was a load (5) or a store (7); mepc points at the instruction. Without it you would disassemble the faulting instruction at mepc to recover the base register and the offset, which is work the hardware already did for you. One stated limit: a zero mtval means the platform chose not to report, so treat zero as "not told", never as "the fault was at address zero". [2]

    One sentence to carry away: when a load or store faults, check mtval before anything else. If it is nonzero, the hardware already named the bad address.

    Sources

    1. 01
      src/mtval-fault-address: module PROOF.md and the firsthand runChris Dillinger

      The firsthand QEMU run behind the post: one lw and one sw at the unmapped address 0xffffffffc0000000; the load trap reported mcause 0x5 and the store trap mcause 0x7, and both traps reported mtval 0xffffffffc0000000, equal to the faulting address and to each other. Nineteen checks, zero mismatches, QEMU 8.2.2.

    2. 02
      RISC-V ISA Manual, privileged architecture (mtval, section 3.1.16)RISC-V International

      The mtval contract, read from the pinned release: 'When a trap is taken into M-mode, mtval is either set to zero or written with exception-specific information to assist software in handling the trap.' And the reporting rule: 'If mtval is written with a nonzero value when a breakpoint, address-misaligned, access-fault, page-fault, or hardware-error exception occurs on an instruction fetch, load, or store, then mtval will contain the faulting virtual address.'

    The Branch That Inverts the Address Map

    ISA

    The claim is the RV64I branch contract: blt compares its operands as signed two's-complement integers and bltu as unsigned. The run issues both branches on the same register pairs and reads back opposite taken/not-taken verdicts, proving the signedness lives in the instruction.

    MICROARCH

    No claim depends on how any core implements anything. No cache, pipeline, or timing behavior is asserted or measured; QEMU serves as a functional executor only, and the branch contract is complete from the instruction semantics and the run.

    FIRMWARE

    No firmware service takes part in the claim. The binary runs in M-mode on bare QEMU with no SBI or firmware calls; the behavior under test is each branch instruction's own contract.

    KERNEL

    No kernel is involved at any step. The test binary runs on bare QEMU with no operating system, and no system interface appears in the argument.

    ALGORITHM

    The claim is one fixed instruction semantic exercised as fixed branch pairs with readback, not a computation proved against an independent oracle. The range-check habit is shown as the consequence the contract forces, not as a verified algorithm.

    Two addresses sit in registers: 0x8000000000000000 and 0x0000000000001000. Two branch instructions compare the same pair, one after the other, on the same hart. The UART printed the verdicts: blt took the branch, bltu fell through. Same registers, same order, opposite answers. [1]

    The difference is the signedness of the compare, and it lives in the instruction, not the data. blt reads its operands as two’s-complement signed integers: 0x8000...0000 is the most negative 64-bit value, which is less than 0x1000, so the branch is taken. bltu reads the same bits as unsigned: 0x8000...0000 is the larger address, so the branch is not taken. One letter in the mnemonic flips the meaning of every bit pattern with the top bit set. [1] [2]

    The two branches, reduced to their verdicts:

    blt  s0, s1, taken   # signed:   0x8000000000000000 < 0x1000, branch taken
    bltu s0, s1, taken   # unsigned: 0x8000000000000000 > 0x1000, falls through
    Blueprint-style diagram of the blt/bltu signedness split: a vertical 64-bit address map with 0x0000000000001000 near the bottom, 0x8000000000000000 at the bit-63 midpoint, and 0xFFFFFFFFFFFFF000 at the top; beside it, the blt box reading 0x8000000000000000 as negative 9,223,372,036,854,775,808 with verdict BRANCH TAKEN, and the bltu box reading it as positive 9,223,372,036,854,775,808 with verdict FALLS THROUGH
    Same two registers, opposite verdicts. blt reads the pair as signed and takes the branch; bltu reads it as unsigned and falls through.
    Diagram: hand-built by Chris Dillinger for this post

    The run behind it. A bare-metal M-mode program on QEMU 8.2.2 issued both branches on three register pairs: (0x8000000000000000, 0x1000), the reverse, and a high-half address 0xfffffffffffff000 against 0x1000. The disassembly shows the real instructions: blt at 0x80000292, bltu at 0x800002ca, the high-half pair at 0x80000304 and 0x80000320. Six checks, zero mismatches. The high-half pair is the one that matters: blt said 0xfffffffffffff000 was below 0x1000 (taken), bltu said it was above (not taken). [1]

    The bench habit. Address ordering is unsigned, always: a range check addr < LIMIT has to use the unsigned compare. In C that means the unsigned type; the compiler listing for this run showed the same fork one level down, slt for the long version and sltu for the unsigned long version. The trap is the signed cast: the moment an address becomes a signed long, a bounds check inverts the map above bit 63, and a kernel-space address passes a "below the limit" test it should fail. The habit: if the value is an address, the compare is unsigned, no exceptions. [2]

    Sources

    1. 01
      src/blt-bltu-addr: module PROOF.md and the firsthand runChris Dillinger

      The firsthand QEMU run behind the post: blt and bltu issued on (0x8000000000000000, 0x1000), the reverse pair, and (0xfffffffffffff000, 0x1000); blt took the branch wherever the signed reading is less, bltu wherever the unsigned reading is less. Six checks, zero mismatches, QEMU 8.2.2. The compiler listing shows slt for the long compare and sltu for the unsigned long compare.

    2. 02
      RISC-V ISA Manual, unprivileged architecture (branch instructions)RISC-V International

      The branch contract, read from the pinned release: 'BLT and BLTU take the branch if rs1 is less than rs2, using signed and unsigned comparison respectively.' The manual itself blesses the applied habit: 'Signed array bounds may be checked with a single BLTU instruction, since any negative index will compare greater than any nonnegative bound.'

    The Load That Sign-Extended

    ISA

    The claim is the RV64I load contract: lw sign-extends the 32-bit value to 64 bits while lwu zero-extends it. The run executes both loads on the same word and reads back 0xffffffff80000001 and 0x0000000080000001, proving the extension half of each instruction by register readback.

    MICROARCH

    No claim depends on how any core implements anything. No cache, pipeline, or timing behavior is asserted or measured; QEMU serves as a functional executor only, and the extension contract is complete from the instruction semantics and the run.

    FIRMWARE

    No firmware service takes part in the claim. The binary runs in M-mode on bare QEMU with no SBI or firmware calls; the behavior under test is each load instruction's own contract.

    KERNEL

    No kernel is involved at any step. The test binary runs on bare QEMU with no operating system, and no system interface appears in the argument.

    ALGORITHM

    The claim is one fixed instruction semantic exercised as two fixed loads with readback, not a computation proved against an independent oracle. The == consequence is shown as the habit the contract forces, not as a verified algorithm.

    A 32-bit word sits in a scratch buffer holding 0x80000001, its top bit set. Two loads read that same word, one instruction apart, on the same hart. The UART printed 0xffffffff80000001 for the first and 0x80000001 for the second. Same word, same address, two different registers, two different values. [1]

    The difference is the extension. lw loads the 32-bit value and sign-extends it to 64 bits: bit 31 is copied into every bit from 32 through 63. lwu loads the same 32 bits and zero-extends: the upper half is zeros. The manual states both in one breath, and the run shows them side by side. [1] [2]

    The two loads, reduced to their results:

    lw  t0, 0(s0)   # t0 = 0xffffffff80000001 : bit 31 copied upward
    lwu t1, 0(s0)   # t1 = 0x0000000080000001 : bits 63..32 are zero
    Blueprint-style diagram of the lw/lwu extension behavior: a 32-bit memory word holding 0x80000001 with bit 31 highlighted as the sign bit; below, the 64-bit result of lw t0, 0(s0) with bits 63 through 32 all ones, and of lwu t1, 0(s0) with bits 63 through 32 all zeros; at the bottom, t0 == 0x80000001 marked FALSE and t1 == 0x80000001 marked TRUE
    One word, two loads. lw fills the upper 32 bits with copies of bit 31; lwu fills them with zeros.
    Diagram: hand-built by Chris Dillinger for this post

    The run behind it. A bare-metal M-mode program on QEMU 8.2.2 stored 0x80000001 with sw, then issued the lw and the lwu back to back and read both registers off the UART: lw -> 0xffffffff80000001, lwu -> 0x80000001, the same as 0x0000000080000001. The disassembly shows the real instructions: sw at 0x80000204, lw at 0x80000206, lwu at 0x80000208. Four checks, zero mismatches: both exact values, plus the comparison consequence below. [1]

    The bench habit. A 32-bit status word is usually a bit pattern, not a signed number, so the sign-extended upper half is garbage you never asked for. The classic failure is silent: t0 == 0x80000001 is false after the lw and true after the lwu, and nothing in the code warns you. The habit: when the value is 32 bits of flags, reach for lwu (or ld when it is really 64 bits), and never trust a bare == on a register you did not fill yourself. [2]

    Sources

    1. 01
      src/load-sign-ext: module PROOF.md and the firsthand runChris Dillinger

      The firsthand QEMU run behind the post: sw stored 0x80000001 to the scratch word; lw s1,0(a0) returned 0xffffffff80000001; lwu s0,0(a0) returned 0x0000000080000001; the lw result fails == against the 32-bit pattern while the lwu result matches. Four checks, zero mismatches, QEMU 8.2.2.

    2. 02
      RISC-V ISA Manual, unprivileged architecture (RV64I loads)RISC-V International

      The load contract, read from the pinned release: 'The LW instruction loads a 32-bit value from memory and sign-extends this to 64 bits before storing it in register rd for RV64I. The LWU instruction, on the other hand, zero-extends the 32-bit value from memory for RV64I.'

    The Register With No Name

    ISA

    The verdict is the AUIPC semantic from the unprivileged ISA: the 20-bit immediate with 12 zero bits appended is added to the address of the auipc instruction itself. The QEMU run confirmed it twice: the auipc at 0x800001d2 returned 0x800001d2, and the auipc with immediate 0x12345 at 0x800001f4 returned 0x923451f4, which is 0x800001f4 plus 0x12345000.

    MICROARCH

    No claim depends on how any core implements the addition. The three values came from one run on QEMU's virt board, and the post asserts nothing about pipelines, caches, or timing.

    FIRMWARE

    The test runs on bare metal without calling any firmware service, and the verdict asserts nothing about firmware behavior. The auipc semantic is defined by the instruction itself, independent of privilege level.

    KERNEL

    The verdict concerns one user-level instruction and its register result. No trap, no system call, and no operating system data structure takes part in any of the three checks.

    ALGORITHM

    The claim is one instruction semantic checked against three observed register values, not a computation proved against an independent oracle. No invariant is proved beyond the observed output.

    The program counter has no register number. RISC-V names 32 integer registers, x0 through x31, and the PC is not one of them: no instruction takes it as a source operand, and there is no mv t0, pc. The one instruction that looks at it does so sideways: [1]

    auipc s0, 0   # s0 = the address of this very instruction

    On the QEMU virt board that auipc sat at 0x800001d2, and it put 0x800001d2 into s0: its own address, read off the UART. The mechanism is one addition. auipc takes the 20-bit immediate, appends 12 zero bits, and adds the result to the address of the auipc instruction itself. With an immediate of zero the offset is zero, so the PC comes back unchanged. [1]

    With auipc s0, 0x12345 sitting at 0x800001f4, the UART printed 0x923451f4, and 0x800001f4 + 0x12345000 = 0x923451f4 exactly. The immediate is the upper 20 bits; the low 12 are always zero. [1]

    This is how code that does not know where it was loaded still reaches its own data. The pair auipc t0, %pcrel_hi(table) / ld t1, %pcrel_lo(1b)(t0) adds the link-time distance from the auipc to the symbol onto the live PC. In the test it fetched the constant 0x123456789abcdef0 through that pair, and the same two instructions work wherever the image lands, because the distance never changes and the PC is always true. [1]

    Blueprint-style diagram of the auipc PC read: the 32 numbered registers x0 through x31 with the program counter shown outside them in a dashed red box; the auipc s0, 0 instruction at 0x800001d2 with its fields imm 0x00000, rd 01000, opcode 0010111, an arrow down to s0 holding 0x800001d2; and the addition 0x800001f4 + 0x12345000 = 0x923451f4.
    One instruction reads the PC by adding zero to it. With an immediate, the same instruction adds the upper 20 bits.
    Diagram: hand-built by Chris Dillinger for this post

    The bench habit: when a bare-metal image misbehaves after moving to a new load address, the first suspect is an absolute address baked in somewhere. PC-relative access through auipc has no absolute address to go stale, which is why the toolchain reaches for it whenever code must address data without knowing where it will live.

    Sources

    1. 01
      src/auipc-pcread: auipc PC-read checks, plus the firsthand runChris Dillinger

      Three checks built from src/boot.S and src/uart.c, run on QEMU 8.2.2 with the image at 0x80000000: auipc s0,0 at 0x800001d2 printed 0x800001d2; auipc s0,0x12345 at 0x800001f4 printed 0x923451f4, equal to 0x800001f4 plus 0x12345000; the auipc t0,%pcrel_hi(marker) and ld s0,%pcrel_lo(1b)(t0) pair loaded 0x123456789abcdef0 from marker at 0x80000350. The AUIPC semantic (20-bit immediate, 12 zero bits appended, added to the address of the auipc itself) follows the RISC-V User-Level ISA description of AUIPC.

    The Zero That strncpy Skips

    ISA

    No instruction-set claim is made. The guarantee is a C loop invariant: decrementing the count before the loop test reserves the last byte before the first byte is copied. No instruction, CSR, or privilege behavior is asserted or measured.

    MICROARCH

    No claim depends on how any core implements anything. The byte dumps came from compiling the actual xv6 functions on the build VM and running them as a userspace test; no cache, pipeline, or timing behavior is asserted.

    FIRMWARE

    No boot code, machine-mode service, or privilege handoff takes part. Both functions are plain C from the kernel string library, exercised outside any firmware context.

    KERNEL

    The verdict is a kernel string-copy contract. xv6's kernel/string.c carries both functions side by side: strncpy leaves the destination unterminated when the source is longer than n, while safestrcpy decrements the count before copying and then writes the terminator unconditionally, so the last byte always holds the zero, which is exactly what the cited source shows.

    ALGORITHM

    The claim is one loop invariant checked against two observed byte dumps, not a computation proved against an independent oracle. No invariant is proved beyond the observed output.

    The buffer starts full of X. One call through the actual strncpy in xv6's kernel/string.c, strncpy(dst, "hello world", 5), and the first five bytes read 68 65 6c 6c 6f: "hello", exactly as promised. The sixth byte is still 58: an X. No zero landed anywhere in the first five bytes, so anything that prints the result as a string walks straight past the end. [1]

    The same call through safestrcpy, the other function in the same file, writes 68 65 6c 6c 00: "hell" plus the zero. The whole difference is where the decrement lands. strncpy tests n-- > 0: the decrement happens after the test, so all five bytes stay available for copying, and the terminator lands only when the source ends early. safestrcpy tests --n > 0: the decrement happens first, so the loop can consume at most four bytes, and the last byte is reserved before the first byte is copied. [1]

    The reservation, in three lines:

    while (--n > 0 && (*s++ = *t++) != 0)
      ;
    *s = 0;   /* the last byte was reserved before the first was copied */

    The run, with both functions compiled from the real kernel/string.c and run on the build VM: destination pre-filled with X, source "hello world", n = 5. strncpy left 68 65 6c 6c 6f 58 58 58. safestrcpy left 68 65 6c 6c 00 58 58 58. The short-source case shows the other side: strncpy(dst, "hi", 5) gives 68 69 00 00 00, padding zeros once the source ends, while safestrcpy gives 68 69 00 and stops, leaving the old fill behind the terminator. One pads but does not guarantee; the other guarantees but does not pad. [1]

    Blueprint-style diagram of two destination buffers pre-filled with X, each receiving the string 'hello world' with n = 5: strncpy writes h e l l o and leaves the sixth byte as X with no terminator; safestrcpy writes h e l l and a zero terminator in the fifth byte, the decrement's position deciding which byte the zero gets.
    Same source, same n. strncpy spends all five bytes on the copy and leaves no terminator; safestrcpy spends four and reserves the fifth for the zero.
    Diagram: hand-built by Chris Dillinger for this post

    The bench habit: in kernel code a bounded copy has to guarantee its own terminator, because the next reader downstream will treat the buffer as a string. The question is not "did the source fit"; it is "can I point at the byte that ends it". In xv6 that question has one answer: safestrcpy.

    Sources

    1. 01
      kernel/string.c: strncpy and safestrcpy, plus the firsthand runChris Dillinger

      Both functions read directly from the xv6 source: strncpy decrements the count after the loop test, so all n bytes stay copyable and the terminator lands only when the source ends early; safestrcpy decrements before the test, so the loop can consume at most n-1 bytes, then writes the terminator unconditionally. Both compiled from this file on the build VM and run with dst pre-filled with X, src 'hello world', n=5: strncpy left 68 65 6c 6c 6f with the sixth byte still 58; safestrcpy left 68 65 6c 6c 00.

    The Misaligned Access That Never Trapped

    ISA

    The verdict is the ISA's own latitude: the manual leaves misaligned loads and stores to the execution environment, which may handle them invisibly or raise an address-misaligned exception. The run shows which choice this machine made: both accesses completed with no trap, the handler never running.

    MICROARCH

    No claim depends on how any core implements anything. No cache, pipeline, or timing behavior is asserted or measured; QEMU serves as a functional executor only, and the invisible-handling verdict is read off the trap registers, not the microarchitecture.

    FIRMWARE

    No boot code, machine-mode service, or privilege handoff takes part. The M-mode trap handler is the experiment harness, and it never ran: the seen flag stayed zero and mcause, mepc, and mtval read back zero.

    KERNEL

    No kernel is involved at any step. The test binary runs on bare QEMU with no operating system, and no system interface appears in the argument.

    ALGORITHM

    The claim is one fixed machine behavior exercised as two fixed accesses with readback, not a computation proved against an independent oracle. No invariant is proved beyond the two observed outcomes.

    The manual splits every load and store in two. When the effective address is naturally aligned, divisible by the access size, no implementation may raise an address-misaligned exception. When it is not, the choice belongs to the execution environment: it may handle the access invisibly, in hardware or with a hidden trap, or it may raise an address-misaligned exception instead. The trap is optional. [1]

    This machine chose the invisible path. A bare-metal M-mode program on QEMU 8.2.2 installed a trap handler recording mcause, mepc, and mtval, then issued a word load from 0x80000c01, one byte past a four-byte boundary, and a word store of 0x12345678 to 0x80000c02, two bytes past. Neither access trapped: the handler never ran, and all three trap registers read back zero. [2]

    The values came back byte-exact. The load returned 0xffffffffd5a1b2c3: the four bytes C3 B2 A1 D5, assembled little-endian into 0xd5a1b2c3 and sign-extended to 64 bits, because lw sign-extends. The store wrote exactly its four bytes, 78 56 34 12, and the byte just outside the stored range kept its old value, 0xC3. The machine did the unaligned work in software and told nobody. [2]

    The two accesses, reduced to their results:

    lw  @ 0x80000c01  ->  0xffffffffd5a1b2c3   /* no trap */
              sw  @ 0x80000c02  <-  0x12345678           /* no trap, bytes 78 56 34 12 */
    Blueprint-style diagram of the misaligned access experiment: eight bytes of the scratch buffer at 0x80000c00 holding the control fill D4 C3 B2 A1 D5 C3 B2 A1; the lw span covers base+1 through base+4 and the sw span covers base+2 through base+5, both crossing 4-byte boundaries while the trap handler never runs; below, the manual's two choices, handle invisibly as this machine did, or raise the address-misaligned trap, mcause 4 for loads and 6 for stores.
    Both accesses crossed a 4-byte boundary and neither trapped. The manual permits either outcome; this machine chose the invisible one.
    Diagram: hand-built by Chris Dillinger for this post

    Another core is allowed the other choice: raise the address-misaligned trap, mcause 4 for the load and 6 for the store, and make your handler earn its keep. [2] A test that passes here proves the code runs on QEMU; it proves nothing about alignment. The habit: align what the manual says to align, and never let a green run on one machine certify the code for another.

    Sources

    1. 01
      RISC-V ISA Manual, Volume I: Unprivileged Architecture, section 2.6RISC-V International

      The misaligned-access rule, paraphrased: naturally aligned loads and stores shall not raise an address-misaligned exception on any implementation; for the rest, the execution environment may handle them invisibly (in hardware, with a hidden trap, or both) or raise an address-misaligned or access-fault exception. Misaligned accesses are also not guaranteed atomic.

    2. 02
      src/misaligned: module README and PROOF.mdChris Dillinger

      The firsthand QEMU run behind the post, re-verified on this run: a word load from 0x80000c01 and a word store of 0x12345678 to 0x80000c02, each past a four-byte boundary; neither trapped (seen=0, mcause/mepc/mtval all zero); the load returned 0xffffffffd5a1b2c3 and the store round-tripped byte-exact with the neighboring byte untouched. PROOF.md records 0 mismatches and notes real cores may instead trap with mcause 4 (load) or 6 (store).

    Sources

    1. 01
      RISC-V ISA Manual, Volume I: Unprivileged Architecture, section 2.6RISC-V International

      The misaligned-access rule, paraphrased: naturally aligned loads and stores shall not raise an address-misaligned exception on any implementation; for the rest, the execution environment may handle them invisibly (in hardware, with a hidden trap, or both) or raise an address-misaligned or access-fault exception. Misaligned accesses are also not guaranteed atomic.

    2. 02
      src/misaligned: module README and PROOF.mdChris Dillinger

      The firsthand QEMU run behind the post, re-verified on this run: a word load from 0x80000c01 and a word store of 0x12345678 to 0x80000c02, each past a four-byte boundary; neither trapped (seen=0, mcause/mepc/mtval all zero); the load returned 0xffffffffd5a1b2c3 and the store round-tripped byte-exact with the neighboring byte untouched. PROOF.md records 0 mismatches and notes real cores may instead trap with mcause 4 (load) or 6 (store).

    The Sleep That Cannot Miss Its Wakeup

    ISA

    No instruction-set claim is made. The whole mechanism is locks and state flags in C: register a channel, clear a channel, set a state. No instruction, CSR, or privilege behavior is asserted or measured.

    MICROARCH

    No claim depends on how any core implements anything. The ordering argument rests on lock serialization, which holds identically on any core; no cache, pipeline, or timing behavior is asserted.

    FIRMWARE

    No boot code, machine-mode service, or privilege handoff takes part. The code runs in the kernel proper, in wait(), sleep_prepare(), sleep(), exit(), and wakeup().

    KERNEL

    The verdict is a kernel sleep/wakeup protocol. Correctness rests on which lock is held at each step: wait() registers the channel under the process lock while still holding wait_lock, and exit()'s wakeup clears or honors it under the same process lock, which is exactly what the cited source shows.

    ALGORITHM

    The exclusion is a hand-checked case analysis over the three positions a wakeup can take relative to the registration, read off the lock order in the source. No independent oracle, known-answer vector, or mechanized proof is involved.

    A parent calls wait(). No child has exited yet, so the parent must sleep until one does. The oldest race in kernel code lives in the breath between those two facts: the scan says "nothing yet", and before the parent actually goes to sleep, a child exits. A wakeup fired at a process that is not yet asleep reaches nobody, and a wakeup that reaches nobody is lost. The parent sleeps, and nothing will ever wake it. [1]

    The fix is the order of three calls. wait() still holds the wait lock while it scans the children. Finding none exited, it does not release the lock yet. First it calls sleep_prepare(p), which takes the parent's own per-process lock and registers the sleep channel: wake me on this pointer. Only then does wait() release the wait lock, and only then does it call sleep(), which takes the per-process lock again and goes to sleep only if the channel is still registered. [1]

    The child's half runs under the same wait lock. exit() reparents the dying child, then calls wakeup(p->parent). wakeup walks the process table, takes each process's per-process lock, and where the channel matches it clears the channel; if the process already reached SLEEPING, it marks it RUNNABLE instead. [1]

    So order the child's exit anywhere on the timeline. Before the registration: the parent's scan found the zombie, so it never slept. Between the registration and the actual sleep: the wakeup clears the channel under the same lock, and sleep() sees an empty channel and returns without sleeping. After the sleep: SLEEPING flips to RUNNABLE. There is no fourth position. The registration is what collapses the gap: a wakeup can arrive early or late, but it can never arrive between.

    The three calls that seal the gap:

    sleep_prepare(p);      /* register the channel, holding p->lock */
    release(&wait_lock);   /* the decision is sealed */
    sleep();               /* sleeps only if the channel is still set */
    Blueprint-style timeline of the sleep/wakeup ordering: the wait() sequence of scan, registration, lock release, and sleep on a timeline, with three wakeup landing positions. A wakeup before registration finds the zombie child; one between registration and sleep clears the channel so sleep() returns without sleeping; one after the sleep flips SLEEPING to RUNNABLE. No fourth position exists.
    Every wakeup lands on one of three positions. Registering the channel before releasing the wait lock means there is no gap between the decision to sleep and the sleep itself.
    Diagram: hand-built by Chris Dillinger for this post

    The bench habit: whenever you add a sleep and wakeup pair to driver or kernel code, register your interest before you drop the guard lock, then re-read the three positions. If a wakeup can land somewhere with no verdict, the gap is still open.

    Sources

    1. 01
      proc.c: sleep_prepare, sleep, wakeup, wait, and exitChris Dillinger

      The three primitives and their caller order, read directly: sleep_prepare takes the process lock and records the channel; sleep takes the process lock and sleeps only while the channel is still set; wakeup takes each process's lock, clears a matching channel, and marks an already-sleeping process runnable. wait calls sleep_prepare before releasing the wait lock, then sleep; exit calls wakeup on the parent while holding the wait lock, so the child's exit lands either before the scan or after the registration, never between.

    The Shift That Needs Thirty-Three Bits

    ISA

    No instruction-set claim is made. The 33-bit verdict follows from C's type rules for the shift operator: the literal 1 has type int, int is 32 bits, and a signed shift is defined only when the value is representable in the promoted type. The compiler's diagnostic is emitted before any target is chosen, and the verdict holds with the CPU swapped.

    MICROARCH

    No claim depends on how any core implements anything. No cache, pipeline, or timing behavior is asserted or measured; the evidence is the compiler's diagnostic text and the defined value of the unsigned form, both produced before any hardware runs.

    FIRMWARE

    No boot code, machine-mode service, or privilege handoff takes part. The check is a host-side compile of two constant expressions, and the argument never enters firmware.

    KERNEL

    No kernel is involved at any step. The signed form was compiled as a userspace program on the build VM, and the comparison is between two expressions' definedness, read off the compiler's output rather than from any system call.

    ALGORITHM

    The claim is a language contract about representability, not a computation. Nothing is proved against an independent oracle, and no portable mechanism is under test.

    A peripheral register is 32 bits wide, and the bit you want is bit 31: the enable, the top flag, the master interrupt. My UART driver plays this game lower down: src/uart.c defines LSR_THRE as (1 << 5), one bit up from zero. Bit 31 looks like the same trick, one shift higher. [1]

    It is not the same trick. The literal 1 has type int, and int is 32 bits here. Shifting a 1 into the sign position asks for a value that needs 33 bits to represent. GCC 13.3.0 says it out loud with -Wshift-overflow: "result of '1 << 31' requires 33 bits to represent, but 'int' only has 32 bits". The language reference is blunter: for signed left operands the result is defined only when it is representable in the promoted type, otherwise the behavior is undefined. The compiler is allowed to assume it never happens. [2]

    On this machine it produced 0x80000000 anyway, which is exactly why the bug survives for years. It works on every compiler you try, right up until the optimization pass that folds it differently, and then your enable bit is a coin flip. Undefined does not mean broken today; it means no promise about tomorrow.

    The fix is one character: 1u. Unsigned int has the same 32 bits, but its top bit is a value bit, not a sign bit, and an unsigned left shift is defined as the value reduced modulo 2^32. So 1u << 31 is exactly 0x80000000, on every compiler, forever. The habit: every bit mask in a driver is unsigned. (1u << 31), (1u << 5), all of them. [2]

    #define ENABLE_BIT (1u << 31)  /* defined: exactly 0x80000000 */
    
    /* not (1 << 31): that value needs 33 bits in a 32-bit int,
       so the standard calls it undefined */
    Blueprint-style diagram of a 32-bit register row: bit 31 is lit amber holding the shifted 1, and a dashed red 33rd cell hangs off the left edge labeled needs 33 bits. Below, the two verdicts: 1 shifted left by 31 is undefined, 1u shifted left by 31 is defined as exactly 0x80000000.
    One bit past the edge. (1 << 31) asks for 33 bits in a 32-bit int, so it is undefined; (1u << 31) is exactly 0x80000000, defined.
    Diagram: hand-built by Chris Dillinger for this post

    Sources

    1. 01
      uart.c: the polled UART driverChris Dillinger

      The register-mask idiom the post starts from: LSR_THRE is defined with a left shift by 5, safe inside a 32-bit int. The same idiom with a shift of 31 is the post's subject.

    2. 02
      Arithmetic operators (C)cppreference.com

      States the rule the post rests on: a signed left shift is defined only when the result is representable in the promoted type of the left operand, otherwise the behavior is undefined; unsigned shifts are reduced modulo 2 to the n.

    The Registers MRET Will Not Restore

    ISA

    The claim is about the xRET instruction's contract: mret restores the pc from mepc and pops the privilege stack (MPIE into MIE, MPP into the privilege mode), and it restores no general registers. The run executes one ecall and shows all eight argument registers, a0 through a7, coming back with the handler's values after mret, proving the no-restore half of the contract by readback.

    MICROARCH

    No claim depends on how any core implements anything. No cache, pipeline, or timing behavior is asserted or measured; QEMU serves as a functional executor only, and the restore contract is complete from the instruction semantics and the run.

    FIRMWARE

    No firmware service takes part in the claim. The M-mode trap handler is the experiment subject, written for the test; the behavior under test is the mret instruction's own contract, and no boot service or supervisor interface appears in the argument.

    KERNEL

    No kernel is involved at any step. The test binary runs on bare QEMU with no operating system, and no system interface appears in the argument.

    ALGORITHM

    The claim is one fixed instruction semantic exercised as one fixed before-and-after readback, not a computation proved against an independent oracle. The save/restore idiom is shown as the consequence of the contract, but nothing here proves any handler discipline correct.

    A trap is not a function call. When the ecall landed, the hardware set aside exactly three things: mcause (0xb, an M-mode environment call), mepc (0x80000556, the address of the ecall), and the privilege stack in mstatus, the old privilege in MPP and the old interrupt enable in MPIE. It set aside none of the general registers. The eight values in a0 through a7 still belonged to the interrupted program, and they were still sitting in the registers when the handler started. [1]

    The handler wrote eight new sentinels into a0..a7 and executed mret. The specification's contract for xRET fits in two clauses: it manipulates the privilege stack (MPIE back into MIE, MPP back into the privilege mode) and sets the pc to the value in mepc. Register save and restore are not in either clause, because they are not the hardware's job. After mret, every one of the eight registers read back the handler's value: a0 went from 0x1111111111111111 to 0x9999999999999999, a1 from 0x2222222222222222 to 0xaaaaaaaaaaaaaaaa, down to a7 from 0x8888888888888888 to 0x123456789abcdef0. Nothing was restored, because nothing was saved. [1] [2]

    The handler's end, the part that never puts anything back:

        li a0, POST_A0        # the handler's own sentinel set
        ...
        li a7, POST_A7
        mret                  # pc and privilege return; a0..a7 stay as written
    Blueprint-style diagram of the mret no-restore behavior: on trap entry the hardware saves mepc, mcause, and the privilege stack but no general registers; after the handler writes a0..a7 and executes mret, the pc and privilege return while all eight registers still carry the handler's sentinels
    mret returns the pc and the privilege stack. a0..a7 keep whatever the handler last wrote; nothing is restored.
    Diagram: hand-built by Chris Dillinger for this post

    The run behind it. A bare-metal M-mode program on QEMU 8.2.2 loaded eight sentinels into a0..a7, recorded them, issued one ecall, and read the registers back after mret. mie read 0x0 at boot and mstatus.MIE was cleared, so the ecall was the only trap the run could take. One trap, eight readbacks, each matching the handler's sentinel set and none matching the pre-trap value. One honest boundary: the executor is QEMU's machine model, faithful, but still a model, not silicon. [1]

    The habit this buys: a handler parks every register it touches and puts each one back before mret, or the interrupted code resumes with your values in its registers. The save and restore are a convention the handler owns; the hardware signs only for the pc and the privilege stack. [2]

    Sources

    1. 01
      src/mret-no-restore: module README and PROOF.mdChris Dillinger

      The firsthand QEMU run behind the post: one M-mode ecall (mcause 0xb, mepc 0x80000556), the handler writes eight sentinels into a0..a7 and returns with mret and no restore; all eight registers read back the handler's values, none the pre-trap values. Ninety-five checks, zero mismatches, verified again on this run.

    2. 02
      RISC-V ISA Manual, privileged architecture (trap return)RISC-V International

      The xRET contract: manipulates the privilege stack (xPIE into xIE, xPP into the privilege mode) and sets the pc to the value in xepc. General register save/restore is not part of the instruction's defined behavior.

    The Bit That Turns a Wait Into a Trap

    ISA

    The claim is about the mstatus.TW bit's contract: with TW set, a WFI executed in S-mode raises an illegal-instruction exception instead of waiting. The run verifies the TW write sticks (bit 21 readback set), delegates the trap to S-mode, and shows one S-mode wfi taking exactly one trap with scause = 2, sepc exactly at the wfi site, and stval holding the wfi instruction word.

    MICROARCH

    No claim depends on how any core implements anything. No cache, pipeline, or timing behavior is asserted or measured; QEMU serves as a functional executor only. The specification permits the trap after a bounded wait, and the immediate trap observed is this implementation's behavior, stated as such.

    FIRMWARE

    No firmware service takes part in the claim. The M-mode setup (the TW write, the medeleg delegation, the mret drop to S-mode) is the experiment harness; the behavior under test is the S-mode wfi and the delegated trap that follows it.

    KERNEL

    No kernel is involved at any step. The test binary runs on bare QEMU with no operating system, and no system interface appears in the argument.

    ALGORITHM

    The claim is one fixed control bit applied as one fixed interception idiom, not a computation proved against an independent oracle. The world-switch use is the consequence the specification itself names, but nothing here proves any scheduling policy correct.

    Supervisor code with nothing to do runs wfi and sleeps until the next interrupt arrives. It is the polite thing for an idle loop to do. But the machine-mode monitor may not want the guest deciding when the hart sleeps. One bit in mstatus, TW at bit 21, set from M-mode, changes what wfi does everywhere below it. [2]

    With TW set, an S-mode wfi does not wait. It raises an illegal-instruction exception instead. scause reads 2, sepc points exactly at the wfi, and stval carries the faulting instruction word, 0x10500073, the encoding of wfi itself. The handler learns everything from three CSRs: which instruction, and where it sat. One honest boundary: the specification permits the trap to arrive after an implementation-specific bounded wait rather than at once; on QEMU it fires immediately, and that immediacy is the implementation's choice, not the contract's promise. [1] [2]

    Setting the hook, in M-mode, then the one instruction that never sleeps:

    li   t0, 1<<21
    csrs mstatus, t0      # TW = 1: S-mode wfi now traps
    ...
    wfi                   # in S-mode: scause = 2, sepc at this line
    Blueprint-style diagram of the TW bit's two behaviors: with TW = 0 the S-mode wfi sleeps until an interrupt; with TW = 1 (bit 21) the same wfi raises an illegal-instruction trap with scause = 2, sepc at the wfi, and stval holding the wfi encoding
    One bit flips the meaning of wfi. TW = 0: the hart sleeps. TW = 1: the same instruction traps, and the handler gets scause, sepc, and stval.
    Diagram: hand-built by Chris Dillinger for this post

    The run behind it. A bare-metal program on QEMU 8.2.2 set TW from M-mode and read back 0xa00200000, bit 21 set, then delegated the illegal-instruction trap to S-mode and dropped there. One wfi at a labeled site took exactly one trap: scause = 0x2, stval = 0x10500073, sepc exactly the wfi site, sepc+4 exactly the resume label. Six checks, zero failures. One honest boundary: the executor is QEMU's machine model, faithful, but still a model, not silicon. [1]

    The habit this buys: set TW once, at boot, in your machine-mode monitor. Every idle attempt the guest makes after that arrives as a trap you own. The specification names the use outright: trapping wfi can trigger a world switch to another guest OS, rather than wastefully idling in the current guest. Count the idle, switch the guest, or emulate the wait and resume past the wfi. The guest asked to sleep; you get to decide what that means. [2]

    Sources

    1. 01
      src/mstatus-tw-trap: module README and PROOF.mdChris Dillinger

      The firsthand QEMU run behind the post: M-mode sets mstatus.TW (bit 21, readback 0xa00200000), delegates the illegal-instruction trap to S-mode, and one S-mode wfi takes exactly one trap with scause = 2, stval = 0x10500073, and sepc exactly at the wfi site. Six checks, zero failures, verified again on this run.

    2. 02
      RISC-V ISA Manual, privileged architecture (mstatus.TW)RISC-V International

      Defines the TW (Timeout Wait) bit: when TW=1, WFI executed in a less-privileged mode causes an illegal-instruction exception, possibly after an implementation-specific bounded time; notes the use as a hook to switch to another guest OS instead of idling.

    The Store That Fails Quietly

    ISA

    The claim is about the sc.w instruction's contract: a store-conditional with no live reservation for its target address reports failure in rd as a nonzero value, writes nothing to memory, and raises no trap. The run exercises all three shapes, a missing reservation, a mismatched reservation, and the live-reservation control, checking rd and memory readbacks each time.

    MICROARCH

    No claim depends on how any core implements anything. No cache, pipeline, or timing behavior is asserted or measured; QEMU serves as a functional executor only, and the failure contract is complete from the instruction semantics and the run.

    FIRMWARE

    No boot code, machine-mode service, or privilege handoff takes part. The binary installs its own M-mode trap handler on the bare virt machine with no firmware beyond the reset state, and the reservation argument never enters firmware.

    KERNEL

    No kernel is involved at any step. The test binary runs on bare QEMU with no operating system, and no system interface appears in the argument.

    ALGORITHM

    The claim is one fixed instruction semantic applied as one fixed idiom, not a computation proved against an independent oracle. The retry loop is shown as the consequence of the contract, but nothing here proves a concurrent algorithm correct.

    A lock-free counter on RISC-V is built on two instructions. lr.w loads the word and arms a reservation on its address. sc.w stores the new value, but only if that reservation is still live. The condition sits in the hardware, not in your code. [2]

    What sc.w promises is narrower than it looks. With no live reservation for the target address, the instruction does three things: it writes a nonzero value into rd, it writes nothing to memory, and it raises no trap. That is the entire report, and it arrives in silence. The reservation is dead when you never armed one, or when you armed one on a different address. Either way the answer is identical: rd = 1, the word untouched, no exception. [1] [2]

    The idiom this forces:

    retry:
      lr.w t0, 0(a0)      # load the word, arm the reservation
      addi t0, t0, 1      # do the actual work
      sc.w t1, t0, 0(a0)  # attempt the store
      bnez t1, retry      # nonzero means it never happened: try again
    Blueprint-style diagram of three store-conditional cases: sc.w with no lr.w and lr.w on one cell with sc.w on another both report rd = 1 with memory unchanged; lr.w and sc.w on the same cell reports rd = 0 with the value stored
    The whole report arrives in rd. No reservation, or the wrong reservation: rd = 1, nothing written, no trap. Live reservation: rd = 0, stored.
    Diagram: hand-built by Chris Dillinger for this post

    The run behind it. A bare-metal program on QEMU 8.2.2 ran all three shapes against two aligned cells. sc.w with no lr.w at all: rd = 1, the cell still 0xaaaaaaaa. lr.w on cell A followed by sc.w on cell B: rd = 1, both cells unchanged. The control, lr.w then sc.w on the same cell: rd = 0, and 0x12345678 read back. Eight checks, zero failures, and no trap fired in any run. One honest boundary: the executor is QEMU's machine model, faithful, but still a model, not silicon. [1]

    The habit this buys: read rd after every sc.w, and treat nonzero as routine, not as an error. Contention, a stray store between the pair, or a missing lr.w all report the same way. The dangerous case is the one the hardware cannot flag: code that skips the check and assumes the store landed, because a failed sc.w leaves no trace except the value in rd. [2]

    Sources

    1. 01
      src/sc-fail: module README and PROOF.mdChris Dillinger

      The firsthand QEMU run behind the post: sc.w with no reservation and with a mismatched reservation both reporting rd = 1 with memory unchanged, the live-reservation control reporting rd = 0 with the stored value read back, eight checks, zero traps.

    2. 02
      RISC-V ISA Manual, unprivileged architecture (A extension)RISC-V International

      Defines the load-reserved/store-conditional contract: a store-conditional whose reservation is not live for its target address writes a nonzero value to rd and does not write memory.

    The Swap With No Middle

    ISA

    The claim is about the csrrw instruction's semantics: one instruction atomically exchanges a CSR with a register, rd receiving the old CSR value while rs1 is written into the CSR. The run performs the swap twice on mscratch and checks both sides of each exchange, the read side in rd and the write side by readback.

    MICROARCH

    No claim depends on how any core implements anything. No cache, pipeline, or timing behavior is asserted or measured; QEMU serves as a functional executor only, and the swap contract is complete from the instruction semantics and the run.

    FIRMWARE

    No boot code, machine-mode service, or privilege handoff takes part. The binary installs its own M-mode trap handler on the bare virt machine with no firmware beyond the reset state, and the swap argument never enters firmware.

    KERNEL

    No kernel is involved at any step. The test binary runs on bare QEMU with no operating system, and no system interface appears in the argument.

    ALGORITHM

    The claim is one fixed instruction semantic applied as one fixed idiom, not a computation proved against an independent oracle. The swap is shown working across one sentinel round-trip, but nothing here establishes a general algorithm.

    A trap fires and the handler needs a stack. The stack pointer in sp belongs to the interrupted code, and every general register holds something that code was using. You cannot store a single byte until you have a stack, and you cannot get a stack without moving sp somewhere first. [1]

    One instruction moves it. csrrw sp, mscratch, sp writes the old sp into mscratch and loads the old mscratch value into sp, as one atomic step. Point mscratch at your handler stack once at boot, and trap entry becomes this single instruction: the victim's stack pointer is parked in mscratch, the handler stack lands in sp. Because it is one instruction, no interrupt can be taken between the read half and the write half. There is no between. No temporary register, no memory traffic. [1] [2]

    The exchange, in both directions:

    csrrw sp, mscratch, sp   # entry: victim sp parked, handler stack live
    # ... save registers, handle the trap ...
    csrrw sp, mscratch, sp   # exit: the same instruction swaps them back
    Blueprint-style diagram of csrrw sp, mscratch, sp: before the instruction sp points at the victim stack and mscratch at the handler stack; after, the two have traded places, the victim stack parked in mscratch
    One instruction, no middle. csrrw sp, mscratch, sp parks the victim's stack in mscratch and loads the handler stack into sp; running it again swaps them back.
    Diagram: hand-built by Chris Dillinger for this post

    The run behind it. A bare-metal M-mode program on QEMU 8.2.2 swapped a sentinel through mscratch twice. The boot read found 0x0. The first csrrw returned the old value 0x0 in rd while mscratch read back 0xa5a55a5a5a5a5a5; the restore swap returned the sentinel in rd while mscratch read back 0x0. Five checks, zero failures, zero traps. One honest boundary: the executor is QEMU's M-mode model, faithful, but still a model, not silicon. [1]

    The habit this buys: set mscratch once, at boot, to the top of the handler stack. Every trap entry then starts with one instruction instead of a register-shuffling prologue, and trap exit runs the mirror image. The swap is its own undo: run it twice and everything is exactly where it was. [2]

    Sources

    1. 01
      src/mscratch-csrrw: module README and PROOF.mdChris Dillinger

      The firsthand QEMU run behind the post: the two csrrw swaps on mscratch, the measured values 0x0 and 0xa5a55a5a5a5a5a5 on both the read side in rd and the write side by readback, and the PASS verdict.

    2. 02
      RISC-V ISA Manual, unprivileged architecture (Zicsr)RISC-V International

      Defines the CSR read-write instructions: csrrw atomically reads the CSR into rd and writes rs1 into the CSR as one operation.

    The Bit That Sorts the Trap

    ISA

    The claim is about mcause bit 63 semantics: the top bit marks asynchronous interrupts and stays clear for synchronous exceptions, with the low bits carrying the cause code. The run reads mcause after a real M-mode ecall and a real machine timer interrupt, and checks the bit and the full register value on both.

    MICROARCH

    No claim depends on how any core implements anything. No cache, pipeline, or timing behavior is asserted or measured; QEMU serves as a functional executor only, and the bit rule is complete from the architecture definition and the run.

    FIRMWARE

    No boot code, machine-mode service, or privilege handoff takes part. The binary installs its own M-mode trap handler on the bare virt machine with no firmware beyond the reset state, and the argument never enters firmware.

    KERNEL

    No kernel is involved at any step. The test binary runs on bare QEMU with no operating system, and no system interface appears in the argument.

    ALGORITHM

    The claim is one fixed CSR semantic applied as one fixed idiom, not a computation proved against an independent oracle. The bit rule is shown working across one exception and one interrupt, but nothing here establishes a general algorithm.

    Two traps hit the same handler on a bare-metal hart. First an M-mode ecall: the handler read mcause and found 0xb, an environment call from M-mode, with the register's top bit clear. Then a machine timer interrupt, armed by writing mtimecmp 50000 ticks ahead: the handler read mcause and found 0x8000000000000007, a machine timer interrupt with the top bit set. Same register, same handler, one bit of difference between the two visits. [1]

    On RV64, bit 63 of mcause is the sorting office. The hardware sets it when the trap is an asynchronous interrupt and leaves it clear when the trap is a synchronous exception. The remaining bits carry the code: 11 for the ecall above, 7 for the timer. The handler's first decision is one test of one bit, and the two answers demand opposite handling. An interrupt wants its source acknowledged and cleared. An exception wants the faulting instruction decoded, with mepc pointing at it. Mix them up and you treat a timer tick like a broken instruction, or you try to step past an interrupt the way you step past a fault. [2]

    The whole dispatch, in six lines:

    unsigned long cause;
    __asm__ volatile("csrr %0, mcause" : "=r"(cause));
    if (cause & (1UL << 63))
        interrupt(cause & ~(1UL << 63));  /* async: the low bits are the code */
    else
        exception(cause);                 /* sync: mepc holds the faulting PC */
    Blueprint-style diagram of the 64-bit mcause register drawn twice: after an M-mode ecall with bit 63 clear (exception, code 11) and after a machine timer interrupt with bit 63 set (interrupt, code 7)
    One bit, two stories. mcause reads 0xb after an M-mode ecall, bit 63 clear; it reads 0x8000000000000007 after a machine timer interrupt, bit 63 set. The handler's first branch is that one bit.
    Diagram: hand-built by Chris Dillinger for this post

    The run behind it. A bare-metal M-mode program installed one direct-mode handler, fired an ecall, then armed the machine timer and waited. Sixteen in-program checks, zero mismatches: the ecall printed mcause=0xb bit63=0, the timer printed mcause=0x8000000000000007 bit63=1, the disarm read back all ones, and no unexpected trap fired in either quiet window. One honest boundary: the executor is QEMU 8.2.2's M-mode model, faithful, but still a model, not silicon. [1]

    The habit this buys: branch on the bit before touching anything else. The interrupt half of your handler clears its source first, because a source left armed re-fires the moment you return. The exception half reads mepc first, because the faulting address is the whole story. One bit decides which of those two jobs you are doing, and the register tells you for free. [2]

    Sources

    1. 01
      src/mcause-interrupt-bit: module README and PROOF.mdChris Dillinger

      The firsthand QEMU run behind the post: the 16-check sequence, the measured mcause values 0xb and 0x8000000000000007, and the PASS verdict.

    2. 02
      The RISC-V Instruction Set Manual, Volume II: Privileged Architecture (mcause register definition and cause table)RISC-V International

      Defines the mcause Interrupt bit and lists the machine cause codes: 7 for machine timer interrupt, 11 for environment call from M-mode.

    The Add That Returns the Old Value

    ISA

    The claim is about the amoadd.w instruction's semantics: rd receives the pre-add value while memory receives old plus rs2, as one atomic operation. The listings show each drop as a single amoadd.w against the naive lw, addiw, sw triple, and the QEMU run shows rd holding the old value on every call.

    MICROARCH

    No claim depends on how any core implements anything. No cache, pipeline, or timing behavior is asserted or measured; QEMU serves as a functional executor only, and the old-value contract is complete from the instruction semantics and the run.

    FIRMWARE

    No boot code, machine-mode service, or privilege handoff takes part. The experiment is a freestanding bare-metal binary with no runtime beyond a UART print, and the argument never enters firmware.

    KERNEL

    No kernel is involved at any step. The test binary runs on bare QEMU with no operating system, and no system interface appears in the argument.

    ALGORITHM

    The claim is one fixed instruction semantic applied as one fixed idiom, not a computation proved against an independent oracle. The old==1 rule is shown working across three drops and one acquire, but nothing here establishes a general algorithm.

    A shared object keeps a reference count in one word of memory. Two harts finish with it at the same moment, and both run the drop: read the count, subtract one, write it back. Compiled, that is three separate instructions with the read and the write split apart: lw, addiw, sw. Between the load and the store the second hart can run its own load, and both write back the same decremented value. One reference is silently lost: the object is freed while someone still holds it, or it is never freed at all. [1]

    One instruction closes the window. amoadd.w a0, a1, (a2) adds a1 into the word at the address in a2, and writes the value the word held before the add into a0. The read, the add, and the write happen as one indivisible operation: no hart can observe the middle. The return value is the whole trick. For a drop, pass -1: if the old value comes back as 1, this drop took the count to zero, and the caller holding that return value is the last holder. No lock, no retry loop. [1] [2]

    The run confirms the contract. On the virt UART under QEMU 8.2.2, starting from a count of 3: the first drop printed old=3 now=2, the second old=2 now=1, the third old=1 now=0, and that third call, the one that saw the 1, is the one that frees. An acquire from zero printed old=0 now=1. The listing shows each drop as a single amoadd.w, against the naive lw, addiw, sw triple. [1]

    The one instruction that does the drop:

    unsigned int rc_drop(volatile unsigned int *p) {
        unsigned int old;
        __asm__ volatile("amoadd.w %0, %2, (%1)"
            : "=r"(old) : "r"(p), "r"(-1) : "memory");
        return old;  /* 1 here means this drop took the count to zero */
    }
    Blueprint-style diagram of amoadd.w: a memory cell holding 3, one instruction producing rd = 3 (the old value, highlighted) and memory = 2, then the drop chain 3 to 2 to 1 to 0 with the drop that saw old = 1 freeing the object
    One instruction, two results. amoadd.w writes old + (-1) back to memory and hands the old value to the caller in rd; the drop that sees old = 1 knows it took the count to zero.
    Diagram: hand-built by Chris Dillinger for this post

    The habit this buys: design the decision around the old value, never a re-read. if (rc_drop(&refs) == 1) free(obj); A load after the atomic op is a second, separate observation; the old value in the destination register is the observation that belongs to your update. [1]

    Sources

    1. 01
      lab/165-amoadd-refcount: the amoadd.w listings and QEMU runChris Dillinger

      The firsthand objdump listings from riscv64-unknown-elf-gcc 13.2.0 (-O2 -march=rv64imac_zicsr): each rc_drop/rc_acquire inlines to a single amoadd.w, the naive drop is lw, addiw, sw, and the UART log from QEMU 8.2.2 shows rd taking the old value on all four operations.

    2. 02
      RISC-V ISA Manual, unprivileged architectureRISC-V International

      The A extension defines each AMO as one atomic read-modify-write: the read, the operation, and the write happen with no observable intermediate state, which is what closes the lost-update window the naive sequence leaves open.

    The Shift That Is Not a Division

    ISA

    The claim is about the srai instruction's semantics: an arithmetic right shift replicates the sign bit, which makes it floor division for negative values, while C's / truncates toward zero. The listings show the single srai for the shift against the compiler's four-instruction bias sequence for division, read straight off objdump.

    MICROARCH

    No claim depends on how any core implements anything. No cache, pipeline, or timing behavior is asserted or measured; QEMU serves as a functional executor only, and the rounding argument is complete from the instruction semantics and the listings.

    FIRMWARE

    No boot code, machine-mode service, or privilege handoff takes part. The experiment is a freestanding bare-metal binary with no runtime beyond a UART print, and the argument never enters firmware.

    KERNEL

    No kernel is involved at any step. The test binary runs on bare QEMU with no operating system, and no system interface appears in the argument.

    ALGORITHM

    The claim is one fixed instruction semantic against one fixed language rule, not a computation proved against an independent oracle. The bias trick is shown working on thirteen inputs, but nothing here establishes a general algorithm.

    I compiled two three-line functions this morning, gcc 13.2.0 at -O2 for rv64g. int shr3(int x){ return x >> 3; } came back as one instruction: srai a0, a0, 3, then ret. int div8(int x){ return x / 8; } came back as four: sraiw a5, a0, 31; srliw a5, a5, 29; addw a0, a5, a0; sraiw a0, a0, 3; then ret. Same operation on paper, one instruction against four. [1]

    The difference is the rounding. An arithmetic right shift fills the vacated top bits with copies of the sign bit, so for a negative value the shift rounds toward negative infinity: it keeps going down. C's integer division truncates toward zero instead: it stops at the first integer on the way back up. [2] [3] For positive values the two agree, and the compiler is happy to use the single shift. For negative values they diverge, and the compiler has to repair the shift before it may use it. [1]

    The repair is the middle three instructions, and it is a small bias. sraiw a5, a0, 31 smears the sign bit across the whole register: 0 for a non-negative x, all ones for a negative x. srliw a5, a5, 29 turns that into 0 or 7. addw adds the bias into x, and then the shift runs. For x = -7: -7 + 7 is 0, shifted right 3 is 0, which is what -7 / 8 must be. Without the bias the shift gives -1, the wrong answer for division. The general shape: to turn a floor shift into a truncating division by 2^k, add 2^k - 1 to negative values first. [1]

    The two functions, reduced to the instructions:

    int shr3(int x){ return x >> 3; }  /* srai a0, a0, 3 */
    int div8(int x){ return x / 8; }   /* sraiw a5, a0, 31
                                          srliw a5, a5, 29
                                          addw  a0, a5, a0
                                          sraiw a0, a0, 3 */
    Blueprint-style bit diagram of -7 as 0xFFFFFFF9 with the sign bit highlighted, the srai by 3 replicating it to produce -1, contrasted with -7 / 8 = 0 under C truncation toward zero and the compiler's four-instruction bias sequence
    One shift, two roundings. The srai replicates the sign bit and rounds toward negative infinity, giving -1; C division truncates toward zero, giving 0, so the compiler adds a bias of 7 before shifting.
    Diagram: hand-built by Chris Dillinger for this post

    The run confirms it. On the virt UART under QEMU 8.2.2, thirteen inputs from -19 to 19: -7 >> 3 printed -1 while -7 / 8 printed 0; -19 >> 3 printed -3 while -19 / 8 printed -2; every non-negative input agreed. The one-instruction path and the four-instruction path disagree exactly where the two rounding rules say they must. [1]

    Two habits fall out of this. Reading a disassembly: a shift preceded by a sign-smear and an add is the compiler dividing by a power of two; the bare srai is just a shift, with floor rounding. Writing C: never hand-rewrite x / 8 as x >> 3 when x can be negative, because that changes the rounding. The compiler already performs that optimization itself, bias included, and it does it correctly. Use the shift when floor is what you want, which in fixed-point and bit-index code it often is; write the division when truncation is what you want, and let the compiler add the bias.

    Sources

    1. 01
      lab/164-srai-division: the srai/div8 listings and QEMU runChris Dillinger

      The firsthand objdump listings from riscv64-unknown-elf-gcc 13.2.0 (-O2 -march=rv64g): shr3 as a single srai a0, a0, 3, div8 as sraiw, srliw, addw, sraiw, and the thirteen-input UART log from QEMU 8.2.2 showing the two paths diverging on negative inputs.

    2. 02
      RISC-V ISA Manual, unprivileged architectureRISC-V International

      SRAI is an arithmetic shift: the sign bit is replicated into the vacated high bits, which is what makes the shift round toward negative infinity for negative values.

    3. 03
      Arithmetic operatorscppreference.com

      Integer division yields the algebraic quotient truncated toward zero since C99, the rounding rule the compiler's bias sequence restores.

    The Twelve Bits That Borrow From the Twenty

    ISA

    The claim is about the RISC-V instruction encoding itself: lui carries a 20-bit immediate into bits 31:12 and addi carries a 12-bit signed immediate into bits 11:0, and that signedness forces the assembler's rounding. The listings show the exact two encodings the split produces, read straight off objdump.

    MICROARCH

    No claim depends on how any core implements anything. No cache, pipeline, or timing behavior is asserted or measured anywhere in the argument; the rounding is an assembler decision read off the listings, before any hardware runs.

    FIRMWARE

    No boot code, machine-mode service, or privilege handoff takes part. The experiment is freestanding assembly with no runtime, and the argument never enters firmware.

    KERNEL

    No kernel is involved at any step. The listings come from assembling a bare function with no operating system, and no system interface appears in the argument.

    ALGORITHM

    The claim is a fixed assembler convention, not a computation. Nothing is proved against an independent oracle; the recombination arithmetic only checks the listings against themselves.

    I asked the assembler for one constant this morning: li a0, 0x12345EEF, assembled for rv64g with the 13.2.0 toolchain. Two instructions came back: lui a0, 0x12346, then addiw a0, a0, -273. The constant's top twenty bits are 0x12345, not 0x12346, and its bottom twelve are 0xEEF, not -273. Neither half of the pair looks like the constant it builds. [1]

    The split point is fixed by the encoding: lui carries twenty bits into positions 31:12, and addi carries twelve bits into positions 11:0. The catch is that addi's twelve bits are signed, -2048 to 2047, while the constant's low twelve bits are unsigned, 0 to 4095. When the low twelve reach 0x800, bit 11 set, no signed twelve-bit field can hold them: 0xEEF is 3823, past the 2047 limit. So the assembler rounds the high twenty up by one, 0x12345 becomes 0x12346, and writes the low part as the signed remainder, 0xEEF minus 0x1000, which is -273. Recombined: 0x12346000 minus 273 is 0x12345EEF. [2]

    The edges confirm the rule. li a0, 0x7FF needs no lui at all: 2047 fits the signed immediate, so a single addi does the whole job. li a1, 0x800 is the smallest constant that needs the pair, and the rounding shows at its barest: lui a1, 0x1, then addiw a1, a1, -2048. The lui shows 0x1 for a constant whose top twenty bits are 0x0. And li a2, 0x12345678 needs no rounding: its low twelve bits are 0x678, bit 11 clear, so the pair is the naive split, lui a2, 0x12345 with addiw a2, a2, 1656. [1]

    The two interesting pairs, reduced to the instructions:

    # bit 11 of the low 12 clear: the naive split
        lui   a2, 0x12345
        addiw a2, a2, 1656          # 0x12345678
    # bit 11 set: the lui rounds up, the low part goes negative
        lui   a3, 0x12346           # 0x12345 + 1
        addiw a3, a3, -273          # 0xEEF - 0x1000
    
    Blueprint-style diagram of a 32-bit constant split into high 20 and low 12 bits, showing the lui rounding up by one when bit 11 is set and the addi carrying the signed remainder -273
    One constant, two instructions. Bit 11 of the low twelve is set, so the lui carries 0x12346 instead of 0x12345, and the addi carries -273 instead of 0xEEF.
    Diagram: hand-built by Chris Dillinger for this post

    Two habits fall out of this. Reading a disassembly: when the addi after a lui is negative, the constant's true high twenty bits are one less than the lui shows; the value is the lui shifted left twelve plus the signed immediate, and treating the immediate as unsigned puts you a full 0x1000 off. Writing assembly by hand, in startup code or a trap handler: add one to the lui whenever the low twelve bits are 0x800 or more, because the naive pair does not assemble at all. I tried it: lui a0, 0x12345 followed by addi a0, a0, 0xEEF dies with "illegal operands", since 0xEEF cannot fit a signed twelve-bit field. The assembler forces the rounding; the only choice is whether you do it on purpose. [1]

    Sources

    1. 01
      lab/163-lui-addi-rounding: the lui/addi listingsChris Dillinger

      The firsthand objdump listings from riscv64-unknown-elf-gcc 13.2.0 (-march=rv64g): 0x7FF as a single addi, 0x800 as lui 0x1 plus addiw -2048, 0x12345678 as the naive pair, 0x12345EEF as lui 0x12346 plus addiw -273, and the assembler's illegal-operands rejection of the naive hand-written pair.

    2. 02
      RISC-V ISA Manual, unprivileged architectureRISC-V International

      The I-type encoding: the 12-bit immediate is sign-extended, so addi's range is -2048..2047; the U-type encoding: lui places its 20-bit immediate in bits 31:12. Together they fix the split point and force the rounding the post demonstrates.

    The Read the Compiler Is Not Allowed to Skip

    ISA

    No instruction-set claim is made. volatile is a contract with the C abstract machine: every access through a volatile lvalue is an observable side effect the compiler cannot optimize out. The lbu listings illustrate the mechanism on RISC-V, but the verdict follows from the type qualifier, and every paragraph holds with the CPU swapped.

    MICROARCH

    No claim depends on how any core implements anything. No cache, pipeline, or timing behavior is asserted or measured anywhere in the argument; the hoist is a compiler decision read off the listings, before any hardware runs.

    FIRMWARE

    No boot code, machine-mode service, or privilege handoff takes part. The experiment is two freestanding functions compiled for a bare-metal target, and the argument never enters firmware.

    KERNEL

    No kernel is involved at any step. The driver is polled bare-metal code, and the comparison is made by reading compiler listings, never by running under an operating system.

    ALGORITHM

    The claim is a compiler contract about observable side effects, not a computation. Nothing is proved against an independent oracle, and no portable mechanism is under test.

    The transmit path of my UART driver waits on one register: the line-status register at 0x10000005 on the QEMU virt board, bit 5, which the transmitter sets when its holding register is empty and ready for the next byte. The wait loop is the obvious three-liner: read the byte, test the bit, spin until it arrives. [1]

    Drop the word volatile from the pointer type, compile at -O2, and the loop stops touching the hardware. I compiled both variants with the riscv64-unknown-elf 13.2.0 toolchain and read the difference straight off the two listings. Without volatile, GCC emits a single lbu before the loop and then a jump to itself: if bit 5 was clear on entry, the copy held in a5 can never change, because nothing in the loop writes to that address, so the compiler is entitled to treat the memory as unchanged. The wait becomes permanent. With volatile, the lbu moves inside the loop, one fresh read per iteration, until the transmitter sets the bit. [1]

    The two listings, reduced to the loop itself:

    # plain pointer, -O2: one read, then a jump to self
        lbu a5,5(a4)
    .L3: j .L3
    # volatile pointer: a fresh read every iteration
    .L6: lbu a5,0(a4)
        andi a5,a5,32
        beq a5,zero,.L6
    
    Blueprint-style diagram comparing the two compiled loops: the plain pointer reads the UART register once and spins on the cached byte, while the volatile pointer re-reads the register every iteration
    Two loops, one word apart. The plain pointer's loop reads the register once and spins on the cached byte; the volatile loop re-reads 0x10000005 every iteration until bit 5 arrives.
    Diagram: hand-built by Chris Dillinger for this post

    volatile is a contract with the compiler, not the hardware. Every access through a volatile lvalue is an observable side effect the compiler must evaluate strictly, in order, which is exactly why volatile objects model memory-mapped I/O ports. [2] The rule at the bench: every memory-mapped register is volatile, or the optimized build turns a wait loop into a hang. The nasty part is where the bug hides. At -O0 the compiler hoists nothing, so the plain loop happens to work, and the failure appears only in the -O2 build you actually ship. One word in the type, at the declaration. That is all volatile buys you, and it is everything.

    Sources

    1. 01
      uart.c: the polled UART driverChris Dillinger

      The transmit wait loop polls the line-status register through a volatile unsigned char pointer. The firsthand -O2 listings from riscv64-unknown-elf-gcc 13.2.0 show the load hoisted out of the loop without volatile and inside the loop with it; the -O0 listing shows the plain loop re-reading, which is where the bug hides.

    2. 02
      volatile type qualifiercppreference.com

      Every access through a volatile lvalue is an observable side effect evaluated strictly per the abstract machine, so the compiler cannot optimize it out; volatile objects model memory-mapped I/O ports.

    The Child That Refuses to Be a Session Leader

    ISA

    No instruction-set claim is made. fork, setsid, and waitpid are kernel interfaces, and the argument never depends on which CPU the machine speaks. Every paragraph holds with the CPU swapped.

    MICROARCH

    No claim depends on how any core implements anything. No cache, pipeline, or timing behavior is asserted or measured anywhere in the argument.

    FIRMWARE

    No boot code, machine-mode service, or privilege handoff takes part. Every step is an ordinary unprivileged process operation on a running system.

    KERNEL

    The whole argument is kernel-enforced process semantics. setsid refuses a process group leader, and the refusal was verified live with errno EPERM. Session leadership is the pid and the session id agreeing. Only a session leader can acquire a controlling terminal, and the kernel reparents the orphaned grandchild to pid 1. The firsthand run reads each of these facts off live process state.

    ALGORITHM

    The claim is a protocol about process state, not a computation. Nothing is proved against an independent oracle, and no portable mechanism is under test.

    The ritual runs in three moves: fork, setsid, fork again. I ran all three in a small C program, and the numbers tell the story plainly. The parent was pid 13480. The child was 13481, still sitting in the parent's session, and that first fork was load-bearing: setsid refuses to run in a process group leader, so the child had to exist before it could leave the old session. A one-line test confirmed the refusal for real: a process that made itself a group leader watched setsid fail with EPERM. [2]

    After setsid, the child's session id was 13481, equal to its own pid. Session leadership looks exactly like that: a process whose id and session agree, holding a new session with no controlling terminal. Then the second fork, and the middle child, the session leader, exited at once. The grandchild woke up as pid 13482, reparented under pid 1, still sitting in session 13481. The parent reaped the middle child with waitpid, so no zombie remained anywhere in the chain. [2]

    A weathered blue ONE WAY street sign with a large white arrow, mounted on a pole above green foliage
    A one-way sign on Old Upper Thomson Road. The second fork is a move the process cannot unmake: once the session leader exits, the grandchild can never quietly acquire a controlling terminal.
    Photo: BenTanXiaoMing, CC BY-SA 4.0, via Wikimedia Commons

    The whole ritual fits in six lines:

    if (fork() == 0) {
        setsid();           /* new session; this child is its leader */
        if (fork() == 0) {  /* grandchild can never claim a terminal by accident */
            /* daemon body */
        }
        _exit(0);           /* leader exits, orphaning the grandchild to init */
    }
    

    The second fork is the one that looks redundant, and it is the point. A session leader with no controlling terminal can still acquire one later, simply by opening a free terminal device. The grandchild is not a session leader, and without that office it cannot acquire a controlling terminal, even by accident. So the second fork is not about the terminal the daemon left. It is about the terminal the daemon might one day be handed. By stepping out of eligibility for the office, the daemon makes the accident structurally impossible. [1]

    Under a supervisor like systemd the ritual is mostly obsolete, because the supervisor does the detaching for you. But the mechanism is still the clearest demonstration of what sessions and controlling terminals are: a small piece of Unix state machine you can watch move. The takeaway I keep: the first fork buys eligibility, the setsid call buys the new session, and the second fork buys ineligibility. The daemon's freedom is not that it ran away from the terminal. It is that it made itself unable to come back. [1]

    Sources

    1. 01
      Daemon (computing)Wikipedia

      The rationale for the second fork: a session leader with no controlling terminal can acquire one by accident when it opens a free tty, so the daemon forks and exits again to stop being a session leader; plus the note that a supervisor like systemd does the detaching instead.

    2. 02
      forkfork-demo: the double-fork run logChris Dillinger

      The firsthand run of the full ritual in dfork.c (pids 13480, 13481, 13482, the sid agreement after setsid, reparenting to pid 1, waitpid reaping with no zombie) and the setsid_eperm.c check that setsid fails with EPERM in a process group leader.

    The Four Fields Inside One Address

    ISA

    Sv39 is the privileged architecture's own address format: the manual fixes bits 38:30, 29:21, and 20:12 as the three VPN fields over a 12-bit offset, and the canonical-form rule sign-extends bit 38 into the high bits. The article's central claim is that layout and its extraction, read straight off the specification.

    MICROARCH

    No claim depends on how any core implements translation: no TLB, cache, or pipeline behavior is asserted or measured. The single timing figure is a host-side loop measurement whose own proof note limits what it covers, so it cannot carry a microarchitecture verdict.

    FIRMWARE

    No boot code, machine-mode service, or privilege handoff takes part: the fields are read from a value already in hand, and every step of the argument is the format contract itself, before any firmware or privilege transition enters the picture.

    KERNEL

    The argument stops before the walk: it never enters a page-table walk, a fault path, or any kernel's use of these fields. Kernels consume the four fields, but the claim proven here is the partition itself, which holds before any kernel code runs.

    ALGORITHM

    The extraction is a small procedure with a stated invariant: four disjoint masks cover bits 38:0 with no overlap and no gaps, so recombine(extract(va)) restores the input exactly. A per-bit oracle that builds each field without shifting a whole field proves the split on 26,777,374 cases with 0 mismatches.

    A virtual address looks like one number. Under Sv39, the 39-bit virtual-address format in the RISC-V privileged architecture, it is four fields sharing one value: bits 38 to 30 are VPN[2], bits 29 to 21 are VPN[1], bits 20 to 12 are VPN[0], and bits 11 to 0 are the offset inside the page [1]. Each VPN is an index into one page table, and a page walk reads them in order: VPN[2] picks an entry in the root table, that entry names the next table, VPN[1] picks an entry there, VPN[0] picks the leaf entry that holds the physical page number, and the offset picks the byte inside that page.

    The 9-bit width is the page size wearing a disguise. A page table is one 4 KiB page and each entry is eight bytes, so one table holds 4096 / 8 = 512 entries, and 512 is 2 to the 9th [1]. Nine bits name exactly one entry in one table, with no code left over and no entry unreachable. Take the address 0x40403ABC: VPN[2] is 1, VPN[1] is 2, VPN[0] is 3, and the offset is 0xABC. Three small numbers pick three entries in three tables, and the fourth field rides through untouched to land on one byte inside the page.

    A wooden library card catalog with one drawer open, a hand holding an index card above the rows of cards inside
    A card catalog is an index you can touch: the label on the drawer front picks the drawer, and the card's place inside picks the entry. An Sv39 address picks one page table per field the same way, then one byte inside the page.
    Photo: Shyamal L., CC BY 4.0, via Wikimedia Commons

    The extraction, in four lines:

    f.page_offset = (uint16_t)(va & 0xFFFULL);
    f.vpn0 = (uint16_t)((va >> 12) & 0x1FFULL);
    f.vpn1 = (uint16_t)((va >> 21) & 0x1FFULL);
    f.vpn2 = (uint16_t)((va >> 30) & 0x1FFULL);
    

    The extraction is four masks: page_offset is va & 0xFFF, VPN[0] is (va >> 12) & 0x1FF, VPN[1] is the same shift at 21, and VPN[2] at 30 [3]. The four masks, 0xFFF, 0x1FF << 12, 0x1FF << 21, and 0x1FF << 30, touch no bit twice and skip no bit from 38 down to 0, so the split loses nothing: shift the fields back to their positions, OR them together, and the original address comes back. recombine(extract(va)) == va is not a hope; it is what disjoint and complete means.

    One contract hides inside that simplicity. A canonical 64-bit Sv39 address sign-extends bit 38 through bits 63 to 39 [1], while a raw 39-bit field leaves those high bits clear. The extractor reads only bits 38 to 0, so both forms give identical fields, and recombine returns the raw 39-bit field rather than inventing an extension it was never given [3]. Feed it either form; the answer is the same four fields.

    The lab proves the split against an oracle that shares no code with it. The oracle builds each field one bit at a time, never shifting a whole field, and the test demands field equality plus recombine(extract(va)) == va on every case: 117 directed edges around powers of two, a canonical-address row with the sign extension applied, an exhaustive sweep of every 24-bit value, and 10,000,000 fixed-seed splitmix64 values masked to 39 bits [2]. That is 26,777,374 checks with 0 mismatches, and the same FNV-1a checksum, 262f6db6f6303175, at -O0, at -O2, and under the address and undefined-behavior sanitizers [2]. The bench reads 3.460 ns per value at -O2, with the caveat printed in the proof: the number covers the array load and the running XOR accumulate, not the function body alone [2].

    Sources

    1. 01
      The RISC-V Instruction Set Manual, Volume II: Privileged Architecture (Sv39 paging)RISC-V International

      The Sv39 layout the fields are read from (Figure 4.19): VPN[2], VPN[1], VPN[0] over a 12-bit offset, and the rule that bit 38 sign-extends into bits 63:39 in a canonical address.

    2. 02
      PROOF.md, lab/132-sv39-vpn-extractdillingerstaffing/systems-lab

      The verification record: the per-bit oracle, the directed edges, the canonical row, the exhaustive 24-bit sweep, the fixed-seed values, the checksum held across three builds, and the bench caveat.

    3. 03
      lab/132-sv39-vpn-extract: vpn_extract.h and vpn_extract.cChris Dillinger, systems-lab

      The code under discussion: the four masks, the stated contract that extraction reads only bits 38:0, and the recombine that returns the raw 39-bit field.

    The One Call That Closes a Whole Range

    ISA

    The piece reasons about a syscall contract: flags, range bounds, shared descriptor tables, and error rules. It names no instruction, no encoding, and no register or trap convention, so nothing in the argument hangs on what the hardware does with an opcode.

    MICROARCH

    No pipeline, cache, or timing observation enters the argument. The race under discussion is threads opening descriptors between a /proc listing and a close loop; the fix is one kernel pass over a range, which is a software contract, not a hardware property.

    FIRMWARE

    No machine-mode service, boot step, or firmware handoff takes part. The call goes from the process into the kernel's descriptor-table code and back; firmware never appears in the mechanism.

    KERNEL

    The entire mechanism lives in the kernel's descriptor table: close_range walks the caller's table in one pass, applies CLOEXEC marks without closing, copies the table first under UNSHARE, ignores per-descriptor errors, and returns EINVAL on bad flags or first greater than last. The workbench tests proved each behavior against a live kernel.

    ALGORITHM

    The insight is a contract with three behaviors, not a procedure to analyze. The article states what one call does to a range and what two flags do to its meaning; it derives no steps, states no invariant, and measures no complexity.

    Every shell, daemon, and container runtime does the same cleanup before exec: close every file descriptor the child must not inherit, except 0, 1, and 2. The old way walks /proc/self/fd and closes each number in a loop, one close per descriptor [1]. The loop has a race: a thread can open a new descriptor between the listing and the close, and the new descriptor escapes.

    close_range(2) closes a whole span in one call: close_range(4, 6, 0) closes every descriptor from 4 through 6 [1]. On the workbench, five descriptors sat open: two plain files, a pipe pair, and one more file. The call closed the range and left neighbors 3 and 7 untouched, one motion instead of a listing and a loop [3].

    A matrix of small toggle switches on an electrical test panel, viewed at an angle
    A matrix of toggle switches on an electrical test panel. close_range flips a whole row in one motion: no listing, no loop, one call.
    Photo: Martin Birkin, CC0, via Public Domain Pictures

    Then the two flags that change the call's meaning. CLOSE_RANGE_CLOEXEC closes nothing; it marks every descriptor in the range close-on-exec, so they close at exec time instead [1]. CLOSE_RANGE_UNSHARE first detaches the caller's descriptor table from every thread that shares it, conceptually unshare(CLONE_FILES) followed by close_range [1]; the kernel does it by copying the table before applying the closes [2]. In the workbench test the unsharing thread's close left the main thread's copy open; the same close without the flag closed it for everyone [3].

    The three forms, in three lines:

    close_range(4, 6, 0);                     /* the range, one motion */
    close_range(4, 6, CLOSE_RANGE_CLOEXEC);   /* mark the range, close nothing */
    close_range(3, ~0U, CLOSE_RANGE_UNSHARE); /* private table first, then 3..MAX */
    

    The contract has sharp edges. Errors on individual descriptors are ignored, so one dead descriptor in the middle does not abort the range [1]. Bad flags, or first greater than last, return EINVAL [1]. The pre-exec idiom is close_range(3, ~0U, CLOSE_RANGE_UNSHARE): everything past stderr, privately, in one motion. The call arrived from FreeBSD, landed in Linux 5.9 with glibc 2.34, and the CLOEXEC flag joined in 5.11 [1].

    Sources

    1. 01
      close_range(2)man-pages project

      The contract this run: flag semantics, per-descriptor errors ignored, EINVAL on bad flags or first greater than last, and the close_range(3, ~0U, CLOSE_RANGE_UNSHARE) pre-exec idiom.

    2. 02
      fs/file.c: sys_close_rangetorvalds/linux

      The kernel implementation the UNSHARE table-copy behavior was cross-checked against.

    3. 03
      run.txtdillingerstaffing/closerange-demo

      Three runs of the firsthand workbench, all PASS: the range close, the CLOEXEC marking, and the UNSHARE table detach.

    The Nap Measured in Ticks

    ISA

    The mechanism never leaves supervisor-mode C: lock ordering around sleep_prepare, a shared counter, and an unsigned elapsed comparison. No CSR, trap entry, or privilege-level reasoning appears in the path.

    MICROARCH

    No pipeline, cache, or predictor behavior is reasoned about: the lost-wakeup argument is pure lock ordering in C, and the wrap safety comes from unsigned arithmetic, not from any hardware timing property.

    FIRMWARE

    The clock interrupt and the sleeping process meet in the kernel's own sleep and wakeup protocol; no machine-mode service, boot step, or firmware handoff participates.

    KERNEL

    The entire mechanism is a kernel sleep protocol: a system call that registers on the ticks channel with sleep_prepare, releases tickslock, and sleeps, while the clock interrupt bumps the counter and wakes sleepers under the same lock.

    ALGORITHM

    The insight is an ordering discipline, not a procedure with steps to analyze: register-before-release is a two-line protocol rule, and the elapsed-time comparison is one unsigned subtraction whose wrap behavior follows from the arithmetic alone.

    The pause(n) system call in my xv6-getscount tree asks the kernel to sleep for n clock ticks, then return 0 [1]. A negative request is clamped to zero, so the worst case is an instant return. The call keeps no time of its own; it trusts the global ticks counter that the clock interrupt maintains, and waits until that counter has advanced by n.

    The danger is the gap between deciding to sleep and actually sleeping. A tick that fires in that gap wakes nobody, and the sleeper then waits for a wakeup that already happened. The code closes the gap with ordering. First sleep_prepare(&ticks) records this process on the ticks channel; then release(&tickslock) lets go of the clock; only then does sleep() block. Registration comes before release, so no tick can fall into the gap. And ticks is shared between the clock interrupt and every sleeping process, so every touch of it happens under tickslock: the lock is what makes one counter safe to read from two contexts at once.

    A silver twin-bell alarm clock with Roman numerals on its face
    An alarm clock registers the wake time before anything else happens. sys_pause registers its channel before it releases the lock. The ordering is the whole trick.
    Photo: Ales Krivec, CC0, via Wikimedia Commons

    The ordering, in six lines:

    while (ticks - ticks0 < n) {
      sleep_prepare(&ticks);  /* register first */
      release(&tickslock);     /* then let go */
      sleep();                 /* now safe to wait */
      acquire(&tickslock);     /* re-arm and re-test */
    }

    The wait is a loop, not a single sleep. Every wakeup re-reads ticks and re-tests ticks - ticks0 < n, because wakeups are shared: a tick can wake this process when another sleeper is the one whose time is up, and only the comparison decides whether the nap is over. The killed() check inside the loop is the escape hatch; a process told to die while napping returns -1 instead of sleeping on. And the subtraction is unsigned 32-bit arithmetic, so it stays exact when ticks wraps past its maximum: the wrap cancels out of the difference, as long as the requested nap is shorter than one full wrap.

    The read side of the same protocol is sys_uptime: it takes tickslock, copies ticks into a local, releases, and returns the copy [1]. No sleeping, no loop, just the discipline that every reader of the shared counter holds the lock. One lock guards the counter, and every reader and writer uses it. That is the entire protocol.

    Sources

    1. 01
      kernel/sysproc.c, dillingerstaffing/xv6-getscountChris Dillinger

      sys_pause and sys_uptime, and the sleep_prepare, release, sleep ordering in the wait loop, read firsthand from the local checkout of the tree. The clock side, clockintr in kernel/trap.c, bumps ticks and calls wakeup under the same tickslock.

    The Bouncer Who Ranks Every Knock

    ISA

    The mechanism is RISC-V privileged architecture: per-input pending, enable, attribute, and level/priority registers defined by the CLIC specification, up to 256 interrupt levels per privilege mode with hardware same-mode preemption, a threshold register per privilege mode, CLIC mode entered through xtvec.mode=11 with a 64-byte-aligned NBASE, and selective hardware vectoring at TBASE plus XLEN/8 times the interrupt id. The article names the registers and the exact dispatch formulas.

    MICROARCH

    No processor internals are measured or reasoned about: the ranking, the threshold, and the vector table are a register contract any CLIC implementation honors, so no pipeline, cache, or timing behavior is examined. The mechanism is judged at the ISA layer.

    FIRMWARE

    Machine mode never appears: the CLIC registers are programmed by the operating system or bare-metal code directly, the threshold save and restore live in the interrupt path, and no supervisor binary interface call or boot firmware is in the picture.

    KERNEL

    The subject is the controller's architecture, not kernel internals: the one operating-system appearance is NuttX's threshold swap, used as a real-world illustration of a register the specification defines, and no kernel code is examined, measured, or modified.

    ALGORITHM

    No algorithm is presented: the article walks a register layout and a dispatch rule with one fixed address formula per interrupt, not a procedure with an invariant to prove.

    On stock RISC-V, every interrupt knocks the same way. The hart jumps to one trap handler, the handler reads mcause to learn who knocked, and nothing about the knock is ranked by the hardware. If one handler is running when a more urgent interrupt arrives, the urgent one waits for the handler to return, unless the handler re-enables interrupts and re-sorts the queue by hand [2].

    The CLIC, the Core-Local Interrupt Controller, puts a bouncer on the door of every hart. It takes up to 4096 interrupt inputs per hart, and each input gets four small 8-bit registers: a pending bit, an enable bit, attribute bits that pick the privilege mode, the trigger type, and the hardware-vectoring choice, and control bits for the level and priority [1]. The first 16 inputs are the classic interrupts, the ones in the low bits of the old pending and enable registers; the other 4080 are local lines the core wires up however it likes [1].

    Two young bouncers standing at a bar entrance at night, one close to the camera, unsmiling
    Two young bouncers at a bar entrance at night: they decide who gets in and in what order. The CLIC does the same for interrupts, ranking every knock by level and letting higher ranks preempt lower ones in hardware.
    Photo: Xxinvictus34535, CC BY-SA 4.0, via Wikimedia Commons

    Then comes the ranking. Every interrupt gets a level, up to 256 of them per privilege mode, and a higher level now preempts a lower one inside the same mode, in hardware, no handler cooperation needed [1]. And each privilege mode gets a threshold register, a velvet rope: only interrupts ranked above the threshold are taken at all. Raise it to the top and you have a do-not-disturb sign. NuttX uses exactly this in its RISC-V interrupt save path: on a CLIC chip it swaps the threshold register to its maximum instead of clearing the global enable in mstatus, masking every level at once [3].

    Then selective hardware vectoring. Each interrupt has one bit that decides whether it jumps straight to its own slot in the trap vector table or falls through to the shared handler. The choice is per interrupt, not per chip. To run in CLIC mode, software writes 11 to xtvec's mode field with the shared base 64-byte aligned; an interrupt with its vectoring bit set lands at TBASE plus 8 times its id on a 64-bit hart, where the entry holds the handler's address with the low bit cleared [1].

    The address rule, in four lines:

    /* shv = 1: this interrupt gets its own slot in the table */
    trap_pc = TBASE + 8 * interrupt_id;  /* 8 is XLEN/8 on RV64 */
    
    /* shv = 0: this one joins the shared handler at the base */
    trap_pc = NBASE;                     /* xtvec.mode = 11, base 64-byte aligned */

    The last register is mnxti, the tail-chainer. At the end of a handler, software reads it: if a higher-level interrupt is already pending, the read returns that handler's address and re-arms the enables, so the next handler starts with no return-and-retrap through the context save. For edge-triggered interrupts the same read clears the pending bit as a side effect. Back-to-back interrupts, no round trip [1].

    One honest boundary: the CLIC is the embedded answer. Application-class cores use the Advanced Interrupt Architecture instead, with its APLIC, its message-signaled interrupts, and virtualization support [4]. Different battlefields: the CLIC exists for cores where the claim-and-complete round trip and the software priority sort are themselves the latency you cannot afford.

    Sources

    1. 01
      RISC-V Core-Local Interrupt Controller (CLIC), v0.10 draftRISC-V International

      The four 8-bit registers per input: clicintip pending, clicintie enable, clicintattr with the mode, trigger, and hardware-vectoring bits, and clicintctl with level and priority. Up to 4096 inputs per hart with the first 16 reserved for the classic interrupts. Up to 256 levels per privilege mode with same-mode hardware preemption, one threshold register per privilege mode, CLIC mode entered with xtvec.mode equal to 11 and a 64-byte-aligned NBASE, selective hardware vectoring at TBASE plus XLEN over 8 times the interrupt id, and the mnxti tail-chaining register with its edge-triggered pending-clear side effect.

    2. 02
      RISC-V ISA Manual, privileged architectureRISC-V International

      Classic trap delivery: the handler reads mcause to classify the trap, and interrupt enables are cleared on entry, so nested handling inside one privilege mode is the handler's own work.

    3. 03
      NuttX RISC-V interrupt management documentationNuttX project

      The RISC-V interrupt management notes show up_irq_save on CLIC targets saving the threshold and swapping the threshold CSR to its maximum instead of clearing the global enable in mstatus, masking every level at once.

    4. 04
      RISC-V Advanced Interrupt Architecture, v1.0-RC1RISC-V International

      The Advanced Interrupt Architecture, with its APLIC and message-signaled interrupts plus virtualization support, is the application-class counterpart to the CLIC's embedded profile.

    The Two-Phase Birth of Every Process

    ISA

    The commit runs on privileged ISA machinery: the new world is an Sv39 page table of PTEs with R/W/X permission bits, the stack keeps 16-byte alignment because the RISC-V calling convention requires it, and the trapframe's epc and sp fields are the registers sret will resume from. The article names PTE_R and PTE_U, the uvmalloc guarantee, and the two register fields that main(argc, argv) falls out of.

    MICROARCH

    No processor internals are measured or reasoned about: the build-then-commit discipline, the four ELF sanity checks, and the three-assignment swap are supervisor-mode code identical on any hart running xv6, so the mechanism is judged at the ISA and kernel layers.

    FIRMWARE

    Machine mode never appears: the private page table is built and committed entirely in supervisor mode, with no firmware behavior in the path.

    KERNEL

    The entire mechanism is xv6 kernel code: kexec and loadseg in kernel/exec.c, proc_pagetable and uvmclear in kernel/vm.c, all read firsthand from the xv6-getscount checkout. The two phases exist so a failed exec can never leave a process half-born.

    ALGORITHM

    No algorithm is presented: the article walks a syscall implementation with a fixed order of checks and a single commit block, not a procedure with an invariant to prove.

    Every process on xv6 is born the same way. init forks, the child calls exec with a path, and 176 lines of kernel/exec.c take over. The first thing exec does is not touch the running process at all. It opens the executable under begin_op, finds the inode with namei, and reads the ELF header, checking the magic 0x464C457F, the little-endian spelling of the four bytes 0x7F, E, L, F [1].

    Then it builds a brand-new page table, private and uncommitted, and walks the program headers. Only ELF_PROG_LOAD segments get loaded, and each one must pass four sanity checks: memsz is not smaller than filesz, because the zero-filled remainder is what bss becomes; vaddr plus memsz must not wrap around; and vaddr must be page-aligned. Permissions come from flags2perm, which reads only two ELF bits, bit 0 for execute and bit 1 for write, because uvmalloc always adds PTE_R and PTE_U on its own, so a page can never be born kernel-only or unreadable by accident [1].

    A chick hatching out of a cracked egg, half-emerged, wet feathers and beak visible through the broken shell
    A chick mid-hatch at The Big E, 2007: the new world is built whole inside the shell before it breaks out. exec works the same way, the entire address space is complete in a private page table before three assignments and two register fields commit it.
    Photo: grendelkhan, CC BY-SA 2.0, via Wikimedia Commons

    loadseg fills each page with readi from the inode, but before a single byte is copied it looks the page up with walkaddr and panics with loadseg: address should exist if the mapping is missing. The mapping exists first, the bytes second [1]. The stack gets its own rite: the size is rounded up, one extra page is allocated beyond the user stack pages and cleared by uvmclear into an inaccessible guard page, and the argument strings are copied down from the top of the stack with 16-byte alignment, because the RISC-V calling convention requires it [2].

    Only when the new world is complete comes the commit. The source comment names the phase: Commit to the user image. Three assignments swap the page tables, the trapframe's epc is set to elf.entry and its sp to the new stack top, the old table is freed, and argc returns as the syscall value, landing in a0 with argv in a1, so main(argc, argv) is not a convention anyone agreed on, it is just what falls out of two registers [1].

    The commit, in six lines:

    // Commit to the user image.
    oldpagetable = p->pagetable;
    p->pagetable = pagetable;
    p->sz = sz;
    p->trapframe->epc = elf.entry;
    p->trapframe->sp = sp;

    The running process is never touched while its replacement is built. The file could be corrupt, the disk could fail, memory could run dry, and the old process would still be standing there, mid-instruction, untouched. The new world is complete before it is committed, or it never exists at all.

    Sources

    1. 01
      dillingerstaffing/xv6-getscount kernel/exec.cChris Dillinger

      kexec (kernel/exec.c): the ELF magic check, the program-header walk with four sanity checks, flags2perm reading two ELF bits, loadseg's walkaddr-first discipline and 'address should exist' panic, the stack rite with the uvmclear guard page, the 'Commit to the user image' block, and the bad: cleanup path. Read firsthand.

    2. 02
      RISC-V ISA Manual, privileged architectureRISC-V International

      Sv39 page-table entries with the V/R/W/X permission bits, sret resuming through sepc keyed off sstatus SPP and SPIE, and the 16-byte stack alignment of the RISC-V calling convention.

    The Thirty-Five Registers of a Rescue Plan

    ISA

    The rescue plan runs on privileged ISA primitives: sscratch parks a0 when no register is free, sfence.vma fences both satp switches, and sret returns through sepc with SPP and SPIE. The article quotes uservec's csrw sscratch, a0 and the fence pairs from kernel/trampoline.S and names the privileged spec as the contract behind each.

    MICROARCH

    Nothing in the article measures or reasons about any processor's internals: the trapframe layout, the sscratch swap, and the fence pairs are supervisor-mode code identical on any hart running xv6, so the mechanism is judged at the ISA and kernel layers.

    FIRMWARE

    Machine mode sets up the stage with stvec and the page tables, but the article never goes there: the catch, the save, and the return are supervisor-mode trap machinery built from the return ticket and thirty-one register slots, none of it firmware behavior.

    KERNEL

    The entire mechanism is xv6 kernel code: struct trapframe in kernel/proc.h, uservec and userret in kernel/trampoline.S, usertrap and prepare_return in kernel/trap.c, all read firsthand from the xv6-getscount checkout. The return ticket exists so the kernel can suspend a process and set it back down.

    ALGORITHM

    No algorithm is presented: the article walks a data structure and two assembly routines with fixed offsets and a fixed instruction order, not a procedure with an invariant to prove.

    A user process is running. A timer interrupt fires, or the program calls a syscall. The hardware does almost nothing for it: it records the cause, stashes the faulting address, and jumps to a vector. Every register the process was holding is still sitting in the physical registers, and the first real instruction of the trap handler is about to overwrite them. Before the kernel can do a single thing, it needs somewhere to put the process down.

    xv6's answer is struct trapframe in kernel/proc.h. Its first five fields are not registers at all: kernel_satp, kernel_sp, kernel_trap, epc, kernel_hartid. They are the return ticket. Only then comes the process itself, all thirty-one integer registers in ABI order, ra at byte 40 through t6 at byte 280 [1]. Every process maps its trapframe at the same virtual address, TRAPFRAME, so the catch code can write li a0, TRAPFRAME and mean it for any process.

    Two trapeze artists mid-flight: the catcher holds the flyer upside down under a star-painted circus tent
    Double trapeze act, Continental Circus Berlin, Aviemore, 2009: the catcher takes the flyer mid-flight and sets her back down. The trapframe is where xv6 catches a running process mid-stride, thirty-five registers holding everything it was, so sret can set it back down exactly where it was.
    Photo: Aaron Sneddon, CC BY, via Wikimedia Commons

    The catch is uservec in kernel/trampoline.S, and its first instruction is the whole philosophy: csrw sscratch, a0. On trap entry you have exactly zero free registers, so a0 is parked in sscratch, a swap that needs no scratch space, and only then does the code reach for the trapframe. Thirty-one stores. Then the kernel stack pointer into sp, the hartid into tp, the address of usertrap into t0, the kernel page table into t1. The satp switch is fenced by sfence.vma on both sides, because a TLB entry cached under one page table is a lie under the other [2]. Then jalr t0, into usertrap.

    usertrap does the C work. sepc is stashed into the trapframe's epc first, and on the syscall path epc is bumped by four before interrupts are enabled, because the ecall is finished and the return must point past it, and an interrupt would move sepc out from under the bump [1]. prepare_return() rebuilds the trip back: stvec points to uservec again, the four kernel ticket fields are refreshed, SPP is cleared so sret drops to user mode, SPIE is set, sepc is reloaded. userret flushes the instruction cache, switches back to the user page table under the same fence pair, reloads all thirty-one registers, and sret.

    The trapframe earns its thirty-five registers by being honest about the constraint. On trap entry the hardware hands you nothing but a0's old value and one constant address. The ticket, the save area, the fences: every part of the rescue plan is built out of that.

    Sources

    1. 01
      dillingerstaffing/xv6-getscount kernelChris Dillinger

      struct trapframe layout (kernel/proc.h), uservec and userret (kernel/trampoline.S), usertrap and prepare_return (kernel/trap.c): the five-field return ticket, the thirty-one register slots in ABI order, the sscratch swap, the sfence.vma pairs around both satp switches, the epc bump before intr_on. Read firsthand.

    2. 02
      RISC-V ISA Manual, privileged architectureRISC-V International

      sscratch as the supervisor scratch register for the trap-entry sequence, sfence.vma ordering requirements around satp writes, sret privilege transition and interrupt behavior keyed off sstatus SPP and SPIE, sepc as the saved trap program counter.

    The Two Bits That Deliver the Block or Drop It

    ISA

    CBIE is bits 5 and 4 of menvcfg, senvcfg, and henvcfg, defined by the RISC-V cache-block management base spec: the article quotes the 00 trap, 01 flush, 10 reserved, and 11 invalidate encodings and verifies the field with a WARL write and readback probe.

    MICROARCH

    The probe ran on QEMU's functional model of the virt board, not on silicon: the article states nothing about any processor's implementation of the cache or the field.

    FIRMWARE

    The M-mode program is a test harness that writes and reads back a CSR: the mechanism the article presents is the ISA-defined permission field, not firmware behavior.

    KERNEL

    The mechanism is an ISA privilege contract between machine, supervisor, and user mode, plus the hypervisor extension: no kernel code or kernel data structure takes part.

    ALGORITHM

    No algorithm is presented: the article walks a permission field with four encodings and a write and readback contract, not a procedure with an invariant to prove.

    A cache block holds the only fresh copy of a piece of memory. The processor changed the data, and the copy sitting in main memory is stale. Now a less privileged program runs cbo.inval, the cache-block management instruction that says throw this block away. If the block is clean, nothing is lost. If it is dirty, throwing it away destroys work that main memory never saw. The program holding the instruction cannot be trusted to make that call.

    So the decision is not the program's. It lives in two bits of menvcfg, bits 5 and 4, named CBIE, and they belong to machine mode, the highest privilege in the machine [1]. The four encodings are a ladder. 00 means the instruction traps: it is simply not allowed. 01 means flush: write the block back to memory first, then discard it. 10 is reserved, and the manual says software must not rely on it. 11 means invalidate: discard the block without writing anything back.

    A U.S. Mail carrier carrying parcels through the snow from a parcel post truck, winter 1949
    Winter, circa 1949: every parcel on that truck is either delivered to its door or it is not leaving. The CBIE bits make the same call for a cache block: 01 writes it back to memory first, 11 drops it, and 00 never lets the instruction run.
    Photo: Smithsonian Institution, CC BY-SA 4.0, via Wikimedia Commons

    The permission follows privilege down the ladder. Anything below machine mode answers to menvcfg. A user program needs supervisor mode to agree as well, through senvcfg; a guest under a hypervisor needs henvcfg too [1]. The spec states the reason plainly: until a modified block has updated memory, an invalidate can expose stale data, so the higher privilege must clean or flush the block first, or keep the lower privilege on 00 or 01.

    A bare-metal WARL probe confirmed the field is real. In M-mode I wrote each CBIE value with every other menvcfg bit held at its boot value: 1, 2, 3, then 0 each read back exactly as written. An all-ones write legalized the field identically on both tries, the boot value restored exactly, and the trap handler recorded nothing. Nine checks, zero mismatches, on QEMU 8.2.2 [2].

    The contract, in three lines:

    csr_write(menvcfg, boot | (cbie << 4));
    unsigned long rb = csr_read(menvcfg);
    check(((rb >> 4) & 0x3) == cbie, "CBIE readback");

    The reserved encoding is the part implementations get to disagree about. On this hart 2'b10 reads back exactly as written, which is why the manual says software must not rely on it. CVA6's CSR file accepted the reserved value until a September fix taught it to hold the previous value instead [3].

    Sources

    1. 01
      riscvarchive/riscv-CMOs cmobase/csr_state.adocRISC-V International

      CBIE is bits 5:4 of the xenvcfg CSRs, encodings 00 trap, 01 flush, 10 reserved, 11 invalidate; the privilege-mode decision table for CBO.INVAL; the stale-data security rationale for keeping lower privilege on 00 or 01.

    2. 02
      riscv-baremetal-demo src/menvcfg-cbie-writeChris Dillinger

      Bare-metal WARL write and readback probe of menvcfg.CBIE: boot value printed, CBIE written 1, 2, 3, 0 with exact readbacks, all-ones legalized identically twice, boot value restored, zero traps: 9 checks, 0 mismatches on QEMU 8.2.2.

    3. 03
      openhwfoundation/cva6 PR 3513OpenHW Group

      fix(csr): reject reserved CBIE encoding 2'b10 in menvcfg/senvcfg/henvcfg, merged 2026-09-04: the write logic stored the reserved encoding unchanged, so a 2'b10 write read back unmodified.

    The Half of the Interrupt That Waits Its Turn

    ISA

    The mechanism is Linux kernel design, not instruction-set law: the softirq type list, the 2ms and 10-restart governors, and the tasklet SCHED/RUN bit contract are quoted from the v6.5 kernel source, not from an architecture manual.

    MICROARCH

    The article's mechanism is kernel scheduling policy: how Linux decides where deferred work runs. It measures and cites nothing about processor implementation.

    FIRMWARE

    The whole mechanism is kernel code: softirqs run on hardirq exit, tasklets run on the TASKLET softirq, and ksoftirqd is a kernel thread. Nothing below the kernel boundary takes part.

    KERNEL

    The article reads the deferred-work machinery straight from the kernel: the ten softirq types in kernel/softirq.c priority order, the 2ms and 10-restart governors, the tasklet SCHED/RUN bit contract in include/linux/interrupt.h, and the ksoftirqd handoff. This is the kernel's own interrupt plumbing.

    ALGORITHM

    No algorithm is presented: the post describes a scheduling policy and a bit-level contract, not a procedure with an invariant to prove.

    A packet arrives on the wire. The NIC raises its interrupt line, and the hardirq handler starts running. It runs with interrupts off and no process to its name. It cannot sleep, it cannot wait on anything, and every other interrupt in the machine is lining up behind it. So it does the minimum: acknowledge the device, capture the data, mark the work as pending [3]. Then it leaves. The rest of the work does not run in the handler. It runs in the bottom half.

    Linux keeps ten softirq types in a fixed priority order: HI, TIMER, NET_TX, NET_RX, BLOCK, IRQ_POLL, TASKLET, SCHED, HRTIMER, and RCU last, with a comment in the source that RCU should always stay last [1]. When the hardirq handler exits and no interrupt context is nested, the kernel walks the pending bitmask in priority order, lowest bit first. The handler loop carries two governors: two milliseconds (MAX_SOFTIRQ_TIME) and ten restarts (MAX_SOFTIRQ_RESTART), and the comment says these limits were found by experimentation, balancing latency against fairness [1]. When either budget is spent, the kernel wakes ksoftirqd, a per-CPU thread, which finishes the leftover work as ordinary scheduled work. A softirq therefore has two personalities: under light load it runs eagerly, almost as fast as the hardirq that raised it; under heavy load it demotes itself to a thread instead of starving the machine.

    Operators at a Bell System telephone switchboard in December 1943, patching overseas calls by hand
    December 1943: the operator answers the instant the lamp lights and patches the circuit; the conversation happens on the wire she connected. The hardirq handler answers the interrupt; the bottom half carries the rest.
    Photo: U.S. National Archives, no known copyright restrictions, via Wikimedia Commons

    Tasklets are the friendlier face of the same machinery, built on the TASKLET and HI softirqs [2]. Their whole contract is test-and-set. tasklet_schedule sets the SCHED bit, so scheduling a tasklet twice collapses into a single run. tasklet_trylock sets the RUN bit, so the same tasklet can never execute on two CPUs at once; if it is already running, the action function puts it back on the list and re-raises the softirq, so the work is honored later instead of being lost [2]. The per-CPU tasklet list is stolen under disabled interrupts, then each tasklet runs with interrupts enabled: a tasklet can be preempted by a hardirq, but never by a second copy of itself. One flag for scheduled, one for running, and re-queue as the honest answer to contention.

    The whole contract, in three lines:

    static inline void tasklet_schedule(struct tasklet_struct *t)
    {
    	if (!test_and_set_bit(TASKLET_STATE_SCHED, &t->state))
    		__tasklet_schedule(t);
    }

    There used to be a simpler version of all this. The old bottom halves numbered 32, ran globally synchronized, and only one was allowed to run anywhere in the system at a time [3]. That was the bottleneck, and during 2.5 the BH interface was thrown away; every user moved to softirqs, tasklets, or the workqueue. The sibling that survives alongside them is the workqueue, which exists for the one property softirqs and tasklets still lack: the ability to sleep. So the three mechanisms are not three ways to do the same thing. They are a ladder: the hardirq does the minimum, the softirq and the tasklet take the urgent remainder that still cannot sleep, and the workqueue takes the part that needs to sleep. Each rung exists because the rung above it is missing exactly one property.

    Sources

    1. 01
      torvalds/linux v6.5 kernel/softirq.cLinux kernel

      Ten softirq types in priority order with RCU last (L550-561); the 2ms and 10-restart governors found by experimentation, balancing latency against fairness (L461-475); the ksoftirqd handoff when the budgets are spent (L566-578).

    2. 02
      torvalds/linux v6.5 include/linux/interrupt.hLinux kernel

      The tasklet contract: tasklet_schedule sets TASKLET_STATE_SCHED so a double schedule collapses into one run (L705-709); tasklet_trylock sets TASKLET_STATE_RUN so one tasklet never runs on two CPUs at once (L687-690).

    3. 03
      Linux Kernel Development, 3rd edition, Chapter 8Robert Love, Addison-Wesley

      The old bottom halves: 32 of them, globally synchronized, only one running anywhere in the system at a time; the BH interface removed during 2.5, with every user converted to softirqs, tasklets, or workqueues.

    The Bit That Lets the Supervisor Read User Memory

    ISA

    SUM is bit 18 of sstatus, defined by the privileged architecture, and the article verifies the exact fault rule the manual states for U=1 pages.

    MICROARCH

    No microarchitectural claim is made: the behavior was measured on QEMU's functional Sv39 page-walk model, not on silicon.

    FIRMWARE

    The M-mode boot code is a test harness that sets up tables and delegates the fault; the article's mechanism is the S-mode SUM gate, not firmware behavior.

    KERNEL

    The article's final paragraph is the kernel's real alternative: xv6 copyin walks the user page table with walkaddr and memmoves from the resolved physical address, never setting SUM.

    ALGORITHM

    No algorithm is presented; the post measures a single architectural permission bit through fault and load probes.

    I put a canary word on a U=1 user page at virtual address 0x40000000, dropped a bare-metal RISC-V machine into S-mode with SUM, bit 18 of sstatus, clear, and ran one ld from that page. Exactly one trap: scause 0xd, a load page fault, with stval 0x40000000 naming the faulting address. The destination register had been poisoned to zero before the load and stayed zero, so the load never completed [2].

    Then I set bit 18 with csrs sstatus and ran the identical load again. The canary came back, 0xc0decafe5ca1ab1e, with no new trap. The full bench is 31 checks, 0 mismatches, on QEMU 8.2.2: the SUM=0 phase faulted exactly once, and the SUM=1 phase read the page cleanly [2].

    A brass key inserted in a door lock, the rest of the door softly out of focus
    One bit, one door: SUM opens supervisor data access to user pages, and nothing else.
    Photo: Shixart1985 (CC BY 2.0), via Wikimedia Commons

    The boundary is fetch. With SUM still set, I jumped into the same user page, and the machine took one instruction page fault: scause 12, with sepc and stval both 0x40000000. The privileged manual states it as an absolute: "S-mode can never execute instructions from user pages, regardless of the state of SUM." [1] The bit rewrites the data rule for loads and stores, and never the fetch rule.

    This is the kernel's everyday question: how does the supervisor touch user memory without becoming it? xv6 answers by never asking. Its copyin walks the user page table with walkaddr, resolves the user virtual address to a physical address, and memmoves from the physical address in the kernel's own mapping, so the kernel never performs a supervisor-mode load from a user virtual address at all [3]. SUM exists for kernels that do ask: the manual pairs the bit with the absolute fetch ban as the two mechanisms that keep supervisor data access controlled and supervisor execution of user pages impossible at all times [1]. The bit is a data door, never an execution door.

    Sources

    1. 01
      The RISC-V Instruction Set Manual, Volume II: Privileged ArchitectureRISC-V International

      Defines sstatus.SUM (bit 18): when SUM=0, S-mode accesses to U=1 pages fault; when SUM=1 they are permitted; and states that S-mode can never execute instructions from user pages, regardless of the state of SUM.

    2. 02
      src/sstatus-sum: sstatus.SUM gate on U-page loadsChris Dillinger, riscv-baremetal-demo

      The firsthand experiment behind this post: SUM=0 faults exactly once (scause 0xd, stval 0x40000000, load never completes), SUM=1 returns the canary 0xc0decafe5ca1ab1e with no new trap; 31 checks, 0 mismatches on QEMU 8.2.2.

    3. 03
      xv6-riscv kernel/vm.c: copyinMIT PDOS

      xv6's copyin walks the user page table with walkaddr, resolves the user virtual address to a physical address, and memmoves from the physical address, so the kernel never performs a supervisor-mode load from a user virtual address.

    The Extension You Cannot Disassemble

    ISA

    Ztso directly changes the architectural memory-order contract the post demonstrates: the spec strengthens RVWMO so loads act as acquire and stores as release, which is exactly what makes the compiler's fence deletion legal, and the _ztso1p0 architecture tag is an ISA-level declaration.

    MICROARCH

    The post constrains observable ordering but never reasons about a particular pipeline, store buffer, cache, or other microarchitectural mechanism; the deleted fences are a compiler decision against the architectural contract, not a hardware structure.

    FIRMWARE

    No bootloader, machine-mode firmware, or privilege-mode handoff takes part: the demonstration is a freestanding compile of C11 atomics to object files, and nothing in the post executes in or depends on firmware.

    KERNEL

    The proof uses freestanding C atomics compiled to object files, never a running kernel: no syscall, trap, page table, or kernel path appears in the experiment or the argument.

    ALGORITHM

    The post derives no lock-free algorithm and proves no algorithmic property; the four atomics are a compiler-input fixture for observing fence lowering, not a concurrent algorithm under analysis.

    I compiled the same four C11 atomics twice, xPack GCC 15.2.0 at -O2, once for rv64gc and once for rv64gc_ztso. The only difference between the two runs was the Ztso flag. For a release store the base target emits fence rw,w and then sw. The Ztso target emits just sw. For an acquire load the base target emits lw and then fence r,rw. The Ztso target emits just lw. Two fences, deleted by a compiler flag [2].

    The spec explains the deletion. Ztso strengthens the base memory model, RVWMO, into RVTSO: every load acts as an acquire, every store as a release, and AMOs as both, so a fence that only restated that ordering is redundant [1]. Under RVWMO the fences were load-bearing: without them the hardware could let a store or a load slide past a neighboring access. Under Ztso the ordering is a guarantee of the model, so the compiler stops emitting the instruction. A sequentially consistent atomic still keeps one fence rw,rw, because only a full barrier orders a store before a later load, and Ztso does not add that [1]. The compiler knows exactly which fences the promise covers.

    A section of the Berlin Wall days after it opened in November 1989, people walking past where the barrier stood
    November 1989: the barrier opens and the line keeps moving in order. Ztso deletes the fence instructions; the ordering promise remains.

    The two builds side by side:

    release store   base: fence rw,w ; sw     ztso: sw
    acquire load    base: lw ; fence r,rw     ztso: lw
    seq_cst         base: fence rw,rw         ztso: fence rw,rw

    The deletion is exact: release loses one fence, acquire loses one fence, and sequential consistency keeps its full barrier on both targets. The compiler is not guessing. The Ztso model tells it which orderings are already guaranteed, and it emits fences only for the ones that are not [1] [2].

    You cannot find Ztso in the disassembly. The extension adds no instructions, so there is nothing to disassemble [1]. The only trace is the object file's architecture string, where the Ztso build records _ztso1p0 in Tag_RISCV_arch: the binary's declaration that it requires the stronger model [2]. An extension that exists as a promise shows up only where promises are recorded, in the metadata.

    Ztso is the extension you cannot disassemble: no new instructions, no fences, just an ordering promise and a flag in the object file.

    Sources

    1. 01
      The RISC-V Ztso Extension, version 1.0RISC-V International

      Defines RVTSO as a delta from RVWMO: loads act as acquire-RCpc, stores as release-RCpc, AMOs as acquire-RCsc plus release-RCsc; non-I/O fences lacking both PW and SR become redundant; the extension adds no instructions; binaries that assume Ztso must identify that requirement.

    2. 02
      lab/161-ztso-fence-delete: Ztso fence deletion through the compilerChris Dillinger, systems-lab

      The firsthand experiment behind this post: xPack RISC-V GCC 15.2.0 at -O2 for rv64gc versus rv64gc_ztso, the deleted release and acquire fences, the retained sequential-consistency fence, the _ztso1p0 architecture tag, and the 36-check verification run.

    The Promise That Names a Byte Range

    ISA

    Nothing in the post depends on the instruction set: the range granularity comes from the kernel's page cache, not from any instruction's semantics, and the same flag contract holds on x86-64, ARM, and RISC-V (the latter via sync_file_range2).

    MICROARCH

    The post never reasons about pipelines, predictors, or on-chip caches; the only hardware it names is the drive's onboard write buffer, which the call explicitly does not flush, and the timing numbers are presented as ratios from a shared VM, not as microarchitectural measurements.

    FIRMWARE

    No bootloader, machine mode, or device firmware takes part: the demo runs as an unprivileged userspace program against the host kernel, and the drive firmware is named only to say the syscall does not reach it.

    KERNEL

    The whole mechanism is a Linux syscall interpreted by the kernel's writeback path: the flags, the page-grained rounding of the range, and the EINVAL and ESPIPE error returns are all kernel ABI, verified firsthand against the running kernel.

    ALGORITHM

    The post's insight is a two-phase protocol, start writeback with WRITE and wait with WAIT_AFTER, with documented flag combinations for start-for-integrity and write-for-data-integrity; the phases are separately observable and the gap between them is usable work time.

    I wrote 8 MiB of dirty pages to a file and asked the kernel to make them durable two ways. fsync took 18 to 19.5 milliseconds. sync_file_range with all three flags took 8.5 to 10. Same bytes, same disk, roughly half the time. The difference is what each call promises: fsync promises the whole file, metadata included [2], while the range call promises only the bytes you name [1].

    The signature is sync_file_range(fd, offset, nbytes, flags), in Linux since 2.6.17 [1]. The range is page-grained: the offset rounds down, the end rounds up, and an nbytes of 0 means offset through end of file. The flags are the point. SYNC_FILE_RANGE_WRITE alone starts writeback of the range's dirty pages and returns immediately; the man page says outright it is not suitable for data integrity. Add WAIT_BEFORE and the call first waits for already-submitted writeback, then starts the range's write: the start-for-data-integrity operation. Add WAIT_AFTER too and it waits after as well: all three flags together are the range's write-for-data-integrity operation.

    Splitting start from wait is the whole design. On 8 MiB of dirty pages, WRITE alone returned in about 2.3 milliseconds because it only started the write; a separate WAIT_AFTER then took about 40 milliseconds doing the actual waiting. Two calls where fsync is one, and the gap between them is yours to use: start the write, do other work, wait later. That is why a database overwriting a hot 4 MiB region of a 40 GiB file wants this call. It does not drag every cold page along, it does not pay the metadata tax, and it can pipeline the writeback instead of blocking on it.

    the split: start and wait are two calls
    sync_file_range(fd, 0, 0, SYNC_FILE_RANGE_WRITE);      /* start: returns now */
    do_other_work();                                       /* the gap is yours */
    sync_file_range(fd, 0, 0, SYNC_FILE_RANGE_WAIT_AFTER);  /* done: waits */
    A hard disk drive actuator arm assembly photographed on a white background: the metal arm that moves the read/write head across the disk platters
    The part that puts the bytes where the promise lands: a hard disk drive actuator arm assembly, the arm that carries the read/write head across the platters.
    Photo: Malcolm Koo (CC BY 4.0), via Wikimedia Commons

    The man page calls this call extremely dangerous, and the warning is part of the mechanism, not decoration [1]. It writes no metadata. It gives no guarantees unless the program is purely overwriting blocks that are already instantiated, which no userspace interface can confirm, and which is impossible on copy-on-write filesystems. It does not flush the drive's onboard write buffer. So the promise is narrow by construction: the bytes you named, written out, nothing else. Where that narrow promise is exactly what you need, this is the tool; everywhere else, reach for fsync.

    fsync is a promise about a file. sync_file_range is a promise about a byte range, split into start and done.

    Sources

    1. 01
      sync_file_range(2) man pageLinux man-pages project (man7.org)

      The contract this post proves firsthand: the three flags and their documented combinations, page-grained ranges, the flags=0 no-op, the EINVAL and ESPIPE errors, and the 'extremely dangerous' warning covering metadata, overwrites of instantiated blocks, and disk write caches.

    2. 02
      fsync(2) man pageLinux man-pages project (man7.org)

      The comparison point: fsync flushes all modified in-core data of the file plus the metadata associated with it, which is why it costs more than the range-scoped call on the same dirty pages.

    The Store That Isn't

    ISA

    matters at ISA because the verified properties are the concrete rv64 instruction sequences read off the disassembly this run: the volatile poll loop reloads LSR with lbu every iteration and transmits with one sb to 0x10000000, while the plain-pointer loop hoists the load out and spins on a jump to itself, both produced by gcc 13.2.0 at -O2.

    MICROARCH

    not at Microarch because nothing was timed and no pipeline, cache, or predictor behavior enters the argument: the UART's 38.4K baud timing is the peripheral's own clock, and the compiled sequences would carry the same argument on any RV64 implementation.

    FIRMWARE

    not at Firmware because no firmware contract enters the argument: the driver programs the UART's registers directly with loads and stores, and no SBI call, trap delegation, or machine-mode handoff is quoted or needed.

    KERNEL

    matters at Kernel because the claims are about kernel execution context: xv6's UART driver builds register access from the Reg, ReadReg, and WriteReg macros and polls the Line Status Register's transmitter-idle bit in uartputc_sync, each read off xv6's kernel source.

    ALGORITHM

    matters at Algorithm because the volatile rule is the portable contract every optimizing C compiler honors: accesses through volatile-qualified lvalues are visible side effects that cannot be hoisted or deleted, which is why the poll loop survives -O2 on any target.

    I compiled two one-byte functions, gcc 13.2.0 at -O2 for rv64, and read the disassembly. Both poll bit 5 of the byte at 0x10000005, then store a byte to 0x10000000. Polling means asking the device, over and over, "ready yet?": the loop reads the status register on every iteration until the bit says yes. The source differs by one keyword.

    mmio.c compiled: gcc 13.2.0 -O2, rv64 (excerpts)
    putc_nv:        ; plain pointer
      lbu a5,5(a4)  ; ask once
      andi a5,a5,32
      bnez a5,.write
    .spin:
      j .spin       ; never asks again
    .write:
      sb a0,0(a5)   ; 0x10000000: the store that sends
    
    putc_v:         ; volatile pointer
    .poll:
      lbu a5,0(a4)  ; ask every iteration
      andi a5,a5,32
      beqz a5,.poll
      sb a0,0(a5)   ; 0x10000000: the store that sends

    putc_nv takes a plain pointer. a4 arrives holding 0x10000000 (the excerpt trims the lui), so lbu a5,5(a4) loads the Line Status Register at 0x10000005, once, before the loop. The compiler hoists it: in its model of memory, a load from an address nothing in the program writes cannot change between iterations. andi a5,a5,32 keeps only bit 5, the transmitter-idle bit. bnez a5,.write skips the spin if the UART was already ready. Otherwise the loop body is empty, and an empty loop is j .spin, a jump to itself. The device can raise the bit a microsecond later; this code will never ask again. sb a0,0(a5) stores the argument byte to 0x10000000; the excerpt trims a second lui that reloads a5 with the base, the polled value being dead after the branch.

    putc_v takes a volatile pointer, and the load stays inside the loop. lbu a5,0(a4) reads the register every iteration (a4 holds 0x10000005 here, setup trimmed the same way). andi isolates the bit; beqz a5,.poll goes back while it is clear. A volatile access is a visible side effect: the optimizer may not hoist it, delete it, or merge two of them. The loop survives -O2 because the compiler is forbidden from assuming what the device does between two reads.

    Those two addresses are the whole story. This is xv6's UART driver turning an integer into a pointer [1]:

    xv6 kernel/uart.c (excerpts)
    /* the UART control registers are memory-mapped
       at address UART0. this macro returns the
       address of one of the registers. */
    #define Reg(reg) ((volatile unsigned char *)(UART0 + (reg)))
    #define ReadReg(reg)     (*(Reg(reg)))
    #define WriteReg(reg, v) (*(Reg(reg)) = (v))

    Reg casts UART0 + reg to volatile unsigned char *. The arithmetic is in bytes, so Reg(5) is exactly 0x10000005; there is no scaling to get wrong. The volatile is the entire contract: every dereference is one bus transaction, emitted exactly as written, in order. ReadReg is one load, WriteReg one store. That cuts both ways: an extra ReadReg dropped in for debugging is not a free peek, it is another transaction on the wire. Count your accesses.

    The CPU runs the same sb whether the target is DRAM or a device register; the instruction itself cannot tell the two apart. The address decides: the hardware sends different address ranges to different destinations, and 0x10000000 goes to the UART, not to RAM. So the same instruction does two different jobs. To DRAM, sb saves a byte a later load can read back. To 0x10000000, sb drops the byte into the transmit holding register, and the UART clocks it out over the serial line. That is what memory-mapped I/O means: the address selects the destination, not just a cell. DRAM is storage: a store saves a value, a load brings it back. A UART register is a hardware interface: a load returns bits the hardware computed, for example bit 5, which the UART sets itself when its transmitter goes idle and no store from the CPU can set; the store itself is what sends the byte out the serial line.

    An NS16550AFN UART chip in a ceramic package, the kind of serial hardware xv6's driver speaks to
    The store instruction ends here: an NS16550AFN UART, National Semiconductor, 1992.

    The compiler treats memory as a closed system. A load from an address nothing in the program wrote is assumed to return the same value every time, so the compiler keeps the first load and deletes the rest. A store to an address nothing in the program reads is assumed to change nothing anyone can see, so the compiler deletes the store. Those are two different failures on a UART. The status register changes on its own schedule, so when the compiler deletes the repeated loads, the poll loop spins forever on the first reading and never sees the device become ready. The transmit register's whole job happens off-chip, so when the compiler deletes the store, the byte is simply never sent. volatile tells the compiler an address is not ordinary memory: every load and store through it must be emitted exactly as written, in order [2]. That is why the volatile poll loop survives -O2, and why the plain-pointer version degrades into a jump to itself.

    xv6's driver is the same loop as a function. uartputc_sync spins on bit 5 of the Line Status Register, then calls WriteReg, which is one sb through a volatile pointer to 0x10000000 [1]. Ask the device if it is ready, then store the byte. The store is not a write to memory; it is a message to a second computer, delivered by an instruction that thinks it is writing RAM.

    Sources

    1. 01
      xv6-riscv kernel/uart.cMIT PDOS

      The literal driver this post reads: the Reg, ReadReg, and WriteReg macros that turn integers into pointers, and uartputc_sync's poll on LSR_TX_IDLE.

    2. 02
      volatile semanticscppreference.com

      The portable contract behind the experiment: every access through a glvalue of volatile-qualified type is treated as a visible side effect for the purposes of optimization, so the poll loop's load cannot be hoisted and the transmit store cannot be deleted.

    The Bit That Decides Who Writes the A and D Bits

    ISA

    the switch is drawn by the ISA: menvcfg.ADUE is bit 61, a WARL field the privileged architecture reserves for exactly this choice; the fault codes 13 and 15 and the A/D bit positions in the PTE are architected, and the load-needs-A, store-needs-A-and-D split is the contract both sides implement.

    MICROARCH

    not at Microarch because the post describes the architected choice between a hardware update and a software update, not how any pipeline implements the atomic compare-and-swap; no reordering, prediction, or timing claim appears.

    FIRMWARE

    M-mode does the setup the machine layer owns: it probes ADUE writability, grants the PMP entry, delegates the faults with medeleg, and flips ADUE on the S-mode ecall, because menvcfg is writable only in M-mode.

    KERNEL

    the software half of the switch is kernel work: the S-mode handler reads scause and stval, sets A and D in the entry, issues sfence.vma, and retries by returning the unchanged sepc; an OS on a chip without Svadu does exactly this on every first touch.

    ALGORITHM

    not at Algorithm because the post describes who maintains two bookkeeping bits and how the choice is configured, not a computational method; nothing is stated, timed, or compared as an algorithm.

    Take one page, at virtual address 0x80100000, identity mapped so virtual equals physical, its page-table entry starting with the Accessed and Dirty bits clear. Accessed means the page has been touched; Dirty means it has been written and must be written back before the OS reuses the frame. Now store a word to that page. What happens next depends on one bit: ADUE, bit 61 of the M-mode CSR menvcfg, the Svadu extension.

    Two hand stamps and ink pads on a table, the kind used to mark documents
    The hand stamp marks the paper. The post asks who stamps the A and D bits: the hardware walker or the software handler.

    With ADUE=0, the store traps exactly once. scause reads 15, a store page fault, and stval holds the faulting address. The S-mode handler sets A and D in the entry, issues sfence.vma to make the update visible, and the retried store succeeds; the entry reads 0x200400c7. A load traps exactly once too, scause 13, and the handler sets A only: 0x20040047. Loads need A, stores need A and D, and the software side of the switch respects exactly that split.

    svadu.c, S-mode trap handler (excerpt)
        if(scause==15){    /* store/AMO page fault: software sets A and D */
            if(stval != TEST_VA){ uputs("S-UNEXPECTED store tval="); uputhex(stval); uputc('\n'); for(;;); }
            *test_pte |= (PTE_A|PTE_D);
            sfence_vma();  /* retry the faulting store (sepc unchanged) */
            return sepc;
        }

    With ADUE=1, the same store traps zero times. The page-table walker sets A and D itself with an atomic update; the load leaves D clear with A set. QEMU 8.2.2 implements exactly this switch: ADUE gates an atomic compare-and-swap on the entry, otherwise the walk fails into a page fault. Four checks, four passes, three byte-identical runs.

    The obvious alternative would be to fix the behavior in silicon, but simple implementations may not want the atomic walker-update logic, so the architecture makes it a runtime bit and standard supervisor software assumes either scheme may be in effect. One bit of configuration replaces a fixed property of the chip, and the trap count tells you who did the writing.

    It's a Trap!

    ISA

    the contract is drawn by the ISA: ecall raises a synchronous trap, sepc, scause, stval, and stvec are CSRs with architected meanings, and sret is the architected return; the software half exists because the manual puts the line where it does.

    MICROARCH

    not at Microarch because the post describes the architectural contract between hardware and software, not how any pipeline implements it; no reordering, prediction, or timing claim appears.

    FIRMWARE

    not at Firmware because the post never leaves S-mode; it describes the kernel's trap entry, handling, and return, and makes no claim about M-mode delegation or boot firmware.

    KERNEL

    the entire software half of the contract is kernel code: uservec saves the registers one by one, usertrap decodes scause and steps past the ecall, kerneltrap asserts the entry conditions, and the timer interrupt drives preemption.

    ALGORITHM

    not at Algorithm because the post describes a control-transfer contract and its failure modes, not a computational method; no algorithm is stated, timed, or compared.

    A user program wants to print two characters. It puts 16 in a7, the number for the write system call, the file descriptor, the buffer address, and the length in a0, a1, and a2, then executes a single instruction: ecall. It cannot touch the UART itself; only the kernel may. Everything after that instruction runs in strict order, and this post follows it: the hardware, the assembly, the C, and the way back.

    The It's a trap meme: Admiral Ackbar at the bridge window, captioned IT'S A TRAP!
    Every trap handler's first words.

    The mechanism is a contract, and the hardware upholds only its half. On the ecall the CPU writes four CSRs and nothing else: sepc gets the address of the ecall, scause gets 8, the code for an environment call from user mode, stval gets zero, and sstatus stashes the old privilege mode and interrupt setting in SPP and SPIE while interrupts go off. Then privilege rises to supervisor mode and the program counter jumps to stvec, which xv6 has pointed at uservec. That is the whole hardware half. What it does not write is any of the 32 general registers: the program's a0 through a2, holding the system call arguments, are still sitting there untouched. They have to be saved because the handler is ordinary compiled code, usertrap, syscall, the write handler, and compiled code keeps its working values in those same registers. Skip saving one and the program resumes with the handler's leftovers in it, then breaks later in innocent-looking code, with nothing at the failure pointing back at the trap.

    THE CONTRACT hardware parkssepcwhere you werescausewhy you camestvalwhich address, on a faultprivilegeraised to supervisorinterruptsoff until sret stvec software savesx1-x31one store per registersstatusSPP: user return; SPIE: irq onsepcresume addr, stepped past ecallstvecre-armed for the next trapkernel/trap.c, kernel/trampoline.S
    The hardware half is automatic and fixed. Everything else is the handler's job.

    That someone is assembly, and it has to be: C cannot run yet, because there is no stack. The opening of uservec, the entry point for traps from user space, faces a puzzle. To save the registers you need a free register to point at the save area, but every register belongs to the interrupted program.

    trampoline.S, uservec (excerpt)
            csrw sscratch, a0  # save user a0 in sscratch so a0 can be used to get at TRAPFRAME.
            li a0, TRAPFRAME
            sd ra, 40(a0)      # save the user registers in TRAPFRAME
            sd sp, 48(a0)
            # ... one store per register ...
            csrr t0, sscratch  # save the user a0 in p->trapframe->a0
            sd t0, 112(a0)

    sscratch is a CSR the handler may clobber, so a0 is parked there and a0 is pointed at the trapframe, the per-process save area. The stores begin, one per register. Thirty stores later the parked a0 is recovered from sscratch and stored last. Nothing about this is automatic: miss one register and the program resumes with the wrong value in it, failing far from the trap with no trace of the cause. Every word the program owned now sits in the trapframe, and the registers are free.

    But C still cannot run. It needs a stack, a page table, and a way to be reached. The tail of uservec builds all three, still in assembly:

    trampoline.S, uservec tail (excerpt)
            ld sp, 8(a0)   # initialize kernel stack pointer, from p->trapframe->kernel_sp
            ld tp, 32(a0)  # make tp hold the current hartid, from p->trapframe->kernel_hartid
            ld t0, 16(a0)  # load the address of usertrap(), from p->trapframe->kernel_trap
            ld t1, 0(a0)   # fetch the kernel page table address, from p->trapframe->kernel_satp.
            # ... fences ...
            csrw satp, t1  # install the kernel page table.
            jalr t0        # call usertrap()

    Four loads from the trapframe: the kernel stack pointer into sp, the hart id into tp, the address of usertrap() into t0, the kernel page table into t1. A fence, the page-table switch, another fence, and then jalr t0: the exact moment assembly hands control to C. Everything the C code will read as p->trapframe->a7 or p->trapframe->a0 was placed there by the stores above. The trapframe is the handoff document between the two languages.

    usertrap() starts by reading what the hardware left behind, before anything can disturb it:

    trap.c, usertrap (excerpt)
      p->trapframe->epc = r_sepc();  // save user program counter.
      if (r_scause() == 8) {         // system call
        // ... killed check ...
        p->trapframe->epc += 4;      // sepc points to the ecall instruction, but we want to return to the next instruction.
        // an interrupt will change sepc, scause, and sstatus,
        // so enable only now that we're done with those registers.
        intr_on();
        syscall();

    Line by line, in order. First the program counter is parked in the trapframe while sepc is still pristine. Then the cause check: scause 8 means this trap was an ecall, a system call. Inside that branch comes the chronological fix this post is really about: sepc still points at the ecall instruction itself, so epc is stepped past it by 4. Return to the unstepped address and the program would re-execute the ecall, trap again, and never make progress. Only now, with sepc, scause, and sstatus consumed, are interrupts enabled; the comment says why, and the order is the point. Then syscall().

    syscall() never touches a real register. It reads the trapframe the assembly filled:

    syscall.c, syscall (excerpt)
      num = p->trapframe->a7;
      if (num > 0 && num < NELEM(syscalls) && syscalls[num]) {
        // ... count the call ...
        // Use num to lookup the system call function for num, call it,
        // and store its return value in p->trapframe->a0
        p->trapframe->a0 = syscalls[num]();

    The number comes from trapframe->a7, the exact word uservec stored from the user's a7, holding 16. The dispatch calls the write handler, which fetches its arguments the same way: argraw case 0 returns trapframe->a0, case 1 returns trapframe->a1, case 2 returns trapframe->a2, the descriptor, the buffer, the length, exactly as the program left them. The handler writes the two characters and returns 2, and syscall() stores that return value in trapframe->a0. Note where it is not: the real a0 still holds the trapframe address from li a0, TRAPFRAME. The program's registers will be rebuilt from the trapframe on the way out, so writing the answer into the trapframe is writing the answer into the program's future a0.

    The trap is handled. The return trip is the entry in reverse, and usertrap's last act is to prepare it:

    trap.c, prepare_return (excerpt)
      unsigned long x = r_sstatus();  // set S Previous Privilege mode to User.
      x &= ~SSTATUS_SPP;              // clear SPP to 0 for user mode
      x |= SSTATUS_SPIE;              // enable interrupts in user mode
      w_sstatus(x);
      // ... stvec and trapframe refresh ...
      w_sepc(p->trapframe->epc);      // set S Exception Program Counter to the saved user pc.

    prepare_return() sets everything sret will need. Interrupts go off first, because a trap landing mid-return would be a disaster. stvec is re-armed to uservec for the next trap, and the trapframe fields uservec will need next time are refreshed. Then sstatus: SPP cleared to 0, so sret will drop to user mode; SPIE set, so interrupts work there. And sepc loaded with trapframe->epc, the stepped-past address. usertrap then returns the user page-table address in a0, and that return lands directly in userret: uservec's jalr t0 left the return address pointing at the instruction after the jump, which is userret's first line. The C function never really comes back to its caller; it falls into the second half of the assembly.

    trampoline.S, userret tail (excerpt)
            # ... one load per register ...
            ld a0, 112(a0)  # restore user a0
            sret            # return to user mode and user pc. prepare_return() sets up sstatus and sepc.

    The mirror image of the entry. The user page table is reinstalled, then the loads rebuild every register from the trapframe, a0 last, because a0 was needed to point at the trapframe until the final load. That last load is the point of the whole trip: trapframe->a0 holds 2, the write's return value, so the program's a0 comes back carrying its answer. Then sret, and the hardware keeps its half of the contract in reverse: privilege drops to user because SPP is 0, interrupts turn on because SPIE is 1, the program counter becomes sepc, the instruction after the ecall. The program continues and never knew it left.

    One sentence to keep: a trap is a handoff in strict order, hardware to assembly to C and back, and the trapframe is the document they all sign. The assembly writes it, the C code reads and edits it, the assembly restores from it.

    The Comparison That Leaves No Trace

    ISA

    matters at ISA because the integer base keeps no condition flags: blt fuses compare and branch so the verdict goes straight to the program counter, and slt materializes a boolean into a named GPR; both encodings were verified against real assembler output this run, and the single flags register that exists, fflags, is quarantined in its own CSR for IEEE 754.

    MICROARCH

    not at Microarch because the post makes no claim about pipelines or hardware internals; it describes what software must save on a trap, a firmware-visible consequence, not a microarchitectural mechanism.

    FIRMWARE

    matters at Firmware because trap entry must preserve exactly the architectural state, and with no flags register the integer trap frame is the 31 general registers plus the few CSRs the handler actually uses; there is no extra word to spill and no hidden compare state for a nested trap to disturb.

    KERNEL

    matters at Kernel because a context switch saves and restores exactly the named registers; no hidden compare result can leak from one thread into the next, so the switch path carries one fewer piece of state that could be saved wrong.

    ALGORITHM

    not at Algorithm because the post describes where a comparison result lives, not a computational method; no algorithm is stated, timed, or compared.

    A trap can land at any instruction, so the handler's first job is to save everything the interrupted program will want back: the 31 general-purpose registers, x1 through x31, plus the few control registers the handler itself needs. Here is the complete save list from a real M-mode trap entry, excerpted with the pattern intact (full source linked below):

    Ocean waves washing footprints from a beach
    No flags register exists, so the trap save list ends at 34 entries.
    trap.S, M-mode trap entry (excerpt)
    trap_entry:
        csrrw t0, mscratch, t0  # frame address into t0; old t0 parked in mscratch
        sd x1, 0*8(t0)          # store 1 of 31
        sd x2, 1*8(t0)          # store 2 of 31
    # ... x3 through x28, one store each (x5 rejoins from mscratch)
        sd x29, 28*8(t0)        # store 29 of 31
        sd x30, 29*8(t0)        # store 30 of 31
        sd x31, 30*8(t0)        # store 31 of 31: the register list ends here
        csrr t1, mepc
        sd t1, 31*8(t0)         # three CSRs this handler uses
        csrr t1, mstatus
        sd t1, 32*8(t0)
        csrr t1, mcause
        sd t1, 33*8(t0)
    
    trap_bank:
        .space 34*8             # 31 registers + 3 CSRs: the complete frame

    Count the stores with me: thirty-one, x1 through x31, the entire integer register file. Then three CSRs the handler actually uses: mepc, mstatus, mcause. Thirty-four slots, and the frame ends. A context switch carries the same list. There is no thirty-fifth store, because there is nothing else to save: no hidden register where a comparison might have left its verdict.

    Other machines keep a flags register: a compare or an add records its verdict there, and a later branch reads it back. On those machines this list needs one more entry, saved and restored by every handler, even one that never branches, because the interrupted program's next decision might be sitting in it.

    The reason the list ends at thirty-four is in the branch encoding. blt t0, t1, less compares and branches in a single instruction; the verdict exists only in what the program counter does next. Assembled and disassembled this run, rv64g:

    flags.s, objdump -d
    cmp_demo:
        blt    t0, t1, less  # compare and branch; verdict goes to the PC
        li     a0, 0
        ret
    
    less:
        li     a0, 1
        ret

    When the verdict must outlive the branch, it gets a name. slt t0, t1, t2 writes a 1 or a 0 into t0, an ordinary register the allocator can see and the debugger can print:

    flags.s, objdump -d
    bool_demo:
        slt    t0, t1, t2   # the boolean lands in t0, a named register
        bnez   t0, nonzero  # branch reads t0 like any register
        li     a0, 0
        ret
    
    nonzero:
        li     a0, 1
        ret

    The price is real: multi-precision carry chains, the core of bignum arithmetic, take more instructions when the carry must travel through a named register instead of a flag. One workload pays more so that every trap frame stays at thirty-four entries.

    Floating-point exception flags do exist, in their own CSR, fflags, because IEEE 754 requires them. Nothing outside floating-point touches them. Verified this run: csrr t0, fflags assembles cleanly.

    One sentence to keep: the trap frame lists every register there is, and you can check it by counting.

    The Allocator That Stores Its Free List in the Free Pages

    ISA

    not at ISA because every verified claim is about the freelist algorithm and its guards, which hold under any machine contract: the drained page count, the LIFO return order, the 0x01/0x05 junk fills, and the three guard panics are all properties of the list mechanics, and the article asserts no instruction encoding, register, or ABI behavior.

    MICROARCH

    not at Microarch because nothing was timed and no pipeline, cache, or execution behavior was measured: the verified properties are which page comes back and in what order, which hold on any implementation.

    FIRMWARE

    not at Firmware because no boot, machine-mode, or supervisor-interface claim is made: kinit, freerange, kalloc, and kfree are kernel functions exercised against a host arena, and the PHYSTOP bound comes from memlayout.h read as a constant, not executed as firmware.

    KERNEL

    matters at Kernel because kalloc.c is the kernel's physical page allocator: kinit, freerange, kalloc, and kfree are kernel functions, and the verified claims are about kernel memory management, the exact list that feeds user pages, kernel stacks, page-table pages, and pipe buffers.

    ALGORITHM

    matters at Algorithm because the verified mechanism is the freelist itself: a stack threaded through free pages with LIFO return order, PGROUNDUP rounding on unaligned ranges, and one pointer read or write per operation, all proved by the harness independent of the kernel it came from.

    I pointed xv6's page allocator at a 64 MiB arena this morning and watched it drain 16383 pages, every one distinct, aligned, and inside the range. Then I freed three pages, a, b, and c, and asked for three back. It returned c, b, a. The freelist is a stack: last freed, first allocated.

    Empty wooden archive shelves in a 1930s reading room
    The free list lives in the free pages themselves.

    The allocator is 76 lines of C in kernel/kalloc.c, and it stores no metadata of its own. That sounds impossible until you read the struct it is built on, and then the lines that prove it:

    struct run {
      struct run *next;    /* stored in the free page itself */
    };
    r = (struct run *)pa;  /* freeing page pa: the page becomes its own list node */
    r->next = kmem.freelist;
    kmem.freelist = r;

    A free page's first eight bytes hold the link to the next free page. Nothing else is stored in a free page, so the list node lives in the page itself. Allocating is popping the head of the list, one pointer read. Freeing is pushing onto the head, one pointer write, under a single spinlock. Every allocator faces the bootstrap question of where to keep its metadata; xv6 answers by storing it in the free pages themselves.

    The shape works because everything xv6 hands out comes in whole 4096-byte pages: user pages, kernel stacks, page-table pages, pipe buffers. The allocator never thinks smaller than a page, so one link per page is all the metadata it needs, and there is nothing to allocate in order to store it, which matters when the allocator itself is what provides memory. The obvious alternatives each fail one requirement. A bump allocator cannot free, and every page must come back. A buddy allocator coalesces, but costs complexity this teaching kernel refuses to pay.

    The honest cost is the single global list under one lock, and MIT's own locks lab exists to fix exactly that, having students split the allocator into per-CPU freelists with stealing because kalloctest contends on kmem.lock. The file also carries its own tripwires. Freeing fills the page with 0x01 and allocating refills it with 0x05, junk that makes a dangling reference visible. Freeing a misaligned address, an address below the kernel's end, or one at or past the 128 MiB mark panics, all three verified this run. One sentence to keep: xv6's physical memory is a linked list threaded through the free pages themselves, so the allocator stores no separate metadata, and handing you a page costs one pointer read.

    The Variable That Is Not the Same Variable

    ISA

    matters at ISA because the access lowering is fixed by the machine contract: on RISC-V the psABI names tp the thread pointer and Variant I TLS lowers to lui/add/lw off tp, verified in the cross-toolchain disassembly, and on x86-64 the %fs-based addressing lowers to the single instruction mov %fs:0xfffffffffffffffc,%ecx, read verbatim from this run's objdump.

    MICROARCH

    not at Microarch because nothing was timed and no pipeline, cache, or execution behavior was measured: the verified property is which per-thread storage an access lands on, which holds on any implementation.

    FIRMWARE

    not at Firmware because no boot, machine-mode, or supervisor-interface claim is made: the whole experiment runs in Linux userspace, and the thread pointer is installed by the kernel at thread creation, not by firmware.

    KERNEL

    matters at Kernel because the per-thread copy of the template and the installation of the thread pointer happen at thread creation, arranged by the kernel and the loader: the differing addresses with identical initial values prove the copy, and errno, the kernel-visible per-thread variable, behaved the same (worker 5, main 0).

    ALGORITHM

    not at Algorithm because no computational mechanism was constructed or measured: the verified claim is storage identity, which address a name resolves to per thread, read off running threads rather than computed.

    I declared one variable this morning and got two of them. At file scope I wrote __thread int counter = 7;, then main printed the address and value, spawned a worker thread, and the worker printed the same variable's address and value. On this run main saw 0x786b5c3b873c holding 7, and the worker saw 0x786b5c3b76bc holding 7. The worker stored 42 into counter, printed 42, and joined. main printed its counter afterward: 7, untouched. Same name, same line of source, two different pieces of storage.

    Identical twins in school uniforms
    One name in the source, two separate copies, one per thread.

    Threads share the whole address space, so per-thread state is a real problem. errno is the famous case: if every thread wrote to one global errno, one thread's failed read would overwrite another thread's clean slate. C still needs per-thread homes for errno, allocator state, and RNG seeds. The loader's answer is a template. The linker gathers every thread-local variable into a TLS template, described by the PT_TLS segment in the ELF: initialized data lives in .tdata, zeroed data in .tbss. When a thread is born, the loader copies the entire template into fresh memory for it. Each thread also gets a thread-pointer register, %fs on x86-64 and tp on RISC-V, and every access to a thread-local variable is address math off that register.

    The access shape depends on what the linker knows. When the variable is defined in the binary being linked, the offset is fixed at link time and the whole access collapses to a single instruction. A shared library cannot know the offset, because the final program lays out the template, so it gets the general-dynamic model instead: load an index, call __tls_get_addr, use the returned address. The linker even rewrites the lazy form into the fast one when it can prove the variable is defined locally. The shapes, all from this run's disassembly:

        __thread int counter = 7;              /* one name, one copy per thread */
        mov %fs:0xfffffffffffffffc,%ecx        /* x86-64, offset fixed at link time: the whole access is one insn */
        lui a5,0x0; add a5,a5,tp; lw a4,0(a5)  /* RISC-V: the same idea, three instructions off the thread pointer tp */

    Why not the obvious alternatives? pthread keys charge a dynamic lookup on every access, a tax on each read. A context pointer threaded through every function means rewriting every signature. A thread-id-indexed array hashes on every access. The thread pointer is already sitting in a register, so the access costs one load, and the per-thread template copy is what keeps errno, allocator state, and RNG seeds from colliding. One sentence to keep: threads share every address but not every variable, because the loader gives each thread its own copy of the TLS template, and the address of your variable is whatever your thread pointer says it is.

    The Descriptor That Belongs to No Process

    ISA

    not at ISA because the claim lives in the kernel's descriptor tables, not in the machine contract: no instruction encoding, decoding, or extension behavior is exercised, and the verdict (shared open file description, FD_CLOEXEC, EINVAL on reserved flags) is kernel policy, not ISA law.

    MICROARCH

    not at Microarch because nothing was timed and no pipeline, cache, or execution behavior was measured: the verified property is which process's table a descriptor is duplicated from and whose offset a read lands on, which holds on any implementation.

    FIRMWARE

    not at Firmware because no boot, machine-mode, or supervisor interface claim is made: the whole experiment runs in Linux userspace under a stock kernel, and the permission gate (PTRACE_MODE_ATTACH_REALCREDS) is enforced by the kernel, not by firmware.

    KERNEL

    matters at Kernel because pidfd_getfd is a Linux kernel primitive (5.6+, no glibc wrapper): the duplicate refers to the same open file description, so parent and child share status flags and the living file offset, proved firsthand with 3/3 byte-identical reads at the child's offset; the returned descriptor arrives FD_CLOEXEC; reserved flags are refused with EINVAL; and the only gate is PTRACE_MODE_ATTACH_REALCREDS, otherwise EPERM.

    ALGORITHM

    not at Algorithm because no computational mechanism was constructed or measured: the verified claim is what the kernel's descriptor table points at, read off a running process rather than computed.

    This morning I reached into another process's file-descriptor table and took one. The setup was a fork: the child opened an unlinked 20-byte tmpfile holding "0123456789ABCDEFGHIJ", its fd 3, sought to offset 5, and reported the fd number over a pipe. I called pidfd_open on the child, then pidfd_getfd to duplicate fd 3 into my own table. Then I read 15 bytes through the new descriptor with no seek of my own, and got "56789ABCDEFGHIJ": the child's file, at the child's offset. Three runs, byte-identical.

    A close-up of a key with a red arrow on its teeth
    A copy of a key you never handed over.
        long pfd    = syscall(SYS_pidfd_open, child, 0);    /* fd 4 */
        int  stolen = syscall(SYS_pidfd_getfd, pfd, 3, 0);  /* fd 5 */
        char buf[16];
        read(stolen, buf, 15);                              /* "56789ABCDEFGHIJ", the child's offset */

    The two calls are the whole mechanism. pidfd_open turns a pid into a pidfd, a handle on the process itself. pidfd_getfd(pidfd, targetfd, 0) asks the kernel to copy that process's descriptor into your table. The duplicate refers to the same open file description, so the two descriptors share the file status flags and the file offset: the shared offset, which advances as either side reads, not a snapshot. There is no glibc wrapper for either call (Linux 5.6 and up), so both go through syscall(2) directly. Two details the man page promises and the run confirmed: the returned descriptor arrives with FD_CLOEXEC already set, and a flags argument of 1 is refused with EINVAL, because the flags are reserved for future use.

    The usual way to pass a descriptor between processes is SCM_RIGHTS over a Unix domain socket, and it demands two things: a connection already established, and the cooperation of the process whose descriptor is being copied. pidfd_getfd demands neither. It needs only the pidfd and one permission check, PTRACE_MODE_ATTACH_REALCREDS, the same ptrace gate that guards non-dumpable processes. Without that permission it answers EPERM. So this is the supervisor's primitive: no socket, no handshake, no cooperation, just the ptrace permission check, and the duplicate shares the file offset with the original descriptor in the other process.

    One sentence to keep: a file descriptor names an entry in your process's table, but the open file description it points to belongs to no process at all, which is why pidfd_getfd can hand you one.

    The Six Instructions That Run Before Yours

    ISA

    matters at ISA because the reset contract is an ISA promise every hart honors: begin fetching at the reset vector, and the six-instruction ROM (auipc, addi, csrr mhartid, two loads, jr) was decoded instruction by instruction from a live UART dump and matched QEMU 8.2.2 hw/riscv/boot.c byte for byte.

    MICROARCH

    not at Microarch because nothing was timed and no pipeline, cache, or execution-port behavior was measured: the verified claim is the reset ROM's fixed instruction sequence and the equal-treatment result, which hold on any implementation of the reset contract.

    FIRMWARE

    matters at Firmware because the A/B result is a firmware verdict: with -bios none all four harts arrived (the shared counter read 1, 2, 3, 4), while with OpenSBI in the loop only one arrived, since OpenSBI parks the secondaries itself and waits for the operating system to start them; the hart hierarchy lives in firmware, not in the reset hardware.

    KERNEL

    not at Kernel because nothing ran under an operating system: the probe is -bios none bare metal, so no scheduling, system call, or memory-management claim is made or needed.

    ALGORITHM

    not at Algorithm because no computational mechanism was constructed or measured: the verified claim is the fixed six-instruction ROM and the hart-equality result, read off the wire rather than computed.

    On QEMU's virt board with no firmware, every RISC-V hart wakes up at address 0x1000. Sixty-four bytes live there, a tiny ROM that QEMU builds at boot. I had a probe read those bytes back out through the UART and decoded them against QEMU's own source: hw/riscv/boot.c in the 8.2.2 tree, the function riscv_setup_rom_reset_vec. Here is the complete ROM, six instructions:

    A sprinter in the starting blocks
    Every hart runs these six steps first.
        auipc t0, 0        # t0 = 0x1000, the ROM's own address
        addi  a2, t0, 40   # a2 = 0x1028, a pointer to the firmware info block
        csrr  a0, mhartid  # a0 = this hart's number
        ld    a1, 32(t0)   # a1 = 0x87e00000, where the device tree was placed
        ld    t0, 24(t0)   # t0 = 0x80000000, the kernel's entry address
        jr    t0           # and we are gone, off to your code

    Right after the code sit the two addresses it loads: the kernel entry 0x80000000 at 0x1018, and the device-tree address 0x87e00000 at 0x1020. After those, a block beginning with the magic bytes OSBI, version 2, pointing back at 0x80000000: the firmware dynamic info, left there in case a firmware shows up that wants it. Every byte I printed matched the source. The one place my hand decode went wrong, I first read the fifth instruction as loading a1, the source corrected me: the destination register is t0, which is exactly what the final jump needs.

    Then the part I did not expect. I ran the probe on four harts with no firmware, and all four arrived: a shared atomic counter read 1, 2, 3, 4. The reset ROM treats every hart the same. Every hart runs those six instructions and jumps to the kernel. I ran it again with OpenSBI in the loop, and only one hart arrived. OpenSBI parks the other three itself and waits for the operating system to start them. So hart 0 leads and the rest wait, but that boot order is not in the reset hardware at all. It is software's idea, enforced by firmware. Without firmware there is no boot order, just four equals waking at the same address.

    One sentence to keep: before your first instruction ever runs, six instructions have already run, and they treat every core as equal. The hierarchy is policy, not physics.

    The Stack Frame Is Optional

    ISA

    matters at ISA because the frame is built from the ISA's own contract: addi, sd, and ld move the stack pointer under the ABI's 16-byte alignment rule, and the -O2 output is two instructions, addiw and ret, that the manual defines exactly; the whole comparison was verified against real gcc 13.2.0 output.

    MICROARCH

    not at Microarch because nothing was timed and no pipeline, cache, or predictor behavior was measured: the claim is which instructions the compiler emits at each level, and it holds on any implementation.

    FIRMWARE

    not at Firmware because no boot code, SBI call, or privilege transition appears: both listings run entirely in user mode after the program is already loaded.

    KERNEL

    not at Kernel because no system call, trap, or scheduler is involved: the frame is a user-space compiler convention, and the trap path that saves the full register file is a different post.

    ALGORITHM

    not at Algorithm because no computational mechanism is claimed: the function adds one to its input, and the post's insight is the compiler's frame budget, not how the addition works.

    Here is an entire C function compiled two ways. Same source, same compiler, same machine. RISC-V gcc 13.2.0, asked to emit assembly:

    An empty picture frame on a wall
    A frame with nothing in it. Just like -O2.
    next.c
    int next(int x) {
        int y = x + 1;
        return y;
    }

    At -O2, the whole function is two instructions. No stack frame. Nothing is claimed, nothing is parked, nothing is restored. Against the thirteen-instruction version below, the frame simply is not there:

    next.s · -O2
    next:
        addiw   a0, a0, 1
        ret

    The -O0 output, annotated line by line. Assembler directives trimmed; the instruction sequence is complete:

    next.s · -O0, annotated
    next:
        addi   sp, sp, -48  # claim 48 bytes for the frame
        sd     s0, 40(sp)   # park the caller's frame pointer
        addi   s0, sp, 48   # anchor the new frame pointer at the frame's top
        mv     a5, a0       # x arrives in a0; copy it to a scratch register
        sw     a5, -36(s0)  # give x a home address, 36 bytes below the frame pointer
        lw     a5, -36(s0)  # load x back from its address
        addiw  a5, a5, 1    # add 1; word-sized because x is a 32-bit int
        sw     a5, -20(s0)  # give y its address, 20 bytes below the frame pointer
        lw     a5, -20(s0)  # load y back from its address
        mv     a0, a5       # the answer travels home in a0
        ld     s0, 40(sp)   # restore the caller's frame pointer
        addi   sp, sp, 48   # release the frame
        jr     ra           # return; ret is the usual spelling of this jump

    Forty-eight bytes is roomier than the sixteen the data strictly needs. The unoptimized compiler does not pack tightly, and the ABI requires the stack pointer to stay 16-byte aligned at all times.

    One thing is missing from the longer listing: the return address is never saved. The compiler proved this is a leaf function, a function that calls no other function, so nothing in it can overwrite the return address and saving it would be pure waste. That is the exact reasoning the frame shop drills into you: the return address gets parked because a nested call would destroy it. No nested call, no parking. The compiler applies the rule where it saves work and skips it where it does not.

    Why does -O0 emit all these frame instructions? The unoptimized compiler has one simple strategy: every local gets a real address in the frame, so a debugger can inspect every variable at any moment and code generation stays simple and predictable. The frame pointer exists so those addresses never move while the function runs. It is built for humans and debuggers, not for the machine.

    Why does -O2 delete it? The optimizer proved three things: no address of any local is ever taken, the whole computation fits in registers, and the function is a leaf. With nothing to keep and no reason to touch the stack, the frame is pure overhead. Gone. The function is the addition and the return. Everything else was overhead.

    One sentence to keep: the stack frame is not a law of the machine; it is a budget the compiler spends only when the function needs it.

    The Width the Program Never Asks For

    ISA

    matters at ISA because the verified properties are the concrete vsetvli semantics (rd = new vl, rs1 = AVL), the VLMAX = VLEN x LMUL / SEW identity, and the firsthand UART readings vl=4/8/16 across VLEN 128/256/512 from the same unmodified ELF.

    MICROARCH

    not at Microarch because nothing was timed and no pipeline, cache, or execution-port behavior was measured: the verified claim is the negotiation contract, which holds identically on any VLEN implementation.

    FIRMWARE

    matters at Firmware because the experiment depends on a firmware action: boot.S sets mstatus.VS=0x600 (VS=Initial) at machine mode before any vector instruction executes, and without that firmware handoff every vector instruction traps.

    KERNEL

    not at Kernel because nothing ran under an operating system: the program is -bios none bare metal, so no scheduling, system call, or memory-management claim is made or needed.

    ALGORITHM

    matters at Algorithm because the strip-mining shape, re-ask every iteration and advance by the returned vl, is the portable loop idiom the spec's middle-band clause demands, and it removes the scalar tail epilogue by construction.

    I built one bare-metal binary this morning, a ten-element vector add with a strip-mining loop, and ran the identical file under QEMU at three different vector widths. At VLEN 128 it reported vl=4 for sixteen remaining 32-bit elements. At VLEN 256, vl=8. At VLEN 512, vl=16. Asked for a huge request it returned exactly VLMAX; asked for one element it returned one. All three runs printed PASS. Zero changes to the binary on three different machines, because the program never once assumed the width.

    An adjustable spanner wrench
    One wrench fits every width. So does vsetvli.

    The negotiation is a single instruction: vsetvli. Give it how many elements remain, plus the element width and the register grouping you want, and it writes back the vl you actually get. The loop re-asks every iteration and advances by whatever came back. The two lines that carry the whole discipline, inside a loop that runs while elements remain:

        unsigned long vl = vsetvli_e32m1(n);
        a += vl; b += vl; c += vl; n -= vl;

    VLMAX, the most elements one instruction can touch, is the register width times the number of registers you group, divided by the element width: VLEN times LMUL divided by SEW. At VLEN 128 with one register and 32-bit elements that is four, exactly what the machine reported. The spec's contract is three lines: vl equals the request when the request fits, vl equals VLMAX when the request is huge, and in between, an implementation may hand back fewer lanes to balance the final two iterations. That middle clause is why the loop re-asks every time instead of caching the first answer. Ten elements on a four-lane machine go 4, 4, 2. There is no scalar cleanup loop at the end. The leftover elements are handled by the same re-asking loop.

    On x86 the width is baked into the opcode: xmm, ymm, and zmm are different instructions, so one binary cannot be width-agnostic and libraries ship several compiled paths with runtime dispatch. RISC-V does not bake the width into the opcode. The width lives in the machine, not the program, and vsetvli is the negotiation at the boundary. Two footnotes, both honest. At machine mode I had to set the VS bits in mstatus before any vector instruction would execute: the extension is gated even when present. And QEMU's adjustable VLEN is a test convenience. Real silicon fixes VLEN per chip, which is exactly why the negotiation matters.

    One sentence to keep: RISC-V vector code never asks the machine how wide it is, it asks how many elements it may do, and the machine returns the vl, every single iteration.

    The Most Honest Lie in C

    ISA

    matters at ISA because the verified properties are the concrete RISC-V instruction sequences gcc emits for memset at -O2: eight sb zero stores inline for the 8-byte call, a tail call to memset for the 16-byte call, a 32-iteration sb loop for the volatile-pointer wipe, and four sd zero stores surviving the compiler barrier, each read off the object disassembly firsthand this run.

    MICROARCH

    not at Microarch because the verified properties are the compiler's compile-time instruction choices, not the behavior of the machine executing them: nothing was timed, no buffer or line was measured, and the same objects would carry the same argument on any RV64 implementation.

    FIRMWARE

    not at Firmware because no firmware contract is involved: the objects were compiled and read with objdump, never linked into a boot image and never booted, so trap delegation and the machine-mode handoff never enter the argument.

    KERNEL

    matters at Kernel because the second half makes explicit kernel claims: the kernel may page the secret's anonymous page to the swap device at any time, and the mlock, munlock, and RLIMIT_MEMLOCK sequence is a system-call contract with the kernel's memory manager. Those claims rest on the cited manual and documentation pages; the firsthand bench work here remains compile-and-read, nothing was executed.

    ALGORITHM

    matters at Algorithm because the verified properties are the portable optimizer contract every language with an as-if rule shares: stores to provably dead memory may be deleted, and a compiler barrier declaring memory observable elsewhere restores the wipe, which is the explicit_bzero bargain and the memset_s contract.

    I compiled two one-line functions this morning, gcc 13.2.0 at -O2 for rv64g, and read the disassembly. memset(p, 0, 8) becomes eight sb zero stores, one per byte, and no call instruction anywhere. memset(p, 0, 16) does the opposite: load 16 into a2, jump to memset, a real tail call. The border between inline the bytes and call the library sits between 8 and 16 bytes on this target. The compiler is not running your function. It is choosing the implementation from the size.

    A chalkboard wiped clean
    You wrote the wipe. The binary never did.

    The decision that matters lives in a dumber function. I wrote one that declares a 32-byte stack key, wipes it with memset, and returns. Its compiled body, the whole of it:

    0000000000000044 <secret>:
      44:   00008067    ret

    One instruction: ret. The wipe is gone. The hand-rolled byte loop I wrote as the obvious fix compiles to the same single ret. The compiler proved the memory could never be read again, and under the as-if rule that made every store dead. You can see the wipe in the source. It is not in the binary.

    The as-if rule is the contract behind the deletion. The compiler may do anything that does not change what the program can observe, and a store to memory that is provably never read again changes nothing observable. So it deletes the stores, the call and the loop alike. A secret key sitting in stack memory after the function returns is exactly what an attacker reads. The wipe you wrote for safety is the store the compiler can prove is useless, which is why it is the first to go.

    Two spellings survived my objects. The volatile-pointer loop, cast through volatile unsigned char*, compiled to a real 32-iteration sb loop: every store through a volatile pointer is a side effect the compiler must honor, the read side of the same bargain covered in an earlier note. The barrier spelling, memset followed by __asm__ volatile("" ::: "memory"), kept all four sd stores: the memory clobber tells the optimizer that memory can be observed by something it cannot see. glibc ships exactly this bargain as explicit_bzero, memset plus a compiler barrier, with the promise that the call will not be deleted even when the buffer is dead afterward [2]. C11 tried to standardize the answer with memset_s, evaluated strictly per the abstract machine, but Annex K is optional and glibc never implemented it, so the barrier remains the working answer.

    This is not a theoretical hazard. Yang, Johannesmeyer, Olesen, Lerner, and Levchenko examined eleven open-source security projects in a 2017 USENIX Security paper [6] and found four with flawed memory scrubbing, plus four more that owned a scrubber and used it inconsistently. Eight of eleven, wrong in two different ways. The compiler was never working against you. It applied the as-if rule, and the rule said those stores could go. One sentence to keep: memset is a request the compiler is allowed to deny, so wiping a secret takes not just a function call but a barrier that stops the optimizer from deleting the stores.


    Update, , prompted by a reader

    The wipe can survive and still lose. There is a second deletion that no compiler barrier stops: the kernel paging the secret to swap. Watch the shape where this applies clearly.

    char *key = malloc(32);
    read_key(key);
    serve_clients(key);
    explicit_bzero(key, 32);
    free(key);

    The wipe ran. The 32 bytes in RAM are zero. But the kernel was free to page that anonymous page out to the swap device at any point while the secret sat there, and page it back in when the process touched it next. The copy on disk was written before the wipe and is never touched by the wipe. It outlives the process. Anyone with read access to the swap device or a disk image of it, a forensics capture, or the disk of a stolen unencrypted laptop, reads the key in the clear. Encrypted swap closes this particular window; disabling swap closes it more completely [3]. Your program cannot observe the kernel doing this: paging is transparent to the running process, so nothing in your code can tell you whether that disk copy exists.

    The fix is to tell the kernel the pages are not pageable, and to do it before the secret arrives:

    char *key = malloc(32);
    if (mlock(key, 32) != 0)
        exit(1);              /* no lock, no secret */
    read_key(key);
    serve_clients(key);
    explicit_bzero(key, 32);  /* locked */
    munlock(key, 32);
    free(key);

    Three details carry the whole fix. First, the lock comes before the secret, because a page already written to swap is already lost. Second, the mlock return value is checked: the call can fail, the per-process lock limit RLIMIT_MEMLOCK is the usual reason, and an unchecked failure is the same as no lock. Third, the wipe happens while the pages are still locked: munlock marks the pages swappable again, so wiping after the unlock reopens the window. libsodium gets this ordering right, zeroing the memory in sodium_munlock before the pages become swappable again [3].

    When does this not apply? Two conditions have to hold for the risk to be real: the secret sits in ordinary pageable memory, and the process lives long enough under enough memory pressure for the kernel to page it out. A TLS server holding its private key for weeks on a machine with swap: applies. A password checked and dropped in the same second on a box with no swap: does not.

    What the six sources say, each in one line. OpenSSL documents the wipe half: OPENSSL_cleanse fills ptr with zeros, and its clear_realloc and clear_free "should be used when the buffer at addr holds sensitive information", zeroizing the old buffer before freeing it [1]. The OpenBSD manual states the wipe half as the reason explicit_bzero exists: it "will not be removed by a compiler's dead store optimization pass, making it useful for clearing sensitive memory such as a password"; the swap control lives one man page over, in mlock(2) [2]. libsodium is the one source that names swap directly and hands you the mechanism: sodium_mlock "can help avoid swapping sensitive data to disk", its guarded allocator locks memory by default, and it recommends disabling swap or using encrypted swap [3]. The book states the general law: wipe a secret's storage location as soon as it is no longer needed, because a page the kernel copied to swap is a storage location you can no longer wipe [4]. The secure-coding standards state the wipe as curriculum: inspect the optimized release assembly, because if the compiler optimizes out memory-clearing code, an attacker can gain access to sensitive data [5]. The USENIX paper measured the compiler half against eleven open-source security projects: four with flawed scrubbing, four more with a scrubber used inconsistently [6].

    One more sentence to keep: a wipe that survives the compiler cleans only RAM, because the kernel may already have copied the secret to swap, so lock the pages before the secret arrives. The working review habit checks the pair in that order: lock first, then a wipe the optimizer cannot delete. Lock without a wipe leaves the live copy; a wipe without a lock leaves the swapped copy.

    Sources

    1. 01
      OpenSSL documentation: OPENSSL_cleanseOpenSSL Project

      The manual's wipe half, stated plainly: OPENSSL_cleanse() fills ptr of size len with a string of 0's, and OPENSSL_clear_realloc() and OPENSSL_clear_free() 'should be used when the buffer at addr holds sensitive information', zeroizing the old buffer via OPENSSL_cleanse before freeing it.

    2. 02
      explicit_bzero(3), OpenBSD manual pagesOpenBSD

      The manual states the wipe half as the reason the function exists: explicit_bzero 'will not be removed by a compiler's dead store optimization pass, making it useful for clearing sensitive memory such as a password'. The swap control lives one man page over, in mlock(2).

    3. 03
      Memory management, libsodium documentationlibsodium

      The one source that names swap directly: sodium_mlock 'locks at least len bytes of memory starting at addr. This can help avoid swapping sensitive data to disk.' Locking can fail because operating systems limit locked memory, so sodium_mlock returns -1 on failure; sodium_munlock zeroes the memory before making the pages swappable again; the guarded allocator locks by default and may use MAP_NOCORE or MADV_DONTDUMP. The docs recommend disabling swap on machines handling sensitive data, with encrypted swap as second choice, and disabling core dumps.

    4. 04
      Cryptography Engineering: Design Principles and Practical ApplicationsWiley, 2010. Ferguson, Schneier, Kohno

      Chapter 21, 'Storing Secrets', section 21.10, 'Wiping Secrets': states the general law that a secret's storage location should be wiped as soon as the secret is no longer needed. A page the kernel copied to swap is a storage location you can no longer wipe, which is the gap this section warns about.

    5. 05
      SEI CERT C Coding Standard, MSC06-CCarnegie Mellon SEI

      The standard's canonical instance: a memset meant to clear a password can be removed by compiler optimization when the buffer is never read afterward, so the optimized release assembly must be inspected to confirm the clearing survived. Risk assessment: 'If the compiler optimizes out memory-clearing code, an attacker can gain access to sensitive data.'

    6. 06
      Dead Store Elimination (Still) Considered HarmfulUSENIX Security 2017. Yang, Johannesmeyer, Olesen, Lerner, Levchenko

      Examined eleven open-source security projects: four used flawed scrubbing techniques that may fail to scrub sensitive data, and four more owned a scrubbing function but used it inconsistently. The paper the post's compiler half is measured against.

    The Division That Always Answers

    ISA

    matters at ISA because the verified properties are the division corner cases the unprivileged specification's table defines: the quotient of division by zero has all bits set, the remainder of division by zero equals the dividend, and signed overflow, only possible when the most-negative integer is divided by -1, yields the dividend as quotient and zero as remainder. The post verifies the instruction's answers against the manual's table on every input.

    MICROARCH

    not at Microarch because the verified property is implementation-invariant: the same eight answers come back on QEMU 8.2.2 and on any RV64 core, since the spec table fixes the outputs; the post verifies the div and rem contract, not how any divider circuitry produces all-ones.

    FIRMWARE

    not at Firmware because the verified property holds in every privilege mode with no enable gate: no firmware register opens or closes the division answers, and the eight cases ran without consulting any machine-mode service.

    KERNEL

    matters at Kernel because the verified property removes a trap class the kernel would otherwise handle: the div instructions cannot fault on any input, so a RISC-V kernel carries no divide-error handler and its trap path never receives arithmetic distress from ordinary division.

    ALGORITHM

    matters at Algorithm because the verified properties are the portable edge-case contract that code reasoning about division depends on: every input has a defined answer with no trap and no flag, so divisor-zero handling can rely on the all-ones quotient and dividend remainder without a guarding branch.

    I wrote an eight-case assembly program this morning and read its answers off the virt UART on QEMU 8.2.2. Signed 10 divided by 0: all bits set, which reads as -1. Unsigned 10 divided by 0: all bits set, two to the 64th minus one. Signed and unsigned remainder of 10 by 0: both hand back the dividend, 10. The most-negative 64-bit integer divided by -1: the most-negative integer itself, with a zero remainder. A 32-bit divw of the most-negative 32-bit integer by -1: sign-extended 0x80000000. And the sanity case, 22 divided by 7: 3. No trap fired, no flag was set, the exception handler was never consulted. Eight answers to eight questions, three of them undefined in ordinary mathematics.

    A Magic 8-Ball answering DON'T COUNT ON IT
    Ask anything, even division by zero. It answers.
        li   a0, 10
        li   a1, 0
        div  s0, a0, a1
        jal  ra, print

    This is not emulator generosity. It is the contract, printed in the unprivileged manual's division corner-case table. The quotient of division by zero has all bits set. The remainder of division by zero equals the dividend. Signed division overflow, which can only happen when the most-negative integer is divided by -1, yields the dividend as the quotient and zero as the remainder. The hardware answers exactly what the table says, on every input, without exception.

    The manual says why, in one plain sentence. The designers considered raising exceptions on integer divide by zero, but this would be the only arithmetic trap in the standard ISA. Floating-point exceptions set flags and write default values but never trap, and the integer side refuses to be the exception to that rule. Where a language standard mandates that divide-by-zero changes control flow, a single branch instruction after the divide is enough, one the manual notes should be very predictably not taken. And all-ones is the natural value for divider circuitry to produce, for both signed and unsigned, which simplifies the hardware. The refusal to trap and the all-ones answer are the same decision: keep the divider simple, with a fixed answer for every input.

    That leaves the alternatives, and they both lose something. x86's idiv, as I understand it, raises a divide-error fault on these inputs: the processor suspends your program and hands you to a trap handler, because x86 answers arithmetic faults with interrupts. Floating-point division answers differently again: it completes the operation and sets the NV flag to mark what happened, which was the subject of an earlier note. RISC-V's integer division takes the third path: no trap, no flag, just the defined answer.

    The practical shape of this is worth naming. Because div and rem are total functions, defined on every input pair, the edge case stops being special and becomes just another value to compute with. Code that divides can reason about divisor zero as arithmetic on the answers, all ones and the dividend, instead of exception handling around the call. The hardware implements the table, and the table covers every input.

    One sentence to keep: ordinary arithmetic never traps in RISC-V, so division by zero gets an answer instead of an exception, all ones for the quotient and the dividend for the remainder.

    The ID Card Inside Your CPU

    ISA

    matters at ISA because the verified properties are the misa CSR semantics the privileged specification defines: MXL equals 2 maps to RV64, twenty-six bits name the extension alphabet A through Z, G is the IMAFD plus Zicsr plus Zifencei shorthand with no G bit stored, and the WARL extensions field reverts cleared extensions to reserved behavior. The post verifies register semantics from the spec text.

    MICROARCH

    not at Microarch because the verified property is implementation-invariant: the same sixteen digits come back on QEMU 8.2.2 and on any RV64 core with these extensions; the post verifies the register's contract, not how any core implements it.

    FIRMWARE

    matters at Firmware because the verified properties are the ones boot code consumes: one CSR read names the whole machine for firmware that did not choose the chip, and the sign-bit bootstrap derives MXLEN as two to the power of (MXL plus 4) before the firmware knows the register width it stands on.

    KERNEL

    not at Kernel because the verified property is privilege-invariance: the register is unreadable below machine mode, so kernel code reaches misa only through environment calls; the post verifies the machine-mode gate, which holds identically for every kernel.

    ALGORITHM

    not at Algorithm because the decode is a table lookup against the manual, not a portable computation: no invariant survives translation out of the RISC-V register encoding, and the hand decode checks a contract, not a mathematical property.

    I wrote a thirty-four-line assembly program this afternoon whose entire job was one instruction: csrr s0, misa. It printed sixteen hex digits over the virt UART on QEMU 8.2.2 and then parked: 80000000001411ad. You can read that number by hand and it names the whole machine. The top two bits are 10, MXL equals 2, which the privileged manual's Table 11 maps to RV64. The lower twenty-six bits are one per letter of the alphabet, bit 0 for A through bit 25 for Z, and 0x1411ad lights exactly A, C, D, F, H, I, M, S, U. QEMU's virt board is RV64IMAFD, the general-purpose set, plus compressed instructions and the H, S, U privilege modes. One read, one register, the entire alphabet.

    A Norwegian national ID card specimen
    One card read names the whole machine.
    _start:
        csrr s0, misa            # the ID card, read whole
        li   t1, 0x10000000      # virt UART base
        li   t2, 16              # 16 nibbles

    Getting that read was the first lesson, and it arrived before the program ever ran. The assembler refused the instruction: unrecognized opcode, extension zicsr required. CSR access is itself an extension, so you must pass _zicsr in -march before the chip will answer what it has. The ID card sits behind a door that is itself one of the things the card lists. I confirmed the refusal and the fix both ways with the same three lines of assembly.

    Why keep such a register at all? Because the firmware that reads it runs on chips it did not choose. One CSR read names the width, the alphabet, and the privilege modes, everything early boot needs before it can trust anything else. The encoding even carries its own bootstrap: branch on the sign of misa and you learn MXLEN as two to the power of (MXL plus 4) without knowing the register width of the machine you are standing on. On x86 the same question goes through the CPUID leaf-selection dance, as I understand it; here it is one register and one read.

    The manual is honest about what the card is and who holds it. It calls misa 'a rudimentary catalog of CPU features to machine-mode code', and it forbids lower privilege levels from reading it at all. Supervisor and user code must ask through environment calls, which means a hypervisor can present a different ISA than the silicon underneath. The ID card stays in machine mode's hands so the firmware decides what ISA the layers below see.

    One footnote is worth the whole read. The extensions field is WARL, write-any-read-legal: clear a bit and that extension's instructions revert to their reserved behavior, as if the extension were not implemented. Software can de-feature the chip on purpose, to walk the fallback path and prove it works. An ID card you can edit, to rehearse being a lesser machine.

    One sentence to keep: the chip carries its own ID card, one read names its width and its alphabet, and the manual keeps the card in machine mode's hands so the firmware decides what the layers below see.

    The Eight Bytes That Became Four

    ISA

    matters at ISA because the verified properties are what the psABI contract says the call sequence may become: AUIPC plus JALR relaxes to a single JAL inside minus one mebibyte to plus one mebibyte minus two, and R_RISCV_CALL_PLT names the destination while R_RISCV_RELAX names nothing at all. The post verifies relocation semantics from the spec text.

    MICROARCH

    not at Microarch because no pipeline, cache, or predictor behavior was measured or is at issue: the before and after are linker-time bytes, and the distance test is a static layout check, not a property of any core.

    FIRMWARE

    not at Firmware because no privilege contract enters: the relocation table, the auipc and jalr encodings, and the psABI rule live entirely in the build toolchain and the ELF contract, needing no trap, no delegation, and no machine-mode enable gate.

    KERNEL

    not at Kernel because no address translation, scheduling, or syscall behavior is verified: the shrink happens before the program ever runs, and the addresses the linker rewrites are link-time layout facts, not runtime mappings.

    ALGORITHM

    not at Algorithm because the mechanism is a toolchain rewrite, not a portable computation: no invariant survives translation out of the RISC-V toolchain, and the range test is a linker policy on instruction bytes, not a mathematical property.

    Disassemble a RISC-V object file and look at a call. Where the C source had one function call, you find two instructions: auipc ra, 0x0 followed by jalr ra. Eight bytes of conservative reach. Link the same objects with the default linker and disassemble again. The pair is gone, and in its place stands one instruction: jal 80000016 <target>, encoding 0x00e000ef. The .text section shrank from 40 bytes to 36, exactly the four bytes the auipc had cost. Run the link a second time with --no-relax and the pair survives, both instructions standing where the compiler left them. The control experiment is what turns the observation into an argument.

    A lane-merge road sign, two lanes becoming one
    Two lanes in, one out. Relaxation in action.
    auipc   ra, 0x0      ; R_RISCV_CALL_PLT -> target()
    jalr    ra           ; R_RISCV_RELAX -> *ABS*
    linked, relaxation on:
    jal     80000016 <target>      ; 0x00e000ef
    .text: 40 bytes -> 36 bytes

    The compiler writes the call that works everywhere because it writes blind. target() lives in another translation unit, and at compile time its address is genuinely unknowable. So the compiler emits the sequence that reaches anywhere: auipc covers plus or minus two gigabytes, jalr carries the low twelve bits, and together they can call any address in a flat four-gigabyte window. To ask for a short jump at compile time is to ask the compiler to know the layout, the one thing it cannot see.

    The linker is the one moment in the whole toolchain when someone sees the entire layout at once. The RISC-V ELF psABI names the rule: an AUIPC plus JALR pair may be relaxed to a single JAL when the procedure sits within minus one mebibyte to plus one mebibyte minus two of the call site. When that distance test passes, the linker deletes the auipc and emits the single jal. Nothing else moves except the bytes after the deleted instruction, whose addresses the linker fixes up. Eight bytes in, four bytes out, decided by a range check.

    How does the linker know it is allowed to touch the sequence at all? The relocation table says so. The auipc line carries two relocations. R_RISCV_CALL_PLT names target(), the destination. R_RISCV_RELAX points at *ABS*, absolute nothing. It names no destination at all. The relaxation annotation is a permission slip taped to the instruction sequence itself, separate from the relocation that says where the call goes. The address answers where. The slip answers whether the sequence may be rewritten.

    Two footnotes from the spec text, both confirmed in the same session. First, R_RISCV_CALL itself is deprecated; the psABI says to use R_RISCV_CALL_PLT instead, and the compiler obliged, emitting CALL_PLT even for a plain static non-PIC call. Second, the assembler manual notes that a region marked .option relax emits R_RISCV_RELAX even when the linker would not relax. The compiler marks the sequence as a candidate; the linker decides. The mark is a request, not a promise.

    One sentence to keep: the compiler writes the call that works everywhere, and the linker, once it finally knows the addresses, replaces the pair with the single jal.

    The Register That Is Always Zero

    ISA

    matters at ISA because the verified properties are instruction encodings and their architecturally defined semantics: mv a0,a1 assembles to addi a0,a1,0 and disassembles as 0x00058513, the nop, ret, neg, and csrr idioms are writes to x0 ignored or reads from x0 as zero, and the manual's own sentences fix the canonical NOP and its cost rationale. The post verifies what the contract says the mnemonics mean.

    MICROARCH

    not at Microarch because the post's only implementation-adjacent sentence, the manual's claim that ADDI is the cheapest NOP across a range of systems, arrives as a rationale quoted from the spec and never as a measured property of any pipeline or core: the verified facts are assembler input and disassembler output, identical on every implementation that honors the contract.

    FIRMWARE

    not at Firmware because no privilege-level contract enters the argument: csrr a3,mstatus appears only as an encoding idiom, csrrs with rs1 set to x0 so the read happens without a write, and the verified properties, assembler and disassembler behavior plus spec sentences, need no trap, no delegation, and no machine-mode enable gate.

    KERNEL

    not at Kernel because the argument never leaves user-visible assembler and contract text: no scheduling decision, no address mapping, and no syscall or driver behavior is verified anywhere in the post, and the question it answers is what the mnemonics mean, not what the supervisor does.

    ALGORITHM

    not at Algorithm because every idiom is x0 semantics made concrete: each line names the zero register as a source or a destination of a RISC-V instruction, so the family cannot survive translation to another instruction set as a portable mechanism. The mnemonics differ; the contract's zero is what they share.

    Type mv a0, a1 and ask what the machine executes. There is no MOV instruction in the base ISA, not even an opcode for one. What runs is addi a0, a1, 0, encoding 0x00058513, which I read off my own objdump this morning: opcode 0x13, funct3 000, rs1 = a1, immediate = 0, destination = a0. A move is an add against x0, the register that always reads zero. The assembler never told me it was doing arithmetic. The hardware never had to learn what 'move' means.

    The Event Horizon Telescope image of the M87 black hole
    x0, where unwanted results vanish forever.

    Once you see it, the whole family lines up:

    mv   a0, a1         addi  a0, a1, 0        ->  0x00058513
    nop                 addi  x0, x0, 0        ->  0x00000013
    ret                 jalr  x0, 0(ra)        ->  0x00008067
    neg  a5, a6         sub   a5, x0, a6       ->  0x410007b3
    csrr a3, mstatus    csrrs a3, mstatus, x0  ->  0x300026f3

    Read left to right, each line is the same trick. A nop is an add whose result is discarded into x0, so nothing happens, and the manual names addi the canonical NOP because it is 'most likely to take fewest resources to execute across a range of systems': the instruction reads one register, and address-generation units already execute base-plus-offset math with hardware they have, while a register-register add would need extra hardware. A ret is a jump to the return address with the new link discarded into x0. A negate is a subtract from zero. A CSR read is a csrrs with rs1 set to x0, reading the register while the 'write' lands in the ignored register. Even addi x0, x0, 1, which is 0x00100013, assembles without complaint. The architecture simply ignores the write.

    Here is the why. Register fields are five bits wide, thirty-two slots, and every instruction format has fixed operand positions. Sometimes an instruction needs a source it will not really use, or a destination it will not keep. Spend one of those thirty-two encodings on a constant zero and the ISA never needs a MOV opcode, a RET opcode, a jump-without-link opcode, or a compare-against-zero immediate. Zero is available anywhere a register operand fits, so the hardware implements a dozen idioms and the assembler invents the friendly names.

    The alternatives all cost more. x86 zeroes a register with xor eax, eax, a real instruction that writes the register file and rewrites the flags; RISC-V's li rd, 0 is one addi with no flags to touch, because there are none. ARM had the same idea but spent its last register, x31, and dual-purposed it as the stack pointer in stack instructions, so 'register 31' means zero or SP depending on context; RISC-V kept x0 unambiguous, always zero, no context to track. The idea is inherited rather than invented: MIPS had $zero first, and RISC-V kept the good part. The honest boundary is that it is not free, only cheap: a physical register file still has to make x0 read zero, one small constant mux, and the ISA really has thirty-one writable integer registers, one slot spent on the constant.

    The discarded-write side is the part I keep returning to. x0 is the architecture's bit bucket: anything you do not want back, aim at x0. My own spinlock's unlock path does exactly this: sw zero, 0(%0), the zero alias, clearing the lock in one store with no register spent holding the constant. (An AMOSWAP with x0 as the destination would perform the atomic store and throw the returned old value away, the same bit-bucket trick at the atomic level.) One methodology note, because the encodings above were the exhibit: binutils defaults to the C extension, so my first objdump session handed me compressed forms (mv came back as 0x852e, ret as 0x8082); the 32-bit forms quoted here are what you get with .option norvc. When the encoding is the exhibit, turn the compressor off first.

    One sentence to carry away: RISC-V spent one of its thirty-two register encodings on the number zero and bought move, negate, return, jump, compare-with-zero, and a bit bucket, without adding a single opcode.

    The Conditional Move RISC-V Added as Two Instructions

    ISA

    matters at ISA because the verified properties are instruction semantics and encodings: czero.eqz means zero-unless and czero.nez means zero-if, objdump round-trips the pair as 0ec5d533 and 0ec5f533 one funct3 bit apart, and the spec's own sentences fix the shape. The refusal of predication and flag-based moves is the ISA's design philosophy stated as architecture, and the post verifies the contract's text.

    MICROARCH

    not at Microarch because the post's only implementation story, cores fusing a short forward branch over a single ALU op, arrives explicitly as a debated report rather than a verified property: the spec sentence quoted is about what implementations do not need, no core's behavior was measured, and the verified facts stay on the contract side.

    FIRMWARE

    not at Firmware because nothing in the post runs at firmware's privilege level or uses its services: the verified facts are assembler input, disassembler output, compiler output, and spec text, and czero needs no trap, no delegation, and no machine-mode enable gate.

    KERNEL

    not at Kernel because no kernel mechanism enters the argument: the post verifies instruction encodings, compiler output, and spec sentences, and the select lowering it shows is a compiler's code-generation rule, not a privilege or scheduling contract.

    ALGORITHM

    not at Algorithm because the lowering is spelled in Zicond instructions: cond ? x : y as OR of czero.eqz and czero.nez exists only where the extension does, so it is an ISA-specific idiom rather than a portable computational mechanism, and the motivating lab's checks judge a C construction, not this lowering.

    Pick x when the condition holds and y when it does not, with no branch. Base RISC-V has no instruction for that. An earlier letter built a branchless binary search on the ISA anyway: each iteration's comparison produces a 0/1 integer, and the search window is steered with integer arithmetic alone, no data-dependent branch in the loop body. It works, and it is honest code. But the shape shows an instruction is missing.

    A manual railway switch beside the tracks
    The railroad switch: pick a path, branch never taken.

    The missing instruction was deliberate, and the rejected designs are worth naming, because the new instructions only make sense against them. ARM-style predication, where nearly every instruction carries a condition, was refused as decode cost paid on every fetch. The x86 conditional-move family was refused because it needs a condition-flags register, and the ISA pointedly does not have one. The Zicond spec's own architecture comment says the quiet part out loud: defining more comparisons does not offer a benefit, given the lack of immediates or an additional register operand to compare against. Minimalism is structural here, not decoration.

    The addition, when it came, is two instructions. czero.eqz rd, rs1, rs2 puts zero in rd if rs2 equals zero, otherwise it moves rs1 into rd. czero.nez is the mirror: zero in rd if rs2 is nonzero, otherwise move rs1. Zero this, unless. The spec gives the reason for this shape and no other: a simple solution that provides most of the benefit and all of the flexibility one would desire for conditional arithmetic and conditional select, while staying true to the RISC-V design philosophy. Branchless sequences come out in typically two instructions, and the spec names the price of admission: no instruction fusion, no special provisions during decoding, and no other microarchitectural provisions.

    The canonical lowering is worth seeing once. cond ? x : y becomes three lines:

    czero.eqz t0, x, cond
    czero.nez t1, y, cond
    or        rd, t0, t1

    Each line glossed: the first yields x when cond is nonzero and 0 otherwise. The second yields y when cond is zero and 0 otherwise. The OR keeps exactly the surviving side. That is the rule a Go compiler proposal uses for RVA23 targets. No branch, no flags: three instructions where the branchy version needed a label.

    The toolchain knows the name already. This run assembled both mnemonics with binutils 2.42 and the disassembler round-tripped them: czero.eqz a0,a1,a2 is 0ec5d533, czero.nez is 0ec5f533, one funct3 bit apart. But gcc 13.2.0, handed -march=rv64imac_zicsr_zicond, accepts the extension string and still emits beq plus mv for the textbook gate (c ? x : 0) and for the two-way select. The assembler knows the word. The compiler has not learned to reach for it.

    Honest boundaries, as always. Zicond is an extension, not base: the ratified RVA23 profile made it mandatory for application processors, but portable code still cannot assume it. This note assembled and disassembled the two instructions and never executed them, so its claims are about encodings and semantics, not about silicon. The one implementation story in the neighborhood, cores fusing a short forward branch over a single ALU op in hardware, arrives as a debated forum thread rather than a measured fact, and the note treats it that way.

    The thread back to the branchless search: for years x86 shipped a conditional move the RISC-V base ISA left unnamed. It has a name now, and the two spellings differ in one funct3 bit. One sentence to keep: RISC-V left the conditional move out until it could add it in two instructions, and the addition is spelled 'zero this, unless.'

    The Receipt for the Bit That Fell Off

    Relevance by layertest log
    ISA

    matters at ISA because the verified property is the F-extension's inexact contract: IEEE 754 defines inexact as the rounded result differing from the mathematically exact one, RISC-V accrues it in fflags bit 0 with no trap, and the module's 0x01-after-inexact versus 0x00-after-exact pair shows the contract firing exactly when the exact sum needs 54 bits and the format holds 53.

    MICROARCH

    not at Microarch because the property is implementation-invariant: the inexact definition, the NX bit position, and the no-trap rule are fixed in the spec's text, so no implementation choice changes a readback.

    FIRMWARE

    matters at Firmware because the module runs at firmware's own privilege level: it reads the boot mstatus, moves FS from Off to Initial before the first floating-point instruction (with FS Off an FP instruction raises illegal-instruction), and the trap counter stays 0 across both phases.

    KERNEL

    matters at Kernel because the no-trap discipline fixes the kernel's contract with user space: there is no exception path to audit and no trap handler to write for a rounding, an inexact operation is detected by polling fflags after the fact, and the module's zero trap count is that discipline holding.

    ALGORITHM

    not at Algorithm because the verified claim is the hardware's flag contract, not a portable computation: the eighteen checks are CSR readback assertions judged against the spec's text and the module's analytic derivation, and Kahan summation enters the post as the named customer, not as a verified computation.

    Add 1.0 to 10^16 and watch the 1 disappear. A bare-metal module ran a single fadd.d on the pair (1e16, 1.0) and read the result bits back: 0x4341C37937E08000, which is exactly 1e16. The +1 vanished without a trace in the result. But it left a receipt. The fcsr register read exactly 0x01 afterward: the NX bit set, the other four exception flags clear. The operation rounded, and the hardware said so in one bit.

    A supermarket receipt
    The hardware's receipt for one lost bit.

    The module states the flag layout in two lines of its source:

    #define FFLAGS_NX  0x01UL  // fcsr bit 0: inexact
    #define FFLAGS_ALL 0x1FUL  // fcsr bits 4:0: NV|DZ|OF|UF|NX

    The vanishing is arithmetic, not a bug, and it is worth doing by hand once. 10^16 factors as 2^16 times 5^16, and 5^16 is 152587890625, so 1e16 is exactly representable as a double: exponent field 0x434, a 53-bit significand whose least significant bit is even. It sits in the binade from 2^53 to 2^54, where representable doubles stand 2 apart. The exact sum 10^16 + 1 sits exactly halfway between 10^16 and 10^16 + 2, and round-to-nearest-ties-to-even picks the even neighbor: 10^16 itself. The exact answer needed 54 significant bits; the format carries 53. A host-side check agrees: 1e16 + 1.0 is bit-identical to 1e16.

    So why does the machine keep a flag for this instead of rounding silently, or instead of trapping? Trapping is the obvious alternative, and ordinary arithmetic breaks it. Inexact results are routine: 1.0/3.0 rounds every single time, and a trap per rounding would fire constantly through ordinary arithmetic, which is why the ISA chose a no-trap discipline for these flags. Silence is the other alternative, and it breaks the programs that need to know. Kahan's compensated summation exists precisely to recover the rounding error and feed it back into the sum, and it cannot recover what it cannot see. The flag is the middle path: accrue, don't interrupt. NX sets, the program keeps running, and whoever cares reads the receipt afterward.

    The module proved the receipt is exact, not approximate. After clearing fcsr to 0x00, the inexact add left (fcsr & 0x1f) == 0x01: NX set, and NV, DZ, OF, and UF all clear, which is the whole point of the isolation. Nothing else had cause to move: both operands were finite positive normals, the result was finite and nowhere near the subnormal range or the overflow threshold, and no division or invalid operation was involved. The control ran fadd.d on (1.0, 2.0): the exact sum 3.0 is representable, the result bits came back 0x4008000000000000, and fcsr read exactly 0x00. No flag moved at all. Eighteen checks, zero mismatches, three byte-identical runs under QEMU 8.2.2, and the trap counter stayed at 0.

    This is the complement of an earlier note on this blog, the one about 0.0 divided by 0.0. That was the operation with no answer, and the NV flag marked the refusal. This one is the operation with an answer that cannot be written down. One sentence to keep: when the exact answer needs more bits than the format holds, the hardware keeps the best approximation and leaves you a one-bit receipt for what fell off.

    The Bridge That Doesn't Translate

    Relevance by layertest log
    ISA

    matters at ISA because the verified property is an instruction contract: FMV.D.X copies 64 bits from the integer register file to the floating-point file without interpreting them, the manual promises the bits are not modified and noncanonical NaN payloads are preserved, and the post's 1.0 versus 4607182418800017408.0 pair shows the contract is what separates a transport from a translation.

    MICROARCH

    not at Microarch because the promise is implementation-invariant: whether a core renames the two register files together or apart, and through which pipeline it issues the move, the observable result is the same unchanged 64 bits, and the post verifies the contract, not any implementation's choice of how to honor it.

    FIRMWARE

    not at Firmware because the move is privilege-invariant: it executes identically at every privilege level with no trap, no SBI call, and no PMP entry involved, and nothing firmware configures changes what the instruction promises about the bits.

    KERNEL

    not at Kernel because the property is policy-invariant: the kernel's work is managing when the floating-point file is live, the mstatus.FS bookkeeping the post cites, and that lifetime policy is orthogonal to the crossing itself, which moves bits identically whether it runs in a user process, a trap handler, or a bare-metal binary.

    ALGORITHM

    not at Algorithm because the post computes nothing: FMV is a move, not a computation, and the discipline it teaches, knowing whether you want the bits or what they mean, is a property of one instruction's contract, independent of any algorithm that later consumes the bits.

    The module needed the double 1e16 inside a floating-point register, and it had a problem. It builds with -march=rv64imac_zicsr, a target with no floating point at all, so the compiler cannot name f1, f2, or f3; the source comment says so outright, and the floating-point instructions only assemble because of an in-asm ".option arch, +d". The way in was the integer 0x4341C37937E08000 sitting in an integer register, then one instruction: fmv.d.x. FMV.D.X moved the 64 bits into the floating-point register file unchanged. On the way back, fmv.x.d carried the result bits out for inspection.

    The Sidney Lanier cable-stayed bridge
    fmv carries the bits across, unchanged.

    There is a conversion instruction sitting right next to it, and reaching for it is the whole bug. Feed those same 64 bits, 0x3FF0000000000000, to FCVT.D.L, and the machine reads them as the integer 4,607,182,418,800,017,408 and hands you back the double 4607182418800017408.0. Feed them to FMV.D.X and you get exactly 1.0. One instruction translates. The other transports.

    This is the entire crossing, four instructions quoted from the module's source:

    fmv.d.x f2, %1
    fmv.d.x f3, %2
    fadd.d f1, f2, f3, dyn
    fmv.x.d %0, f1

    The two operands arrive as raw bits, the add runs, and the result bits are read out for inspection. The %1 and %2 are the integer registers holding the bit patterns; %0 is where the result bits land. No host floating point touches the values at any point. The module's own comment states the rule: the operands arrive as integer bit patterns precisely so the test's hands never shape a float. When the thing under test is what the hardware does with a float, the measurement must not pass through your tools' idea of a float.

    The manual draws the line in one sentence: "FMV.X.D and FMV.D.X do not modify the bits being transferred; in particular, the payloads of noncanonical NaNs are preserved." A converter cannot make that promise, because conversion interprets. Only a transporter can promise the payload survives, and that sentence is the proof the instruction is a copy, not a conversion.

    The reason the bridge is narrow is a design decision, not an accident. The ISA was defined to reduce the number of explicit int-float register moves: conversions and comparisons write their results straight into the appropriate register file, so the crossings most programs need are already built into the operations themselves. FMV exists for the one case nothing else covers: when you want the bits themselves, not what they mean. It is an RV64-only instruction, for 64-bit integer registers; the early ISA's half-register transfer moves were cut because partial register writes would have forced a read-modify-write through renamed pipelines. x86 keeps the same bridge under another name: MOVQ between an xmm register and a 64-bit general register.

    For this work the bridge has two customers. The first is the hermetic test: feeding bit patterns through integer registers keeps the host toolchain's floating point out of the measurement loop, which is the difference between measuring the machine and measuring your tools. The second is the kernel: the floating-point registers are a whole separate file of state, f0 through f31 beside x0 through x31, and that separation is why mstatus.FS exists at all, the two-bit receipt that lets the kernel skip saving thirty-two registers when the running code never touched them. The bridge is narrow because the ISA keeps the two register files separate; FMV is the only direct move between them. One sentence to keep: RISC-V keeps two register files and one narrow bridge between them that copies bits without reading them, and the discipline is knowing whether you want the bits, or what they mean.

    The Fence the Instruction Cache Never Sees

    ISA

    matters at ISA because fence.i is a base-ISA instruction whose semantics are the machine contract: the manual permits an implementation to cache fetched bytes and never read memory for fetches again, so the fence is the architecturally defined moment the data view and the fetch view agree.

    MICROARCH

    matters at Microarch because the two eyes are the split first-level caches: whether a jump after a store fetches new or stale bytes is decided by the implementation's instruction cache, and the post's QEMU mirror is the same problem in software, translation blocks as a software I-cache with the same invalidation discipline.

    FIRMWARE

    not at Firmware because the announcement needs no trap, no SBI call, and no PMP change: any privilege level issues fence.i straight to its own hart's fetch engine, and the post's examples, a JIT, a debugger, and kernel livepatch, announce for themselves rather than asking firmware to do it.

    KERNEL

    matters at Kernel because Linux owns the policy around the announcement: __riscv_flush_icache has ordered user stores against instruction fetches since Linux 4.15, and since 6.10 a prctl lets a process declare whether it may emit fence.i, with the kernel keeping the cache coherent when threads migrate between harts.

    ALGORITHM

    not at Algorithm because the fence computes nothing and moves no data: it only orders two views of the same bytes under one machine contract, and the store, fence.i, jump shape is a protocol for that contract, not a computation that ports to another machine.

    Picture a just-in-time compiler at work. It writes a few dozen bytes of fresh machine code into a buffer, then jumps to the first byte. This should work: the bytes were just stored, and the jump reads them back. On x86, as I understand it, it does work, and that is the trap. Nothing in this picture looks broken until you move it to RISC-V.

    A snow-capped wooden fence
    fence.i: the announcement the fetch engine needs.

    The CPU reads memory with two eyes. The data eye is the load/store engine, filling the data cache. The instruction eye is the fetch engine, filling the instruction cache. When your program stores a new byte, it lands in the data eye's view. The instruction eye may still hold the old bytes it fetched long ago, and the manual permits the disagreement: a valid implementation may cache every fetchable byte at the earliest opportunity and never read main memory for instruction fetches again. So the jump runs the old bytes. The new code sits in memory, correct under every load you care to run, and the CPU executes something else.

    The obvious repair is to make the hardware keep the two eyes in sync on every store. The RISC-V designers refused, and the refusal is about cost. Keeping the instruction cache coherent with every store would tax every store in every program for an event that almost never happens: almost no program rewrites its own code. So the architecture moved the price to the rare path. Instead of the hardware watching all stores, the software announces the one store that matters. The announcement is one instruction: fence.i.

    The shape is three steps, in this order, and skipping the middle one is the whole bug:

    store the new bytes      # the data eye sees them
    fence.i                  # announce: instruction eye, refresh
    jump to the buffer       # the new bytes run

    The stores put the new bytes where loads can see them. The fence orders this hart's instruction stream against those stores (a hart is RISC-V's word for a hardware thread): the fetch engine drops what it cached and looks again. The jump then fetches the new bytes. Across two harts the shape stretches but does not change: the writer stores, issues a write barrier, and sets a flag; the reader sees the flag, issues its own fence.i, and only then executes.

    Everyone who writes code while the machine is running needs this. A JIT compiles a function, fences, and jumps. A debugger overwrites an instruction with ebreak, the breakpoint instruction, and must fence before resuming its target. The kernel patches its own text for livepatch and ftrace. Linux gave user space a system call for it: __riscv_flush_icache, in the kernel since 4.15 with a glibc wrapper since 2.27, which enforces ordering between stores and instruction-cache fetches; in 6.10 a prctl let a process declare whether it may emit fence.i at all, with the kernel keeping the cache coherent when threads migrate between harts. QEMU has the same problem one layer up: it translates guest code into host code and caches the translations, a software instruction cache, so it write-protects the pages holding them and throws translations away when a write lands. Its own docs note that on RISC targets, correctly written software uses barriers and flushes, so the trick would be unnecessary. One honest footnote: none of my bare-metal labs has ever needed this instruction. They write their code once at load time and never modify it, so the two eyes never disagree. This post is mechanism from the manual and the kernel docs, not a measured lab. One sentence to carry away: the CPU reads memory with two eyes, one for data and one for instructions, and fence.i is the moment they agree.

    The Bouncer on the Stopwatch

    Relevance by layertest log
    ISA

    matters at ISA because the verified property is the privileged ISA's own rule: mcounteren.CY is the M-level gate on U-mode cycle reads, and the module proves both directions, reads succeed when the bit is set and the same read traps with scause 2 when it is clear.

    MICROARCH

    not at Microarch because the gate is an architectural access rule, and the observed outcomes, a trap versus two increasing samples, are identical on any pipeline, cache, or predictor that implements the privileged spec: the proof asserts nothing about how the read is implemented, only whether it is permitted.

    FIRMWARE

    matters at Firmware because M-mode firmware owns mcounteren, and the experiment is written as that firmware: it sets and clears CY itself and performs the real M to S to U drops, so the gate is the firmware's own policy for exposing the cycle counter to user mode.

    KERNEL

    not at Kernel because the verified property is the M-level hardware gate on a counter read, and the S-mode code exists only to reach U-mode where the gate bites: no supervisor timing or scheduling policy is under test, and the same gate would bite under any kernel.

    ALGORITHM

    not at Algorithm because no computational mechanism is under test: the claim is an access-control invariant, one bit deciding whether a read is permitted, and the converse-pair experiment design is a testing method, not an algorithm.

    At boot, mcounteren reads back 0x0: user mode may see nothing, and nobody granted it. The experiment sets bit 0, CY, then drops from M-mode through S-mode down to user mode and reads the cycle counter twice: no trap, two strictly increasing samples, the door open. Then it clears that one bit, drops to user mode again, and runs the same instruction. This time the machine traps with scause 2, illegal instruction, sepc pointing exactly at the rdcycle site, and the destination register still holding its 0xdeadbeefdeadbeef sentinel, proof the read never happened. Twenty-two checks, zero mismatches, three byte-identical runs under QEMU 8.2.2. One bit decides whether a user process may know what time it is.

    A bouncer checking IDs at a nightclub door
    One bit decides who reads the clock.

    Why would a machine hide the time from its own programs? The unprivileged manual says it plainly: "Some execution environments might prohibit access to counters to impede timing side-channel attacks." A cycle counter is an oracle. Diffing two timestamps around someone else's code measures what that code did, and that trick has a published attack literature behind it: keystroke intervals, memory access patterns, the Spectre-era classics. So the privileged ISA puts the bouncer in M-mode. The obvious alternative is to hand back a zero or a clamped value, but a silent zero is a lie the program cannot detect, so the ISA refuses it: a clear CY bit raises illegal instruction, the architectural equivalent of the door staying shut. The manual is careful about what hiding is and is not. "The settings in this register only control accessibility. The act of reading or writing this register does not affect the underlying counters, which continue to increment even when not accessible." The clock still ticks; you simply may not ask it the time. An earlier module proved the brake pedal, mcountinhibit, which stops the clock. This one proves the bouncer, which bars the door. Stopping versus hiding: two different promises, same family.

    The experiment earns its verdict one gate at a time. Two gates sit in series on the road from user code to the cycle counter, the M-level mcounteren and the S-level scounteren, so the module pins the S-level gate open, held set and read back as 0x1 before each phase, and wiggles only the M-level one. A mirror-image module did the reverse, holding the M-level gate open while toggling the S-level one. A single experiment can only blame one gate when the other is nailed open, so the two arrive as a converse pair. And the failure carries its own proof inside the success. The phase-B payload loads the destination register with a sentinel before attempting the read, so a completed read would have overwritten it. The trap alone says the instruction faulted; the untouched register says the read never happened:

    li t0, 0xdeadbeefdeadbeef
    rdcycle t0

    Scope, honestly held: this verifies QEMU 8.2.2's model of the gate, not silicon, and the gate only bites below M-mode, which is why both phases run through two real privilege drops, M to S to U, instead of asserting anything from the top. One sentence to carry away: time is a hardware resource, and one bit in one register is the bouncer who decides which rings of privilege get to see it.

    The Write That Sleeps

    Relevance by layertest log
    ISA

    not at ISA because the verified property is the kernel's scheduling decision, when a full pipe makes a write sleep, and that decision is identical for the same kernel on any instruction set: the proof asserts nothing about any instruction's specified behavior, and no ISA rule distinguishes a sleeping write from a returning one.

    MICROARCH

    not at Microarch because the measured quantity is scheduler time in whole timer ticks, forty of them against a thirty-tick gate: pipeline, cache, and predictor effects live orders of magnitude below the gate, so no implementation detail could change whether the verdict passes. The timing the module measured is kernel-visible, not machine-visible.

    FIRMWARE

    not at Firmware because the measured path never leaves the kernel: the sleep and the wakeup happen between user processes and xv6's scheduler, with no privilege register, trap vector, or SBI call under the kernel under test. Nothing configured beneath the kernel stands between the syscall and the stall.

    KERNEL

    matters at Kernel because the property under test is the kernel's own pipe scheduling contract: a full pipe makes pipewrite sleep on the nwrite channel instead of spinning, and piperead wakes that channel when it drains. The module proves the block from outside the kernel with the uptime tick counter as a stopwatch, 40 ticks against a 30-tick gate, the shadow of a sleep measured in time.

    ALGORITHM

    not at Algorithm because the claim is a kernel scheduling decision, when a write sleeps for a reader, not a computational mechanism: the tick-edge choreography that makes the measurement repeatable is craft around the claim, not the claim itself, and the FNV-1a fold only collapses the measured values into one checkable number.

    Fill an xv6 pipe with exactly 512 bytes, the whole buffer, and write one more byte. The call does not return. It comes back 40 ticks later, when the child finally drains the pipe, and all 513 bytes arrive byte-exact: seven checks, zero mismatches, three byte-identical runs under QEMU. No one inside the kernel told the test the write slept. It proved the block from outside, with nothing but the uptime tick counter for a stopwatch.

    The Hoover Dam from the air
    Full pipe: the write waits for the drain.

    The determinism comes from careful timing. The parent fills the pipe before the fork, so the fill can never block by accident. Then it spins on the tick counter until a fresh tick edge, captures t0 microseconds after the edge, and only then forks: both sides inherit one absolute deadline, t0 plus 40. The child touches nothing until that tick; the parent's second write is issued in tick t0, so it must wait the full 40. An early revision captured t0 after the fork, and the count jittered between 39 and 40 where a tick boundary fell between the fork and the write. The fix was not a bigger gate. It was putting the boundary where it belongs. The capture is four lines of C:

    te = (uint64)uptime();
    while ((uint64)uptime() == te)
      ;
    t0 = (uint64)uptime();
    pid = fork();

    On the kernel side the rule is small: when the buffer is full, pipewrite wakes the reader and sleeps on its own nwrite channel, and the reader's piperead answers with a wakeup on that same channel when it drains. No polling, no timeout, no retry. And underneath that is a design argument I keep turning over. The writer cannot spin for the reader, because the reader may be asleep or unscheduled, and burning cycles while the only party that can make progress is not running is how a machine does nothing expensively. My ring buffers spin, and rightly so: known parties, nanosecond stakes. The kernel's pipe sleeps, because the kernel serves parties it has never met.

    Scope, honestly held: one byte past full, one child, one fixed 513-byte pattern. No partial writes, no multiple writers, no read-side blocking, and the PROOF.md says so. One sentence to carry away: a kernel block can never be watched from user space, so you prove it by measuring precisely what the machine did not do while you waited.

    The Return With Nothing to Return From

    Relevance by layertest log
    ISA

    matters at ISA because the verified content is the privileged architecture's own contract for sret: executed in U-mode it traps as illegal instruction with mcause=2, mepc at the sret site, trapped mstatus.MPP=0, and the faulting instruction word in mtval. The module probed all four with real CSR reads against the manual's supervisor-instruction text, the Sail model's bare user-mode match clause that routes straight to the illegal-instruction handler, and the SPP/SPIE/sepc restore semantics the control phase exercised from S-mode.

    MICROARCH

    not at Microarch because the refusal is a contract rule about register state, identical on every conforming implementation: the proof measured no timing and no pipeline, cache, or predictor behavior, and no microarchitectural choice could change whether the trap fires or what the CSRs read back. The QEMU 8.2.2 numbers are labeled as the model's, not the architecture's.

    FIRMWARE

    matters at Firmware because the trap's destination is firmware's decision: medeleg was written 0 and read back 0 so the illegal-instruction trap could not be delegated away, and the M-mode handler recorded mcause, mepc, mtval, and mstatus before jumping to the C continuation. On this machine the receiver, the delegation lock, and the scripted drop into U-mode are all M-mode operations.

    KERNEL

    matters at Kernel because sret is the supervisor trap return path the kernel walks on every trap exit: privilege restored from SPP, interrupt enable from SPIE, the program counter from sepc. The module proved the gate in both directions, S-mode sret works with control_ok=1, U-mode sret traps with mcause=2, so a kernel knows exactly where its return instruction is legal and what the hardware does when user code reaches for it.

    ALGORITHM

    not at Algorithm because the sret refusal is the architecture's privilege mechanism, not a portable technique: with no privilege modes and no return-from-trap instruction the claim has nothing to mean, and nothing in the verified behavior travels to another machine.

    The program runs the same four bytes twice: 0x10200073, the encoding of sret, the supervisor return-from-trap instruction. The first run happens in S-mode, and it works: the control phase records control_ok=1 and the program comes back to the pad with no trap fired. The second run executes the identical bytes in U-mode, and the machine refuses. The hart traps to M-mode with mcause=2, illegal instruction. mepc reads 0x80000344, the exact site of the sret. mstatus.MPP reads 0, the hardware's own record that the offender was in user mode. And mtval holds 0x10200073, the faulting instruction word itself.

    A full-height metal turnstile
    sret in user mode: no trap to return from.

    sret is the second half of the trap contract. When it executes, privilege is restored from sstatus.SPP, interrupt enable from SPIE, and the program counter from sepc. All three are supervisor-owned state. In U-mode there is no supervisor trap to return from, and no legal way to have built that state, so the ISA does not define the behavior. It refuses the instruction. The formal Sail model of the privileged architecture writes the rule as a bare match: in user mode, sret goes straight to handle_illegal(). No conditions, no escape hatch.

    There is a mirror image in the same manual. The TSR bit in mstatus lets M-mode forbid even S-mode from executing sret, so a hypervisor can intercept it and emulate the missing extension. Returning from a trap is itself a gated privilege. And the night's neighboring module, mstatus-tvm-trap, probes the gate next door: the TVM bit makes S-mode writes to satp and sfence.vma trap to M-mode. Taken together the pair maps who is allowed to come back from where.

    The discipline held, too. medeleg was written 0 and read back 0, so the trap could not be delegated away from M-mode; it had to land where the handler was waiting. And the mtval check does not compare the trap's evidence against a constant anyone typed from memory. It reads the actual instruction word at mepc and compares the two measured values against each other:

    unsigned long word_at_mepc = *(volatile unsigned int *)mepc;
    check(mtval == word_at_mepc,
          "mtval does not match the word at mepc");

    Eighteen checks, zero mismatches, checksum 0x802872738f9db42a identical across three byte-identical runs on QEMU 8.2.2. One sentence to carry away: sret needs supervisor trap state that user mode can never build, so the ISA raises an illegal instruction, delivers the trap to M-mode, and mtval holds the offending instruction word.

    The Division That Isn't

    Relevance by layertest log
    ISA

    matters at ISA because the verified content is the F/D chapters' invalid-operation contract: 0.0/0.0 raises NV alone, the quotient is the canonical quiet NaN, and no trap fires. The module probes all three halves against the manual's statements: the fcsr triple 0x0 to 0x10 to 0x0, the 0x7FF8000000000000 quotient readback, and the trap counter at zero. The canonical-NaN wording and the payload-refusal reasoning are the spec's own.

    MICROARCH

    not at Microarch because the values under test are architectural constants: the NV definition, the canonical NaN pattern, and the no-trap rule are fixed in the spec's text, so no implementation choice changes a readback. The proof never times anything, and the QEMU 8.2.2 numbers are labeled as the model's, not the architecture's.

    FIRMWARE

    matters at Firmware because the module runs at firmware's own privilege level: it reads the boot mstatus, moves FS from Off to Initial before the first floating-point instruction (Off would raise illegal-instruction), installs an M-mode trap handler as the witness, and reads the trap counter back at zero. That is the enable, arm, and leave-no-trace discipline of M-mode boot code around the floating-point unit.

    KERNEL

    matters at Kernel because the no-trap discipline fixes the kernel's contract with user space: there is no exception path to audit and no trap handler to write, an invalid operation is detected by polling fflags after the computation, and fflags is per-hart state the context switch must save and clear so one process's invalid never accuses another.

    ALGORITHM

    not at Algorithm because the verified claim is the hardware's flag contract, not a portable computation: the fourteen checks are CSR readback assertions judged against the spec's text, and no host-independent computation can reproduce an fcsr readback. The indeterminate-form mathematics motivates the rule, but the proof targets the flag, not the math.

    Clear fcsr to 0x00, execute one fdiv.d of 0.0 by 0.0, read fcsr back: 0x10. The NV bit, bit 4, stands alone: NX, UF, OF, and DZ all clear, the rounding mode still RNE, the trap counter at zero. The quotient comes back as 0x7FF8000000000000. Fourteen checks, zero mismatches, three byte-identical runs on QEMU 8.2.2. But the interesting half of this proof is not the checks; it is why the standard declares this operation invalid in the first place.

    A car dashboard glowing with warning lights at night
    NaN rides along; the flag tells you later.

    Divide 1.0 by 0.0 and the answer is honest: positive infinity, with the DZ flag raised. The earlier divide-by-zero module probed exactly that case. But 0.0 divided by 0.0 has no answer, because the limit depends on how you approach it: x over x tends to 1, 2x over x tends to 2, x-squared over x tends to 0. The arithmetic cannot name a number, so it must not name one. Infinity minus infinity, infinity times zero, and the square root of a negative number sit in the same box, and IEEE 754 gathers them all under one heading: invalid operation.

    The obvious design would be to stop the machine: raise a trap and hand the program an exception. SPARC did exactly that, with hardware trap-enable modes for each flag. RISC-V does not trap. Its rule is quieter: return a NaN, set the NV bit, keep going. That behavior is deliberate. Feed a NaN into further arithmetic and a NaN comes back out, so the error rides the data all the way to wherever you finally look. Finish the work, then read the receipt. One register that remembers, no wire that interrupts. The NaN you get is always the canonical one, 0x7FF8000000000000 for a double: positive sign, all significand bits clear except the quiet bit, in the manual's own words. Carrying the error's origin in payload bits was considered and refused: the manual states plainly that it would have raised the hardware cost, and since payloads are optional in the standard they cannot be used in portable code.

    The module is built so the only floating-point actor in the room is the FPU. It compiles for rv64imac_zicsr, which has no F or D, so the C compiler cannot even name the float registers; the operands travel from integer registers through fmv.d.x, and the divide runs inside volatile in-asm so the compiler cannot fold 0.0/0.0 at compile time. A bare fdiv.d assembles with the dynamic rounding mode, so the source spells out the ,rne. The whole divide is five lines:

    __asm__ volatile(
        "fmv.d.x f2, %1\n\t"          /* +0.0 as a bit pattern, into f2 */
        "fmv.d.x f3, %2\n\t"          /* +0.0 as a bit pattern, into f3 */
        "fdiv.d f1, f2, f3, rne\n\t"  /* the real instruction under test */
        "fmv.x.d %0, f1\n\t");        /* quotient back through an integer register */

    Fourteen checks proved three things at once: the operation admits it has no answer, the bit remembers that it happened, and the machine never stops. One sentence to carry away: an operation with no answer returns a value that admits it, sets a bit that remembers it, and lets the machine keep going.

    The Switch With Nothing Behind It

    Relevance by layertest log
    ISA

    matters at ISA because menvcfg is a privileged CSR whose bit 62 the spec defines as the Svpbmt enable; the module proves the WARL contract holds, writing 1 reads back 0 on a hart without the extension, and the PBMT vocabulary the bit gates is PTE bits 62:61 in leaf entries.

    MICROARCH

    not at Microarch because the legalization is an architectural choice visible to software, not a pipeline, cache, or predictor behavior: the proof reads back register values, never times anything, and the verdict would be identical on any microarchitecture implementing the same privileged spec.

    FIRMWARE

    matters at Firmware because menvcfg is M-mode only, so only machine-mode firmware can probe the WARL field or flip the enable; the article's lesson is that firmware must measure rather than assume, and the henvcfg read-only-zero rule is the same privilege ladder M-mode enforces everywhere.

    KERNEL

    not at Kernel because menvcfg is unreachable from S-mode: a supervisor kernel can neither set PBMTE nor observe its readback, so the verified legalization is identical no matter what the kernel does, and the PBMT field the OS would use sits behind a gate the kernel cannot touch.

    ALGORITHM

    not at Algorithm because no computational mechanism is under test: the six checks are register readback assertions, and the FNV-1a checksum only collapses the measured values into one checkable number, so the verdict would stand under any other hash.

    Write 0x6000000000000000 to menvcfg, the M-mode environment configuration register, and read it back: 0x2000000000000000. Bit 62, the PBMTE switch, refused to stick, and every other bit came back exactly as written. Saying it properly took six checks: a set probe, a clear probe, two all-ones legalizations that agreed with each other, a restore of the boot value, and a trap count of zero. Three byte-identical runs on QEMU 8.2.2, one checksum over every readback, verdict PASS. This hart has no Svpbmt.

    An open knife switch connected to nothing
    The switch is open and nothing is behind it

    The measurement is a WARL probe, and WARL is the whole method. Write-any-read-legal means the register may legalize any value you write, so the experiment writes values and reads back what the hart allows. The set probe is three lines:

    unsigned long boot = read_menvcfg();  /* 0x2000000000000000 */
    write_menvcfg(boot | MENVCFG_PBMTE);  /* ask for bit 62 */
    unsigned long set = read_menvcfg();   /* 0x2000000000000000: refused */

    The question behind the switch is who decides what a physical address is. Today the answer is the platform: physical memory attributes are fixed at boot, this region is RAM, that region is a device, and the page table encodes no such distinction. That works until the operating system maps a device register as ordinary cacheable memory. Then reads go stale in the cache, and speculative reads fire side effects on hardware that was only ever supposed to be asked. The fix is to let the page table say what each page is, and that is what the Svpbmt extension, RISC-V's page-based memory types, does: a two-bit PBMT field, bits 62:61, in every leaf page-table entry, so one page can be memory and its neighbor can be a device.

    The vocabulary is three words. Zero means PMA, the physical memory attributes: ask the platform, the old world, no override. One means non-cacheable memory: idempotent and weakly ordered, you may read it speculatively and read it twice, you just may not keep a copy in the cache. Two means this page is hardware: non-idempotent and strongly ordered, every access a real conversation with a device that has side effects. Three is reserved, and the machine raises a page fault instead of guessing what you meant. My favorite sentence in the spec is the one proving the bits are not a label: mark an I/O-underlying page as non-cacheable, and for FENCE and acquire/release its accesses count as main memory, not I/O. The bits define the ordering rules that FENCE and acquire/release follow.

    And bit 62 of menvcfg is the master switch for the whole vocabulary. The spec's rule: while PBMTE is zero, the implementation behaves as though Svpbmt were not implemented at all. If the extension is not implemented, the bit is read-only zero. The hypervisor's copy in henvcfg is read-only zero while M-mode's copy is clear. Each privilege level gated by the one above it, in strict order.

    The module answers two different unknowns with two different probes and never lets them mix. The set probe asks whether the feature exists: the bit does not stick, so this hart has none. The all-ones probe asks what legalization looks like: 0xa0000000000000f1, stable across two writes, bit 63 surviving and bit 62 reading zero. The check that PBMTE would survive is gated on the set probe's answer, so the same binary would prove the positive case on a hart that implements it. One program proves presence and absence alike. One sentence to carry away: the page table already knew where every byte was and who could touch it; two bits in the leaf entry let it say what the byte is, and one bit in menvcfg decides whether the machine listens. The readback says: not on this hart.

    The Signal That xv6 Never Sends

    Relevance by layertest log
    ISA

    not at ISA because the verified property is the write syscall's contract, refuse with -1 and leave the writer alive, which is identical on every machine the kernel could run on: the proof compares behavior against POSIX and the kernel source, never against the machine manual.

    MICROARCH

    not at Microarch because every check compares a syscall return value against its expected value, so the verdict depends only on the observed values and not on how the machine produced them: the proof is a value test, not a timing test.

    FIRMWARE

    not at Firmware because the claim lives entirely in the kernel and its userland test: the pipe write path touches no trap vector or privilege register beneath the kernel, so nothing configured under the kernel stands between the syscall and the -1.

    KERNEL

    matters at Kernel because the property under test is the kernel's write-to-pipe contract: Linux's fs/pipe.c answers a readerless pipe with a signal plus an error, xv6's kernel/pipe.c answers with the error alone, and the module verifies the xv6 side.

    ALGORITHM

    not at Algorithm because the claim is a kernel interface decision, how a write reports a missing reader, not a computational mechanism: FNV-1a only collapses the measured values into one checkable number, and the -1 verdict would stand under any other hash.

    Make a pipe, close the read end, and write sixteen bytes. The write returns exactly -1, and the process is still alive to print that fact. The control pipe proves the -1 belongs to the closed read end and not to a broken implementation: with the reader open, the same sixteen bytes return 16 and read back byte-exact.

    A red and white megaphone
    Linux shouts. xv6 just returns minus one.
    Photo: Solomon203 (attribution required) (CC BY-SA 4.0)

    A pipe is a two-party contract, and with no reader the bytes have nowhere to go. So who tells the writer? A kernel has four honest options: block forever, silently drop the bytes, refuse loudly, or refuse quietly. Blocking is a hang, the quietest failure of all. Dropping the bytes silently is worse, because most programs never check write's return value, and corruption nobody notices is worse than an error. That leaves the two refusals, and POSIX chose the loud one.

    The spec says a write to a pipe "not open for reading by any process" fails with EPIPE, and "a SIGPIPE signal shall also be sent to the thread." Two deliveries, the signal and the error. Linux's fs/pipe.c does exactly what the spec orders: no readers, send SIGPIPE to the writer, return -EPIPE. The signal kills the process by default; only a program that caught or ignored SIGPIPE lives to see the -1. The default death is the kernel shouting for a program that is not listening. EPIPE is the polite fallback for the programs that asked to handle it.

    xv6 cannot shout. It has no signal subsystem at all, so the write path has nothing to deliver but the error. In kernel/pipe.c, before a single byte is copied, the write loop checks two things: is anyone still listening, and has this process already been marked for death:

    if (pi->readopen == 0 || killed(pr)) {
      release(&pi->lock);
      return -1;
    }

    readopen counts the open read ends; killed is the per-process death flag. When the last reader is gone, the loop drops the lock and returns -1. The -1 is the SIGPIPE, in the only language xv6 speaks. Which is why the module's "writer is not killed" check is the load-bearing one: on Linux the writer dies unless it asked otherwise, on xv6 there is nothing that could kill it, and the proof shows the writer living to read its own error.

    Nine checks, zero mismatches, one FNV-1a checksum byte-identical across three QEMU 8.2.2 runs. One sentence to carry away: a pipe with no reader leaves the bytes with nowhere to go; Linux shouts and then hands you a note, xv6 just hands you the note.

    The Register That Never Interrupts You

    Relevance by layertest log
    ISA

    matters at ISA because the verified content is the unprivileged ISA's own F-extension contract: the five frm encodings, the five fflags bits with their mnemonics, the static-rm-beats-frm rule, and the no-trap discipline are stated in the F-extension chapter, and four bare-metal modules probed each one against those statements with 65 checks, so the argument binds every compliant hart.

    MICROARCH

    not at Microarch because the verified properties are architectural constants: the frm encodings, the flag definitions, and the static-override rule are fixed bit-for-bit in the ISA text, so no implementation choice changes a readback, and the QEMU 8.2.2 numbers are labeled as the model's, not the architecture's.

    FIRMWARE

    matters at Firmware because the modules run in M-mode, firmware's own privilege level: the sequence reads the boot mstatus, moves FS from Off to Initial before any floating-point instruction, and restores fcsr to zero at the end, which is the enable, configure, and leave-no-trace discipline that M-mode boot code follows around the floating-point unit.

    KERNEL

    matters at Kernel because the kernel's context switch carries fcsr with the thirty-two floating-point registers: frm must be restored so a process keeps its rounding mode, fflags must be saved and cleared so one process's inexact does not accuse another, and the no-trap discipline fixes the kernel's contract with user space as poll, never interrupt.

    ALGORITHM

    not at Algorithm because the verified claim is a hardware register contract read back from one machine model, not a portable computation: the frm write-readback pairs and the accrued flags are facts about QEMU 8.2.2's floating-point unit, judged against the spec's text, and no host-independent computation can reproduce a CSR readback.

    One third has no exact double, so the true quotient of 1.0 divided by 3.0 sits between two adjacent doubles, one ulp apart. A new module ran fdiv.d 1.0/3.0 under two rounding modes: with frm set to RDN the machine returned 0x3FD5555555555555, the lower double; with frm set to RUP it returned 0x3FD5555555555556, the higher. The mode steered the answer, not the other way around.

    Cash register receipts showing rounded totals
    Flags accrue like receipts, never interrupting you

    The register that controls it is fcsr, the floating-point control and status register. It has two jobs in 32 bits. Bits 7:5 are frm, the dynamic rounding mode. Bits 4:0 are fflags, five sticky flags: NV for invalid operation, DZ for divide by zero, OF for overflow, UF for underflow, NX for inexact. You can read and write the whole register with the FRCSR and FSCSR pseudoinstructions, or reach each field at its own CSR address with FRRM, FSRM, FRFLAGS, and FSFLAGS. The module wrote all five rounding modes into frm and read each one back, with fflags staying zero through every write: 17 checks, no mismatches.

    Every floating-point instruction carries its own 3-bit rm field, the per-instruction alternative to frm. Encode it as 111 and you get DYN, meaning ask frm. Encode anything else and the instruction's own choice wins over frm, whatever frm says. A second module proved it: static-RNE fdiv.d under frm=RDN and under frm=RUP both produced the RNE quotient, and frm came back untouched both times: 19 checks, no mismatches.

    Why two mechanisms instead of one? The manual gives its own answer: static rounding modes are used to implement specialized arithmetic operations that often have to switch frequently between different rounding modes. The engineering reason underneath is global state. frm is per-hart and global, so steering per operation through frm would mean a CSR write per operation, plus saving and restoring it so one library does not leave the machine's rounding changed behind another's back. A static rm puts the choice inside the instruction: no churn, no footgun. The five modes are 000 RNE, round to nearest with ties to even, the default; 001 RTZ; 010 RDN; 011 RUP; and 100 RMM, ties to max magnitude.

    Then the flags, which do the opposite of interrupting: they accrue. Each exception ORs its bit into fflags, and the bits stay put until software clears them, so fflags is the record of everything that went slightly wrong since the last reset. Two modules are the clean demonstration. Dividing 1.0 by 3.0 sets only NX, because rounding was the only thing that happened. Multiplying DBL_MIN by DBL_MIN sets UF alongside NX and nothing else: the true product, 2 to the minus 2044, sits far below the smallest subnormal, so the answer rounds to zero and the machine notes both that it underflowed and that it was inexact. The discipline is clear, compute, read:

    csrw fcsr, x0   # clear both fields
    ...             # the arithmetic under test
    frflags t0      # the receipt

    And the why-not that completes the picture. The base ISA does not generate a trap when a floating-point exception flag sets; the F extension requires explicit checks of the flags in software. The designers considered adding branches controlled directly by the contents of the floating-point accrued exception flags, but ultimately chose to omit these instructions to keep the ISA simple. Other architectures let you unmask a flag and take a trap. RISC-V chose poll over interrupt, simple over clever. Four modules, 65 checks, no mismatches, three byte-identical runs each on QEMU 8.2.2, with the FS gate open. One sentence to carry away: on RISC-V you can set the rounding mode for a single instruction, the exception flags accumulate without ever trapping, and software reads them when it wants.

    The Four Legal Ways to See Memory

    Relevance by layertest log
    ISA

    matters at ISA because the verified content is the privileged specification's own contract: the four legal MODE encodings are the spec's Table 114, quoted verbatim from the pinned release, and the validator reproduces that table in C with two independently shaped implementations, so the argument binds every compliant RV64 hart rather than one machine.

    MICROARCH

    not at Microarch because legality of the encoding is an architectural constant: the spec's table is identical on every compliant hart, and the module draws the spec's own line between legality and support, so implementation differences can only narrow the accepted subset, never enlarge the legal universe.

    FIRMWARE

    matters at Firmware because boot firmware is the layer that actually chooses a MODE when it brings the machine up: selecting 8 versus 11 versus 15 is a firmware decision made before any kernel exists, and this validator is the machine-checkable form of the rule that choice must not violate.

    KERNEL

    matters at Kernel because the supervisor kernel installs address spaces through satp: the legality table bounds every satp value a kernel can legitimately write, so the MODE a supervisor may select on any compliant hart comes from this table of four.

    ALGORITHM

    matters at Algorithm because the verification is a portable computational argument: a range predicate and a hand-transcribed table are two independent computations of the same legality function, and their agreement on all sixteen in-domain values plus six out-of-domain probes is a verdict comparison reproducible on any host.

    Four bits at the top of the satp register choose the machine's whole memory model. On RV64 exactly four encodings are legal: 0 is Bare, no translation and no protection at all, and 8, 9, and 10 are Sv39, Sv48, and Sv57, page-based virtual addressing with 39, 48, and 57-bit address spaces. The other twelve are not memory models: 1 through 7 and 12 through 13 are reserved for future standard use, 11 is reserved for an Sv64 scheme that does not exist yet, and 14 and 15 are designated for custom use.

    A rotary telephone dial
    Sixteen positions, only four are legal

    Why validate a table? Because legality is not the same as support. The spec says an implementation is not required to support every MODE setting, and that writing an unsupported one has no effect at all. An earlier module probed which MODE values one QEMU model actually accepts; this module validates the table itself, the full set of legal values before any one machine narrows it. And the two sides of the check are deliberately shaped nothing alike: the implementation is a range predicate, mode is 0 or in 8 through 10, while the oracle is a 16-row table transcribed by hand from the spec's Table 114, the document's own row text quoted in the comments. Agreement between two differently-shaped descriptions proves the rule, not shared code.

    The whole implementation is one line:

    int satp_mode_legal_rv64(uint64_t mode) {
        return (mode == 0) || (mode >= 8 && mode <= 10);
    }

    The oracle is the opposite shape: an explicit 16-entry list, each row transcribed from Table 114 with the document's wording in the comments. The six rows that never fit in four bits, 16, 17, 31, 32, 100, and 0xFFFFFFFF, have no table row covering them, and the function must judge each one illegal. Running them is what separates a test of the table from a test of the function: the table cannot be wrong about values it never lists.

    Value 11 gets the same verdict for the opposite reason. The pinned release reserves it for an Sv64 scheme to be defined in a later version of the specification, so the module quotes the release version and counts it illegal, and a future spec version will change that verdict explicitly. The module also corrected its own planning note on the way in: the backlog gloss labeled value 9 as Sv40, but the document's row reads Sv48, page-based 48-bit virtual addressing, and the code, the oracle, and the proof all follow the document. Twenty-two checks, zero mismatches, and one checksum identical across the -O2, -O0, and sanitizer builds, the byte-level signature that all three builds agreed on every verdict.

    One sentence to carry away: four bits choose the machine's whole memory model, and this validator agrees with the spec's table on every value the field can hold, plus six it cannot.

    The Register That Answers in Readback

    Relevance by layertest log
    ISA

    matters at ISA because the verified behavior is the privileged specification's own contract: section 2.3.3 prescribes exactly this experiment, that the range of supported values is determined by writing a desired setting and reading back whether it was retained, and that unsupported WARL writes never raise; the MODE encodings, 0 Bare, 8 Sv39, 9 Sv48, 10 Sv57, are the spec's table, so this probe binds every compliant hart.

    MICROARCH

    not at Microarch because the verified contract is an architectural property: section 2.3.3 guarantees an unsupported WARL write never raises and the readback is legal on every compliant hart, so no implementation choice changes the readback; the Sv48 and Sv57 stick is this QEMU model's retained set, measured and labeled as QEMU 8.2.2 behavior.

    FIRMWARE

    matters at Firmware because machine-mode firmware owns satp at boot and chooses the translation scheme: the module records the boot word 0x0, runs the MODE discovery in M-mode where a sticking scheme cannot fault instruction fetch, and restores satp before dropping to S-mode, so the write and readback discipline is load-bearing for whoever writes the boot code.

    KERNEL

    matters at Kernel because the supervisor kernel is the layer that switches address spaces through satp: the module's S-mode canary read is the supervisor's own proof that translation is live, and the WARL write and readback discipline is how a kernel discovers which address schemes a hart will accept before committing an address space to one.

    ALGORITHM

    not at Algorithm because the verified claim is a hardware register contract measured on a specific machine model, not a computation: write then read back is a probe discipline, not a portable mechanism, and the Sv48 and Sv57 results travel no further than the QEMU 8.2.2 model they were measured on.

    The satp register carries the page-table scheme in its MODE field: 0 is Bare, 8 is Sv39, 9 is Sv48, 10 is Sv57. The new module wrote each one and read it back. MODE=8: write 0x8000000000000000, readback 0x8000000000000000, stuck. MODE=9: write 0x9000000000000000, readback 0x9000000000000000, stuck, the whole write took effect. MODE=10: the same, stuck at 0xa000000000000000. Sv48 and Sv57 accepted, which the backlog had not expected. Then MODE=15, a reserved encoding: write 0xf000000000000000, readback 0xa000000000000000, the prior value bit for bit. The whole write ignored.

    A person throwing a boomerang
    Write a value; the register throws it back

    MODE is a WARL field, and WARL is the spec's arrangement for registers whose legal values vary by implementation: you may write anything, but what you read back must be one of the legal values. The privileged specification prescribes exactly this experiment in section 2.3.3: the range of supported values can be determined by attempting to write a desired setting and then reading to see if the value was retained. It adds the sentence that makes the experiment safe: implementations will not raise an exception on writes of unsupported values to a WARL field. An illegal write is not a fault. It is a question, and the hardware answers in the readback.

    The MODE=15 row is the one that had to be designed, not just run. The write went in while the register already held MODE=10, and the readback came back identical to the prior value. The nonzero prior matters: had the register held zero, an ignored write would read back zero, exactly what a write that stuck at zero would also produce, and the test could not tell the two answers apart. Running with a nonzero prior makes no-effect and stuck look different, which is what turns the absence of an effect into a finding. The module states the remaining boundary plainly: the readback cannot distinguish a wholly ignored write from every field independently legalized back to its prior value, so the claim is exactly the observed equality, nothing more.

    The probe idiom is three lines:

    uint64_t prior = read_satp();
    write_satp((prior & ~MODE_MASK) | ((uint64_t)mode << 60));
    uint64_t kept = read_satp();  /* the hardware's answer */

    The discovery ran in M-mode on purpose: a MODE write that sticks cannot fault anything there, because M-mode accesses are never translated. The first version probed MODE=9 in S-mode instead. The write stuck, and the next instruction fetch faulted with mcause 0xc, an instruction page fault at the faulting PC. That crash was converging evidence: the hart had accepted MODE=9 and tried to translate. After the discovery the module dropped to S-mode, enabled Sv39, and read a canary, 0xc0ffee11deadbeef, stored with translation off, back through the active walk at its virtual address, bit-exact. Nineteen checks, zero mismatches, three byte-identical runs, all on QEMU 8.2.2, which the module names plainly. Silicon gets its own say.

    One sentence to carry away: on a WARL field, the question is never what you wrote, it is what the hardware agreed to keep, and the only way to ask is to write it and read it back.

    The Two Bits That Spare the Kernel Thirty-Two Saves

    Relevance by layertest log
    ISA

    matters at ISA because the verified behavior is the privileged specification's own contract, section 3.1.6.7: FS, the field in mstatus bits 14:13, reports the floating-point unit's save state, SD at bit 63 is the OR of the dirty states, and Off makes floating-point instructions trap, so this state machine binds every machine-mode supervisor.

    MICROARCH

    not at Microarch because the verified contract is an architecturally specified state machine: the Initial-to-Dirty move on a single fmv.d.x and the trap on Off are specified by the privilege manual, so they hold on every compliant hart and vary with no implementation choice.

    FIRMWARE

    matters at Firmware because machine-mode firmware owns mstatus at boot and sets FS before any supervisor runs: the verified sequence opens with the boot word 0xa00000000, FS at Off, and that starting value is firmware's decision, so the field is load-bearing for whoever writes the boot code.

    KERNEL

    matters at Kernel because the kernel's context switch is the consumer of the verified bits: the save discipline writes the floating-point state out only when FS reads Dirty and marks it Clean, the restore discipline loads from memory only when Clean, and Initial is restored from the constant instead of memory, so the two bits delete thirty-two register spills on the switches that never needed them.

    ALGORITHM

    not at Algorithm because the verified claim is a hardware state transition read from mstatus, not a computation: the Initial-to-Dirty move on a real fmv.d.x exists only where a floating-point unit sits behind the FS field, so no portable argument can carry it.

    The module starts at boot and reads mstatus: 0xa00000000, with FS, the floating-point status field in bits 14:13, sitting at 0, Off. One csrs sets FS to 1, Initial. One fmv.d.x f1, x0, an instruction that moves a 64-bit value into a floating-point register, which counts as touching the unit, moves FS to 3, Dirty, and bit 63, SD, the summary dirty bit, lights with it. A second fmv.d.x leaves FS at 3: sticky. A csrc clears it back to the exact boot word. The trap counter never moved, across three byte-identical runs on QEMU 8.2.2.

    A do-not-disturb hanger on a hotel door handle
    Do not disturb means no save needed.
    Photo: Raysonho (Wikimedia Commons user Raysonho) (CC0)

    The honest version of that sequence was not the first plan. The plan was to write f1 with FS at Off and watch it go Dirty. The hardware refused: at Off, a floating-point instruction does not execute and get recorded, it raises an illegal-instruction exception instead. Off is not a starting point: floating-point instructions trap there. The unit is disabled until software enables it at Initial, and only then does a write dirty it. The plan needed two more corrections of the same kind, and all three shipped in the module's PROOF.md: the gloss said to clear FS through fcsr, but FS lives in mstatus bits 14:13; it named sstatus, but the module runs in M-mode and reads mstatus directly, sstatus being only the supervisor's view of the same bits. A module that publishes its own corrections is one worth reading.

    Why do the two bits exist at all? A process's floating-point state is thirty-two registers plus fcsr, 256 bytes of doubles the kernel must preserve across a context switch. Without FS, every switch saves and restores all of it, even for the integer-only process that never touched floating point. With FS, the trap handler reads one field and skips the spill when the answer is not Dirty. The privileged manual states the whole contract in section 3.1.6.7: the design anticipates that most context switches will not need to save or restore the floating-point state, so it provides a fast check via the SD bit. The four states are Off, where floating-point instructions trap; Initial, where the state holds the constant initial value; Clean, where the state matches the last context save; and Dirty, where the state may have changed since.

    The discipline the manual demands fits in three lines:

    if (fs == DIRTY)   { save_fpu(); fs = CLEAN; }
    if (fs == CLEAN)   { restore_fpu(); }
    if (fs == INITIAL) { zero_fpu(); }  /* constant, never memory */

    That last line is a security boundary wearing a performance costume. Restoring Initial from memory would load another process's registers into this one, so the manual demands the constant instead. The module measured exactly the flip the kernel trusts: Initial to Dirty on a single instruction, sticky on the next, cleared back to the baseline word, with no trap fired.

    One sentence to carry away: the CPU keeps a two-bit receipt of whether the floating-point state changed since the last save, so the kernel can skip thirty-two register stores on the switches that never needed them.

    The Alignment the Hardware Checks in the Entry Itself

    Relevance by layertest log
    ISA

    matters at ISA because the verified rule is the RISC-V privileged specification's own sentence, section 4.3.2: a superpage leaf whose low PPN segments are nonzero raises a page fault, so the alignment constraint binds every program that builds Sv39 page tables.

    MICROARCH

    not at Microarch because the property under test is the architecturally specified fault, identical on every compliant hart: no pipeline, cache, or predictor choice can change whether a nonzero low PPN segment faults, so the verdict is invariant across implementations.

    FIRMWARE

    matters at Firmware because the first page tables are built by hand in early boot code: a misaligned superpage entry in firmware's own mappings faults on first access, so the alignment rule is load-bearing for whoever writes the initial page-table setup.

    KERNEL

    matters at Kernel because the kernel is the heaviest user of superpage mappings, direct maps and huge pages: its page-table code must keep the low PPN segments zero when installing a superpage leaf, or every access through that mapping faults.

    ALGORITHM

    matters at Algorithm because the verification is a portable computational argument: the mask test and the top-down bit scan are two structurally different computations of the same predicate, and their agreement on thirty million pairs proves the rule rather than the code, on any target.

    Give a level-1 leaf in an Sv39 page table a physical page number of 0x200, which is bit 9 standing alone. The alignment check looks at bits 8 down to 0, finds nothing set, and the translation proceeds. Now flip one bit: a PPN of 0x201. Bit 0 sits inside the checked range, and the translation raises a page fault. Bit 9 is the first bit of the superpage's base address; bit 8 is the last bit of the offset inside the superpage. The boundary is exactly that sharp, and 53 directed rows test the bit on each side of it, plus the all-ones and all-zeros corners.

    A child fitting wooden blocks into the matching shaped holes of a sorter board
    Each shape fits only its own hole.
    Photo: Shixart1985 (attribution required) (CC BY 2.0)

    Sv39 is RISC-V's 39-bit virtual address scheme: three 9-bit page-number fields, vpn[2], vpn[1], and vpn[0], plus a 12-bit offset inside a 4 KiB page. A normal translation walks all three levels of the page table. A superpage leaf stops the walk early, at level 1 or 2, and the VPN fields the skipped levels would have consumed become the offset inside the large region instead. The finished physical address takes its low segments from the virtual address, not from the entry, so the entry's own low PPN bits, nine per skipped level, go unused. The tempting implementation ignores them. The specification refuses, in its own sentence from the virtual-address translation process, section 4.3.2: if i > 0 and pte.ppn[i-1:0] is not zero, this is a misaligned superpage. A stray bit in a hand-built entry would otherwise describe a region whose base the entry does not fully determine, and the error would be silent. The hardware faults instead of quietly using an address the entry does not fully describe.

    The check is three lines. The level tells you how many low PPN segments the leaf skipped, nine bits per level, so the mask is one shifted by nine times the level, minus one:

    uint64_t mask = (1ULL << (9 * level)) - 1;
    if (ppn & mask)
        return PAGE_FAULT;  /* misaligned superpage */

    For a level-1 leaf the mask is 0x1FF, bits 8 down to 0, which is why 0x200 passes and 0x201 faults. A level-0 leaf, an ordinary 4 KiB page, skips no levels, so the mask is zero and the rule never fires there.

    What makes the verification honest is that the oracle is a different machine from the implementation. The code above builds the mask and tests the masked PPN. The oracle never builds a mask: it walks the 44-bit PPN field from the top down and faults the moment it finds a set bit below position nine times the level. Two constructions, same verdict, on thirty million pairs (30,000,063), zero disagreements, with an FNV-1a checksum identical under -O0, -O2, and the sanitizers. The module states its edges plainly too: no walking, no permission bits, no accessed-or-dirty updates; those live in the sibling labs. A module that states its boundaries plainly is one I can trust.

    One sentence to carry away: when a page table entry maps a whole region at once, its low address bits must be zero where the region's offset lives, and the hardware faults if they are not.

    The Alarm That Will Not Leave Its Room

    Relevance by layertest log
    ISA

    matters at ISA because the enable/pending split and the WARL delegation behavior are the privileged architecture's own contracts: interrupt i is taken only when mstatus.MIE, mie[i], and mip[i] are all set, and mideleg is write-any-read-legal, so the machine may legally refuse the bit-7 write; the modules verified both with real CSR reads and writes: mip 0x80 stayed silent under mie 0x0, mcause read 0x8000000000000007 under mie 0x80, and every mideleg bit-7 write read back 0x1444 with the bit dropped.

    MICROARCH

    not at Microarch because both modules' verdicts are contract rules about register state, identical on every conforming implementation: no timing, pipeline, or cache behavior was measured, and none could change whether the trap fires or whether the delegation bit takes.

    FIRMWARE

    matters at Firmware because mie.MTIE and mideleg are writable only in M-mode, so every action under test belongs to firmware: the 64-bit arming write, the handler's all-ones disarm, the mideleg write probes, and the drop-to-S-mode observation are all M-mode operations, and on this machine the decision to hear the alarm, and the discovery that it cannot be delegated, sits in firmware's hands.

    KERNEL

    not at Kernel because the machine timer interrupt can never reach S-mode on this machine: mideleg bit 7 is read-only zero, so the armed timer trapped in M-mode with zero S-mode arrivals; a supervisor kernel's behavior is invariant under this bit, and its own timer arrives through the supervisor interrupt path, which the modules never programmed.

    ALGORITHM

    not at Algorithm because the enable gate and the WARL refusal are the architecture's privilege mechanism, not a portable technique: with no M-mode enable register and no delegable-bit contract the claim has nothing to mean, and nothing in the verified behavior travels to another machine.

    Light a fuse. On a bare-metal RISC-V machine running M-mode firmware, one 64-bit MMIO write of mtime + 5000 ticks lands in the CLINT's mtimecmp register for hart 0 at 0x02004000. The board's mtime runs at 10 MHz, so 5000 ticks is exactly 500 microseconds: a half-millisecond fuse, lit in software. Set mstatus.MIE, the master interrupt switch, but write zero to mie, the register with one enable bit per interrupt source. Poll mip, the pending register. Bit 7, MTIP, reads set: the CLINT, the core-local interruptor, lifted it when the running clock crossed the compare. Two million reads of the cycle counter roll by, a window in which an enabled interrupt would have fired within a handful of instructions, and the trap count stays zero. The fuse burned, the alarm rang, and the hart did not move. Then set bit 7 of mie, the MTIE enable. Exactly one trap fires. mcause reads 0x8000000000000007: the top bit says interrupt, the low bits say code 7, machine timer interrupt. The handler's first duty is to write mtimecmp to all ones, lifting the compare above the running clock so the alarm cannot refire. The second quiet window confirms it: the trap count stays exactly one. Three runs, byte-identical transcripts.

    A vintage twin-bell alarm clock
    The alarm rings, but the room stays shut

    Why does the enable bit exist at all? The obvious machine needs only one: the pending bit says the alarm wants attention, so take it. The break is who writes what. The CLINT sets MTIP when the clock crosses the compare; no code writes that bit, the hardware raises it and only a disarm clears it. Firmware writes MTIE: that is the running code deciding, per source, whether it may be interrupted right now. Without the split, arming the timer would be taking it: the write that sets the deadline would guarantee a trap at the deadline, with no way to leave the alarm pending while the work in flight finishes. And the split is what makes the handler's discipline load-bearing rather than polite: clear the source first, then leave. With the gate still open and the source uncleared, the trap would refire the instant the handler returns. Phase C, the trap count staying exactly one after the all-ones write, is the test that the disarm actually disarmed.

    The second module asked the next question. If MTIP is just bit 7 of the pending register, can the alarm be handed down to S-mode, where a kernel would receive it? The backlog item assumed yes: set bit 7 of mideleg, the machine interrupt delegation register, and the timer interrupt should arrive in supervisor mode. The measurement said no. mideleg is a WARL register, write any value and read back a legal one, and on this machine bit 7 is read-only zero: writes of 0x0, 0x80, and 0x14c4 all read back 0x1444, the bit dropped every time, matching the earlier mideleg-warl module's published delegable mask. The module dropped the hart to S-mode anyway and armed the timer 500 ticks out. Exactly one trap, in M-mode, mcause 0x8000000000000007, zero S-mode arrivals. On QEMU 8.2.2's virt board, the machine timer interrupt has no other room to go to. The honest scope: this is the emulator's CSR model, not silicon; real silicon publishes its own delegable set.

    The checks that carry the argument, verbatim from the two modules:

    check(trap_count == 0, "trap fired while mie.MTIE was clear");
    check(mie == MIE_MTIE, "mie readback != 0x80 after csrs mie, 0x80");
    check((rd_bit7 & MIDELEG_MTIP_BIT) == 0, "mideleg bit 7 took on readback");
    check(s_regs[0] == 0, "an S-mode trap fired: the interrupt was delegated");

    Twenty checks per module, zero failures. Three runs of the gate module on QEMU 8.2.2 produced byte-identical transcripts, checksummed identically. That is what a tight test looks like: the expected outputs are small integers, a trap count of 0 or 1, a cause code, a register readback, so there is nowhere for nondeterminism to hide.

    The module's notes contain a debugging lesson worth noting. The first routing build armed the timer 500 ticks out, 50 microseconds at the board's 10 MHz mtime, then printed its arm line before reading the armed value back. One UART line at 115200 baud takes about seven milliseconds, 139 timer expiries, so the readback measured history, not the arm. The fix reads the armed value immediately after the arm write, before any slow output. On bare metal, ordering a measurement around slow I/O is the experiment's design, not its plumbing. One sentence to carry away: a pending interrupt is a fact, an enabled interrupt is a permission, and some interrupts cannot be delegated to a lower privilege mode at all; check the delegation mask before assuming the interrupt will arrive where you want it.

    The Bell and the Switch

    Relevance by layertest log
    ISA

    matters at ISA because the trap rule (an interrupt fires only when the global MIE, the per-source mie bit, and the per-source mip bit are all set) is the privileged architecture's own contract, and the module verified it with real register reads: mie at 0x0 held the hart silent under a pending MSIP, and mie at 0x8 delivered exactly one trap with mcause reading the machine-software-interrupt code.

    MICROARCH

    not at Microarch because the gate's verdict is a contract rule about register state, identical on every conforming implementation: no timing, pipeline, or cache behavior was measured, and none could change whether the trap fires.

    FIRMWARE

    matters at Firmware because mie.MSIE is writable only in M-mode, so the arming decision belongs to firmware: the module's phase-B write is the firmware action under test, and this gate sits in firmware's hands on every RISC-V system.

    KERNEL

    not at Kernel because a supervisor kernel cannot write mie.MSIE, so its behavior is invariant under this bit: its own enable is sstatus.SIE, and its inter-processor interrupts arrive as supervisor software interrupts through firmware's sbi_send_ipi regardless of the M-mode gate.

    ALGORITHM

    not at Algorithm because the enable/pending split is the architecture's privilege mechanism, not a portable technique: with no M-mode enable register the claim has nothing to mean, and nothing in the verified behavior travels to another machine.

    Boot a bare-metal RISC-V machine in M-mode (machine mode, the most privileged; firmware runs here). Set mstatus.MIE, the master interrupt switch, and write zero to mie, the register with one enable bit per interrupt source. Now ring the bell: write 1 to the CLINT's msip register for hart 0. The CLINT, the core-local interruptor that raises software interrupts, lifts the MSIP bit, bit 3 of the pending register mip. Read mip: 0x8. Then wait. Two million reads of the cycle counter roll by, a window in which an enabled interrupt would have fired within a handful of instructions, and the trap count stays zero, mip still 0x8. The bell is ringing and the hart does not move. One more write: set bit 3 of mie, the MSIE enable. Exactly one trap fires. mcause reads 0x8000000000000003: the top bit says interrupt, the 3 says machine software interrupt. The handler clears the CLINT's msip, and the world goes quiet: the window after shows no re-delivery.

    A brass hand bell resting on a wooden table
    The bell rings; the switch decides

    Why two bits for one interrupt? The obvious machine needs only one: the pending bit says the interrupt wants attention, so take it. The break is who writes what. The CLINT sets MSIP when someone writes its msip register: that is the outside world talking. Firmware writes MSIE: that is the hart deciding, per source, whether it may be interrupted right now. Without the split, a handler could never keep the timer interrupt armed while it services a software interrupt, because arming would be taking. And the split is what makes a level-triggered source safe: the pending bit stays set until the handler clears the source, so with the gate already open the trap would refire the instant the handler returns. The discipline that follows is to clear the source first, then leave. This is not a convention. A public bug report against an open-source RISC-V core's testbench described its MSIP stuck high from reset, so the first time firmware opened the gate the hart took a machine software interrupt nobody had rung for. Hardware logic, not habit.

    The trap rule, from the privileged architecture's own text: interrupt i is taken when mstatus.MIE is set and both mie[i] and mip[i] are set. Three bits, one decision. mie is the enable half, written by the running code; mip is the pending half, written by the world, here by a 32-bit MMIO write to the CLINT at 0x02000000. The test checked the contract from both directions. With MIE set and mie at 0x0, a pending MSIP must never trap; setting mie bit 3 while MSIP is still pending must deliver the interrupt at the next instruction boundary. The machine timer was disarmed at startup, its compare register set to all ones, so the software interrupt was the only source that could ever fire; MIE stayed set for the whole run, so mie.MSIE was the only gating variable.

    The four checks that carry the argument, verbatim from the module:

    check(trap_count == 0, "trap fired while mie.MSIE was clear");
    check(mie == MIE_MSIE, "mie readback != 0x8 after csrs mie, 8");
    check(last_mcause == MCAUSE_MSI, "trap mcause != 0x8000000000000003");
    check(trap_count == 1, "trap_count != 1 after phase-B enable");

    Twenty checks in all, zero failures. Three runs on QEMU 8.2.2 produced byte-identical transcripts, checksummed identically. That is what a tight test looks like: the expected outputs are small integers, a trap count of 0 or 1, a cause code, a readback, so there is nowhere for nondeterminism to hide.

    The same shape repeats one privilege level down, with firmware holding the enable bit. M-mode firmware owns mie.MSIE; a supervisor kernel cannot touch it. So its inter-processor interrupts arrive as supervisor software interrupts instead, raised through firmware's sbi_send_ipi. Linux's RISC-V interrupt handling dispatches software interrupts to handle_ipi(), the IPI handler. Two worlds, same pattern: someone else's firmware owns the enable bit, so your level gets the pending bit plus an SBI call. Two honest boundaries: this ran on QEMU 8.2.2's model of a hart, not on silicon, so it proves the contract as the emulator implements it; and the mepc readback in the test log is this exact binary's resume address, a measurement, not a claim about other builds. One sentence to carry away: an interrupt is not a request, it is a request plus a permission, and the permission is the half you get to write.

    The Bit That Reroutes a Trap

    Relevance by layertest log
    ISA

    matters at ISA because the bit itself is the machine contract: the privileged architecture defines medeleg, assigns cause 9 to a supervisor environment call, and says a set bit 9 routes that trap to S-mode. The module checked the contract's exact shape: identical ecall, two destinations, one bit.

    MICROARCH

    not at Microarch because the destination flip is a contract property, identical on every conforming implementation: no pipeline, cache, or branch-predictor behavior was measured or asserted, and none could change which handler the trap lands in.

    FIRMWARE

    matters at Firmware because firmware is the layer that holds the pen: medeleg is only writable in M-mode, so the decision to delegate is firmware policy, and the module's phase-two setup (write 0x200, read back bit 9 set) is the firmware action under test.

    KERNEL

    matters at Kernel because the delegated trap is the kernel's syscall path: with the bit set, a supervisor kernel fields its own environment calls directly instead of receiving them forwarded down from M-mode, which is the hot path the delegation exists to shorten.

    ALGORITHM

    not at Algorithm because the mechanism is the architecture's privilege rule, not a portable technique: a trap destination switch has no meaning on a machine without M-mode, S-mode, and a delegation register, and nothing in the verified behavior travels.

    Run the same instruction twice. Boot a bare-metal RISC-V machine, drop from machine mode into supervisor mode, and execute ecall, the instruction that asks the layer above for a service. With the medeleg register at zero, the trap lands in the machine-mode handler: its cause register reads mcause = 9, the code for an environment call from supervisor mode. Write 0x200 to medeleg, which is bit 9 set, and execute the identical ecall again. This time the machine handler never fires. The supervisor-mode handler catches the trap instead, with scause = 9. Same instruction, two destinations, one bit of difference.

    Railway points where two tracks merge into one
    One switch sends the train down another track

    The bit exists because of who pays for every trap. The kernel runs in supervisor mode, and a system call is the most frequent request a machine fields: every file read, every byte on the terminal, every new process. Without delegation, each of those traps would rise to machine mode first, usually firmware, which would then have to forward it back down to the kernel that knows what to do with it. The obvious fix is a forwarder in firmware, but it sits on the hottest path in the system and would have to understand the kernel's business. Delegation removes the middleman: bit 9 of medeleg says supervisor environment calls belong to the supervisor, and the trap goes straight there. Trust, expressed as one bit.

    The mechanism, step by step. RISC-V runs code in privilege modes: M-mode, machine mode, the most privileged, where firmware boots; and S-mode, supervisor mode, where an operating system kernel runs. A trap is the hardware interrupting whatever is running and jumping to a handler; each handler reads its mode's cause register, mcause or scause, to learn what happened. medeleg is an M-mode register with one bit per trap cause: when a bit is set, traps of that cause are delegated to S-mode instead of landing in M-mode. The test checks the contract from both sides. Phase one writes 0 to medeleg, reads back 0, and demands exactly one trap in the M-mode handler with mcause = 9 and the resume address mepc pointing at the captured ecall address. Phase two writes 0x200, reads back bit 9 set, and demands exactly one trap in the S-mode handler with scause = 9 and the supervisor's own resume address sepc at the same ecall.

    The check that carries the argument is a list of small exact checks:

    check((p2_medeleg_rb & (1UL << 9)) != 0,
          "phase-2 medeleg readback missing bit 9");
    check(s_regs[0] == 1, "phase-2 S-mode trap did not fire exactly once");
    check(s_regs[2] == SCAUSE_S_ECALL,
          "phase-2 scause != environment call from S-mode (9)");

    Fourteen checks in all: the delegation readbacks, the exact trap counts per mode per phase, the cause codes, the resume addresses matching the captured ecall, the privilege records in mstatus and sstatus confirming arrival from supervisor mode, a cross-phase proof that no trap leaked into the wrong handler, and a quiet window where the counts were required not to move. Three runs on QEMU 8.2.2 produced byte-identical FNV-1a checksums over the verdict values. That is what a tight test looks like: the expected outputs are small integers, a trap count of 1 or 0, so there is nowhere for nondeterminism to hide.

    Two honest boundaries. The module ran on QEMU's model of a hart, not on silicon, so it proves the contract as the emulator implements it: the specification's text, rendered in software. And the backlog item that ordered this test said the phase-one cause would be 0xb; the test asserts 0x9 instead, because the specification assigns 0xb to an environment call from M-mode and 9 to one from S-mode, and this ecall runs in S-mode. One sentence to carry away: the destination of a supervisor's system call is one bit in a register, and setting it is how the firmware gets out of the way.

    The Bit That Survives the Context Switch

    Relevance by layertest log
    ISA

    matters at ISA because the G bit is bit 5 of the Sv39 leaf page-table entry, defined by the privileged architecture, and the verified decision procedure is the specification's own contract: a global entry's translation applies without consulting the ASID, and an sfence.vma that names one ASID must leave global entries cached. The module's walks under ASIDs 1, 2, and 9 checked exactly that shape: global equals 1, the address-space ID never consulted.

    MICROARCH

    not at Microarch because the verified property is the contract's decision procedure, identical on every conforming implementation: the 196.216 ns per lookup figure is the host model's linear scan over 256 slots, an artifact of the model, and no hardware TLB, pipeline, or cache behavior was measured or asserted.

    FIRMWARE

    not at Firmware because the G contract runs between the hart and the page tables, and nothing in the verified behavior depends on firmware: marking mappings global and choosing address-space IDs is the kernel's work, and the property holds identically however the firmware beneath it behaves.

    KERNEL

    matters at Kernel because the kernel is the layer that names address spaces: it picks the ASIDs, decides whether its own mappings are marked global, and issues the address-space-scoped fences on context switch. The module's boundary check makes this concrete, because xv6 never sets a G bit and builds every satp with ASID 0, so its kernel never asks the question this bit answers.

    ALGORITHM

    not at Algorithm because the lookup predicate is not a portable mechanism: the claim has no meaning on a machine without a G bit in its page-table entries, and the module proved the architecture's rule as written, not a software technique that travels.

    Take virtual page number 0x12345, mapped with its page-table G bit set. Walk it under address-space IDs 1, 2, and 9: all three land on the same physical address, (0xABCDE shifted left by 12) plus the 0x678 offset, and every walk reports global equals 1. The address-space ID is never consulted. Now the contrast: the same virtual page number with G clear under ASID 1 lands on a page built from 0x11111, and under ASID 2 on a page built from 0x22222. Same number, different pages, because without the G bit the address-space name is part of the key.

    The Earth seen from space, the Blue Marble
    One mapping shared by every address space.

    Here is the cost it removes. The kernel is mapped at the same virtual addresses in every process, and every context switch loads a new satp register carrying a new ASID. A full TLB flush on every switch would throw away the kernel's translations too, and each one costs three page-table memory reads to rebuild, while the TLB holds only dozens to hundreds of entries. The alternatives are flushing everything every time or storing the kernel's mappings once per address space, the same entry wearing N name tags. The G bit says: this mapping exists in all address spaces, store it once, and when the fence names a single ASID, leave it alone.

    The privileged specification says it plainer than I can. "Global mappings were devised to reduce the cost of context switches." And then the sentence that carries the whole contract: "failing to mark a global mapping as global merely reduces performance, whereas marking a nonglobal mapping as global is an error." G is a performance promise, not a correctness one, and lying in the wrong direction breaks isolation, because one process would start reaching another's pages through a shared cache entry.

    The entire rule fits in one line of the test bench, taken verbatim from the lookup it verified:

    if (e->valid && e->vpn == vpn && (e->global || e->asid == asid)) {
        r.hit = 1;
        r.pa = e->pa;
        return r;
    }

    Global entries skip the ASID check entirely; non-global entries match only on an ID match. The module proved the decision procedure, not silicon: 201,850 checks against an independently written spec table, zero mismatches, with the full result stream checksumming identically under -O0, -O2, and ASan plus UBSan. The rule held for 4K pages, 2M megapages, and 1G gigapages alike, and a branch entry's G bit was correctly ignored, because only the leaf's G decides. Two honest boundaries: the spec's own wording forks on whether a non-leaf G implies globality below it, so the lab tested the leaf-only reading and named the other as an open question. And the boundary I like best: xv6 sets no G bits and builds every satp with ASID 0, so the kernel I study never asks this question. One sentence to carry away: a translation is either named by its address space or it belongs to all of them, and one bit in the page table is the entire difference.

    The Brake Pedal on the Stopwatch

    Relevance by layertest log
    ISA

    matters at ISA because the freeze is a contract clause from the privileged specification, section 3.1.12: with the CY bit of mcountinhibit set, mcycle must not increment, and the module's one thousand identical readbacks are the evidence the clause holds on QEMU 8.2.2.

    MICROARCH

    not at Microarch because the asserted property is the specification's non-increment demand, which every conforming implementation must satisfy identically: the simulators that returned anything else were buggy rather than differently valid, and QEMU's choice of readback value is observed but never asserted.

    FIRMWARE

    matters at Firmware because the brake pedal is M-mode's control to configure: supervisor software cannot write mcountinhibit, so parking the counters nobody reads and handing supervisor mode a start and stop interface, the role RustSBI's performance-monitoring documentation describes, is firmware work.

    KERNEL

    not at Kernel because the verdict was reached with the machine in M-mode throughout and no kernel loaded: whether the counter advances is decided by the CSR bit in hardware, so the property holds identically with or without a kernel running.

    ALGORITHM

    not at Algorithm because no software sequence can stop a hardware counter: the mechanism is the CSR gate itself, and the claim has no meaning on a machine without the bit.

    Yesterday this blog measured the floor for reading the cycle counter. This note asks the opposite question: what happens when you stop it? One write of 0x1 to the mcountinhibit CSR, setting its CY bit, and one thousand back-to-back reads of mcycle came back identical, every one of them 0x0, a delta of exactly zero. One write of 0x0 to clear the bit, and the counter woke up: four samples, strictly increasing, with consecutive deltas in the tens of thousands of ticks. The brake pedal works.

    A Casio stopwatch counting hundredths of a second
    Hiding a counter never stops the counter.

    But why would a CPU ship a brake pedal for its own stopwatch? The obvious move is to simply not read the counter, or to hide it with mcounteren, and skip the register. The privileged manual breaks that answer in one sentence: mcounteren decides only who may see the counters, and the counters keep incrementing even when nobody can read them. Hiding the stopwatch does not stop it. It still ticks, it still burns power, and any reading you take later is stale by the whole interval you skipped. mcountinhibit is the other promise, the one that actually halts the mechanism. The manual gives two reasons for the brake. The first is energy: a counter nobody is reading is heat and switching power for nothing, so M-mode firmware parks the ones it does not need. The second is atomic sampling, and this is the elegant one: one CSR stops every counter at once, so the cycle count and the instruction count can be read at leisure, knowing neither advanced in the gap between the reads. Without the brake, the two samples are taken a few instructions apart, and the pair lies about the same instant. RustSBI's performance-monitoring documentation states it directly: from supervisor mode these counters can only be started, stopped, or configured through mcountinhibit.

    The whole mechanism is one CSR write. Three lines, taken verbatim from the module:

    static void write_mcountinhibit(unsigned long v) {
        __asm__ volatile("csrw mcountinhibit, %0" ::"r"(v) : "memory");
    }

    One call with the CY bit set freezes mcycle; one call with zero restarts it. Seven checks guard the behavior: the CY write reads back with the bit set, all one thousand freeze samples match the first, the clear reads back exact zero, the resume spin never trips its bound, the four resume samples strictly increase, the total resume delta is positive, and the trap count stays zero. Seven checks, zero mismatches, on QEMU 8.2.2.

    Two honest boundaries. If two harts share one mcycle on a core, the CY bit is shared too, so one hart's brake pedal is visible from the other. And mtime, the wall-clock cousin of mcycle, cannot be inhibited at all, because it can be shared across cores and nobody owns the pedal. The QEMU note matters as well: on QEMU 8.2.2 the frozen counter reads back as 0x0, which is the model's choice, not the spec's demand. The spec requires only that it not increment, and the module asserts only that. That distinction is not academic, because this is exactly the corner where simulators have disagreed: Renode once shipped a bug where the inhibited counter advanced one more tick after the bit was set, filed as an issue with a reproducer, while Spike, QEMU, and RVVM all held still. The thousand-identical-reads test is precisely the test that catches that off-by-one, so the module is not only a demo of the gate, it is a conformance clause, and the model's answer is on the record. One sentence to carry away: a cycle counter is not a fact of nature, it is a peripheral with an enable bit, and the architecture gives M-mode both a curtain (mcounteren, which hides) and a brake (mcountinhibit, which stops), because seeing the time and stopping the clock are two different promises.

    The Page That Was Never There

    Relevance by layertest log
    ISA

    not at ISA because the claim is the kernel's growth ceiling, a count of drained page frames: the five checks would give the same verdict on any machine whose kernel refuses growth at its limit, so no machine-contract behavior is what the test proves

    MICROARCH

    not at MICROARCH because where the ceiling sits is set by the pool size and the allocator's arithmetic, not by the implementation behind the kernel: the test counts pages, and the count is indifferent to the core underneath

    FIRMWARE

    not at Firmware because the test runs in user space and the refusal originates in the kernel's page allocator: no machine-mode code or boot configuration decides the number the loop discovers

    KERNEL

    matters at Kernel because the growth ceiling is kernel memory management made measurable: sys_sbrk calls growproc, growproc calls uvmalloc, uvmalloc calls kalloc once per page, and the -1 the loop finally sees is kalloc's empty free list reported up the whole chain

    ALGORITHM

    matters at Algorithm because grow-until-refusal plus recheck is a portable capacity-finding protocol: grow while the allocator succeeds, confirm the boundary arithmetic, confirm the refusal is stable; it ports to any allocator with a hard failure signal

    Ask the operating system a question most programs never ask: how much memory can I actually have? The sbrkoom test asks it the blunt way: call sbrk(4096), the system call that moves the heap's break one page at a time, until the kernel says no. On a 128 megabyte QEMU machine the answer came back as a measured number: 32,468 pages, 132,988,928 bytes, about 126.8 megabytes. The break started at 0x4000 and stopped at 0x7ED8000, exactly 32,468 pages later, and a second sbrk(4096) still returned -1, so the ceiling is stable, not a hiccup.

    A motel with a NO VACANCY sign
    No free page? The allocator posts this sign.

    Here is why the kernel cannot lie about this number. The test used the eager path, which is also the default: sbrk(n) calls sys_sbrk(n, SBRK_EAGER). The syscall calls growproc, growproc calls uvmalloc, and uvmalloc calls kalloc once per page, mapping each physical frame into the page table before the break moves. The -1 you finally see is kalloc finding its free list empty. No policy is consulted and no limit is configured anywhere; the pool of physical pages is literally exhausted. The machine holds 128 megabytes, the test allocated 132,988,928 bytes of it, and the roughly 1.2 megabytes left over are the kernel, its page tables, and everything else alive at boot.

    The obvious alternative is the one most programs live with: ask malloc and trust the number. On a stock Linux box that number can be fiction. The default overcommit mode is heuristic: the kernel approves the mapping and only discovers the shortage when you touch the pages, and then the OOM killer picks a victim and shoots it. The figure malloc hands you is a promise; the truth arrives later, as a dead process. My xv6 tree even ships the lazy twin of that design: sbrklazy moves the break without allocating a thing. The test pinned only the eager ceiling, and the eager one is the honest one: every page paid for in physical frames before the break moves, so the number it reports is measured, not promised.

    The loop is the whole argument, six lines, taken verbatim from the test:

      for (;;) {
        p = sbrk(PAGESZ);
        if (p == (char *)-1)
          break;
        pages++;
      }

    p counts the pages the kernel agreed to, and the loop stops at the first -1, the kernel's only way of saying the free list is empty. Five checks guard the arithmetic: the refusal happened, the final break equals the starting break plus pages times 4096, a second request still fails, the heap end is page-aligned, and the size accounting is consistent. Five checks, zero mismatches, one checksum to recheck the numbers against. One sentence to carry away: a process's growth ceiling is not a configured limit but a measured fact, the exact point where the kernel's page pool runs dry, and in the eager design the kernel tells you the truth at that moment because it already paid for everything it gave you.

    The Multiply With No Multiply

    Relevance by layertest log
    ISA

    matters because whether a multiply instruction exists is an ISA contract question: base RV32I has no MUL, it lives in the optional M extension, and this lab is the software that contract demands on cores that skip M, proved to return exactly what the instruction returns

    MICROARCH

    not here because the verdicts are differential equalities that hold regardless of pipeline, cache, or predictor behavior: no microarchitectural fact can move any check, and the 47.232 ns figure is a timing ceiling, not a claim about any microarchitecture

    FIRMWARE

    not here because the module is ordinary userland C compiled by gcc and run as a process: no boot code, no PMP entry, no SBI call enters the computation, so nothing firmware does can move the result

    KERNEL

    not here because the multiply is a pure function of its two input values: whichever kernel schedules the process, the same inputs give the same product, so kernel behavior cannot move the verdict

    ALGORITHM

    matters because the schoolbook expansion on 16-bit halves, with the 2^32 term provably vanishing, is a pure computational mechanism: the masked-shifted combine performs the inner mod 2^16 in ordinary unsigned arithmetic, and the proof is exhaustive over all 4.3 billion input pairs

    Base RISC-V, RV32I, has no multiply instruction. The mul instruction lives in the M extension, which is optional, and a core that skips M still has to multiply. The software that does it is what compilers emit and what this lab writes by hand. The obvious move is to write a * b and trust the compiler; on an M-less core the compiler has no multiply to emit, so it calls a library routine instead. The lab takes the harder road on purpose: it bans the * operator from the source entirely, then checks the compiled object to make sure the compiler did not smuggle one back in. The claim has to hold beneath the abstraction, so the check runs beneath the abstraction.

    An abacus
    No multiply instruction, just place value discipline.

    One you can check by hand. Take A = 0x00020003 and B = 0x00040005. Split each into 16-bit halves: a1 = 2, a0 = 3, b1 = 4, b0 = 5. Schoolbook multiplication is the grade-school kind: multiply every pair of digits and add the partial products at their positions. The expansion is A*B = a0*b0 + (a0*b1 + a1*b0)*2^16 + a1*b1*2^32. Modulo 2^32, the last term carries a factor of 2^32 and vanishes, and of the middle term only the low 16 bits survive the 2^16 scaling. So a0*b0 = 15, and the cross term is 3*4 + 2*5 = 22, times 65536 is 1,441,792. Add 15: 1,441,807, which is 0x16000F. Check it against the real multiply: 131,075 * 262,149 = 34,361,180,175, and mod 2^32 that is exactly 1,441,807. The shifts and adds agreed with the hardware multiply, without ever being one.

    Each 16-by-16 partial product is exact in 32 bits, built the way lab/126 builds it: for each set bit i of one half, add the other half shifted left by i into a 32-bit accumulator. The lab's function is called mullo32, and the code is the insight here:

    uint32_t r = p0;
    r += (p1 & 0xFFFFu) << 16;
    r += (p2 & 0xFFFFu) << 16;
    return r;

    Four lines, taken verbatim from the module. p0, p1, p2 are the three partial products a0*b0, a0*b1, a1*b0. The masks keep only the low 16 bits of the cross terms, the shifts place them at bit 16, and adding them one at a time in unsigned arithmetic performs the inner mod 2^16 for free. The a1*b1 term is never computed at all: it would carry a factor of 2^32, so it cannot touch the low 32 bits of the answer.

    The test oracle is the native expression (uint32_t)(a * b), deliberately a different computation from the schoolbook expansion, so agreement pins the identity instead of a shared bug. The source ban is checked two ways: a text search for * finds hits only in comment delimiters and prose, and the Makefile compiles the file alone at -O2 and fails the build unless the object contains zero multiply instructions. gcc 13.3.0 compiled the shift-add loops branchless, bit-test plus conditional move, and inlined them; the disassembly has no mul or imul anywhere. Lab/126 ran every one of the 4,294,967,296 pairs of 16-bit values, all 4.3 billion of them, exhaustive, zero mismatches, with one checksum identical across -O0, -O2, and the sanitizer build. Lab/128 ran 17,777,216 checks, 16.7 million exhaustive 24-bit values plus a million random 64-bit pairs, zero mismatches. Best of five at -O2: 47.232 nanoseconds per value, the timing honestly including the random-input step and the running accumulate, about the time light needs to cross a large room. The honest boundary: the module ran on the host toolchain, so what the 4.3 billion checks prove is that the shift-add construction returns exactly what the multiply instruction returns; the M-less core is why the construction matters, not where it was measured. One sentence to carry away: an instruction the base ISA never had, rebuilt from shifts and adds, and proved identical to the hardware multiply on 4.3 billion inputs without a single mismatch.

    The Bit That Reads Execute-Only Pages

    Relevance by layertest log
    ISA

    matters because the gate is the privileged specification's own load rule in section 4.1.1.6: MXR=0 means loads need R, MXR=1 means loads need R or X, and the module measures exactly that contract on 31 checks with zero mismatches

    MICROARCH

    not here because the traps are synchronous and the run is single-hart on QEMU 8.2.2 TCG: no pipeline, cache, or predictor behavior enters any verdict, so microarchitectural variance cannot move the result

    FIRMWARE

    matters because the whole stage is M-mode firmware work: building the Sv39 tables by hand, opening one PMP NAPOT entry, delegating the fault with medeleg bit 13, and mret-ing into S-mode; without that firmware the gate has nothing to measure

    KERNEL

    matters because the S-mode payload is kernel-shaped: its trap handler takes the delegated fault, records scause, stval, and sepc, and resumes at sepc plus 4; and the trap-and-emulate handler the bit was written for is a kernel's job

    ALGORITHM

    not here because nothing is computed: the piece is about a hardware permission record that changes which loads fault, not a procedure

    One page at virtual address 0x40000000, mapped execute-only: the flags read valid, executable, accessed, dirty, and no read bit. A page-table entry is the 64-bit word the memory-management unit reads on every access to decide what a virtual page maps to and what may be done with it; this entry may be executed but not read. Two phases, one load instruction. Phase A runs with MXR explicitly clear: the load raises exactly one trap, scause 0xd, the load page fault, with stval holding the faulting address and sepc pointing at the labeled load. t0 was poisoned to zero right before the load; after the handler advanced sepc past the instruction and returned, t0 was still zero. That is the part that makes it a proof rather than a story: the poison proves the load never completed. Phase B sets MXR with one csrs to sstatus: the identical load from the identical address returns the canary, 0xe4ec0d1edeadbeef, and the trap counter never moves past one. The only thing that changed between a fault and a success was one bit.

    A hallway seen through a one-way mirror
    One bit turns the mirror into a window.

    The natural objection: who marks code execute-only and then reads it? The privileged specification's own commentary answers. Section 4.1.1.6, checked in two copies of the manual this week: MXR was conceived for M-mode routines emulating missing hardware features, misaligned loads and stores being the example. A trap-and-emulate handler has to fetch the very instruction it is about to fake, and if the program's code pages are execute-only, the handler needs a read path that does not relax the page. If you own the pages, the obvious move is to mark them readable too. xv6 does exactly that: its vm.c maps kernel text with read and execute together, so the bit would change nothing there (checked in the tree this week). MXR is useful when the code is not yours to re-mark. It is the emulator's bit.

    MXR is bit 19 of sstatus, and the whole mechanism is one CSR write: the hardware's load rule becomes readable or executable instead of readable. The code is the insight here:

    __asm__ volatile("csrc sstatus, %0" :: "r"(SSTATUS_MXR));  /* Phase A: gate closed. The ld below faults with scause 0xd. */
    __asm__ volatile("csrs sstatus, %0" :: "r"(SSTATUS_MXR));  /* Phase B: one bit. The same ld returns the canary. */

    Six lines, two of them the mechanism, taken verbatim from the module. The csrc closes the gate for phase A, the poison proves the load never completes, and the csrs opens it for phase B. The faulting load carries a global label, mxrs_fault_load, so the handler can check that sepc points exactly at the faulting ld, not merely nearby. One CSR instruction is the entire difference between a fault and a canary.

    Thirty-one checks, zero mismatches, a checksum over the verdict values identical across three runs, and the raw UART outputs byte-identical. The honest boundaries, stated in the module itself: this verifies QEMU 8.2.2's model of the rule, not silicon; only the supervisor load path was measured, stores through X-only pages are untested, and the spec's rule touches loads only. One sentence to carry away: one bit in sstatus rewrites the load rule from readable to readable or executable, and the manual says it exists so an emulator can read the very instruction words it is about to fake.

    The Twelve Bits the Walk Never Touches

    Relevance by layertest log
    ISA

    matters because the 44-bit page number at PTE bits 53:10 and the offset pass-through, pa.pgoff equals va.pgoff, are the privileged ISA's own address-formation contract: the proof checks the implementation against that contract on 60,331,824 cases

    MICROARCH

    not here because the proof checks the address-formation arithmetic in software; no TLB, walk hardware, or cache behavior is exercised, and the formation is identical on any implementation, so microarchitectural variance cannot move the result

    FIRMWARE

    matters because M-mode firmware builds Sv39 page tables: every leaf entry it writes must carry a page number that forms the correct physical address by exactly this shift-and-OR, before the hardware will walk the table

    KERNEL

    matters because the kernel turns page-table entries into physical addresses constantly: xv6's walk() always descends to level 0, so every xv6 mapping is exactly the 4 KiB case this lab proves

    ALGORITHM

    not here because the 44-bit and 12-bit split is the ISA's fixed contract: outside Sv39 the same shift amounts mean nothing, so the proven identity carries no ISA-independent claim

    Take a physical page number, say 0x80000, and an offset, say 0xabc. The physical address is 0x80000abc: the page number shifted left by 12, ORed with the offset. A physical page number names which 4 KiB page holds your byte; the offset is the low 12 bits, which pick the byte inside that page. Everything this lab proves hangs on that split.

    A Hayabusa Shinkansen bullet train at a platform
    The offset rides the walk like an express.

    The part that keeps pulling me back is not the arithmetic, it is what the arithmetic refuses to do. A page-table walk never rewrites the low bits of your address. The privileged specification says it plainly in section 4.3.2: the page offset of the physical address equals the page offset of the virtual address. The tables decide which page your data lives on; the offset rides through the whole walk untouched.

    It generalizes beautifully, and the invariant is the same at every scale. When the walk finds its leaf one level up, a 2 MiB megapage, the pass-through window grows: the upper page-number bits shift by 21 and the low 21 bits of the virtual address are copied verbatim, with the hardware faulting on a misaligned superpage if the low 9 bits of the page number are not zero. At two levels up, a 1 GiB page, the top bits shift by 30 and 30 bits of your address ride through, the low 18 required zero. Translation replaces the page number and copies everything below it untouched. The bigger the page, the more of your address passes through unchanged.

    The code is the insight here:

    uint64_t phys_addr_from_ppn(uint64_t ppn, uint64_t offset) {
        return ((ppn & 0xFFFFFFFFFFFULL) << 12) | (offset & 0xFFFULL);
    }

    Three lines. The shift moves page-number bit k to address bit k plus 12; the masks make the contract explicit, 44 bits for the page number, 12 for the offset, and anything above those widths is never read, so a stray high bit in a caller cannot leak into the address; the OR recombines two disjoint fields, so no carry can cross between them. Your xv6 walk() always descends to level 0, so every mapping it builds is exactly the 4 KiB case this formula covers.

    The test is deliberately built nothing like the code it checks. The oracle never shifts a whole field: it walks destination bits 0 through 55 and sets each one individually from a single-bit extraction, so it shares no structure with the implementation and cannot share its bugs. 60,331,824 checks, roughly one for every second in almost two years, zero mismatches, and the checksum 235e187d99433244 identical across three builds. One conversion costs 4.275 nanoseconds, best observed, about the time light takes to cross four feet of a room. The honest boundary: the lab proves the 4 KiB case. The megapage forms above are verified against the spec text, not yet against a differential oracle, so they are the next rung, not a claimed proof.

    One sentence to carry away: the page walk replaces the page number and copies everything below it untouched, and the bigger the page, the more of the address rides through.

    The Gate With Three Locks

    Relevance by layertest log
    ISA

    matters because the R/W/X/U encodings and the fault rules are the Sv39 privileged ISA's own contract: the proof checks the implementation against the manual's rule table on every one of the 96 flag, access-type, and mode combinations

    MICROARCH

    not here because the proof checks the permission rule table on the host, not a page-table walk; no TLB, walk, or fault-delivery hardware behavior is measured

    FIRMWARE

    matters because M-mode firmware builds the page tables: writing a PTE with W set and R clear bakes in a guaranteed fault, and the proof pins exactly which encodings are legal before any table is built

    KERNEL

    matters because the kernel's page-fault path and its permission changes live by these rules: the checked function is the rule the kernel applies when it decides whether an access faults

    ALGORITHM

    not here because the check transcribes the ISA's rule table into boolean logic; outside Sv39 the same code means nothing, so there is no ISA-independent mechanism to argue

    Take a page-table entry with R=1, W=1, X=0, U=0. Read the flags the way the hardware does: readable, writable, not executable, and owned by the supervisor, since U=0 marks a supervisor page. A page-table entry is the 64-bit word the memory-management unit reads on every access to decide what a virtual page maps to and what may be done with it. Now run a load instruction in supervisor mode against this page. The verdict comes from three questions asked in a fixed order. The load passes all three and proceeds. Run the same load from user mode and it dies at the second question.

    Padlocks chained along a bridge railing
    Three checks in a row, then you pass.

    The questions, in the order the specification's walk step applies them. First, the contradiction check: if W=1 and R=0, the access faults before any permission logic runs. Second, the privilege check: with the SUM bit clear (the lab states this boundary; SUM is the bit that would let the supervisor read user pages), a U=0 page is closed to user mode and a U=1 page is closed to supervisor mode. Third, the grant: a load needs R, a store needs W, an instruction fetch needs X. An entry with R=W=X=0 is not a leaf at all but a pointer to the next table level, so the grant gives it nothing, as it should.

    The obvious design skips the first question and lets the grant logic sort it out: a page marked W=1, R=0 would simply fail loads and pass stores, writable-but-not-readable. The reason the specification bans the encoding instead is the invariant it protects: every writable page is also readable. If the contradiction could be written into a table, some piece of hardware would have to decide what a store to such a page means, and no two implementations would decide the same way. The fault keeps the contract free of contradictions, so no hardware ever has to interpret one.

    The code is the insight here:

    if (w && !r)  /* Rule 1: W=1 requires R=1. Encodings 010 and 110 fault. */
        return 0;

    Three lines, and the placement is the point: this runs before the privilege check and before the grant switch, matching the order of the specification's walk step. The single condition is the whole invariant, writable implies readable, enforced at the gate rather than argued about later.

    The proof runs every combination the table can express: 16 flag combinations times 3 access types times 2 privilege modes, 96 rows. That is the entire rulebook; there is no 97th row to miss. The oracle is built nothing like the implementation on purpose: the forbidden encodings as two explicit (r, w, x) patterns instead of the implication, the grant as a table instead of a switch, the privilege rule as its own predicate instead of early returns, so a bug hiding in one shape cannot hide in the other. Zero mismatches across all 96 rows, with the checksum efd3419afd2b56cb pinned across builds. One check costs 4.423 nanoseconds on this machine, a few billionths of a second, and a running kernel asks this question on nearly every memory access, millions of times a second, which is why the gate has to be cheap. The honest boundary, stated in the lab: this proves the leaf verdict only. Not the valid bit, not the accessed and dirty bits, not physical memory protection, not silicon. A proof that lists its own boundaries is the honest kind.

    One sentence to carry away: a page-table entry's permission bits are a three-filter gate, contradiction first, privilege second, grant third, and the two forbidden encodings exist so that writable-but-not-readable can never be written into a table.

    The Ten Fields in One Word

    Relevance by layertest log
    ISA

    the field boundaries under test are the privileged specification's own Sv39 contract: PPN in bits 53:10, RSW in 9:8, the eight flags in 7:0. The piece checks agreement with that contract on 4,304,967,566 inputs with zero mismatches; the lab did not choose this layout, the specification did.

    MICROARCH

    the proof compares decoded field values against a per-field reference, a value operation on the input word: which bits sit at each position is fixed by the word itself, so no unmeasured pipeline, cache, or predictor behavior could move the result. The 9.626 ns figure is reported as a measurement, not part of the proof.

    FIRMWARE

    the decoder configures no trap vector, CSR, or privilege level; it treats the PTE layout as a bit-field specification to parse, the way one parses a file header. Firmware sets up page tables, it does not decode individual entries, so no firmware configuration stands between the input and the claim.

    KERNEL

    PTE decode is what the kernel does when it walks page tables and handles page faults: xv6's walk() reads each level's entry to extract the page number and check the permission bits. The verified property is the parsing step kernel virtual memory depends on; a misdecoded entry here is a wrong mapping or a missed fault in the kernel.

    ALGORITHM

    teaches the one atomic idea a builder needs: exact bit-contract parsing through shift-and-mask identities, with the round-trip invariant (encode(decode(pte)) equal to pte) as the proof that the fields partition the word. The mechanism ports to every ISA; only the boundaries come from the RISC-V contract.

    Take the word 0x20000007 and read it as a page-table entry. Bit 0 is set, so the entry is valid. Bit 1: readable. Bit 2: writable. Bits 3 through 9 are clear. Shift right by 10, mask to 44 ones, and the top field reads back 0x80000. A valid, readable, writable page at physical page 0x80000. Every page fault your kernel will ever handle starts with exactly this parsing step: xv6's walk() reads each level's entry to pull out the page number and check the permission bits. A misdecoded entry is a wrong mapping or a missed fault, so the parsing gets its own proof, small and focused, nothing else.

    An opened Swiss Army knife with its tools fanned out
    Ten tools in one handle, one word.

    The obvious way to parse a fixed bit layout in C is a struct with bitfields, one named field per entry part, widths in the declaration. The honest reason not to is that C leaves bitfield layout implementation-defined. The compiler is free to pack the fields in an order you did not ask for, so the struct expresses a hope, not a contract. The lab decodes with shift-and-mask identities instead: one shift and one mask per field, every boundary explicit in the source. Shifting right by k moves bit k into position 0; masking with a run of ones keeps exactly the field width and clears everything above. The mechanism is portable to every ISA; only the boundaries come from the RISC-V contract.

    The layout is the privileged specification's own: 44 bits of physical page number in bits 53:10, two bits reserved for supervisor software in 9:8, then the eight flags, dirty, accessed, global, user, execute, write, read, valid. The ten field masks are disjoint and cover bits 53:0 with no overlap and no gaps, so the fields partition the word, and shifting each field back to its position and ORing restores the entry exactly. That partition is the whole invariant: encode(decode(pte)) equals pte, and the test checks it on every one of the 4.3 billion cases.

    The code is the insight here:

    f.v   = (uint8_t)(pte & 1ULL);           /* bit 0: valid */
    f.rsw = (uint8_t)((pte >> 8) & 3ULL);    /* bits 9:8: supervisor software */
    f.ppn = (pte >> 10) & 0xFFFFFFFFFFFULL;  /* bits 53:10: physical page number */

    Three of the ten fields; the other seven follow the same identity. The flag order, valid up through user, matches xv6's kernel/riscv.h bit for bit, so the layout the lab checks is the layout a real kernel reads.

    The best part is the promise about the bits the decoder never touches. Bits 63:54 are reserved for future use: decode never reads them, and encode always leaves them clear. That is checked, not assumed. Every directed edge value goes through twice, once bare and once with those top ten bits set, and the decoded fields must come out identical. 108 checks just to prove the reserved bits never affect the decode.

    The full count: 4,304,967,566 cases, more than 4.3 billion, zero mismatches. Every 32-bit word that exists, ten million fixed-seed 64-bit randoms, 162 directed edges, and the reserved-bits row. The oracle is deliberately built nothing like the implementation: one loop per field, each field assembled bit by bit through a pointer table, no helper code shared with the thing it tests. A second, independently written per-bit Python reference cross-checked 200,162 more values, also zero mismatches, and the checksum of every decoded output is e3c4316e414a6146. One honest caveat on speed: three timing runs on this noisy VM gave 25.782, 9.626, and 11.195 nanoseconds per decode, so the 9.626 number is the best observed, not a promise. One sentence to carry away: a page-table entry is a fixed bit contract from the privileged specification, and this test proved the decoder agrees with it on more than four billion cases without a single mismatch.

    The Bit That Records the Pre-Trap Privilege Mode

    Relevance by layertest log
    ISA

    the behavior under test is the RISC-V privileged specification's trap contract: sstatus bit 8 records the pre-trap privilege mode and sret restores it, measured directly by the module.

    MICROARCH

    no pipeline, cache, or predictor behavior is measured or claimed; the traps are synchronous and the module times nothing.

    FIRMWARE

    the M-mode half of the module is firmware work: it sets medeleg bit 9, opens the address space with one PMP NAPOT entry, and srets into S-mode, and that setup makes the S-mode measurement possible.

    KERNEL

    the S-mode handler is the kernel's trap entry, and the bit is load-bearing for real kernels: xv6's usertrap and kerneltrap panic when SPP contradicts the expected caller.

    ALGORITHM

    no computational mechanism is taught here; the piece is about a hardware record kept across a privilege transition, not a procedure.

    A bare-metal program ran the same trap twice and read the same answer both times. M-mode delegated supervisor ecalls to S-mode with medeleg bit 9, opened the whole address space with one PMP NAPOT entry, and dropped into an S-mode payload through sret. The payload issued two ecalls. Each trap landed in the S-mode handler, which read three values: SPP = 1, scause = 9, sepc = 0x800002a8, identical on both traps. The word sitting at that address was 0x73, the ecall instruction itself.

    A metal bookmark with a pink tassel
    SPP saves the privilege mode that sret restores.

    SPP is bit 8 of sstatus, and the hardware writes it at the instant of the trap: the privilege mode the hart was in just before the trap. At the same time it copies the old interrupt-enable bit into SPIE and clears SIE, so no interrupt can re-enter the handler mid-stream. When the handler executes sret, the reverse happens: the privilege mode is restored from SPP, SIE from SPIE, then SPIE is set to 1, SPP cleared to 0, and the hart resumes at sepc. Push on trap, pop on sret. The trap path has a call stack exactly one frame deep, and the hardware maintains it.

    Why does the hardware keep this record? Because one S-mode handler fields traps from two very different callers, and nothing else records which one called. The xv6 source tree checks it the way the hardware means it to be checked. In usertrap(), near the top of the function: if ((r_sstatus() & SSTATUS_SPP) != 0) panic("usertrap: not from user mode"). In kerneltrap(): if ((sstatus & SSTATUS_SPP) == 0) panic("kerneltrap: not from supervisor mode"). And usertrapret() deliberately clears SPP to 0, with the comment "clear SPP to 0 for user mode", before sret returns to the process. The hardware record is the only one that cannot be forged or miscomputed, because it is written at the exact instant of the trap. Without it the handler would have to infer the caller from sepc or saved state, and a kernel should not guess about who it was talking to.

    One limitation: one bit holds one frame. Every trap overwrites SPP, so a trap taken inside the handler destroys the first record. The module's handler therefore reads sstatus before it dispatches on scause, copying the bit into a sticky per-trap slot. The code is the insight here:

    csrr t1, sstatus  // sstatus.SPP is bit 8
    srli t1, t1, 8
    andi t1, t1, 1

    The record only survives if the handler keeps its own copy, the same discipline as saving callee-saved registers. The M-mode sibling works the same way one level up, except MPP holds two bits because M-mode traps can arrive from three levels: user, supervisor, or machine, with MPIE and MIE mirroring SPIE and SIE around mret.

    The checking, because that is the whole point: 11 checks, zero failures, and the three QEMU runs byte-identical, the same checksum 0x81dc6b1b81f94783 over the recorded values every time. One honest boundary from the proof file: this measures QEMU's model of the privileged contract, not silicon, and only the synchronous S-mode ecall path; interrupts, page faults, and traps from user mode are separate measurements. One sentence to carry away: the hardware records the caller's privilege mode on every trap, and sret restores exactly that.

    The Four Bytes the Trap Handler Skips

    Relevance by layertest log
    ISA

    matters because it pins the mepc-advance rule for skipping exactly one faulting instruction, including the compressed-instruction length check and why assembler labels beat C labels-as-values

    MICROARCH

    not here because the post teaches the mepc-plus-four resume rule; trap timing and pipeline effects are never discussed.

    FIRMWARE

    not here because the article isolates the mepc-advance contract itself; no boot-time firmware code is written.

    KERNEL

    not here because the article derives the skip rule for a bare handler; no kernel trap path runs.

    ALGORITHM

    not here because mepc and variable-length instruction encoding are RISC-V machine specifics, not portable logic.

    A trap fires, say a load from an unmapped address. The hardware writes the faulting instruction's address into the mepc register and jumps to your handler. When the handler returns, the CPU resumes at whatever mepc points to. If the handler changed nothing, the CPU re-runs the same bad load, traps again, and you have an infinite loop. So the handler's most basic job is to move mepc past the dead instruction before returning.

    A tape measure showing inch subdivisions
    Measure the instruction before advancing the PC.

    How far past? RISC-V instructions arrive in 16-bit parcels, and the length hides in the lowest two bits of the first parcel: anything but 11 there is a 16-bit compressed instruction, and 11 starts the longer forms. A handler that blindly adds 4 will land in the middle of an instruction whenever the faulting one was compressed, and the CPU will try to execute half an instruction.

    This module pins the fault site to exactly 4 bytes, twice over. First it assembles the faulting load under .option norvc, which tells the assembler to emit no compressed instructions in that region. Then it refuses to trust that promise alone: it captures the address on both sides of the faulting load with in-assembly numeric local labels, la t0, 1f before and 1: after, and the test asserts at runtime that the two addresses differ by exactly 4.

    Why in-assembly labels instead of a C labels-as-values label? A C label only stays where the programmer put it if a computed goto can reach it. With no computed goto in range, -O2 is free to merge blocks and move the label, and the captured address follows the label to its new home. An assembler numeric label is resolved by the assembler exactly where written. That is the whole reason, and the construction is trustworthy because of it.

    The test then proves the skip happened exactly once: the trap counter reads exactly 1, since a re-trap would have made it 2; the 0xdeadbeefdeadbeef marker still sits at its address, since a skip of 8 would have sailed over it; mcause reads 5 for a load access fault with the bad address in mtval; the instruction word at the fault address reads 0x0005a503, the intended lw; and the destination register still holds its pre-fault sentinel, proving the faulting load never committed. Three QEMU runs, byte-identical.

    One honest boundary. The xv6 kernel gets away with mepc += 4 after an ecall only because ecall has no compressed form. This module is the general case: prove the instruction's length first, then skip it. And the verification is against QEMU's M-mode model, which is faithful, but it is still a model, not silicon. In one sentence: a trap handler that skips must know the instruction's length, and the only length worth trusting is one measured at runtime from both sides of the fault.

        la      t0, 1f          # capture the address before the faulting load
        lw      a0, 0(a1)       # the fault: 4 bytes, guaranteed by .option norvc
    1:                          # mepc advances here; the test asserts the gap is 4
    02 / SERVICES + PRICING

    Choose the closest fit. Each option is fixed-scope, starts with a clear finish line, and ends with a concrete handoff.

    NOT FOR

      Engineering services firms: subcontract firmware and bring-up hours, white-label or bench work. Weekly availability on request.

      03 / HOW IT WORKS

      Problem in, tested handoff out.

      First email in; a result your team can inspect, build, and test out.

      Bring the crash log. I’ll bring the questions.

      Available for small, fixed-scope firmware work and code reviews. A complete first email lets me respond with a useful scope instead of another round of questions. I read every inquiry and reply as soon as I can.

        services

        Choose how to get in touch

        The project brief is filled in for you.

        Compose in Gmail Use my email app