Source-linked AI summary
Extending concurrent separation logic to the hardware level to verify the xv6 OS kernel on RISC-V with AI agents
M. Frans Kaashoek, Nickolai Zeldovich
TL;DR
Verifying OS kernels requires reasoning about intricate hardware behavior and concurrency, a challenge MachCSL addresses by adapting concurrent separation logic to low-level RISC-V semantics. A 77-day effort produced a machine-checked proof of xv6 and uncovered bugs in xv6 and the Sail RISC-V model.
Problem
Verifying OS kernels is difficult because proofs must account for intricate hardware behavior and substantial concurrency.
Source: §1 · pp. 1–2Method
MachCSL adapts concurrent separation logic to machine-check xv6 against Sail RISC-V semantics and models of interconnect, shared memory, devices, and power failures.
Source: §1 · pp. 1–2Results
77 days produced a closed whole-kernel proof of xv6 and uncovered several xv6 bugs plus a bug in the Sail RISC-V model.
Source: §1 · p. 3Takeaways & Limitations
The proof largely worked with xv6 as written, requiring almost no changes beyond bug fixes.
Source: §9.1 · p. 35MachCSL proofs are tied to a precise kernel binary, so source changes can require pervasive proof updates.
Source: §3 · p. 9
Abstract
from arXiv · showhide
MachCSL is a framework for verifying systems software, such as an OS kernel, on top of low-level semantics of a RISC-V computer, based on the Sail RISC-V semantics. The key idea behind MachCSL is to adapt concurrent separation logic, based on Iris, to reasoning about low-level hardware execution at the sub-instruction level: page-table translation, TLB, privilege levels, configuration registers, instruction fetch/decode/execute, traps and interrupts, DMA, shared memory, power failures, etc. Reasoning at this level of detail ensures that the system software correctly manages all of the hardware details. Verifying software at this low level of abstraction is tedious, but LLM-based agents are capable of reasoning about such low-level details. As a case study, we verify the xv6 OS kernel (6,593 lines of C and assembly code), which provides a traditional Unix system call interface (processes, file system, file descriptors, and preemptive scheduling) and has substantial internal concurrency (multi-core support with fine-grained locking, shared memory, interrupts, DMA, etc.). In the verification process, we uncovered nine bugs in the xv6 implementation, as well as one bug in the Sail RISC-V semantics. The verification effort took us 77 days, including the time to develop the MachCSL framework.
MIT CSAIL · 1 Introduction
MachCSL uses concurrent separation logic to verify xv6 against sub-instruction-level RISC-V hardware semantics. The whole-system theorem establishes kernel invariants implying process isolation, crash recovery, and internal consistency.
1 Introduction
- Kernel verification is difficult because operating systems must manage hardware isolation and devices while implementing abstractions and handling concurrency, interrupts, DMA, and crashes.Prior formal-verification work demonstrated proofs for microkernels, hypervisors, and security monitors; this work proves xv6 directly against a low-level RISC-V hardware model.Source: §1 · p. 1
- The proof combines the Sail RISC-V model with a model of interconnect, shared memory, devices, and power failures to capture hardware interactions down to sub-instruction execution.It covers instruction fetch, decode, execute, and retire, hardware page-table walks, TLB caching, interrupts, privilege levels, configuration registers, boot code, context switching, user-kernel transitions, DMA, locks, and file-system crash recovery.Source: §1 · pp. 1–2
- The whole-system theorem reasons about the single xv6 ELF binary and initial fs.img produced by the source-tree build, assuming their bytes initialize kernel memory and disk at boot.Its invariants imply kernel integrity, process isolation, crash safety, and hardware safety; the proof does not verify the build toolchain.Source: §1 · p. 2
- MachCSL adapts concurrent separation logic and Iris to sub-instruction-level RISC-V execution, enabling modular reasoning about functions, CPUs, or devices amid xv6 concurrency.The proof handles multiple CPUs, spinlocks and sleeplocks, shared-memory flag coordination, kernel interrupts and preemption, DMA, and fine-grained locking in the Unix file system and system-call interface.Source: §1 · pp. 1–3
- AI agents (Claude Code) helped write proofs and intermediate specifications for byte-level verification, while Rocq machine-checks that proofs entail the stated theorem.The theorem applies to the specified model and assumptions, rather than making an unqualified claim that xv6 is bug-free.Source: §1 · p. 3
- The theorem covers safety properties, but not liveness or non-interference, and assumes correctness of Rocq’s checker and the modeled RISC-V system, including Sail and interconnect, memory, and devices.It applies to the model of TSO shared memory.Source: §1 · p. 3
- The whole-system theorem establishes xv6 kernel invariants implying user-process isolation, file-system crash recovery, and that internal consistency assertions never fail.The proof covers a 6,593-line kernel compiled to 8,607 RISC-V instructions; its 1.3 million lines of Rocq code took 77 days to develop, including MachCSL, and the effort uncovered several xv6 bugs and one Sail-model bug.Source: §1 · p. 3
2 RISC-V execution model in MachCSL
MachCSL builds on Sail’s RISC-V HART semantics and extends them with concurrent SoC, memory, device, and power-cycle behavior to model execution at sub-instruction granularity.
2 RISC-V execution model in MachCSL
- MachCSL translates Sail’s RISC-V International-adopted HART specification into Rocq, modeling instruction substeps, CSRs, page walks, TLBs, privilege levels, and traps.MachCSL uses the Sail model except for one bug it discovered and fixed.Source: §2 · p. 3
- MachCSL composes the HART with shared memory, devices including a DMA-capable disk controller, and a PLIC, interleaving components at individual memory and register events.This captures page-table walks interleaving with page-table updates or A/D-bit writeback, asynchronous interrupt delivery, and interleavings within instruction fetches and data fetches.Source: §2 · pp. 3–4
- Shared memory follows TSO: reads use each core’s visible log prefix but see its own writes, while atomics advance to the global log end and fences expose its latest write.The model has no separate instruction cache.Source: §2 · p. 4
- A logical power thread models repeated power-on and power-off cycles, restarting HARTs with fresh memory and registers while preserving the disk’s persistent state.The disk model includes atomic-sector-write assumptions, allows larger writes to tear across sector boundaries, and models controller writeback caching.Source: §2 · p. 4
3 MachCSL by example
MachCSL uses concurrent separation logic to prove kernel code safe against low-level RISC-V execution, while abstractions and invariants support modular reasoning about shared state. A spinlock example shows how machine-code specifications, continuations, and atomic instructions fit together, alongside the proof effort’s costs.
Machine-code specifications
- MachCSL grounds specifications and proofs in compiled machine code, making the theorems about execution on RISC-V rather than C semantics or compiler correctness.This factors the compiler, linker, assembler, and other build-process components out of the trusted computing base.Source: §3 · p. 4
Resources and lock specification
- CSL ownership lets a thread reason locally about its resources, while the spinlock transfers predicate P to the acquiring thread and requires it back on release.The lock invariant retains P while the lock bit is 0 and withholds it while the bit is 1.Source: §3 · pp. 4, 7, 8, 9
Reasoning about machine execution
- Because hardware execution has no function-return model and may trap or fetch through changing translation state, MachCSL specifies safety of the CPU’s infinite execution loop with wp CpuLoop.The kernel proof establishes this resource at the initial CPU configuration; the loop covers kernel and user execution, interrupts, page-table switches, and context switches.Source: §3 · p. 6
- Continuations let a function proof establish safety while its instructions run and pass responsibility for safe execution after return to the caller.The acquire specification gives the continuation the return PC, relevant registers, and the predicate representing the acquired lock; real proofs may also cover interrupts or context switches.Source: §3 · pp. 6–7
Instruction specs and framing
- Instruction specifications chain individual machine instructions into function proofs, and framing lets each instruction proof leave unrelated resources untouched.For example, acquire’s proof uses LI’s specification to update the PC and a4 register while passing other resources through unchanged.Source: §3 · pp. 7–8
Invariants
- AMOSWAP opens the lock invariant atomically: observing 0 transfers P to the caller as the lock bit becomes 1, while observing 1 transfers no resources.The callback closes the invariant with the updated lock value and the appropriate resources.Source: §3 · pp. 8–9
Discussion
- MachCSL makes hardware behavior explicit in kernel proofs, avoiding assumptions about synchronization, interrupt handling, page-table setup, or TLB flushing.Its precise RISC-V semantics support reasoning about these operations consistently with the rest of the kernel implementation.Source: §3 · p. 9
- MachCSL proofs can use abstractions and ghost state to connect registers and memory to higher-level state, but their binary-specific detail makes proof writing and updates tedious.The paper says agents automate much of the proof effort and can update proofs after recompilation without substantial developer input.Source: §3 · p. 9
4 CSL for RISC-V
MachCSL extends concurrent separation logic to RISC-V by representing hardware state as owned resources and reasoning about Sail execution at sub-instruction granularity. Its adequacy theorem connects those proofs to concrete system executions and their invariants.
4.1 Ownership of state
- MachCSL assigns separate, HART-indexed ownership resources to CPU registers, enabling precise modeling of asynchronous updates and distribution of hardware state among subsystem predicates.Resources cover general-purpose and control registers, including TLB, satp, and stvec; subsystem predicates can manage translation and interrupts independently. Configuration registers that are never modified can be converted to persistent facts shared by multiple proofs.Source: §4.1 · pp. 9–10
- MachCSL models shared memory with TSO histories and per-CPU timestamps, while spinlock-protected locations use a points-to resource that enforces sequentially consistent reads.Virtual-memory resources combine physical-memory ownership with ghost-map translation facts tied to the page-table predicate. Kernel instruction memory is persistent because xv6 does not modify its code.Source: §4.1 · p. 10
- Each device has an invariant over its state, maintained by both device operations and kernel MMIO accesses, allowing drivers to reason about concurrent device activity and DMA through CSL.For the disk controller, the invariant includes device state and command-queue memory, with command-slot ownership handed between kernel and device; MMIO addresses have separate specifications.Source: §4.1 · pp. 10–11
4.2 Execution
- MachCSL’s HART-level CpuLoop is built on Sail-model WPs for individual execution steps, enabling specifications for translation, instruction stages, and other sub-instruction operations.Instruction-level specifications compose these stages to reflect the Sail model, including fine-grained interleavings with HARTs and devices and power failures between steps. Devices and power cycling also have their own WP-style execution proofs.Source: §4.2 · pp. 11–12
4.3 Adequacy
- MachCSL’s adequacy theorem translates CSL proofs into claims about every system-model execution, ensuring system invariants hold at each step and that all proof invariants can be initialized.For example, it connects the file-system invariant to the literal initial bytes of fs.img by proving that mkfs produces contents satisfying that invariant.Source: §4.3 · p. 12
5 Proving xv6 in MachCSL … 5.3 Context-switching
The xv6 proof uses resource invariants and instruction specifications to reason about interrupt-driven preemption and migration, virtual-memory translation, and kernel-thread context switches.
5.1 Interrupt handling
- Interrupts can preempt kernel execution at any time, run on the interrupted thread’s stack, and sleep or resume that thread on another HART.This makes interrupts a source of concurrency even within supervisor-mode execution.Source: §5.1 · p. 12
- Every developer-visible instruction carries sie_cap_gpr through its specification, enabling reasoning over any number of interrupts at instruction boundaries.The resource tracks whether interrupts are enabled, available stack locations, and general-purpose register values.Source: §5.1 · pp. 12–13
- The proof preserves register values across HART migration and reserves enough stack space for the trap handler whenever interrupts are re-enabled.The stack budget accounts for the handler’s required space, which is reserved when interrupts are enabled and released when disabled.Source: §5.1 · p. 13
- sie_cap_gpr owns stvec while interrupts are enabled, then permits handler replacement while disabled to establish a separate user-mode interrupt-safety invariant.The user-mode handler supports page-fault demand allocation and system calls via ECALL.Source: §5.1 · p. 13
5.2 Page table and TLB
- strans_inv owns the page-table machinery and TLB, tracks logical mappings, and permits arbitrary accessed and dirty bit updates during shared-page-table walks.Its invariant allows page-walk and TLB phases to update physical page-table memory, including when another core walks the shared table.Source: §5.2 · p. 13
- Kernel translation tiers distinguish always-valid identity mappings from page-table mappings, preventing one HART from using mappings another has not reached.Memory load and store specifications require the mapping’s tier to be no greater than the current HART’s tier.Source: §5.2 · p. 14
- During user/kernel page-table switching, the proof requires the TLB to contain only mappings shared by both tables between the two sfence.vma flushes.The shared mapping is the trampoline code page.Source: §5.2 · p. 14
5.3 Context-switching
- The swtch specification lets a scheduler resume a kernel thread from its saved callee-saved registers and program counter, provided the old context is owned and the new one is valid.A valid context includes a continuation that is safe to execute after restoring its registers.Source: §5.3 · pp. 14–15
5.4 Locks · 5.5 Memory allocation
The sections explain how xv6’s lock specifications model interrupt state, lock ordering, and dynamically allocated lock lifetimes. They also describe allocator specifications for boot-time and concurrent operation, including a weaker freeing precondition for TSO shared memory.
5.4 Locks
- Nested push_off calls disable interrupts, and pop_off restores the original interrupt state when the nesting depth returns to zero.The specification tracks the push_off depth and original interrupt-enable bit, including explicit sstatus changes when no push_off is active.Source: §5.4 · p. 15
- A spinlock must be released on the CPU where acquire returns, represented by a CPU-specific lock_held resource.Acquire may be preempted before disabling interrupts, so the CPU where it starts may differ from the CPU where it returns.Source: §5.4 · p. 15
- Acquire requires locks to be taken in rank order, preventing recursive acquisition and conflicting lock orders in xv6’s spinlock discipline.MachCSL’s top-level adequacy theorem does not guarantee deadlock freedom, but the specification enforces the ordering discipline that in practice eliminates spinlock-based deadlock.Source: §5.4 · p. 16
- For dynamically allocated pipes, a cancellable lock invariant permits freeing the page once the pipe’s reference count reaches zero.Each pipe end’s struct file holds a reference; at zero references, no future caller can satisfy the lock-acquisition precondition, enabling invariant cancellation and memory reclamation.Source: §5.4 · p. 16
- Sleeplock acquisition requires an empty spinlock set because switching to the scheduler while holding a spinlock could deadlock.Sleeplocks are used when a lock holder may sleep, such as while the file system waits for disk I/O on an inode.Source: §5.4 · p. 16
- The inode’s last-reference path can acquire a sleeplock while holding its spinlock because zero references rule out competing acquirers.The specification tracks a resource held by active sleeplock holders; with the in-memory reference count at zero, acquisition succeeds immediately without sleeping.Source: §5.4 · p. 16
5.5 Memory allocation
- Boot-time kalloc uses an exclusive counted regime that guarantees success when free pages remain, then switches irreversibly to a duplicable concurrent regime where allocation may fail.The counted resource tracks available pages so boot allocations can be proved successful; after CPU 0 finishes boot-time allocations, the allocator exchanges it for the concurrent-mode resource.Source: §5.5 · pp. 16–17
- Under TSO, kfree requires ownership of each address being freed but not a stable value for that memory on the current CPU.The usual allocator precondition of owning a↦Mem v is stronger than necessary because the allocator does not need the freeing CPU to observe stable values.Source: §5.5 · p. 17
5.6 File descriptors · 5.7 File system
The proof handles xv6’s bounded file-reference accounting and transactional, concurrent file system through ghost resources and invariants, and exposes file-system bugs.
5.6 File descriptors
- File-reference slots bound the number of outstanding references, letting the proof show that incrementing a struct file refcount cannot overflow.Slots are distributed across processes at boot, transferred to struct files on open, and returned on close; each file’s refcount equals its slot count. Shared file descriptors also share fractional ownership of the underlying pipe or inode reference.Source: §5.6 · p. 17
5.7 File system
- The proof shows xv6 commits are crash-atomic: recovery sees either the old or new log header, never a mixture.The durable-state invariant survives reboots; commit makes D equal M, and the log waits for transactions to finish so the consistency invariant holds at commit. The header fits in a sector, and write-through completion ensures the commit record is on disk.Source: §5.7 · pp. 17–18
- Tracking logged blocks accounts for absorption within and across transactions, keeping each transaction within MAXOPBLOCKS even when namei races with unlink.Repeated writes to a block count once; when unlink and namei log the same inode, namei’s update is absorbed by the other transaction’s log entry.Source: §5.7 · pp. 18–19
- Buffer invariants preserve a buffer’s block identity and logical contents across the lock gap in bget and when cached contents differ from disk.Ghost reference-count fragments prevent reuse while any thread holds a reference, even before acquiring the sleeplock; the invariant relates valid data or an in-progress disk read to the block’s logical content.Source: §5.7 · p. 19
- Per-inode ghost state lets the proof express link-count and “..” consistency locally, reducing global reasoning for local file-system operations.Directories own fragments representing their links; directory invariants also track parent inode numbers to establish correct “..” relationships.Source: §5.7 · pp. 19–20
- The proof found missing nlink checks: namex could follow “..” in an unlinked directory, while create and sys_link could add names, causing a kernel panic.The stronger iget specification requires callers to pin down an inode’s identity and rule out its being freed; linked-directory checks are needed to preserve that premise.Source: §5.7 · p. 20
- Proving ialloc required showing that no thread could modify a newly allocated inode between brelse and iget; the proof exposed an iput bug.The agent initially could not prove this claim; an attempted source change and a new axiom were caught before the iput bug was identified.Source: §5.7 · p. 20
- Ghost fractions let iput use a non-blocking acquiresleep specification when the inode reference count is one, avoiding the apparent lock-order conflict.The reference count establishes that iput owns the only holder fraction; returning it makes the potential-holder total zero, proving no thread holds or awaits the sleeplock.Source: §5.7 · p. 21
5.8 Process exit
When xv6 exits a process, it must reclaim the process’s entire kernel stack even though callers still own resources associated with their stack frames. MachCSL handles this by specifying that a function may either return or not return, with the non-returning path allowing stack ownership to be reclaimed.
5.8 Process exit
- Process exit requires reclaiming the full 4KB kernel stack while callers still own resources for their stack frames.The exiting process passes through uservec, usertrap, syscall, and sys_exit before becoming ZOMBIE and switching to the scheduler.Source: §5.8 · p. 21
- The calling-convention specification uses ∧ to represent overlapping alternatives: return to the caller or give up caller stack locations captured in wp CpuLoop.Unlike separating conjunction, ∧ requires choosing one ownership alternative, after which the other disappears.Source: §5.8 · p. 21
- The syscall specification offers return via wp CpuLoop or stack reclamation via stack_reclaim m[sp], while sie_cap_gpr covers free stack locations below sp.Figure 9 illustrates how the specification captures the possibility that syscall does not return and the caller’s stack frame can be reclaimed.Source: §5.8 · p. 21, Figure 9 · p. 22
- Callers supply both resources to a potentially non-returning call, and a function may invoke its own caller’s continuation or stack-reclaim resource to meet those obligations.Functions that never return, such as sys_exit, require only stack_reclaim; swtch and the scheduler use a continuation for RUNNABLE or SLEEPING processes and stack reclamation for ZOMBIE processes.Source: §5.8 · p. 21
5.9 Compiler optimizations … 5.12 Bounded physical memory
The sections show how machine-level verification accommodates compiler-generated behavior, concurrent console output, format-dependent printing, and an adversarial exec panic ruled unreachable by physical-memory limits.
5.9 Compiler optimizations
- MachCSL’s RISC-V-level proof subsumes compiler optimizations, including GCC’s proc-array index computation, which divides pointer differences by sizeof(struct proc) (360 bytes).The procinit code initializes kernel stacks for all struct procs at boot.Source: §5.9 · p. 22, Figure 10 · p. 22
5.10 UART output
- The UART specification tracks an append-only byte list, letting printk guarantee its output appears as a prefix even if other processes or cores append bytes concurrently.The postcondition does not require printk’s bytes to be the entire console output.Source: §5.10 · pp. 22–23
5.11 Specifying printk
- printk’s specification addresses variable arguments by computing their kinds from the format string; escapes and unrecognized conversions consume no arguments.The structural fixpoint kinds is computable in Rocq; for "%d %s: unknown sys call %d\n", it returns [Num; Str; Num].Source: §5.11 · p. 23
- For printk, Num arguments require no resource, while %s requires either a null-pointer proof or a points-to resource for the string.At the RISC-V instruction level, variadic arguments are 64-bit registers, making C distinctions among int, long, and char invisible to the logic.Source: §5.11 · p. 23
- printk’s args resource places argument j in register a(j+1), assumes at most seven arguments, and returns caller resources plus a fact that bytes were appended to the UART.The specification does not pin down the exact output bytes; supporting more than seven arguments would require modeling stack-passed arguments.Source: §5.11 · p. 23
5.12 Bounded physical memory
- kexec can pass untrusted ELF header values to uvmalloc, whose mappages call would panic if an address were already mapped, including the trampoline mapping.The proof therefore considers whether an adversarial ELF image could reach that panic.Source: §5.12 · p. 23
- The panic is unreachable because reaching the trampoline address would require allocating more physical pages than the machine has, contradicting the proof’s separation-logic resources.The contradiction establishes that execution cannot reach the panic through uvmalloc’s loop.Source: §5.12 · p. 23
5.13 User-mode execution
MachCSL proves that xv6 can execute user-mode code for arbitrary cycles while preserving the user-execution invariant or trapping into a verified handler. The proof accounts for user memory ownership, trap configuration, and cores that may sleep while in user mode.
User-mode execution
- The user-mode WP theorem covers arbitrary-PC execution for any number of cycles, proving each fetch/decode/execute step either re-establishes user_inv or traps into the verified handler.The proof considers every outcome of RISC-V instruction fetch, arbitrary decode of the fetched bytes, and arbitrary execution of the decoded instruction; it proceeds by induction over execution.Source: §5.13 · pp. 23, 25
- user_inv permits arbitrary program-counter and general-purpose-register contents, but pins mstatus bits such as MPRV and MXR so user memory accesses remain user accesses.It also requires User privilege, an active or sleeping HART, and allows arbitrary supervisor trap CSR values that are updated on a trap.Source: §5.13 · p. 23
- user_pt owns the page table and exactly its mapped user memory; injective, well-formed mappings and exclusive ownership keep those physical pages disjoint from kernel-owned state.The memory contents are existentially quantified, while the pinned mapping domain represents all of the user's memory and nothing else.Source: §5.13 · p. 24
- Direct-mode stvec, supervisor delegation of user exceptions, and no enabled machine-mode interrupts ensure traps from user mode land at the known kernel handler.The trap-handler WP receives user_trap_frame with Supervisor privilege, PC at stvec, freshly written trap CSRs, and the same page table and configuration; trap CSR values are existential because the handler handles every cause.Source: §5.13 · p. 24
- The invariant includes a sleeping user-mode core because the RISC-V WRS.NTO instruction can put it to sleep; enabled interrupts let the kernel regain execution at the next timer interrupt.The proof initially assumed the core was active, then extended the invariant to allow User privilege while sleeping.Source: §5.13 · p. 25
5.14 Visibility of writes under TSO
Under TSO, store buffering can give cores different views of the same memory, complicating xv6 proofs of shared-state access and process migration. The proof addresses these challenges with view-relative resources that track which writes are visible across cores.
5.14 Visibility of writes under TSO
- TSO complicates spinlock proofs because a released lock invariant may refer to buffered writes, while xv6’s non-atomic lk->cpu holding check may read a stale value and panic.The lock’s shared state must become visible to the acquiring core, and the holding check must account for the possibility that this CPU held the lock in the past.Source: §5.14 · p. 26
- The proof assigns each spinlock a logical view tied to the latest release write, letting acquire establish visibility of the lock’s writes before returning its invariant.If acquire observes the lock as unlocked, the acquiring CPU’s timestamp is high enough to see writes in the lock’s view; the invariant can then be returned relative to the caller’s local view.Source: §5.14 · pp. 26–27
- The proof models non-sequentially-consistent shared locations with a view-relative resource that permits a set of values, preventing lk->cpu checks from seeing values predating spinlock memory reuse.For dynamically allocated pipe spinlocks, the invariant excludes the current CPU from lk->cpu’s possible values in the relevant view, including values left from before the location was reused.Source: §5.14 · p. 27
- For process migration, the scheduler suspends a process thread’s view under its own, transfers that suspended view through p->lock, and the new scheduler un-suspends it on resume.The suspended process view represents writes visible to the process as a subset of those visible to the scheduler; the lock invariant transfers it under the new scheduler’s view.Source: §5.14 · pp. 26–27
- During boot, xv6 uses the started barrier so other cores can learn the first CPU’s view-relative initialization resources once the variable is 1.The invariant allows started to be 0 or 1 from boot, and associates the value 1 with access to resources initialized by the first CPU.Source: §5.14 · p. 27
6 Validating the model
MachCSL’s RISC-V model is validated by checking it against QEMU and a real RISC-V board. The checker aims to show that reference behaviors are allowed by the model, so xv6’s proof over the model covers executions on those implementations.
6 Validating the model
- Conformance tests cross-check MachCSL’s RISC-V model against QEMU and a StarFive JH7110 board, aiming to capture behaviors of both implementations.The JH7110 is manipulated via JTAG; QEMU is the whole-system emulator for xv6’s targeted hardware platform.Source: §6 · p. 27
- The checker proves reference executions are a subset of model executions, extending xv6’s all-model-executions theorem to executions on the reference implementations.Some model operations are undefined; a test where the model gets stuck still counts as correspondence, and xv6’s theorems prove it never triggers that behavior.Source: §6 · p. 27
- Assembly snippets produce 4KB memory-page snapshots, and the checker must reproduce every snapshot observed on QEMU or JH7110.The checker tests the model itself, without CSL machinery; it must handle reference output variation and synthesize model choices such as register contents and CPU/device interleavings.Source: §6 · pp. 27–28
- Tests cover basic instructions, boot-time registers, page tables, and interrupts, as well as shared-memory races with multiple possible snapshots.For races, a barrier releases booted CPUs into concurrent accesses, and the model proof constructs a schedule for every observed outcome.Source: §6 · p. 28
- Device tests exercise the PLIC, UART, disk, and disk DMA through MMIO accesses and shared DMA ring buffers.Source: §6 · p. 28
7 Agent-based verification
The project used parallel coding agents to develop Rocq proofs, with shared repository notes and CI checking that proofs remained valid. The section describes where agents needed human design guidance and the workflows used to keep proof development tractable.
7.1 Abstractions
- Agents could automate proofs once clear separation-logic specifications and invariants were provided, but humans had to design abstractions and concurrency ownership disciplines.For the file system, introducing abstract inodes, directories, and trees replaced verbose reasoning about on-disk blocks and made proofs scalable; other abstractions covered physical memory, page tables, TLBs, kernel stacks, ABIs, and interrupts.Source: §7.1 · pp. 28–29
7.2 Iterating on the design
- When agents spiraled without progress, the authors stopped them, discarded their work, and restarted with a more precise goal informed by the failures.File-system crash consistency required a write-ahead-log boundary proving an atomic logical-disk update and invariants connecting block state to abstract files and directories; rough specs could also be tested through agent-generated proofs that exposed tricky cases.Source: §7.2 · p. 29
7.3 Multi-agent design review
- For difficult TSO proof ports, iterative design reviews by a second agent and reviewer surfaced flaws, after which the implementation agent completed buffer-cache proofs in one pass.The agents exchanged design documents and proof-plan prototypes about ten times over a few hours; a similar approach completed inode-cache proofs with more review rounds.Source: §7.3 · pp. 29–30
7.4 Agent memory is sticky and implicit
- Fresh agents reading checkpointed status and shared design notes could expose implicit assumptions, but revising existing proofs required more supervision than writing new ones.A late review revealed that the file-system crash-safety theorem was vacuous because reboot assumed a fresh mkfs image; the issue had been recorded amid low-level details in a design document.Source: §7.4 · p. 30
7.5 File organization discipline
- A strict file structure separates function specifications, low-level code facts, proofs, and links, helping agents follow modification boundaries and enabling parallel builds.The structure also separates abstraction and invariant files; agents can agree on boundary specs and work independently on function proofs.Source: §7.5 · pp. 30–31
7.6 Performance optimization
- Because proof-checking speed affects iteration, agents profiled and optimized proofs, including by replacing general automation with specialized proof steps.Repeated optimization requests sometimes surfaced new approaches, such as avoiding quadratic Rocq performance through tactic choices; a cached, rewindable rocq repl tool shortened edit-and-recheck cycles for long files.Source: §7.6 · p. 31
7.7 Orchestration for large projects
- For large changes, capable top-level agents designed meaningful specs and proof plans while sub-agents handled scoped tasks; smaller tasks went directly to Opus or Sonnet agents.Once optimization techniques were documented in shared notes, those agents could profile proofs and match observed problems to known techniques.Source: §7.7 · pp. 31–32
7.8 Kernel changes
- After each xv6 source change and recompilation, an agent fixed the resulting ELF-level proof changes within several hours and developed tools to make later iterations cheaper.These tools included symbolic address references, scripts generating CodeF.v files from ELF dumps, and automated replacement of PC-relative offsets.Source: §7.8 · p. 32
8 Bugs found
The verification uncovered ten bugs in total: one in the Sail RISC-V model and nine in xv6.
Sail model bug: TLB writeback
- Verification found ten bugs—one in Sail and nine in xv6; Sail’s A/D writeback could resurrect cleared PTEs because it used a blind write, fixed with atomic read-modify-write.Source: §8 · p. 32
Kernel bug: iput can lose an inode
- In iput, dropping locks let an inode-cache entry be reused before reclamation, so racing unlink/create operations could orphan an on-disk inode.The fix reclaimed the inode by inode number; after proving the kernel correct with the fix, the authors committed it upstream.Source: §8 · pp. 32–33
Creating files in disconnected directories; Overflowing nlink
- Filesystem fixes reject traversal or creation in unlinked directories and reject link creation that would overflow nlink, which otherwise wrapped negative and made unlink panic.Source: §8 · p. 33
Scheduler did not reset push_off count
- The scheduler failed to reset the per-CPU push_off flag after a process context switch, so releasing a lock could re-enable interrupts before its scan-and-WFI sequence finished.The fix explicitly cleared the flag before the scheduler released locks.Source: §8 · p. 33
Failing to log a partial file write
- A failed copyin during a page-spanning write could leave partially changed data in the buffer cache without logging it, so reads changed when the cache was recycled.Source: §8 · p. 33
Missing icache fence when switching to a user process; Boot code does not enable ADUE
- xv6 lacked fence.i before user return, risking stale user instructions, and failed to enable ADUE, leaving it unable to handle A/D-bit traps under software-managed mode.The fixes added fence.i to the userret trampoline and set ADUE in menvcfg.Source: §8 · pp. 33–34
freeproc failed to hold wait_lock while updating p->parent
- freeproc modified p->parent without wait_lock, although that lock’s invariant—not p->lock—owned the field.Source: §8 · p. 34
Inconsistent UART TX FIFO handling
- Unsynchronized user-console and printk writes could race and overflow the UART TX FIFO; the fix made both paths use one spinlock.Source: §8 · p. 34
9 Implementation
The verification largely preserved xv6, with proofs motivating targeted fixes and cleanup. Its correctness theorem relies on a defined trusted base that includes the Sail/Rocq stack and the modeled execution environment.
9 Implementation
- The implementation took 77 days and 5,051 commits, with agents writing 1,001,444 lines of Rocq.Of those agent-written lines, 405,450 implement the logic, 62,590 are specifications, 527,438 are proofs, and 2,983 link function proofs.Source: §9 · p. 34
9.1 Changes to xv6
- The authors made almost no xv6 changes beyond bug fixes, requiring proofs to work with existing code even in tricky cases.Examples include file reference counting that does not overflow and kexec remapping the trampoline page without panicking.Source: §9.1 · p. 35
- Proof exposed that kexec’s argc check was redundant and insufficient, so the check was deleted; sys_exec already checked the limit.The check was off by one in an unsafe direction.Source: §9.1 · p. 36
9.2 TCB
- The theorem trusts the Sail RISC-V model, its Rocq backend, Rocq’s proof-checking kernel, the ELF dumper, and the execution model.The execution model includes TSO shared memory, devices, and power handling; conformance tests validate it but do not prove all possible cases.Source: §9.2 · p. 36
- The kernel implementation, compiler and build tools, and initial file-system image are outside the theorem’s trusted computing base.The excluded kernel implementation includes C and assembly for boot, context switching, hardware configuration, page tables, interrupts, and device I/O.Source: §9.2 · p. 36
- The Sail model over-specifies the TLB as a 64-entry direct-mapped cache, and the authors found and fixed its PTE A/D writeback bug.The model does not allow different TLB sizes or associativities.Source: §9.2 · p. 36
10 Evaluation
The evaluation measures agent effort and the cost of updating proofs as xv6 and the Sail model change, and uses conformance tests to identify discrepancies between the model and reference implementations.
10.1 Agent effort
- 927 hours of wall-clock time covered 407 agent sessions and 2,254 sub-agent runs, with 5,178 human prompts and 1,729 hours of active Claude runtime.The recorded transcripts omit roughly 11% of sessions from one early two-week window; reported token use was 190.5 million output tokens and 133.1 billion input tokens.Source: §10.1 · p. 37
10.2 Re-proving after kernel changes
- 35 minutes and 4 prompts were the median cost of an xv6 kernel bump; the 19 measured bumps took 36.5 hours, or 2.1% of project agent time.Across 18 update commits, 958,816 generated-code lines and 76,044 specification and proof lines changed; the most expensive bump took 12.2 hours.Source: §10.2 · pp. 37–38
10.3 Re-proving after Sail model changes
- 10.9 hours were required to update the Sail model for the PTE A/D writeback fix and associated changes, compared with 1.7 hours for localized axiom-extraction changes.The PTE fix also required revising the page-table proofs.Source: §10.3 · p. 38
10.4 Model discrepancies
- 63 conformance tests surfaced 32 discrepancies between the model and reference implementations, including device-model bugs and disk-request reordering that required revising the xv6 disk-driver invariant and proofs.Tests covered CPU, page tables, interrupts, shared memory, CLINT, PLIC, UART, and disk; xv6’s file-system specification already allowed writes to be reordered.Source: §10.4 · p. 38
- The disk tests found that QEMU can reorder requests while the initial disk model executed them in order, so the model and xv6 disk-driver invariant and proofs were updated.Other device findings included missed multi-byte UART reads at single-byte registers, incorrect PLIC priority thresholds, and incorrect disk used-ring lengths; xv6 did not depend on those features.Source: §10.4 · p. 38
- CPU tests found benign initial-register differences between QEMU, JH7110, and the model, while page-table tests exposed TLB behavior differences and JH7110 tests revealed Sail’s HART 0-only CLINT access limitation.For example, QEMU reports the hypervisor feature in misa while the model does not; Sail’s 64-entry direct-mapped TLB can evict an entry QEMU retains, and non-0-HART CLINT behavior could not be matched.Source: §10.4 · p. 38
- QEMU’s x86 TSO shared-memory behavior was not representable by the initial sequentially consistent model, which was extended to TSO.The CPU tests exposed this behavior in QEMU.Source: §10.4 · p. 38
11 Related work
The related work positions MachCSL as verifying an existing Unix-like kernel against Sail RISC-V semantics while modeling concurrent hardware activity that prior kernel proofs abstracted away.
Related work
- MachCSL verifies an existing Unix-like kernel against Sail RISC-V semantics, modeling concurrent HARTs, hardware page-table walks, interrupts at any instruction, DMA, and power failures.Prior verified kernels generally reason above the hardware and do not include a complete Unix-like environment.Source: §11 · p. 39
- MachCSL proves the file system inside xv6 alongside its disk driver, DMA descriptors, interrupt handler, and per-sector writeback, including crash invariants and interactions with fork/exec and open-unlinked files.Unlike prior file-system proofs that assume an atomic-sector disk behind an abstract or synchronous interface, this proof establishes the crash invariant as each sector reaches disk.Source: §11 · p. 39
- MachCSL uses Sail RISC-V semantics beneath a proof of an entire concurrent kernel and reasons about actual interrupt, trap, and privilege machinery, including its interaction with page-table and context switches.Earlier instruction-level and interrupt-logic efforts addressed architecture properties, small programs, or idealized machines.Source: §11 · p. 40
- MachCSL models the RISC-V page-table walker and its A/D-bit writeback as concurrent hardware activity governed by CSL invariants, rather than treating address translation sequentially or omitting it.Earlier work included simplified page-walk models and sequential logics with explicit TLBs, but not this treatment over machine-checked ISA semantics.Source: §11 · p. 40
- MachCSL provides the first kernel-scale proof in a weak-memory program logic, reasoning about synchronized code with SC-style rules and racy code directly against TSO.This supports xv6’s intentionally racy flag-based coordination, where reduction to sequential consistency breaks down.Source: §11 · p. 41
- To the authors’ knowledge, no prior machine-checked kernel proof models a DMA-capable device running concurrently with the CPU; MachCSL transfers DMA-buffer ownership and accounts for device reads and writes.The proof also accounts for when each disk sector reaches the disk.Source: §11 · p. 41