Skip to content

Port from stdpp bitvectors to stdlib bits - #1

Open
JasonGross wants to merge 3 commits into
mit-plv:mainfrom
JasonGross:fable/stdlib-bits
Open

JasonGross wants to merge 3 commits into
mit-plv:mainfrom
JasonGross:fable/stdlib-bits

Conversation

@JasonGross

@JasonGross JasonGross commented Sep 15, 2026 •

Copy link
Copy Markdown

Port from stdpp bitvectors to stdlib bits (rocq-stdlib 9.1+), the granite half of the request on mit-plv/kami#51; pins the quartz submodule to mit-plv/quartz#2's tip so both share one representation and rocq-stdpp-bitvector is no longer a dependency. 60 files, no admits; Demo.noninterference depends only on functional_extensionality_dep as on main.

Proof scripts change only where the two sides of a simulation used to agree syntactically and now differ in spelling (quartz interprets equality tests as Zmod.eqb, granite programs compare Zmod.unsigned _ =? Zmod.unsigned _), plus auto-generated hypothesis names. Details in the commit message; core/Bits.v replaces what stdpp's bitvector definitions provided.

The first commit is a pre-existing fix (the root dune default alias). Built with Rocq 9.1.1 + stdlib 9.1.0 as the README targets; Rocq 9.2 hits a kernel anomaly on unported main at isaSpec/QuartzImpl.v:118, unrelated to this change. One thing to weigh: the big proof files are slower (clean uncached build: PipelineRefines 2383 s to 3656 s, QuartzImpl 499 s to 741 s, SingleCycleRefines 120 s to 232 s; whole build 3758 s). Profiles show the same hot sentences at a uniform 1.3x to 1.6x with no new hot spot; the likely cause is width arithmetic inside the Zmod (2^n) types (bits (15-12), 2^enum_bitsize) that the unifier evaluates at every type comparison. Set Keyed Unification makes the hottest sentence three times faster (below main) but breaks the existing rewrite automation, so it is left as a follow-up. Warnings are identical to main apart from the intended notation-overridden pair for the 0/1 literals.

Written by Claude Fable 5.1.

🤖 Generated with Claude Code

https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm

JasonGross and others added 2 commits September 15, 2026 22:12
A plain `dune build` at the root recurses into quartz/test, whose rules
run the quartz tests and need a slang binary that is not part of a
granite checkout, so the build fails before compiling anything of
granite. The default alias now covers core, app, isaSpec, quartz/lang
and quartz/examples, which is what quartz's own root dune file does.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm
Bit vectors are stdlib's bits n := Zmod (2^n) (rocq-stdlib >= 9.1),
widths are Z, and the quartz submodule moves to the quartz commit that
makes the same change (mit-plv/quartz#2), so that granite and quartz
share one representation and rocq-stdpp-bitvector is no longer a
dependency.

core/Bits.v provides what stdpp.bitvector.definitions provided: the
bits notation, a Number Notation whose literals are constructor-shaped
so that closed constants still compute with Zmod.of_small_Z opaque
(simpl/cbn through of_small_Z are exponential in the nesting depth),
EqDecision/Countable/Inhabited/Finite instances, and the
granite-specific helpers on top of Zmod. Sections over an abstract
width take a Finite (bits idx_sz) hypothesis whose proof term is
canonical, because hint-generated instances differ between files and
then fail to unify.

Proof scripts change only where the two sides of a simulation used to
be syntactically equal by construction and now differ in spelling:
quartz interprets equality tests as Zmod.eqb while granite's programs
compare with Zmod.unsigned _ =? Zmod.unsigned _, so the scripts unfold
Zmod.eqb (and nonzero of an embedded boolean) before the case splits
that must hit both sides. Auto-generated hypothesis names follow the
new types, and two `clear`s that implicitly kept section variables
through the type of a kept hypothesis are made explicit or dropped.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm
@andres-erbsen

Copy link
Copy Markdown

Also port this gist, in a stacked PR. https://gist.github.com/andres-erbsen/d2a697b60e8455af7110bb4aa0ecafe8

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm
@andres-erbsen

Copy link
Copy Markdown

Also port this gist, in a stacked PR. https://gist.github.com/andres-erbsen/d2a697b60e8455af7110bb4aa0ecafe8

How is this coming along? Can we have a PR on top of the monomorphized cpu support?

@JasonGross

Copy link
Copy Markdown
Author

Not started until now: the gist request was dropped when the granite lane closed after #1/#2. Porting it today on top of #2 (the monomorphized CPU), as a stacked PR: the two gist files go under app/ next to MemoryAPI/MemorySpec, spelled on stdlib bits like the rest of #1, with the simulation proof kept axiom-free beyond what MemorySpec/Simulates already assume. I will link the PR here when it builds.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

@andres-erbsen

Copy link
Copy Markdown

Once that's done, investigate differences between the Granite single-cycle processor specification and riscv-coq. Present an analysis along with options for connecting granite to riscv-coq.

@JasonGross

Copy link
Copy Markdown
Author

Ported: #3, stacked on #2 (the monomorphized CPU). Both gist files build unchanged on main with stdpp, and the port is only the spelling (bv Params.width to bits Params.width, bv_0 to zeroes); no proof script or comment changed. Print Assumptions simulates is closed under the global context.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

@JasonGross

Copy link
Copy Markdown
Author

Granite's single-cycle processor specification is isaSpec/SingleCycle.v: each micro-step fetches,
decodes, executes and writes back one instruction through the same circuit-shaped decoder interface
the Quartz hardware uses. It is proven trace-equivalent to the reference semantics in
isaSpec/Spec.v, which the security theorem is about, and the pipelined model is proven equivalent
to it. Both are deterministic Mealy machines stepped once per clock cycle.

Differences from riscv-coq:

  • ISA: granite has 14 instructions (addi, add, xor, slli, srli, lui, auipc, beq, bne, jalr, lw, sw,
    mul, csrrw). riscv-coq has all of RV32/64 I, M and the CSR instructions.
  • Words: both use the standard library's bits n, so the word type is shared. granite fixes width
    32; riscv-coq covers both.
  • State: granite has a total register vector, separate total instruction and data memories, five
    whole-word CSRs. riscv-coq has partial register and memory maps and a field-level CSR model.
  • Semantics: granite's step is a function; riscv-coq's is a predicate over a free monad with
    nondeterministic MMIO reads.
  • Exceptions and CSRs: granite traps on misaligned data access, jumps to mtvec verbatim, and clears
    a global enable it calls mie (0x304) on every trap. riscv-coq allows misaligned data access,
    shifts mtvec, keeps the global enable in mstatus, and treats 0x304 as the per-source mie.
    riscv-coq has no interrupts; granite takes an external one.
  • MMIO: granite is asynchronous (request, wait phase, valid/ready wires, secret response data).
    riscv-coq completes MMIO inside the instruction and logs it.
  • Leakage: event shapes are close. granite also leaks whether a multiplier operand is zero and the
    values written to mtvec/mie; riscv-coq leaks nothing for mul and drops all guarantees on CSR
    instructions.

Options:

  1. Decoder bridge (200–400 lines): prove the two decoders agree on granite's subset. Cheap.
  2. Leakage vocabulary alignment (100 lines): reshape granite's leakage events to riscv-coq's and
    define the projection.
  3. Refinement proof (1.5–2.5k lines, the Kami/bedrock2 route): relate granite's reference
    semantics to riscv-coq's run1 under MinimalMMIO for programs without interrupts, with
    aligned accesses, not writing mie. One theorem from bedrock2-verified software to the Quartz
    core.
  4. Replace granite's semantics by riscv-coq's Decode/Execute: rewrites about 10k lines of proofs
    and loses the hardware-facing decoder interface. Not recommended.

Recommendation: do 1 now as a small separate theory depending on both projects, file the mie and
mtvec conformance questions as granite issues, then do 3 (using 2) once those are settled.

Full report

Follow-up E: granite#1 "differences between the Granite single-cycle processor specification and riscv-coq"

Lane fu-e, 2026-09-17. Read-only survey of granite b5b2ba5 (granite#3 tip, quartz submodule 8db5ff94),
riscv-coq a98896f (stdlib bits, after riscv-coq#54), coqutil as vendored in bedrock2 447b97df
(deps/coqutil), bedrock2 447b97df processor/, kami 2777a72. Nothing edited, nothing built, no
PR, no GitHub post. Line numbers below are from those trees.

Andres asked (#1): "investigate differences between the Granite single-cycle
processor specification and riscv-coq. Present an analysis along with options for connecting granite
to riscv-coq."

1. Granite's processor specification

Granite has three ISA-level artifacts, not one, and "the single-cycle processor specification" is
the middle one:

  1. Reference semantics isaSpec/Spec.v (Module semantics, 579 lines): a deterministic
    Mealy machine over the decoded instruction type instrs.Instr from isaSpec/Riscv.v. This is
    the thing granite's security theorem is stated against.
  2. Single-cycle processor model isaSpec/SingleCycle.v (885 lines): the same machine shape,
    but instructions are executed from their 32-bit encoding through a circuit-shaped decoder
    interface circuitDefs.IsaParams (isaSpec/Common.v:181-189: decode, execALU,
    execControl, memAddr, illegalInstruction, isMMIOAddr, nextPC), written as a program
    in granite's own method-call monad prog BaseVM BaseAM (core/Program.v:9-13; BaseVM/BaseAM
    at SingleCycle.v:36-59). isaSpec/IsaParams.v instantiates the interface with the concrete
    decoder (IsaParams.v:182-223, 391-399), which is the same decoder the Quartz hardware uses
    (quartz/examples/Processor.v:533-581, Decode module with the same Inst_*/Imm_* enums).
    SingleCycleRefines.v:1321-1330 proves Machine.equivalent (singleCycleMachine) (specMachine).
  3. Pipelined model isaSpec/Pipelined.v (1177 lines; f2d/d2e/e2w bookkeeping records at
    Pipelined.v:71-105, BTB/BHT, scoreboarded register file, multi-cycle multiplier) proven
    equivalent to the single-cycle model (PipelineRefines.v, 5068 lines; MulticycleRefines.v,
    2846 lines), and then to the Quartz circuit (QuartzTopPf.v:111, TopLevelSpec.v:731-757).

"Single-cycle" therefore means: fetch, decode, execute and writeback of one instruction all happen
in one micro-step with no inter-stage state (SingleCycle.v:207-209 execute := execute' ;; finish),
as opposed to the pipelined model. It does not mean one instruction per clock cycle: see the
driver below.

ISA subset

RV32 encodings, 14 instructions plus InvalidInstr (Riscv.v:17-41, decoder Riscv.v:142-188,
opcode/funct constants Riscv.v:86-140):

class instructions
straight-line Addi Add Xor Slli Srli Lui Auipc (RV32I), Mul (RV32M), Csrrw (Zicsr)
control Beq Bne Jalr
memory Lw Sw

Missing from RV32I: Jal, Sub Sll Slt Sltu Srl Sra Or And, Slti Sltiu Xori Ori Andi Srai,
Lb Lh Lbu Lhu Sb Sh, Blt Bge Bltu Bgeu, Fence, Ecall Ebreak; no Mret; only Csrrw of the
CSR instructions; only Mul of M. Immediates are typed bit-vectors (Imm12 := bits 12,
Imm13, Imm20, shift amounts bits 5; Common.v:33-36, Riscv.v:18-35).

Machine word, registers, CSRs

  • WIDTH := 32, mword := bits WIDTH (Common.v:29-32), where bits n := Zmod (2^n) is the
    stdlib type re-declared in core/Bits.v:8 (From Stdlib Require Export ZArith Bits,
    core/Bits.v:3). Literals via a granite-local Number Notation on Zmod_scope
    (core/Bits.v:29-33).
  • Register file: vec mword 32 (RegisterFile.v:13); readReg returns 0 for x0
    (RegisterFile.v:14-16), writeReg writes any index including 0 (:17-19), so x0 is only masked
    on read.
  • Five CSRs: mtvec mepc mcause mtval mie at 0x305/0x341/0x342/0x343/0x304 (Common.v:40-61).
    Spec.v keeps them in a stringmap (RegisterFile.v:23-31), SingleCycle in a 5-field record
    (RegisterFile.v:33-79). Note that granite's "mie" is a whole-word global interrupt-enable that is
    cleared on every trap (Spec.v:461, :528-529), i.e. it behaves like mstatus.MIE, whereas
    RISC-V address 0x304 is the per-source mie register. Csrrw with an unknown CSR index decodes to
    InvalidInstr (Riscv.v:172-176).

Memory and MMIO

  • Harvard: separate Imem and Dmem, both baseMem.Mem := Nmap Byte (stdpp map keyed by N),
    total (a missing byte reads as 0 via !!!, Memory.v:337-339), little-endian word access only
    (Memory.v:355-358). Instruction fetch is LoadWord pc Imem (Spec.v:577, SingleCycle.v:312).
  • Alignment: misaligned Lw/Sw addresses and misaligned taken-branch/Jalr targets raise
    exceptions with mcause 4/6/0 (Riscv.v:50-56, Spec.v:350-351, 366, 426-427, 434-436).
  • MMIO: isMMIOAddr : mword -> bits 1 parameter; default range 0x40000000..0x41000000
    (Riscv.v:201-210). An MMIO Lw/Sw does not complete in the instruction: it enqueues a request
    and moves to phase StepWaitMMIOResp (Spec.v:352-357, 496-499); requests/responses cross the
    boundary through a valid/ready handshake (Spec.v:547-570, 627-651). Handshake bits are public
    inputs/outputs; the response data is a secret input (IFC.v:27-31, 48-49, 59-60).

Exceptions, interrupts, phases, driver

  • handleExn' (Spec.v:456-462): mepc := pc; mcause := code; mtval := info; mie := 0; pc := mtvec (mtvec taken verbatim, not shifted). Illegal instruction is code 2 with
    mtval := encoding.
  • External interrupt: PubInput_interruptValid/Src (IFC.v:29-30) is latched into InterruptSt
    and taken in phase StepInterrupt when mie <> 0 (Spec.v:526-542, 583-591), writing
    mcause := src.
  • Each clock-cycle step (specStep, Spec.v:672-690) consumes (PubInput, SecInput, DriverOut)
    and runs DriverOut_nSteps : list (option unit) micro-steps (IFC.v:84-86); each micro-step
    advances one phase StepLeak -> StepInstr -> StepInterrupt -> StepLeak or waits for MMIO
    (Spec.v:572-611). The DriverPubMachine that picks these lists only sees public inputs and the
    leakage trace (SpecTop.v:35-56, LeakageRefinement.v:533-543). This is how granite makes the
    spec cycle-accurate enough to be trace-equivalent to hardware without fixing timing in the ISA.

Leakage and the security theorem

  • leakage.LeakageEvent := executeInstr (raw: mword) (instr: Instr) (ileakage) (Riscv.v:313-315).
    Per instruction (Riscv.v:217-311): Lw/Sw leak the rs1 value; Beq/Bne leak the taken
    bit; Jalr leaks rs1; Mul leaks whether either operand is zero (early-out multiplier);
    Csrrw to mtvec/mie leaks the written value; everything else leaks only the instruction word.
    No fetch event (commented out, Riscv.v:314). SingleCycle computes the same information as LeakT
    (Common.v:223-235, SingleCycle.v:116-144) and SingleCycleRefines.v:61-95 maps between them.
  • Security: RefinementTheorem.secure_with_driver (LeakageRefinement.v:533-543) and
    driver_noninterference (:545-563): implementation ≡ spec-with-driver, hence same public
    inputs ⇒ same public outputs whenever the spec leakage is secret-independent.
    StaticAnalysis.v is a symbolic executor that discharges secret-independence per program
    (TopLevelSpec.v:806-822).
  • Machine model: Machine.machine := {state; init; step : state -> input -> state * output}
    (Machine.v:17-21), refinement is trace inclusion (:67-70), forward simulation (:128-161),
    and determinism makes refines imply equivalent (:424-432).

Build and dependencies

dune (dune-project), Rocq ≥ 9.0 (README: tested 9.1.1), rocq-stdpp ≥ 1.13,
coq-record-update ≥ 0.3.4, Ltac2, and the quartz submodule; no coqutil (no source file
requires it; the _CoqProject line -Q ../coqutil/src/coqutil coqutil is dead). stdpp is used
pervasively (decide, bool_decide, gmap/Nmap, vec, stringmap, Inhabited, Finite).

2. riscv-coq's specification

  • Decoded instructions Spec/Decode.v: Instruction is a sum over extensions
    (I M A F I64 M64 A64 F64 CSR Invalid, Decode.v:303-316); fields are Z
    (Register := Z, immediates MachineInt := Z, Decode.v:18-25); decode : InstructionSet -> MachineInt -> Instruction (Decode.v:1019) with 16 instruction sets RV32I..RV64IMAF
    (Decode.v:32-48). Encoding lives in Utility/Encode.v with decode/encode proofs in Proofs/.
  • Execution is a program in an abstract monad over the typeclass RiscvProgram M t
    (Spec/Machine.v:35-68: registers, byte/half/word/double loads and stores tagged with a
    SourceType, reservations, getCSRField/setCSRField, PC, privilege mode, fence,
    endCycleNormal/endCycleEarly). RiscvProgramWithLeakage adds leakEvent (:70-74);
    RiscvMachine adds translate/flushTLB/counters (:78-86). Execute.execute dispatches per
    extension and raises for A/F (Spec/Execute.v:13-23). One instruction is run1
    (Platform/Run.v:23-32): getPC; leakEvent (fetchInstr pc); loadWord Fetch pc; decode; leakage_of_instr; leakEvent; execute; endCycleNormal.
  • Exceptions (Machine.v:112-123): MTVal, MPP, MPIE, MEPC, MCauseCode are set and
    pc := MTVecBase * 4, then endCycleEarly. No interrupts ("this simplified spec only supports
    machine mode and no interrupts", Machine.v:114). DefaultRiscvState.translate is the identity
    (Machine.v:136-141), so misaligned loads/stores do not trap (byte-granular memory);
    branch/jump targets are alignment-checked (ExecuteI.v:44-61).
  • Words: MachineWidth t class (Utility/Utility.v:28-93) instantiated once for all widths by
    MachineWidth_XLEN : MachineWidth (bits width) (Utility/MkMachineWidth.v:8-50) under coqutil's
    Bitwidth width (width = 32 \/ width = 64, coqutil Word/Bitwidth.v:35-37). coqutil exports
    the same stdlib Zmod.Bits (Bitwidth.v:3) and declares its own Number Notation on
    Zmod_scope (Bitwidth.v:10-33). So granite's mword and riscv-coq's bits 32 are the same
    type; only the literal notations are declared twice.
  • State Platform/RiscvMachine.v:140-150: getRegs : map.map Z word (partial),
    getPc, getNextPc, getMem : map.map word byte (partial: an address absent from the map is
    "not RAM"), getXAddrs (executable addresses), getLog : list LogItem (external-call/MMIO
    trace), getTrace : option (list LeakageEvent) (None = no leakage guarantee).
    MetricRiscvMachine adds cycle/instruction counters (Platform/MetricRiscvMachine.v:18-21).
  • Step semantics is a predicate, not a function: PrimitivesParams.mcomp_sat : M A -> Machine -> (A -> Machine -> Prop) -> Prop (Spec/Primitives.v:27-47) with per-primitive axioms
    (Primitives.v:138-183). Platforms: MinimalMMIO interprets the free monad
    (Platform/MinimalMMIO.v:96-141) with MMIOSpec := {isMMIOAddr : word -> Prop; isMMIOAligned; MMIOReadOK} (:26-35); MMIO loads/stores are atomic inside the instruction and append
    "MMIOREAD"/"MMIOWRITE" LogItems (:46-50, 54-73); MMIO read values are nondeterministic
    (:66-73); CSR/privilege/fence primitives are False (unsupported) there (:123-131).
    MinimalCSRs has a CSRFile but no MMIO (Platform/MinimalCSRs.v:30-37).
  • CSRs: a field-level model (Spec/CSRField.v, Spec/CSRGetSet.v): mtvec is
    MTVecBase/MTVecMode (CSRGetSet.v:138-141, 352-355), 0x304 is decomposed into
    MEIE/SEIE/... (CSRGetSet.v:261-264, 419), and the global enable MIE is a field of mstatus
    (CSRGetSet.v:85). Csrrw (Spec/ExecuteCSR.v:53-58) checks privilege and skips the rd write
    when rd = 0.
  • Registers: valid_register r := 0 < r < 32 (Primitives.v:15); reading x0 yields 0 and
    writing it is a no-op (Primitives.v:142-155, MinimalMMIO.v:85-94).
  • Leakage Spec/LeakageOfInstr.v: LeakageEvent := fetchInstr addr | executeInstr instr ileakage (:208-210); loads/stores leak the rs1 value (:159-163, 176-178), branches leak the
    taken bit (:190-195), Jalr leaks rs1 (:196), Mul leaks nothing (:68), CSR instructions
    yield None (:223), and leakEvent None collapses getTrace to None
    (RiscvMachine.v:184-186, option_map2).

How bedrock2/processor connects Kami to riscv-coq

processor/src/processor/{KamiRiscv,KamiRiscvStep,KamiProc,Consistency}.v (589 + 3578 + 302 +
343 = 4812 lines) relate Kami's 4-stage pipelined RV32I core p4mm (KamiRiscv.v:268; Kami's own
SC.v/ProcMemCorrect.v/IsaRv32.v, 1366 lines, prove p4mm refines a single-cycle Kami model
first) to riscv-coq:

  • Target: MetricRiscvMachine over MinimalMMIO/MetricMinimalMMIO with FE310ExtSpec
    (KamiRiscv.v:25-29, 80), iset := RV32I (KamiRiscvStep.v:489), 37 of the 40 RV32I
    instructions (IsaRv32.v:96-115), no M, no CSRs.
  • State relation states_related (KamiRiscvStep.v:533-552): Kami pc/rf/mem vs RiscvMachine
    fields, Kami mmioExec method calls vs LogItems (:516-528, 554-570). The leakage field is
    left arbitrary (getTrace := k, :550): the Kami proof says nothing about leakage.
  • Per-step theorem kamiStep_sound (KamiRiscvStep.v:3543-3556): each Kami step is either silent
    (still related) or matches one run1 step and satisfies its mcomp_sat postcondition. Lifted to
    kstep1_sound/ksteps_sound (KamiRiscv.v:162-236) and the end-to-end
    riscv_to_kamiImplProcessor (KamiRiscv.v:519-586): a compiler-proven run1 invariant transfers
    to every Kami Behavior trace.

3. Difference table

Aspect granite (Spec.v / SingleCycle.v) riscv-coq
ISA coverage 14 instructions: RV32I subset + Mul + Csrrw RV32I/RV64I, M, Zicsr in full; A/F decoded but raise
Instruction representation encoded mword at the circuit interface, decoded instrs.Instr with bits k immediates in the spec decoded Instruction with Z fields; decode takes a Z
Word type bits 32, width fixed by WIDTH bits width, width ∈ {32,64} via Bitwidth/MachineWidth
Register file vec mword 32, total, x0 masked on read map.map Z word, partial, x0 read 0/write no-op
Memory Harvard imem/dmem, Nmap Byte, total, word accesses only one map.map word byte, partial, byte..double, XAddrs set
Step semantics deterministic Mealy function per clock cycle, driver chooses micro-steps mcomp_sat predicate per instruction (weakest-precondition), nondeterministic
Exceptions codes 0/2/4/6; pc := mtvec; clears mie codes 0/2 (4 only with an aligning translate); pc := MTVecBase*4; sets MPP/MPIE
Misaligned load/store trap allowed (default translate is identity)
CSRs 5 whole-word CSRs; 0x304 acts as global enable and is cleared on trap field-level model; 0x304 = per-source mie; global enable in mstatus.MIE
Interrupts external input, taken between instructions when mie <> 0 none
MMIO asynchronous request/response on valid/ready wires, wait phase; response is secret input atomic in-instruction, LogItem trace, MMIOReadOK nondeterminism
Leakage vocabulary executeInstr word instr leak; Mul leaks zero-operand bit; Csrrw to mtvec/mie leaks value; no fetch event fetchInstr + executeInstr instr leak; Mul leaks nothing; CSR instruction ⇒ trace becomes None
Security statement trace equivalence impl ≡ spec+driver, noninterference, per-program static analysis none in riscv-coq; bedrock2 proves constant-time compilation on getTrace
Hardware connection Quartz circuit, pipelined model, single-cycle model, all proven equivalent Kami p4mm via KamiRiscv*.v (functional only, no leakage)
Proof style stdpp (decide, gmap, vec), RecordUpdate `<
Build / deps dune; stdpp, record-update, Ltac2, quartz Makefile; coqutil only
Rocq coq >= 9.0, tested 9.1.1, stdpp 1.13 coqutil rocq-core >= 9.0, rocq-stdlib >= 9.1; bedrock2 CI on 9.2 and master

4. Options for connecting them

(a) Refinement proof: granite spec ⇒ riscv-coq run1 (the Kami route)

What: a bridge theory depending on granite, riscv-coq and coqutil, with a relation
states_related : semantics.St -> RiscvMachine -> Prop (regs: vec vs map; mem: Nmap Byte
imem ∪ dmem vs map.map word byte; pc; CSRs → CSRFile fields; MMIO buffers → LogItems;
leakage → getTrace) and a theorem in the shape of kamiStep_sound: a run of granite micro-steps
from StepLeak back to StepLeak (or through StepWaitMMIOResp) matches one run1 step and
its mcomp_sat postcondition. State it against Spec.v's semantics, not SingleCycle.v:
SingleCycleRefines.Secure' already transports it to the single-cycle model and the pipeline.

What has to be resolved first (each is a real semantic gap, not a proof detail):

  • interrupts: assume PubInput_interruptValid = false, or add an interrupt primitive to riscv-coq;
  • misaligned Lw/Sw: pick a riscv-coq platform whose translate traps (there is none today;
    translate_with_alignment_check exists at Machine.v:130-134 but is not wired in), or
    side-condition the theorem on aligned accesses;
  • the mie CSR: either change granite to model mstatus.MIE (0x300, bit 3) or restrict the
    theorem to programs that never touch mie, and drop granite's clear-on-trap or match it with
    riscv-coq's MPIE handling;
  • mtvec: granite uses it verbatim, riscv-coq shifts MTVecBase by 2: only agree when the low two
    bits are zero (mode 0);
  • Csrrw with rd = 0: riscv-coq skips the write, granite writes x0 (masked on read, harmless);
  • Mul leakage: granite leaks strictly more; relate getTrace through a projection that drops the
    zero-operand bit, and handle riscv-coq's None for CSR instructions (granite leaks the written
    value for mtvec/mie; the projection would have to map that to "no guarantee" or riscv-coq's
    CSR leakage would need to be defined);
  • MMIO: relate granite's request/response handshake (multi-cycle) to riscv-coq's atomic
    nonmem_load/store with MMIOReadOK := True (granite's response is an unconstrained secret).

Size: KamiRiscvStep.v is 3.6k lines for 37 instructions largely because Kami steps must be
inverted through kinvert; granite's semantics is a plain function, so the per-instruction cases
reduce to cbn/case_decide plus Zmod arithmetic. Estimate 1.5–2.5k lines (relation + 14
instruction cases + MMIO/exception cases + trace projection). Risks: stdpp and coqutil in one file
(both are notation-heavy; the duplicate Number Notation on Zmod_scope is the concrete one;
manageable by keeping the bridge in its own theory and importing selectively); a granite-side
change (mie) that touches the 10k lines of pipeline proofs. Benefit: bedrock2 programs proven
against run1 (including constant-time results on getTrace) run on granite's verified
pipelined core under one theorem, and granite's leakage contract gets checked against the
Zkt-derived one in riscv-coq.

(b) Reuse riscv-coq Decode/Execute as granite's spec

What: instantiate RiscvProgram with a monad over semantics.St (or prog BaseVM BaseAM) and
replace execStrt/execCtrl/execMem. Everything that case-splits on instrs.Instr
(SingleCycleRefines.v 1336, PipelineRefines.v 5068, MulticycleRefines.v 2846,
StaticAnalysis.v 1701, Riscv.v leakage) would be rewritten against riscv-coq's Instruction,
and granite would inherit riscv-coq's CSR/exception/no-interrupt semantics and lose the typed
immediates and the hardware-facing IsaParams interface. Roughly a rewrite of 10k+ lines of
proofs. Not recommended.

(c) Shared decoded-instruction datatype (decoder agreement only)

What: to_riscv : instrs.Instr -> Decode.Instruction (14 cases; Imm12 etc. sign-extended to
Z, shamt bits 5 to Z, Csr to its 12-bit index) and the lemma
to_riscv (Decode.decode w) = decode RV32IM (Zmod.unsigned w) for every w whose granite decode
is not InvalidInstr, plus "granite InvalidInstr ⇒ riscv-coq decodes to something outside the
14". Needs bit-slice lemmas relating Zmod.slice/Zmod.firstn/Zmod.app (granite) to coqutil's
bitSlice (now stated in division form). Estimate 200–400 lines, one file depending on both.
Benefit: mechanically pins down the instruction subset and the immediate conventions, and is the
first half of (a). Risk: low; it also surfaces the encoding corner cases (e.g. granite's Slli
requires funct7 = 0, riscv-coq tests shamtHi).

(d) Leave separate; align only the leakage vocabulary

What: reshape leakage.LeakageEvent toward riscv-coq's (fetchInstr event, same constructor
names, Mul_leakage (zero_arg) as the one deliberate extension) and write the projection
granite.LeakageEvent -> option riscv.LeakageEvent. About 100 lines, no semantic proof. Benefit:
documents the contract difference (granite's early-out multiplier) in code; makes (a) cheaper
later.

Recommendation

Do (c) now as a small standalone bridge theory (its own dune/_CoqProject, depends on
granite, riscv-coq, coqutil; granite itself stays coqutil-free), and record the semantic gaps
listed under (a) as granite issues, in particular the mie-vs-mstatus.MIE modelling and the
mtvec low bits, since those are ISA-conformance questions independent of riscv-coq. Then do (a)
against Spec.v's semantics for the restricted class (no interrupts, aligned accesses, mode-0
mtvec, programs not writing mie), targeting MinimalMMIO with RV32IM and relating
getTrace through the projection from (d). Skip (b).

5. GitHub-ready summary (for #1)

Granite's single-cycle processor specification is isaSpec/SingleCycle.v: each micro-step fetches,
decodes, executes and writes back one instruction through the same circuit-shaped decoder interface
the Quartz hardware uses. It is proven trace-equivalent to the reference semantics in
isaSpec/Spec.v, which the security theorem is about, and the pipelined model is proven equivalent
to it. Both are deterministic Mealy machines stepped once per clock cycle.

Differences from riscv-coq:

  • ISA: granite has 14 instructions (addi, add, xor, slli, srli, lui, auipc, beq, bne, jalr, lw, sw,
    mul, csrrw). riscv-coq has all of RV32/64 I, M and the CSR instructions.
  • Words: both use the standard library's bits n, so the word type is shared. granite fixes width
    32; riscv-coq covers both.
  • State: granite has a total register vector, separate total instruction and data memories, five
    whole-word CSRs. riscv-coq has partial register and memory maps and a field-level CSR model.
  • Semantics: granite's step is a function; riscv-coq's is a predicate over a free monad with
    nondeterministic MMIO reads.
  • Exceptions and CSRs: granite traps on misaligned data access, jumps to mtvec verbatim, and clears
    a global enable it calls mie (0x304) on every trap. riscv-coq allows misaligned data access,
    shifts mtvec, keeps the global enable in mstatus, and treats 0x304 as the per-source mie.
    riscv-coq has no interrupts; granite takes an external one.
  • MMIO: granite is asynchronous (request, wait phase, valid/ready wires, secret response data).
    riscv-coq completes MMIO inside the instruction and logs it.
  • Leakage: event shapes are close. granite also leaks whether a multiplier operand is zero and the
    values written to mtvec/mie; riscv-coq leaks nothing for mul and drops all guarantees on CSR
    instructions.

Options:

  1. Decoder bridge (200–400 lines): prove the two decoders agree on granite's subset. Cheap.
  2. Leakage vocabulary alignment (100 lines): reshape granite's leakage events to riscv-coq's and
    define the projection.
  3. Refinement proof (1.5–2.5k lines, the Kami/bedrock2 route): relate granite's reference
    semantics to riscv-coq's run1 under MinimalMMIO for programs without interrupts, with
    aligned accesses, not writing mie. One theorem from bedrock2-verified software to the Quartz
    core.
  4. Replace granite's semantics by riscv-coq's Decode/Execute: rewrites about 10k lines of proofs
    and loses the hardware-facing decoder interface. Not recommended.

Recommendation: do 1 now as a small separate theory depending on both projects, file the mie and
mtvec conformance questions as granite issues, then do 3 (using 2) once those are settled.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

@andres-erbsen

Copy link
Copy Markdown

Please sketch what a relationship between riscv-coq and isaSpec/Spec.v would look like. Briefly consider what replacing isaSpec/Spec.v with riscv-coq would require.

granite traps on misaligned data access, jumps to mtvec verbatim, and clears
a global enable it calls mie (0x304) on every trap. riscv-coq allows misaligned data access,
shifts mtvec, keeps the global enable in mstatus, and treats 0x304 as the per-source mie

for each one of these, investigate which repo is more more conformant with official informal specifications of risc-v.

@JasonGross

Copy link
Copy Markdown
Author

Relationship sketch. Relate granite's reference semantics (isaSpec/Spec.v) to riscv-coq's
run1 the way bedrock2's processor/ relates Kami to riscv-coq: a state relation between
granite's St and riscv-coq's RiscvMachine (register vector to register map; instruction and
data memories to one byte map under the invariant that code and data ranges are disjoint; the five
CSRs to CSR fields; MMIO buffers to the log; leakage list to trace through a projection), and a
theorem saying that each granite micro-step is either silent for riscv-coq or completes exactly one
run1 step and its postcondition. riscv-coq would be instantiated at 32 bits with the free-monad
program and a small new platform combining MinimalMMIO with MinimalCSRs (no existing platform
has both). A decoder-agreement lemma is used once per instruction case. Restrictions: no interrupts, no access to CSR 0x304, mtvec low bits zero,
aligned data accesses, and the trace equation holds until the first csrrw because riscv-coq
drops leakage guarantees on CSR instructions.
Estimate: 1.7–2.9k lines; the Kami connection is 4.8k lines for 37 instructions.

Replacing Spec.v with riscv-coq. Thirteen granite files require Spec.v, and the single-cycle
equivalence proof (1.3k lines) and the static analysis (1.7k lines) case-split on its instruction
semantics, so both would be rewritten, and the 8k lines of pipeline proofs would need the leakage and
instruction types changed. Granite would take coqutil and riscv-coq as dependencies (versions are
compatible). Two things make it impossible without changing riscv-coq: granite's MMIO suspends an instruction across clock cycles, which run1 cannot
express, and granite's security proof needs leakage riscv-coq does not define (multiplier
zero-operand bit, values written to mtvec/mie). Granite would also inherit riscv-coq's trap and
CSR semantics, which are not fully conformant either.

Conformance of the four gaps (RISC-V ISA manual, riscv/riscv-isa-manual 2026-09-16):

  • Misaligned loads/stores: the unprivileged spec leaves this to the execution environment.
    Granite's trap with codes 4/6 and riscv-coq's "always completes" are both conformant.
  • mtvec: the privileged spec stores only BASE[31:2] plus a MODE field, and Direct mode sets
    pc := BASE. riscv-coq does that and is conformant. Granite jumps to the register value
    verbatim: conformant while MODE=0, wrong if software sets MODE=1; making the low two bits
    read-only zero would fix it.
  • Global interrupt enable: the spec puts it in mstatus.MIE; CSR 0x304 (mie) holds per-source
    enables, and an interrupt is taken only if both agree with mip. riscv-coq has the right
    registers (it never delivers interrupts). Granite uses 0x304 as the global enable and has no
    mstatus: wrong.
  • On a trap: the spec requires MPIE := MIE; MIE := 0 and never touches mie. Granite clears
    mie and saves nothing: wrong. riscv-coq sets MPIE := 0 and leaves MIE: also wrong, but a
    two-line fix.
Full report (relationship sketch with signatures, replacement analysis, conformance with quoted spec text)

Follow-up E2: granite#1, second round (relationship sketch, replacement cost, RISC-V conformance)

Lane fu-e, 2026-09-17. Follows followup-E-granite-riscv.md. Read-only survey of granite b5b2ba5
(/data/jason/fiat-crypto-worktrees/wp-d/granite), riscv-coq a98896f (wp-g2/riscv-coq; master
58937c33 fetched into fu-e/riscv-coq-master: the diff against a98896f touches only
Utility/BitSlice.v, Utility.v, Encode.v, CSRFile.v, Memory.v, Metric*, Minimal* in
lemma statements, none of the definitions cited below), bedrock2 447b97df processor/, and the
RISC-V ISA manual sources at riscv/riscv-isa-manual 1ea2876 (2026-09-16; latest prefaces are
"Version 20260120" for both volumes; the ratified text quoted is unchanged since 20240411/20241101),
cloned into fu-e/riscv-isa-manual. Nothing edited, nothing built, no posts.

Andres asked: "Please sketch what a relationship between riscv-coq and isaSpec/Spec.v would look
like. Briefly consider what replacing isaSpec/Spec.v with riscv-coq would require." and, for each
of the four conformance gaps, "investigate which repo is more conformant with official informal
specifications of risc-v."

1. Sketch of a relationship between isaSpec/Spec.v and riscv-coq

1.1 Which riscv-coq instantiation

  • Word: bits 32 on both sides. riscv-coq needs Bitwidth 32 (Utility/Words32Naive.v:4-6) and
    gets MachineWidth (bits 32) from MachineWidth_XLEN (Utility/MkMachineWidth.v:8).
  • Monad and program: the free monad free riscv_primitive primitive_result with the
    Materialize/MaterializeWithLeakage instances (Platform/MaterializeRiscvProgram.v:66-94),
    so that run1 iset (Platform/Run.v:23-32) is a concrete syntax tree that a platform interprets.
  • Platform: there is no existing riscv-coq platform with both MMIO and CSRs. MinimalMMIO
    (Platform/MinimalMMIO.v:96-141) makes GetCSRField/SetCSRField impossible (:123-131,
    fun postF postA => False), and every exception goes through raiseExceptionWithInfo, which
    writes CSR fields (Spec/Machine.v:112-123), so under MinimalMMIO no trapping instruction and no
    csrrw has any successor state. MinimalCSRs (Platform/MinimalCSRs.v:30-37, 96-106) has a
    CSRFile but no MMIO. The bridge therefore either (i) targets MinimalMMIO and restricts to
    non-trapping, csrrw-free executions (this is exactly the scope of the Kami proof, which also has
    no CSRs, IsaRv32.v:96-115), or (ii) defines a small platform MinimalMMIOCSRs in the bridge:
    MinimalMMIO.interpret_action plus the two CSR cases of MinimalCSRs.run_primitive
    (MinimalCSRs.v:86-96), roughly 150 lines including the Primitives/PrimitivesSane instances
    copied from MinimalMMIO.v:160-312. (ii) is what makes exceptions and csrrw relatable and is
    assumed below.
  • Instruction set: RV32IM (granite has mul); decode RV32IM (Zmod.unsigned w).

1.2 State mapping

granite semantics.St (Spec.v:306-318) with ArchState (Spec.v:295-301) versus riscv-coq
RiscvMachine (Platform/RiscvMachine.v:140-150; use the plain record, not MetricRiscvMachine,
unless the bedrock2 compiler theorems are to be reused, in which case wrap with getMetrics
unconstrained as KamiRiscvStep.v:551 does).

granite riscv-coq relation
Rf : vec mword 32 (RegisterFile.v:13) getRegs : map.map Z word forall i, 0 < i < 32 -> map.get regs i = Some (readReg (of_Z 5 i) rf); x0 needs nothing (Primitives.v:142-155 handle Register0). Kami's regs_related (Consistency.v:295-297) is the same shape.
Pc : mword getPc, getNextPc getPc = Pc /\ getNextPc = Pc + 4, and Phase = StepLeak (between instructions).
Imem, Dmem : Nmap Byte (total; Memory.v:337) getMem : map.map word byte (partial), getXAddrs riscv-coq has one address space. Relation: map.get mem a = Some (Imem !!! to_N a) for a in the code range C, = Some (Dmem !!! to_N a) for non-MMIO a outside C, = None on MMIO addresses; getXAddrs = C. This needs the invariant that the program never stores into C and never fetches outside it (granite's Harvard split makes a store to address 0 and a fetch from address 0 hit different memories; TestSpec.v programs do exactly that with Sw x.0 x.0 0 at pc 0).
Csrs (RegisterFile.v:23-31 stringmap, 5 CSRs) csrs : CSRFile (Spec/CSRFile.v:106) mtvec ↦ MTVecBase = mtvec >> 2, MTVecMode = mtvec mod 4 (only relatable when the low two bits are 0, see §3.2); mepc ↦ MEPC; mcause ↦ MCauseCode (MCauseInterrupt = 0); mtval ↦ MTVal; granite mie has no counterpart (see §3.3): restrict to programs that never read or write CSR 0x304 and to InterruptSt = None.
MMIOReqBuffer, MMIORespBuffer, PubOutputWires, SecOutputWires (Spec.v:311-315) getLog : list LogItem a completed MMIO load (request sent, response consumed) corresponds to one mmioLoadEvent addr v (MinimalMMIO.v:46-50), a store to one mmioStoreEvent; the relation is only asserted between instructions, when both buffers are empty. The MMIOSpec instance: isMMIOAddr a := isMMIOAddr_g a = 1, isMMIOAligned n a := n = 4 /\ is_word_aligned 4 a, MMIOReadOK _ _ _ _ := True (granite's response is an unconstrained secret input, IFC.v:48-49).
leakage output L_leakage (per step) getTrace : option (list LeakageEvent) getTrace = Some (project (accumulated granite leakage)), see 1.4.
DefaultMachine, InterruptSt none InterruptSt = None assumed; DefaultMachine is unconstrained.

1.3 Theorem shape

granite's step is per clock cycle with a driver-chosen list of micro-steps (Spec.v:652-657, 672-690); riscv-coq's is per instruction. Relate micro-step runs to run1 in the style of
kamiStep_sound (KamiRiscvStep.v:3543-3556): every granite micro-step is either silent for
riscv-coq or completes one run1. Signatures one would write (Coq-ish, names from the two repos):

Section Bridge.
  Context {Registers : map.map Z (bits 32)} {Mem : map.map (bits 32) byte}
          {Registers_ok : map.ok Registers} {Mem_ok : map.ok Mem}.
  Local Existing Instance Words32Naive.                      (* Bitwidth 32 *)
  Context (isMMIOAddr_g : mword -> bits 1) (C : list (bits 32)).  (* code range *)
  Local Instance mmio_spec : MMIOSpec := {| isMMIOAddr a := isMMIOAddr_g a = 1%Zmod;
    isMMIOAligned n a := n = 4%nat /\ semantics.is_word_aligned 4 a = true;
    MMIOReadOK _ _ _ _ := True |}.
  Context {defaultMachine} {isaParams : instrs.params.IsaParams instrs.Instr}.
  Notation St := (semantics.St defaultMachine).

  (* one driver micro-step with no external input (IFC.default_PubInput/SecInput) *)
  Definition gstep (s s' : St) (evs : IFC.L_leakage) : Prop :=
    semantics.doDriverStep s None = (s', evs).                  (* Spec.v:572-611 *)

  Inductive related : St -> RiscvMachine -> Prop :=
  | related_idle : forall s m,                                  (* between instructions *)
      s.(Phase) = StepLeak -> s.(MMIOReqBuffer) = [] -> s.(MMIORespBuffer) = [] ->
      s.(InterruptSt) = None ->
      regs_related s.(ArchSt).(Rf) m.(getRegs) ->
      m.(getPc) = s.(ArchSt).(Pc) /\ m.(getNextPc) = Zmod.add s.(ArchSt).(Pc) 4 ->
      mem_related C s.(ArchSt).(Imem) s.(ArchSt).(Dmem) m.(getMem) /\ m.(getXAddrs) = C ->
      csrs_related s.(ArchSt).(Csrs) m.(csrs) ->
      related s m
  | related_leaked : ...   (* Phase = StepInstr i: instruction word fetched and leaked, not yet executed *)
  | related_mmio_wait : ...  (* Phase = StepWaitMMIOResp: request emitted, response pending *)
  | related_done : ...       (* Phase = StepInterrupt: instruction retired, riscv-coq already stepped *).

  (* decoder agreement, the option-(c) lemma from the first report *)
  Definition to_riscv : instrs.Instr -> Decode.Instruction.     (* 14 cases + InvalidInstr *)
  Lemma decode_agree : forall w, instrs.Decode.decode w <> instrs.InvalidInstr w ->
      to_riscv (instrs.Decode.decode w) = Decode.decode RV32IM (Zmod.unsigned w).

  (* leakage projection *)
  Definition project_event (pc : bits 32) (e : leakage.LeakageEvent) : list LeakageOfInstr.LeakageEvent.
  (* executeInstr raw i l  ↦  [executeInstr (to_riscv i) (project_leak l); fetchInstr pc]
     (riscv-coq traces are consed, newest first: RiscvMachine.v:184-186) *)

  Theorem gstep_sound : forall s s' evs m (post : RiscvMachine -> Prop),
      related s m -> gstep s s' evs ->
      no_mie_access s ->                       (* the instruction at Pc is not csrrw to 0x304 *)
      mcomp_sat (run1 RV32IM) m (fun _ => post) ->   (* MinimalMMIOCSRs primitives *)
      (related s' m /\ evs = [])                                  (* silent *)
      \/ (exists m', post m' /\ related s' m'
              /\ m'.(getTrace) = option_map (fun t => project_event s.(ArchSt).(Pc) (hd_evs) ++ t) m.(getTrace)).

  (* lifted to whole clock cycles and then to traces, as KamiRiscv.v:162-236 does *)
  Theorem cycle_sound : forall s s' out drv m post,
      related s m -> semantics.specStep s ((default_PubInput, default_SecInput), drv) = (s', out) ->
      calways (fun m P => mcomp_sat (run1 RV32IM) m (fun _ => P)) m post ->
      exists m', related s' m' /\ post m'.
End Bridge.

Where the pieces fit:

  • decode_agree is used once per gstep_sound case: granite's StepLeak micro-step calls
    params.decode (Spec.v:578) and riscv-coq's run1 calls decode iset (combine 4 inst)
    (Run.v:28); with mem_related giving combine 4 (loadWord pc) = Zmod.unsigned (LoadWord pc Imem)
    (granite's LoadWord is little_endian_to_bits, Memory.v:355-356; coqutil's combine is
    little-endian too).
  • The per-instruction cases are the 14 arms of execStrt/execCtrl/execMem
    (Spec.v:378-450, 342-376) against ExecuteI.execute/ExecuteM.execute/ExecuteCSR.execute
    after mcomp_sat unfolding through interpret_action. Each is a cbn/case_decide/Zmod
    arithmetic obligation, not a Kami kinvert.
  • Exceptions: granite handleExn' (Spec.v:456-462) versus raiseExceptionWithInfo
    (Machine.v:112-123). Relatable for illegal instruction (code 2, mtval := encoding on both:
    Riscv.v:52, 60; Execute.v:20) and misaligned taken branch/jalr (code 0, mtval := target,
    Spec.v:426-427, 434-436; ExecuteI.v:44-61), under the mtvec low-bits-zero and mie
    restrictions of §3. Misaligned lw/sw are not relatable under the default translate
    (§3.1): exclude them by side condition, or instantiate RiscvMachine.translate in the bridge
    platform with an alignment check (note translate_with_alignment_check at Machine.v:130-134
    raises code 4 for stores too, so it would need a store variant raising 6).
  • MMIO: granite's StepWaitMMIOResp phase spans cycles; the bridge relates the sequence
    (request emitted, silent cycles, response consumed and written back, Spec.v:592-610) to one
    run1 whose nonmem_load (MinimalMMIO.v:66-73) picks the same value. That is the
    related_mmio_wait constructor.
  • Leakage: granite emits one executeInstr raw instr leak per instruction (Spec.v:579,
    Riscv.v:318-320); riscv-coq emits fetchInstr pc then executeInstr (decoded) leak
    (Run.v:26-30). project_leak maps Riscv.v:217-246 constructors to LeakageOfInstr.v:112-152
    ones, dropping the Mul_leakage (zero_arg) bit (riscv-coq Mul_leakage has none,
    LeakageOfInstr.v:55, 68) and mapping Csrrw_leakage* to None (riscv-coq returns None for
    CSR instructions, LeakageOfInstr.v:223, which then makes the whole trace None,
    RiscvMachine.v:184-186). So the trace equation only holds up to the first csrrw; state it as
    "getTrace = Some (...) while no csrrw has executed, None afterwards", or exclude csrrw.

1.4 Restrictions the theorem would carry

  • no interrupts (InterruptSt = None, i.e. PubInput_interruptValid = false throughout);
  • program never accesses CSR 0x304 (mie), and mtvec is only ever written with values whose low
    two bits are 0 (§3.2, §3.3);
  • data accesses aligned, or the bridge platform installs an aligning translate (§3.1);
  • code range C disjoint from all data and MMIO addresses (Harvard split, 1.2);
  • MMIO handshake driven by the default inputs (no back-pressure), or the relation is generalised
    to the buffered states.

1.5 Size estimate

piece lines
bridge platform MinimalMMIOCSRs + Primitives instance (copy of MinimalMMIO.v:96-312 plus two CSR cases) 150–250
to_riscv, decode_agree, bit-slice lemmas (Zmod.slice/firstn/app vs coqutil bitSlice) 200–400
related, regs_related, mem_related, csrs_related and their preservation lemmas 200–300
14 instruction cases (Add, Addi, Xor, Slli, Srli, Lui, Auipc, Mul, Csrrw, Beq, Bne, Jalr, Lw, Sw) 700–1200
exception cases (illegal, misaligned target) and MMIO wait sequence 200–400
leakage projection and trace lemma; cycle/trace lifting (mirrors KamiRiscv.v:144-236) 200–300
total roughly 1.7–2.9k

For comparison: KamiRiscvStep.v 3578 + KamiRiscv.v 589 + KamiProc.v 302 + Consistency.v
343 = 4812 lines for 37 instructions with Kami rule inversion.

2. What replacing isaSpec/Spec.v by riscv-coq would require

2.1 Who depends on Spec.v

Files that Require granite.isaSpec.Spec at b5b2ba5 (13): IsaParams.v, Pipelined.v,
PipelinedImpl.v, Pipelined_QuartzImpl.v, PipelineRefines.v, PipelineRefinesBase.v,
SingleCycle.v, SingleCycleRefines.v, SpecTop.v, StaticAnalysis.v, StaticAnalysisTest.v,
TestSpec.v, TopLevelSpec.v. Spec.v itself Require Exports Riscv.v (Spec.v:278), whose
instrs.Instr and leakage.* types are also used by IFC.v (L_leakage, IFC.v:87),
MulticycleRefines.v, QuartzImpl.v, QuartzImpl_helpers.v, app/Pipelined.v,
app/MemoryImpl.v. Counting textual references to semantics., instrs./Decode., and
leakage.: SingleCycleRefines.v 141, StaticAnalysis.v 124, TestSpec.v 11,
MulticycleRefines.v 10, PipelineRefines.v 8, IsaParams.v 6, Pipelined.v 4, SpecTop.v 3,
PipelineRefinesBase.v 2, and one each in SingleCycle.v, QuartzImpl.v,
QuartzImpl_helpers.v, IFC.v, app/Pipelined.v, app/MemoryImpl.v.

2.2 What would have to change

  1. A RiscvProgram instance for granite's state. riscv-coq's Execute is written against
    RiscvProgram M t (Machine.v:35-68). granite would provide M := free riscv_primitive primitive_result interpreted over semantics.St, or a state monad over St. The interpreter
    must give meaning to getCSRField/setCSRField for MTVecBase/MTVecMode/MEPC/MCauseCode/ MCauseInterrupt/MTVal/MPP/MPIE/MIE (granite has five whole-word CSRs, RegisterFile.v:35-41),
    to endCycleEarly (granite's prog/evalProg has no early exit, core/Program.v:44-60), and
    fail on reservations, privilege, fence, byte/half accesses.
  2. The MMIO wait phase cannot be expressed inside run1. riscv-coq's loadWord returns within
    the instruction (MinimalMMIO.v:66-73); granite suspends the instruction across clock cycles
    until the response handshake completes (Spec.v:496-499, 592-610, 547-570). Keeping granite's
    cycle-level I/O contract means either running run1 only when the response is already
    available (changing when leakage and outputs appear, which the driver machine and the
    pipeline refinement are calibrated to), or changing riscv-coq so run1 can be split at a
    primitive (a coroutine interpretation of the free monad). This alone breaks
    SingleCycleRefines.v and PipelineRefines.v, which case-split on the phases.
  3. Interrupts. riscv-coq has none (Machine.v:114). granite's StepInterrupt phase could stay
    as a wrapper around run1, but then the exception path (raiseExceptionWithInfo) and the
    interrupt path (handlePossibleInterrupt, Spec.v:526-542) would live in two different
    formalisms with two CSR models.
  4. Leakage. granite's security theorem needs the multiplier's zero-operand bit and the values
    written to mtvec/mie (Riscv.v:282-295), because the pipelined multiplier is early-out
    (app/MultiplierSpec.v, Quartz_MultiplierSimulates.v) and the driver depends on those CSR
    writes. riscv-coq's leakage_of_instr leaks nothing for mul and None for CSR instructions
    (LeakageOfInstr.v:68, 223), and None erases the trace (RiscvMachine.v:184-186). Adopting
    riscv-coq's leakage would make granite's noninterference theorem false for its own hardware
    unless riscv-coq's LeakageOfInstr is parameterised or extended.
  5. Semantic deltas granite would inherit (all listed in §3): misaligned data accesses no longer
    trap; mtvec shifted; mie becomes a per-source register with no effect on granite's
    interrupt input; trap entry writes MPIE := 0 rather than clearing the global enable.
    StaticAnalysis.v (1701 lines) mirrors execStrt/execCtrl/execMem case by case and would
    be rewritten against riscv-coq's Execute.
  6. Restating the proofs. SingleCycleRefines.v (1336) becomes a proof that the
    IsaParams-driven single-cycle program refines run1-interpreted-over-St (every lemma
    ExecALU_ok, ExecControl_ok, MemAddr_ok, doDriverStep_sim_*, SingleCycleRefines.v:468-1142
    is rewritten); PipelineRefines.v/MulticycleRefines.v (7914 lines) reference Spec.v only
    through instrs/leakage types and SingleCycle, so they would mostly need the leakage and
    instruction types renamed, but any change to the leakage vocabulary (item 4) or to phase
    structure (item 2) propagates into them; TopLevelSpec.v/SpecTop.v/LeakageRefinement.v
    are generic over the semantics machine and survive if Sem_machine keeps its type.
  7. Build. granite's dune-project would add coq-coqutil and coq-riscv (both are opam
    packages with Makefile builds; riscv-coq/coq-riscv.opam requires coq >= 8.18 and
    coq-coqutil >= 0.0.7; coqutil at bedrock2 447b97df requires rocq-core >= 9.0,
    rocq-stdlib >= 9.1), compatible with granite's Rocq 9.1.1. stdpp and coqutil can coexist
    (they share no module names), but a file importing both gets overlapping notations
    (stdpp's !!, <[ ]>, ∅ versus coqutil's map.* functions are fine; the two Number Notations on Zmod_scope, granite core/Bits.v:29-33 and coqutil Word/Bitwidth.v:10-33,
    collide and the last import wins). Granite would also inherit riscv-coq's Generalizable All Variables/hs-to-coq style files.

Net: replacing Spec.v is a rewrite of the ISA layer plus SingleCycleRefines.v and
StaticAnalysis.v (about 3k lines directly), with knock-on edits in the 8k lines of pipeline
proofs, and it is not possible at all without changing riscv-coq for items 2 and 4 (asynchronous
MMIO, leakage of multiplier operands and CSR writes) and without accepting riscv-coq's CSR/trap
semantics (item 5), which are themselves not fully conformant (§3.3). The bridge of §1 gets the
connection without any of this.

3. RISC-V conformance of the four gaps

Sources: The RISC-V Instruction Set Manual, Volume I: Unprivileged Architecture, chapter "RV32I
Base Integer Instruction Set" (src/unpriv/rv32.adoc), and Volume II: Privileged Architecture,
chapter "Machine-Level ISA" (src/priv/machine.adoc), from riscv/riscv-isa-manual 1ea2876
(2026-09-16). Normative sentences carry norm: anchors in the source; I cite those.

3.1 Misaligned loads and stores

Spec (Vol. I, "Load and Store Instructions", rv32.adoc:697-724):

Regardless of EEI, loads and stores whose effective addresses are naturally aligned shall not
raise an address-misaligned exception. Loads and stores whose effective address is not naturally
aligned to the referenced datatype [...] have behavior dependent on the EEI.
An EEI may guarantee that misaligned loads and stores are fully supported [...] handled in
hardware, or via an invisible trap [...].
An EEI may not guarantee misaligned loads and stores are handled invisibly. In this case, loads
and stores that are not naturally aligned may either complete execution successfully or raise an
exception. The exception raised can be either an address-misaligned exception or an access-fault
exception. [...] the EEI must define if exceptions caused by address misalignment result in a
contained trap [...] or a fatal trap.

(norm:ldst_no_exc_aligned, norm:misaligned_ldst_eei_dependent_behavior,
norm:misaligned_ldst_hw_support, norm:misaligned_ldst_exc_type,
norm:misaligned_ldst_contained_or_fatal_trap.) Exception codes (Vol. II, "Machine Cause
(mcause) Register", table at machine.adoc:1773-1885): 0 instruction address misaligned,
2 illegal instruction, 4 load address misaligned, 6 store/AMO address misaligned.

  • granite: word-aligned lw/sw never trap; misaligned ones raise a contained trap with
    code 4 (load) or 6 (store) and mtval := address (Spec.v:330-331, 350-351, 366;
    Riscv.v:52-55, 62-63; IsaParams.v:337-343). Conformant: this is the "EEI does not
    guarantee invisible handling, contained address-misaligned trap" option, with the right codes.
  • riscv-coq: Lw/Sw call translate Load/Store 4 addr (ExecuteI.v:126-131, 158-164) and
    the default translate is Return (Machine.v:136-141, with the comment "riscv does allow
    misaligned memory access [...] we don't do alignment checks"); memory is byte-granular
    (Platform/Memory.v:33-41), so a misaligned access to RAM completes. Conformant: the
    "fully supported in hardware" EEI. Two footnotes: on MMIO addresses MinimalMMIO requires
    isMMIOAligned (MinimalMMIO.v:55, 67), and a misaligned MMIO access has no successor state,
    which is neither of the two EEI options but "the step is unspecified" (a simplification, not a
    trap); and the unused translate_with_alignment_check (Machine.v:130-134) raises code 4 for
    stores as well, which would be wrong (should be 6) if it were wired in.
  • Verdict: both conformant, under different EEIs; software proven against one is not proven
    against the other unless it never misaligns. Taken-branch/jump targets are alignment-checked with
    code 0 on both sides (Spec.v:426-427, 434-436, 445-447; ExecuteI.v:44-61), matching
    norm:taken_cti_misaligned_exc and norm:branch_misaligned_untaken_exception
    (rv32.adoc:106-109, 625-629), including "only if taken".

3.2 mtvec: verbatim versus shifted

Spec (Vol. II, "Machine Trap-Vector Base-Address (mtvec) Register", machine.adoc:1165-1213):

The mtvec register is an MXLEN-bit WARL read/write register that holds trap vector
configuration, consisting of a vector base address (BASE) and a vector mode (MODE). [...] The
mtvec register must always be implemented, but can contain a read-only value. [...] The value
in the BASE field must always be aligned on a 4-byte boundary [...] Note that the CSR contains
only bits XLEN-1 through 2 of the address BASE. When used as an address, the lower two bits are
filled with zeroes [...]
MODE 0 Direct: All traps set pc to BASE. 1 Vectored: Asynchronous interrupts set pc to
BASE+4×cause. ≥2 Reserved.
When MODE=Direct, all traps into machine mode cause the pc to be set to the address in the
BASE field. When MODE=Vectored, all synchronous exceptions into machine mode cause the pc to
be set to the address in the BASE field, whereas interrupts cause the pc to be set to the
address in the BASE field plus four times the interrupt cause number.

(norm:mtvec_sz_warl_acc, norm:mtvec_rdonly, norm:mtvec_base_align_4B,
norm:mtvec_mode_enc, norm:mtvec_mode_direct_op, norm:mtvec_mode_vectored_op.)

  • granite: mtvec is an arbitrary 32-bit register (RegisterFile.v:29-30, 68-69); on an
    exception or interrupt pc := mtvec verbatim (Spec.v:457, 462, 533, 539;
    SingleCycle.v:73, 78, 103, 108). If software only ever writes values with MODE=0 (low two bits
    zero) this is exactly Direct mode: conformant for that subset. If software writes MODE=1 or a
    reserved mode, granite jumps to BASE+1/BASE+2/BASE+3 and then fetches from a misaligned pc
    without any check (Spec.v:577): wrong. Because mtvec is WARL, the cheapest conformant fix
    is to make bits 1:0 read-only zero in writeCsr (Direct-only implementations are explicitly
    allowed: "can contain a read-only value", "the set of values the register may hold can vary by
    implementation"). Separately, granite writes mcause := src on an interrupt without setting
    the Interrupt bit (Spec.v:535, the comment acknowledges it), against norm:mcause_intr_op
    (machine.adoc:1732).
  • riscv-coq: mtvec is stored as MTVecBase and MTVecMode fields; a CSR read returns
    base << 2 | mode and a write splits the value (CSRGetSet.v:138-141, 352-355); trap entry sets
    pc := MTVecBase * 4 (Machine.v:122). Since riscv-coq raises only synchronous exceptions
    (no interrupts), pc := BASE is the specified behaviour in both Direct and Vectored mode.
    Conformant. (MTVecMode ≥ 2 is accepted on write, which is a WARL liberty.)
  • Verdict: riscv-coq conformant; granite conformant only while MODE stays 0, wrong otherwise, and
    trivially fixable as a WARL restriction.

3.3 The global interrupt enable: mstatus.MIE versus CSR 0x304 (mie)

Spec (Vol. II, "Privilege and Global Interrupt-Enable Stack in mstatus register",
machine.adoc:353-376, and "Machine Interrupt (mip and mie) Registers",
machine.adoc:1327-1353):

Global interrupt-enable bits, MIE and SIE, are provided for M-mode and S-mode respectively.
[...] When a hart is executing in privilege mode x, interrupts are globally enabled when xIE=1
and globally disabled when xIE=0. [...] MIE and MPIE must be writable.
[...] mie is the corresponding MXLEN-bit read/write register containing interrupt enable bits.
Interrupt cause number i (as reported in CSR mcause) corresponds with bit i in both mip and
mie. [...]
An interrupt i will trap to M-mode [...] if all of the following are true: (a) either the current
privilege mode is M and the MIE bit in the mstatus register is set, or the current privilege
mode has less privilege than M-mode; (b) bit i is set in both mip and mie; and (c) if register
mideleg exists, bit i is not set in mideleg.

(norm:mstatus_mie_sie_op1, norm:mstatus_mie_sie_op2, norm:mstatus_sie_spie_rdonly0,
norm:mie_sz_acc, norm:mip_mie_enc_txt, norm:intr_mip_mie_op.) mstatus is CSR 0x300 with
MIE at bit 3 and MPIE at bit 7; mie is CSR 0x304.

  • granite: there is no mstatus. CSR 0x304 is a whole word, and an interrupt is taken iff
    that word is nonzero (Spec.v:528-529; SingleCycle.v:68-71, bool_decide (mie_enabled <> zeroes)),
    regardless of which bit is set and with no mip. So granite uses mie as the global enable
    and has no per-source enables. Wrong with respect to the register map: software that does
    csrrw x0, 0x304, t0 with t0 = 0x800 (enable machine external interrupts) on a conformant
    core additionally needs mstatus.MIE = 1 to receive anything, and software that sets
    mstatus.MIE on a conformant core has no effect on granite because 0x300 decodes to
    InvalidInstr (Riscv.v:63-74, 172-176). It is a consistent simplification (one enable bit,
    one interrupt source), but it is not RISC-V's; a conformant minimal model would implement
    mstatus with MIE/MPIE (MPP hard-wired to 3), keep mie per-source, and take the interrupt iff
    mstatus.MIE && mie[src] && mip[src].
  • riscv-coq: mstatus.MIE/MPIE/MPP are CSR fields (CSRField.v:48, CSRGetSet.v:85, 306-324), mie (0x304) is decomposed into per-source fields (CSRGetSet.v:261-264, 419),
    and mret restores MIE := MPIE; MPIE := 1 (ExecuteCSR.v:105-107), matching
    norm:mstatus_xret_op (machine.adoc:409-413). Conformant in the register layout. Since
    riscv-coq takes no interrupts, condition (a)/(b) is never evaluated, which is a simplification
    (no mip, no interrupt delivery), not a contradiction.
  • Verdict: riscv-coq conformant (modulo having no interrupts at all); granite wrong, in that it
    puts the global enable in the wrong CSR and has no per-source enable.

3.4 What happens to the enables on a trap

Spec (Vol. II, machine.adoc:394-396):

When a trap is taken from privilege mode y into privilege mode x, xPIE is set to the value of
xIE; xIE is set to 0; and xPP is set to y.

(norm:mstatus_xpie_xie_xpp_trap_op.) Nothing in the mip/mie section or the trap-entry
descriptions (norm:mepc_op machine.adoc:1713, norm:mcause_op :1728, norm:mtval_op
:1996) lets the hardware modify mie on a trap; mie is only written by software.

  • granite: on every exception and interrupt, mie := 0 (Spec.v:461, :537-538;
    SingleCycle.v:75, 107), and nothing records the previous enable. Read as mstatus.MIE := 0
    this is the required "xIE is set to 0"; read as CSR 0x304 it is wrong (the spec never clears
    mie, and doing so silently disables every interrupt source until software rewrites the whole
    register). There is no MPIE and no mret, so a handler cannot restore the previous enable
    atomically; it must csrrw the enable back and jalr through mepc (two instructions with an
    interrupt window in between, the situation the note at machine.adoc:422-430 warns about). The
    consistent reading is again "granite's mie is really mstatus.MIE, with MPIE omitted".
  • riscv-coq: raiseExceptionWithInfo sets MTVal, MPP := Machine, MPIE := 0, MEPC,
    MCauseCode, and jumps (Machine.v:112-123); it does not copy MIE into MPIE and does
    not clear MIE. The source comment says the two writes exist "just so that Mret will succeed
    at restoring them". So after trap + mret, MIE is 0 instead of the pre-trap value, and inside
    the handler MIE still has the pre-trap value instead of 0. Wrong against
    norm:mstatus_xpie_xie_xpp_trap_op, though unobservable within riscv-coq because it never
    delivers interrupts; observable only through CSR reads by the program. The fix is two lines
    (mie <- getCSRField MIE; setCSRField MPIE mie;; setCSRField MIE 0).
  • Verdict: neither repo implements the specified trap-entry update of the enable stack. riscv-coq
    has the right registers and a two-line fix; granite has the update in the wrong register and no
    MPIE, so fixing it means adding mstatus.

3.5 Summary table

gap granite b5b2ba5 riscv-coq a98896f spec
misaligned lw/sw contained trap, codes 4/6, mtval = address (Spec.v:350-366) completes (default translate = identity, Machine.v:136-141); MMIO case unspecified both EEIs allowed (Vol. I rv32.adoc:697-724); both conformant
mtvec pc := mtvec verbatim, any value writable (Spec.v:457,462) pc := BASE*4, mode stored separately (Machine.v:122, CSRGetSet.v:138-141,352-355) BASE 4-byte aligned, MODE in bits 1:0, Direct: pc := BASE (Vol. II machine.adoc:1165-1213); riscv-coq conformant, granite conformant only for MODE=0 and wrong otherwise
global enable CSR 0x304 as a whole word, nonzero = enabled, no mstatus/mip (Spec.v:528-529) mstatus.MIE/MPIE/MPP fields, 0x304 per-source (CSRGetSet.v:85,261,306-324,419) global enable is mstatus.MIE; 0x304 is per-source; taken iff MIE ∧ mip[i] ∧ mie[i] (machine.adoc:353-376,1327-1353); riscv-coq conformant, granite wrong
on trap mie := 0, nothing saved (Spec.v:461,537) MPIE := 0, MPP := M, MIE untouched (Machine.v:117-121) MPIE := MIE; MIE := 0; MPP := y (machine.adoc:394-396); mie never touched by hardware; both wrong, riscv-coq closer

4. GitHub-ready summary (for #1)

Relationship sketch. Relate granite's reference semantics (isaSpec/Spec.v) to riscv-coq's
run1 the way bedrock2's processor/ relates Kami to riscv-coq: a state relation between
granite's St and riscv-coq's RiscvMachine (register vector to register map; instruction and
data memories to one byte map under the invariant that code and data ranges are disjoint; the five
CSRs to CSR fields; MMIO buffers to the log; leakage list to trace through a projection), and a
theorem saying that each granite micro-step is either silent for riscv-coq or completes exactly one
run1 step and its postcondition. riscv-coq would be instantiated at 32 bits with the free-monad
program and a small new platform combining MinimalMMIO with MinimalCSRs (no existing platform
has both). A decoder-agreement lemma is used once per instruction case. Restrictions: no interrupts, no access to CSR 0x304, mtvec low bits zero,
aligned data accesses, and the trace equation holds until the first csrrw because riscv-coq
drops leakage guarantees on CSR instructions.
Estimate: 1.7–2.9k lines; the Kami connection is 4.8k lines for 37 instructions.

Replacing Spec.v with riscv-coq. Thirteen granite files require Spec.v, and the single-cycle
equivalence proof (1.3k lines) and the static analysis (1.7k lines) case-split on its instruction
semantics, so both would be rewritten, and the 8k lines of pipeline proofs would need the leakage and
instruction types changed. Granite would take coqutil and riscv-coq as dependencies (versions are
compatible). Two things make it impossible without changing riscv-coq: granite's MMIO suspends an instruction across clock cycles, which run1 cannot
express, and granite's security proof needs leakage riscv-coq does not define (multiplier
zero-operand bit, values written to mtvec/mie). Granite would also inherit riscv-coq's trap and
CSR semantics, which are not fully conformant either.

Conformance of the four gaps (RISC-V ISA manual, riscv/riscv-isa-manual 2026-09-16):

  • Misaligned loads/stores: the unprivileged spec leaves this to the execution environment.
    Granite's trap with codes 4/6 and riscv-coq's "always completes" are both conformant.
  • mtvec: the privileged spec stores only BASE[31:2] plus a MODE field, and Direct mode sets
    pc := BASE. riscv-coq does that and is conformant. Granite jumps to the register value
    verbatim: conformant while MODE=0, wrong if software sets MODE=1; making the low two bits
    read-only zero would fix it.
  • Global interrupt enable: the spec puts it in mstatus.MIE; CSR 0x304 (mie) holds per-source
    enables, and an interrupt is taken only if both agree with mip. riscv-coq has the right
    registers (it never delivers interrupts). Granite uses 0x304 as the global enable and has no
    mstatus: wrong.
  • On a trap: the spec requires MPIE := MIE; MIE := 0 and never touches mie. Granite clears
    mie and saves nothing: wrong. riscv-coq sets MPIE := 0 and leaves MIE: also wrong, but a
    two-line fix.

Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

@andres-erbsen

Copy link
Copy Markdown

What if we are instead looking for a connection theorem of the form "if riscv-coq executions from a starting state satisfy a postcondition (eventually run1), the chosen granite spec risc-v will in some number of instructions reach a state related to one that satisfies the riscv-coq postcondition?

@andres-erbsen

Copy link
Copy Markdown

Also investigate what it would take to remove the coqutil dependency from riscv-coq, building on standard library instead. maybe values of Interface.map can be replaced with functions (->), something like Zbitwise can be used instead of coqutil bitwise provers, and word/lia might already be strong enough in stdlib?

@JasonGross

Copy link
Copy Markdown
Author

Yes, and it is the direction bedrock2 already consumes: riscv_to_kamiImplProcessor in
processor/KamiRiscv.v takes an invariant preserved by each run1 step (the compiler's invariant
is "runs to a good state", so runsTo enters through it) and concludes that every hardware trace
has a related riscv-coq trace. The eventuality form you
describe (related s m -> runsTo run1 m post -> exists n s' m', granite steps n s s' /\ related s' m' /\ post m') follows from the same per-instruction lemma by induction on runsTo, using granite's
determinism; the safety form (every reachable granite state is related to a riscv-coq state
satisfying the invariant) is what plugs into End2EndPipeline.v. The granite target is the reference
semantics in isaSpec/Spec.v; the existing equivalence proofs carry the result to the hardware.

Why it is easier: with plain MinimalMMIO, a riscv-coq run that traps or touches a CSR has no
successor state, so the hypothesis only covers trap-free, csrrw-free runs. Granite's mtvec and
mie behaviour never matters, no CSR platform is needed, and if the bridge's translate checks
alignment, misaligned accesses are excluded too. The code/data split goes through riscv-coq's
executable-address set, leaving only "data memory agrees with instruction memory on the code range
initially". What stays: no interrupts, and every fetched word must decode on granite's side. That
is the practical blocker: the bedrock2 compiler emits 38 RV32IM instructions and granite implements
12, so compiled bedrock2 programs cannot run on granite's ISA until it grows.

Size: about 1.4-2.3k lines, versus 4.8k for the Kami connection, which also bridged two word
types and inverted Kami rules.

Leakage: for the security theorem to compose, granite's leakage must be a function of riscv-coq's
trace. It is for 13 of the 14 instructions (instruction word from the public program, branch bit,
load/store base register, jalr target). It is not for mul: granite's early-out multiplier leaks
whether an operand is zero; riscv-coq's mul leaks nothing. Either restrict composed programs to
never multiply secrets by possibly-zero values, extend riscv-coq's Mul_leakage (and the
compiler's constant-time proof) with that bit, or make the multiplier constant-time.

Full addendum (theorem signatures, why easier/harder, Kami comparison, leakage)

5. Addendum: the other direction (riscv-coq runsTo postcondition ⇒ granite reaches a related state)

Andres (17:30Z): "What if we are instead looking for a connection theorem of the form 'if
riscv-coq executions from a starting state satisfy a postcondition (eventually run1), the chosen
granite spec risc-v will in some number of instructions reach a state related to one that
satisfies the riscv-coq postcondition'?"

5.1 How bedrock2 actually consumes the Kami theorem

riscv_to_kamiImplProcessor (KamiRiscv.v:519-586) is not an eventuality statement. It takes
an invariant RvInv with establishRvInv, preserveRvInv : RvInv m -> mcomp_sat (run1 iset) m RvInv, and useRvInv : RvInv m -> exists t, traces_related t m.(getLog) /\ traceProp t, and
concludes that every Kami Behavior p4mm mFinal t has an MMIO trace t' with traceProp t'.
runsTo enters only through the invariant: the compiler's ll_inv is
runsToGood_Invariant ll_good iset := runsTo (mcomp_sat (run1 iset)) m (goodReadyState false) /\ valid_machine m (compiler/src/compiler/RiscvEventLoop.v:99-101, ToplevelLoop.v:159), and
runsToGood_is_Invariant (RiscvEventLoop.v:105-112) shows one run1 step preserves it
("runs to a good state" is itself a safety property). End2EndPipeline.v:274-345 instantiates
RvInv := ll_inv. Underneath, ksteps_sound (KamiRiscv.v:219-236) is an induction over Kami's
Multistep using the per-step kstep1_sound (KamiRiscv.v:162-204): for every hardware step,
the related riscv-coq state satisfying calways cstep1 rs1 inv steps or the hardware step is
silent. So the existing pipeline needs exactly the per-step forward simulation of §1.3 (hardware
step ⇒ riscv-coq step), applied to states that satisfy an invariant, and never needs "in some
number of instructions". The eventuality theorem Andres describes is a corollary of that per-step
lemma (induction on runsTo, using granite's determinism to pick the path), and the per-step
lemma is what composes with bedrock2 today. Both are written out below; the work is the same.

5.2 The theorem

Granite side: Spec.v's semantics.machine (Spec.v:758-765), i.e. Machine.execution
(Machine.v:44-49) of specStep over an input stream. Not SingleCycle.v: SingleCycleRefines.v:1321
and TopLevelSpec.v:633-654, 731-757 already transport any statement about the Spec.v machine to the
single-cycle model, the pipeline and the Quartz circuit through Machine.equivalent (equal I/O
traces for equal inputs, Machine.v:95-96), and the security theorem is stated against the Spec.v
machine (SpecTop.v:47-61).

riscv-coq side: RV32IM, bits 32, the free-monad program (MaterializeRiscvProgram.v:66-94)
under plain MinimalMMIO (MinimalMMIO.v:131-141), no CSR support. In this direction that is a
feature (5.3). RiscvMachine.translate instantiated with an alignment check (a store variant of
translate_with_alignment_check, Machine.v:130-134) so that a misaligned access has no riscv-coq
successor (raising writes a CSR field, which MinimalMMIO maps to False, MinimalMMIO.v:123-131).

Section GraniteReaches.
  Context {Registers : map.map Z (bits 32)} {Mem : map.map (bits 32) byte}
          {Registers_ok : map.ok Registers} {Mem_ok : map.ok Mem}.
  Local Existing Instance Words32Naive.
  Context (isMMIOAddr_g : mword -> bits 1).
  Local Instance mmio_spec : MMIOSpec := {| isMMIOAddr a := isMMIOAddr_g a = 1%Zmod;
    isMMIOAligned n a := n = 4%nat /\ semantics.is_word_aligned 4 a = true;
    MMIOReadOK _ _ _ _ := True |}.
  Local Instance RVS : RiscvMachine (free riscv_primitive primitive_result) (bits 32) :=
    {| translate := translate_with_alignment_check_ldst; (* code 4 loads, 6 stores *) ... |}.
  Notation cstep := (fun m P => mcomp_sat (run1 RV32IM) m (fun _ : unit => P)).   (* KamiRiscv.v:153 *)

  Context {defaultMachine} {isaParams : instrs.params.IsaParams instrs.Instr}.
  Notation St := (semantics.St defaultMachine).
  Notation M := (semantics.machine defaultMachine (pub_init) (sec_init)).         (* Spec.v:758 *)

  (* input stream, one element per clock cycle *)
  Context (inp : nat -> IFC.Input * IFC.DriverOut).
  Hypothesis no_interrupts : forall i, (fst (fst (inp i))).(PubInput_interruptValid) = false.
  Hypothesis driver_progress : forall i, exists j, i <= j /\ (snd (inp j)).(DriverOut_nSteps) <> [].
  Hypothesis mmio_responsive : (* every request is eventually accepted and answered *) ...

  (* n clock cycles of the granite machine along [inp], with its I/O trace *)
  Definition steps (n : nat) (s s' : St) (tr : Machine.trace _ _) : Prop :=
    Machine.execution M s tr s' /\ length tr = n /\ (forall i ev, nth_error tr i = Some ev -> Machine.Input ev = inp i).

  (* state relation, as §1.2 but with the Harvard split handled through XAddrs (5.3) *)
  Inductive related : St -> RiscvMachine -> Prop := (* idle / leaked / mmio_wait / done, §1.3 *) .

  (* granite leakage so far ↔ riscv-coq getTrace (5.5) *)
  Inductive leak_related : list (mword * leakage.LeakageEvent) -> option (list LeakageEvent) -> Prop := ... .

  (* one riscv-coq instruction is matched by a finite granite prefix (the per-step lemma of §1.3
     read the other way round: WP on the riscv-coq side, one deterministic path on the granite side) *)
  Lemma instr_sim : forall s m (midset : RiscvMachine -> Prop) i,
      related s m -> idle s ->                       (* Phase = StepLeak, buffers empty *)
      cstep m midset ->
      exists k s' tr m', steps_from i k s s' tr /\ idle s' /\ midset m' /\ related s' m'
                         /\ leak_related (granite_leaks s' ) m'.(getTrace).

  (* the eventuality theorem *)
  Theorem granite_reaches_post : forall s m (post : RiscvMachine -> Prop),
      related s m -> idle s ->
      runsTo cstep m post ->                                    (* runsToNonDet.v:11-18 *)
      exists n s' tr m', steps n s s' tr /\ related s' m' /\ post m'
                         /\ leak_related (granite_leaks s') m'.(getTrace)
                         /\ mmio_related (granite_mmio tr) m'.(getLog).
  (* Proof: induction on runsTo; runsToDone gives n = 0; runsToStep uses instr_sim with the
     midset, then the IH at the chosen mid.  Determinism of specStep (Machine.v:275-289)
     makes the granite path unique once inp is fixed. *)

  (* the safety form bedrock2 consumes (KamiRiscv.v:219-236, 519-586) *)
  Theorem granite_always_related : forall (inv : RiscvMachine -> Prop) s m,
      related s m -> inv m -> (forall m', inv m' -> cstep m' inv) ->
      forall n s' tr, steps n s s' tr -> exists m', related s' m' /\ inv m'.
End GraniteReaches.

Instantiating inv := ll_inv and reading off getLog through mmio_related gives the granite
analogue of riscv_to_kamiImplProcessor; granite_reaches_post is then runsTo-induction on top
of instr_sim. Everything hard is in instr_sim, which is §1.3's gstep_sound with the
quantifiers rearranged (there: given a granite step, find the riscv-coq step; here: given the WP of
the riscv-coq step, show granite's deterministic outcome is one of the outcomes the WP covers).
Because mcomp_sat under MinimalMMIO is a weakest precondition over all outcomes of every
primitive (MinimalMMIO.v:66-73: forall v, MMIOReadOK ... -> post v ...), granite's secret MMIO
response is always one of them; so are its register and memory reads. This is the same direction as
kamiStep_sound's conclusion exists m2', ... /\ post m2' (KamiRiscvStep.v:3552-3556).

5.3 Easier or harder than the per-step sketch

Easier, and mostly for the reason Andres gives: the theorem only has to simulate riscv-coq
behaviours that the postcondition proof exercises, and under MinimalMMIO a riscv-coq run that
would trap or touch a CSR has no successor at all (GetCSRField/SetCSRField are False,
MinimalMMIO.v:123-131; every trap goes through raiseExceptionWithInfo, Machine.v:112-123). So
runsTo cstep m post is only inhabited by trap-free, csrrw-free runs, and:

  • granite's trap behaviour (mtvec verbatim, mie cleared, codes) never matters: §3.2-3.4 drop
    out entirely; no bridge platform with CSRs is needed (saves the 150-250 lines of §1.5);
  • misaligned lw/sw: with the alignment-checking translate in the bridge's RiscvMachine
    instance, a misaligned access is a riscv-coq trap, hence excluded by the hypothesis; the
    "aligned accesses" side condition moves from the theorem statement into the instantiation.
    (With the default identity translate it would have to stay, since riscv-coq would complete
    the access and granite would trap.)
  • code/data overlap: riscv-coq's Fetch requires isXAddr4 pc (Primitives.v:109,
    MinimalMMIO.v:76) and a store removes its addresses from XAddrs (MinimalMMIO.v:62). State
    the memory relation as map.get mem a = Some (Dmem !!! to_N a) for every non-MMIO a, plus the
    invariant a ∈ XAddrs -> Dmem !!! a = Imem !!! a. Stores preserve it (they leave XAddrs),
    fetches use it (granite reads Imem, riscv-coq reads mem = Dmem = Imem there), data loads use
    Dmem on both sides. The disjointness restriction of §1.4 weakens to an initial condition:
    SecInit_dmem agrees with PubInit_imem on the code range (which then has to be public data,
    reasonable for a code region).
  • unsupported instructions: this restriction does not disappear and is the practically decisive
    one. riscv-coq happily executes sub, and, jal, lbu, ... and granite decodes them to
    InvalidInstr and traps (Riscv.v:187-188). The theorem needs "every word fetched decodes on the
    granite side", i.e. forall a, isXAddr4 a xaddrs -> instrs.Decode.decode (Imem word at a) <> InvalidInstr _, discharged per program. The bedrock2 compiler's code generator
    (compiler/src/compiler/FlatToRiscvDef.v) emits 38 distinct RV32IM instructions (Addi Lui Jal Xori Slli Lw Add Or Sw Sub Jalr Beq Xor Srli Srl Srai Sra Sltu Sltiu Slti Slt Sll Sh Sb Remu Ori Mulhu Mul Lhu Lbu Divu Bne Bltu Blt Bgeu Bge Andi And), of which granite implements 12; the
    compiled init/loop programs of End2EndPipeline.v will not run on granite's ISA. For the
    composition to be more than a theorem about hand-written 14-instruction programs, granite's
    Instr (and the Quartz decoder, IsaParams.v, and all four refinement proofs) would have to
    grow to the compiler's subset. That is a granite-hardware decision, not a bridge decision.
  • interrupts stay excluded (no_interrupts): riscv-coq has none, and granite would divert to
    mtvec on one (Spec.v:583-591).
  • the mie restriction disappears (no csrrw can be executed); the mtvec restriction
    disappears (no trap can be executed).

Harder, in two ways:

  • Progress. The eventuality form needs granite to reach the state, so the input stream must
    let it: the driver must schedule micro-steps (DriverOut_nSteps, Spec.v:652-657), and every
    MMIO request must be accepted and answered through the ready/valid handshake
    (Spec.v:547-570, 627-651). These are fairness hypotheses on inp (driver_progress,
    mmio_responsive) that the per-step/safety form does not need. bedrock2's use (5.1) is the
    safety form, so this cost can be avoided by proving granite_always_related and deriving
    granite_reaches_post only if wanted.
  • Nondeterminism bookkeeping. runsTo's runsToStep gives a midset and an IH for every
    mid in it; instr_sim must exhibit the specific m' granite's outcome corresponds to and show
    midset m'. With MinimalMMIO this is direct (the WP quantifies over exactly the choices
    granite makes); it would not be if riscv-coq's platform made choices granite does not make
    (e.g. is_initial_register_value on an uninitialised register that granite reads as 0:
    MinimalMMIO.v:136 sets it to True, so fine, but the relation must then say every register is
    present in getRegs, as riscvRegsInit does, KamiRiscv.v:276-311).

5.4 Comparison with the Kami proof, and size

Kami (processor/) granite, this direction
induction over Kami Multistep (ksteps_sound), invariant on the riscv-coq side (calways) granite_always_related: over steps n (granite cycles), same invariant shape; granite_reaches_post: over runsTo
per-step core kamiStep_sound (KamiRiscvStep.v:3543), one case per Kami rule (pgmInit, pgmInitEnd, execLd, execLdZ, execSt, execNm, execNmZ), each obtained by kinvert on the Kami module, 400-450 lines per case instr_sim: one case per granite instruction (14) plus the MMIO wait sequence; each is cbn/case_decide/Zmod reasoning on execStrt/execCtrl/execMem (Spec.v:342-450) against mcomp_sat of ExecuteI/ExecuteM unfolded through interpret_action; 40-80 lines per case
in-flight states pinit = false (program loading), RiscvXAddrsSafe after loading (KamiRiscvStep.v:533-552); silent steps for non-retiring rules granite phases StepLeak/StepInstr/StepInterrupt/StepWaitMMIOResp (Common.v:253-257); silent cycles for StepInterrupt, for empty driver lists, and while an MMIO response is pending
trace equation KamiLabelR/KamiLabelSeqR from Kami method calls to Event, traces_related to LogItem (KamiRiscvStep.v:516-528, 554-570) mmio_related: from granite's per-cycle PubOutput_mmio handshake + SecOutput_mmioData (and the response on SecInput) to mmioLoadEvent/mmioStoreEvent (MinimalMMIO.v:46-50); plus leak_related (5.5), which Kami does not have
word bridging Kami Word.word ↔ stdlib bits (KamiRiscvStep.v:52-450, ~400 lines) none: same bits 32 type; only Zmod.slice/app ↔ bitSlice for the decoder lemma
decoder Kami's rv32DoExec cases vs riscv-coq decode, inside each rule case decode_agree once (§1.3)
size 4812 lines (KamiRiscvStep.v 3578, KamiRiscv.v 589, KamiProc.v 302, Consistency.v 343) estimate below
piece lines
to_riscv, decode_agree, slice lemmas 200-400
related, regs_related, mem_related (XAddrs form), mmio_related, leak_related + preservation 250-350
instr_sim: 14 instruction cases 600-1000
MMIO wait sequence (request cycle, silent cycles, response cycle) 150-250
granite_always_related (cycle induction), granite_reaches_post (runsTo induction), fairness plumbing 150-250
total 1.4-2.3k, i.e. a few hundred lines less than §1.5 (no CSR platform, no exception cases)

5.5 The leakage story in this direction

For granite's security theorem to compose, granite's leakage must be secret-independent whenever
riscv-coq's is: driverSem_SecretIndependent (LeakageRefinement.v:198-203) asks that equal public
inputs give equal L_leakage outputs; bedrock2's constant-time compiler theorem gives that
getTrace is Some (f public_inputs) (compiler_correct_wp, Pipeline.v:790, with the leakage
function f). So we want granite_leaks = G (riscv_trace) for a function G that does not look at
secrets. Per instruction, granite's event executeInstr raw i l (Riscv.v:313-320) versus
riscv-coq's fetchInstr pc :: executeInstr i' l' (Run.v:26-30):

  • raw: granite leaks the instruction word; riscv-coq leaks pc and the decoded instruction.
    raw = Imem[pc] and Imem is public (PubInit_imem, IFC.v:67-70), so raw is a function of
    the riscv-coq trace and the public program (riscv-coq's Decode.decode is also injective on the
    encodings, LeakageOfInstr.v:18-20, Proofs/DecodeEncode.v).
  • LeakMem rs1, LeakBranch b, LeakJalr rs1 (Riscv.v:248-274): identical to riscv-coq's
    Lw_leakage rs1/Sw_leakage rs1, Beq_leakage b/Bne_leakage b, Jalr_leakage rs1
    (LeakageOfInstr.v:159-196). G is the identity here.
  • Mul_leakage (zero_arg : bool) (Riscv.v:282-285): riscv-coq's Mul_leakage carries nothing
    (LeakageOfInstr.v:55, 68). zero_arg is not a function of the riscv-coq trace. This is the
    one place where granite's contract is strictly weaker than riscv-coq's and where the composition
    breaks: a bedrock2 program proven constant-time for riscv-coq may multiply a secret by a value
    that is sometimes zero, and granite's early-out multiplier (app/MultiplierSpec.v,
    Quartz_MultiplierSimulates.v) leaks that. Three ways out, in increasing cost: (i) restrict the
    composed theorem to programs whose mul operands are never zero on secret data (a side condition
    on the riscv-coq trace, checkable per program); (ii) add the operand-zero bit to riscv-coq's
    Mul_leakage and let the compiler's constant-time proof carry it (bedrock2 would then have to
    prove mul operands are public, which its current leakage model deliberately does not require);
    (iii) make granite's multiplier constant-time and drop the bit (a hardware change, and the
    reason the bit exists is to model the cheap early-out design).
  • Csrrw_leakage_mtvec v/Csrrw_leakage_mie v (Riscv.v:286-295): irrelevant here, csrrw is
    excluded by the MinimalMMIO hypothesis; if a CSR platform were used instead, riscv-coq's None
    for CSR instructions (LeakageOfInstr.v:223) makes getTrace = None, i.e. no guarantee, and
    G would be undefined there (consistent: granite's leakage of v is then "more than nothing").
  • InvalidInstr_leakage: excluded (no traps).
  • riscv-coq's fetchInstr pc has no granite counterpart, but pc is recoverable from the
    granite trace (initial pc public, branch bits and jalr targets leaked), so the two traces are
    inter-definable except for the mul bit.

So leak_related in 5.2 is the graph of G on the 13 non-mul instructions and a relation on
mul; the security composition ("riscv-coq trace public ⇒ granite trace public ⇒ granite
noninterference, LeakageRefinement.v:545-563") goes through for programs satisfying (i), or after
(ii)/(iii). None of this depends on the direction of the functional theorem; it is the same
projection as §1.3, but in this direction it is natural to state it as granite = G(riscv) rather
than riscv = project(granite).

5.6 GitHub-ready reply (for #1)

Yes, and it is the direction bedrock2 already consumes: riscv_to_kamiImplProcessor in
processor/KamiRiscv.v takes an invariant preserved by each run1 step (the compiler's invariant
is "runs to a good state", so runsTo enters through it) and concludes that every hardware trace
has a related riscv-coq trace. The eventuality form you
describe (related s m -> runsTo run1 m post -> exists n s' m', granite steps n s s' /\ related s' m' /\ post m') follows from the same per-instruction lemma by induction on runsTo, using granite's
determinism; the safety form (every reachable granite state is related to a riscv-coq state
satisfying the invariant) is what plugs into End2EndPipeline.v. The granite target is the reference
semantics in isaSpec/Spec.v; the existing equivalence proofs carry the result to the hardware.

Why it is easier: with plain MinimalMMIO, a riscv-coq run that traps or touches a CSR has no
successor state, so the hypothesis only covers trap-free, csrrw-free runs. Granite's mtvec and
mie behaviour never matters, no CSR platform is needed, and if the bridge's translate checks
alignment, misaligned accesses are excluded too. The code/data split goes through riscv-coq's
executable-address set, leaving only "data memory agrees with instruction memory on the code range
initially". What stays: no interrupts, and every fetched word must decode on granite's side. That
is the practical blocker: the bedrock2 compiler emits 38 RV32IM instructions and granite implements
12, so compiled bedrock2 programs cannot run on granite's ISA until it grows.

Size: about 1.4-2.3k lines, versus 4.8k for the Kami connection, which also bridged two word
types and inverted Kami rules.

Leakage: for the security theorem to compose, granite's leakage must be a function of riscv-coq's
trace. It is for 13 of the 14 instructions (instruction word from the public program, branch bit,
load/store base register, jalr target). It is not for mul: granite's early-out multiplier leaks
whether an operand is zero; riscv-coq's mul leaks nothing. Either restrict composed programs to
never multiply secrets by possibly-zero values, extend riscv-coq's Mul_leakage (and the
compiler's constant-time proof) with that bit, or make the multiplier constant-time.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

@andres-erbsen

Copy link
Copy Markdown

what about riscv-coq without coqutil?

and could we state a variant of granite_always_related for always properties as defined in coqutil right now? could this updated theorem compose with the fiat-crypto Garagedoor proof to make a End2EndLightbulb-like hardware-software connection by only composing implications from riscv-coq postconditions to granite executions?

@JasonGross

Copy link
Copy Markdown
Author

Both under way: the riscv-coq-without-coqutil investigation (inventory of coqutil uses on the bits-interface branch, stdlib replacements tried on representative goals, bedrock2 impact) and the always variant of the connection theorem with the composition path through the GarageDoor proof. I will post both here.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

@JasonGross

Copy link
Copy Markdown
Author

riscv-coq without coqutil:

I looked at what it would take to drop coqutil from riscv-coq, on master and on the
fable/littleendian-bits branch (which already removes HList, PrimitivePair and the tuple
LittleEndian, but leans harder on coqutil's Map.Memory).

Inventory (53 of 102 files): maps (map.map/get/put/empty/undef_on/ok,
coqutil's load_Z/store_bytes memory model, sorted-list instances), the bitwise prover
prove_Zeq_bitwise (16 files in Proofs/), Bitwidth, le_split/le_combine, a handful of
tactics (destruct_one_match, ssplit, destr, rdelta, simp), PropSet in the MMIO
valid_machine, and trivia (blia, byte notation, option_map2, sanity).

Findings:

  • Maps: riscv-coq itself only needs get/put/empty and three lemmas. A 20-line riscv-owned
    class works, with instances from any coqutil map (3 lines) or from plain functions (no
    funext). Bare functions are not viable for memory because bedrock2 uses one coqutil map
    object as both its source memory and riscv-coq's Mem, with sep-logic (map.split,
    map.fold) and coqutil's SeparationMemory lemmas about riscv-coq's load_Z; a total
    Register -> word would also change spec_getRegister's uninitialised-register clause.
  • Bitwise: stdlib Zbitwise is a lemma library, not a prover; bits_inj'+btauto fails on
    all 5 representative encode/decode goals, and lia/nia after bitSlice_alt only handle
    concrete-width arithmetic. But prove_Zeq_bitwise and its deps only need stdlib: a
    vendored copy (917 lines, trimmable to ~600) compiles without coqutil and proves the same
    goals at the same speed (0.1-11 s each).
  • lia is already enough everywhere except 15 blia in BitSlice.v. Bitwidth,
    little-endian and the tactics are ~300 stdlib-only lines to copy.

Downstream: steps that do not touch the map type are invisible to bedrock2. The map step
costs bedrock2 an instance plus bridge lemmas and edits at ~50 sites in the compiler,
processor and end2end (~2 weeks), and the Bitwidth move needs a coordinated bump.

Estimate: ~1.5 weeks in riscv-coq, ~2 weeks downstream, ~1.3k lines vendored.
Recommendation: do the coqutil-free Proofs/Examples/tactics/prover steps now on the
littleendian-bits branch; move Bitwidth/le_split with the next bedrock2 bump; only take
on the map interface if a coqutil-free coq-riscv package is the goal, and then with a
riscv-owned map class rather than bare functions.

Full report (inventory, experiments, downstream impact, plan)

Follow-up H: removing the coqutil dependency from riscv-coq

Lane fu-h, 2026-09-17. Requested by Andres Erbsen (#1, 2026-09-17 17:37Z):
"investigate what it would take to remove the coqutil dependency from riscv-coq, building on
standard library instead. maybe values of Interface.map can be replaced with functions (->),
something like Zbitwise can be used instead of coqutil bitwise provers, and word/lia might
already be strong enough in stdlib?"

Sources (read-only):

  • riscv-coq master 58937c33 (Merge PR #59, lia import) and the option-A branch
    JasonGross/riscv-coq fable/littleendian-bits (45dc8df, load/store interface on bits).
    Scratch clones: /data/jason/fiat-crypto-worktrees/fu-h/riscv-coq (master) and
    /data/jason/fiat-crypto-worktrees/fu-h/riscv-coq-optA (option A). Paths below are
    relative to src/riscv/ of the option-A tree unless stated.
  • coqutil master 4b19efb3 at /data/jason/fiat-crypto-worktrees/fu-b/coqutil (built).
  • bedrock2 447b97df tree at /data/jason/fiat-crypto-worktrees/wp-j3/bedrock2.
  • Stdlib: rocq-stdlib 9.1.0 on the rocq-9.2 switch
    (/data/jason/.opam/rocq-9.2/lib/coq/user-contrib/Stdlib).
  • Experiments: /data/jason/fiat-crypto-worktrees/fu-h/scratch/{vendored,exp}.

1. Inventory

Master: 54 of 102 .v files Require coqutil (147 Require lines). Option A: 53 files.
Per directory (option A, files with coqutil / total): Spec 3/20, Platform 19/21,
Proofs 17/26, Utility 10/27, Examples 4/4.

Option A vs master: option A already removes coqutil.Datatypes.HList (3 files),
coqutil.Datatypes.PrimitivePair (Memory.v) and the tuple-based coqutil.Word.LittleEndian
(RiscvMachine.v, MetricRiscvMachine.v, Run.v) because w8..w64 became bits 8..64
(Utility/Utility.v:17-20). In exchange it adds reliance on coqutil's memory model:
Memory.v now defines load_bytes/store_bytes via coqutil.Map.Memory.load_Z/store_Z
(Platform/Memory.v:15-24), uses coqutil.Map.SeparationMemory.same_domain_store_bytes
(Platform/Memory.v:41-45) and LittleEndianList.le_split_mod/le_combine_bound
(Platform/Memory.v:90-103). The inventory below is for option A; master differs only by the
three modules just named.

Require lines by coqutil module (option A), with the names riscv-coq actually uses:

Category Modules (files) Names used in riscv-coq Where
Maps Map.Interface (23), Map.Properties (5), Map.Memory (2), Map.SeparationMemory (1), Map.SortedList (3), Map.SortedListWord (2), Map.Z_keyed_SortedListMap (3), Map.OfFunc (1) map.map 42, map.undef_on 20, map.ok 18, map.empty 18, map.put 14, map.get 13, map.same_domain 1, map.same_domain_preserves_undef_on 2, map.get_put_same/_diff 1 each; Memory.load_bytes/store_bytes/unchecked_store_bytes/load_Z/store_Z; same_domain_store_bytes; instances SortedList.map (Spec/CSRFile.v:100-110), SortedListWord.map (Utility/DefaultMemImpl32.v:6-7, 64), Zkeyed_map + OfFunc (Examples) Context {Registers: map.map Register word} {Mem: map.map word byte} in RiscvMachine.v:17-18, Primitives.v:22-23, MetricPrimitives, Minimal*, MinimalMMIO*, Sane, MetricSane, AtomicMinimal, FE310ExtSpec, LogInstructionTrace, MinimalLogging, MinimalCSRs*
Bitwise provers Z.prove_Zeq_bitwise (16), Z.BitOps (13), Z.bitblast (1), Z.ZLib (2) tactic prove_Zeq_bitwise (Proofs/invert_encode_*.v x12, EncodeBound.v, EncodeDecode.v, VerifyDecode.v, DecodeEncodeProver.v:105, Examples/WMMFree.v:1067); signExtend (28 uses, Notation at Utility/Utility.v:15), signExtend_alt_bitwise; Z.smodulo_pow2 (VerifyDecode.v:44), Z.shiftl_minus_one_neg (Utility/BitSlice.v:127) Proofs/, Utility/BitSlice.v
Lia Z.Lia (20) only blia, 15 uses, all in Utility/BitSlice.v; every other file already uses lia (riscv-coq #57/#59). coqutil now defines Ltac blia := lia (coqutil Z/Lia.v:75) everywhere
Tactics Tactics.Tactics (12), Tactics.destr (3), Tactics.rdelta (3), Tactics.fwd (1), Tactics.Simp (1) eqapply 12, so 11, head 10, destruct_one_match 7, spec 4, ssplit 3, destruct_products 2, forget 1; destr 4; rdelta 6 (VerifyDecode.v:24); fwd (VerifyDecode.v:59); simp 26 (WMMFree.v only). Note so/forget are already duplicated in riscv's own Utility/Tactics.v (17 lines) Platform/, Proofs/, Examples/
Bitwidth Word.Bitwidth (8) class Bitwidth, width_pos, width_nonneg, modulus_pos, shamt_of_Z_small, the Zmod Number Notation, Arguments Zmod.unsigned: simpl never (coqutil Word/Bitwidth.v, 60 lines; depends only on Stdlib Zmod+Lia once its one blia becomes lia) Utility/Utility.v:4 (Export), MkMachineWidth.v, Words32/64Naive.v, DefaultMemImpl*, Memory.v, MetricMaterializeRiscvProgram.v
Little-endian Word.LittleEndianList (3) le_split, le_combine, le_split_mod, le_combine_bound Platform/Memory.v:90-103, RiscvMachine.v:193 (Z32s_to_bytes), MetricRiscvMachine.v
Byte Byte (2) only the notation byte := (Init.Byte.byte : Type); no byte.<lemma> is referenced anywhere in riscv-coq (git grep 'byte\.' is empty) Utility/Utility.v:5 (Export), Memory.v
Sets/lists Datatypes.PropSet (2), Datatypes.ListSet (2), Datatypes.List (2) of_list, disjoint (11 each), disjoint_diff_l, ListSet.of_list_removeb, List.removeb, endswith(+_refl,_cons_l) Platform/MinimalMMIO.v:140,172-208,265, MinimalMMIO_Post.v:131-165 (valid_machine = map.undef_on mem isMMIOAddr /\ disjoint (of_list xAddrs) isMMIOAddr)
Misc Datatypes.Option (1), Datatypes.RecordSetters (1), Decidable (2), Word.Properties (2), sanity (3) option_map2 (RiscvMachine.v:186,190), eq_of_eq_Some, inversion_option; { mach with f := v } notation, 5 uses (MinimalCSRs.v:43-83); EqDecider notation (SMTVerif.v:29, WMMFree.v:135); Word.Properties: no name used (dead Require); sanity = 2 Set lines Platform/, Examples/

Build wiring: coq-riscv.opam depends on coq-coqutil >= 0.0.7; Makefile:19 adds
-Q $(DEPS_DIR)/coqutil/src/coqutil coqutil. Examples/ are in the all target but not in
spec (Makefile:10-11).

2. Replacement per category, with what stdlib offers and what I measured

2.1 Maps (the only structurally hard one)

What riscv-coq itself needs from a map: get, put, empty, and three facts
(get_empty, get_put_same, get_put_diff); the derived notions undef_on,
same_domain, putmany (for unchecked_store_bytes) can be defined from get. Nothing in
riscv-coq uses map.fold, map.split, map.of_list outside Examples, or extensionality.

Experiment scratch/exp/Exp5.v (compiles in 0.5 s): a 20-line class rmap.map
(rep/get/put/empty) plus rmap.ok with those three lemmas; an instance built from any
coqutil map.map in 3 lines (rmap_of_coqutil), and an instance built from a plain function
K -> option V with a boolean equality (rmap_of_func) that needs no functional
extensionality. So "values of Interface.map replaced by functions" works inside
riscv-coq for both Registers and Mem.

Two caveats on going to raw functions rather than a riscv-owned class:

  1. Registers as a total function Register -> word changes the spec, not just the encoding:
    spec_getRegister (Spec/Primitives.v, match map.get regs x with None => forall v, is_initial_register_value v -> ...) models uninitialised registers; a total function has
    no None. Keep Register -> option word (or the class) unless that spec change is wanted.
  2. Memory as word -> option byte cannot be a coqutil map.ok (needs map_ext, i.e.
    funext, and fold), and bedrock2's compiler proof lives on map.split/sep-logic over the
    same memory object (section 3). So the memory type must stay a parameter that bedrock2
    can instantiate with a coqutil map: a riscv-owned class, not a bare function type.

Cost inside riscv-coq: riscv.Utility.Map (~60 lines), rewrite Platform/Memory.v
(copy footprint/load_bytes/unchecked_store_bytes/store_bytes/load_Z/store_Z, coqutil
Map/Memory.v:24-47, ~25 lines, plus same_domain_store_bytes, ~30 lines), swap
Context {Registers: map.map ...} in ~19 Platform/Spec files (mechanical), replace the
CSRFile sorted-list instance (Spec/CSRFile.v) by a function map keyed by CSRField
(decidable equality already proven via CSRField_to_Z_inj), and DefaultMemImpl32/64 by
the function instance (fine for cbv in Examples; no extraction of memory is done).
Estimate 2-3 days.

2.2 Bitwise reasoning

Stdlib status on rocq-stdlib 9.1: Stdlib.ZArith.Zbitwise exists but is a lemma library
(Z.lnot_lnot, Z.add_lor_land, carry identities; Zbitwise.v:41-175) whose own proofs use a
#[local] tactic (bitwise as i ?Hi; autorewrite; btauto, Zbitwise.v:29-38). There is no
exported bitwise decision procedure. bitwise (Numbers/Integer/Abstract/ZBits.v:580) is just
Z.bits_inj' + intros. Z.div_mod_to_equations / Z.to_euclidean_division_equations are
stdlib (omega/PreOmega.v:171,227) and riscv-coq already uses the former (BitSlice.v:97,
VerifyDecode.v:41). Zmod/bits ship 239+78 lemmas (ZmodBase.v, Bits.v), including
testbit_*, unsigned_and/or/xor, unsigned_slu/srs, signed_srs.

Measured on 5 representative goals (scratch/exp/Goals.v.in: invert_encode_I,
encode_I_bitSlice_idemp, funct7_from_funct12, invert_encode_SB with the mod 2 side
condition, encode_decode_I):

Tactic G1 G2 G3 G4 G5
coqutil prove_Zeq_bitwise (Exp1) 3.7 s 1.6 s 0.17 s 11.0 s 1.6 s
same tactic, vendored stdlib-only copy (Exp3) 3.5 s 1.5 s 0.14 s 10.6 s 1.6 s
naive stdlib Z.bits_inj' + autorewrite + btauto (Exp2) fail fail fail fail fail
rewrite bitSlice_alt; Z.to_euclidean_division_equations; nia (Exp4) n/a n/a ok 0.15 s n/a n/a

Exp4 also shows nia handles concrete-width slice arithmetic (bitSlice inst 0 7 + 2^7 * bitSlice inst 7 32 = inst) but not the symbolic-width bitSlice_split without the manual
Z.rem_mul_r step that coqutil's proof already does. It cannot touch the Z.lor-based
encode goals at all.

Conclusion: stdlib is not strong enough to replace prove_Zeq_bitwise; but the prover itself
only needs stdlib. The vendored chain Lia.v + bitblast.v + ZLib.v + BitOps.v + prove_Zeq_bitwise.v (917 lines, scratch/vendored/, produced by sed 's/coqutil.Z./riscvutil./')
compiles with no -Q coqutil in 2.7 s and proves all five goals at identical speed. Trimming
to what riscv-coq uses (prove_Zeq_bitwise, signExtend, signExtend_alt_bitwise,
or_to_plus, Z.smodulo_pow2, Z.shiftl_minus_one_neg) is ~600 lines; bitblast is only
used by signExtend_alt_bitwise's proof (BitOps.v:172). Estimate 1 day.

2.3 Lia, sanity, Byte, Option, Decidable, Word.Properties, Tactics

All mechanical:

  • blia: 15 occurrences in Utility/BitSlice.v become lia (the remaining 19 files only
    import coqutil.Z.Lia and use lia).
  • sanity: inline the two Global Set lines (Utility.v:10 already has one of them).
  • Byte: Notation byte := (Init.Byte.byte : Type) in Utility.v; stdlib Strings.Byte
    provides to_N/of_N/eqb; byte.unsigned is only needed by the vendored le_combine.
  • Option: option_map2, eq_of_eq_Some, inversion_option are 10 lines.
  • Decidable.EqDecider is a Notation for forall x y, BoolSpec (x = y) (x <> y) (f x y).
  • Word.Properties: dead Require in both Examples.
  • Tactics: move destruct_one_match, ssplit, eqapply, head, spec, destruct_products,
    destr, rdelta (~90 lines, stdlib-only) into the existing Utility/Tactics.v; fwd is
    used once (VerifyDecode.v:59) and can be replaced by destruct_products; subst-style
    steps; simp (WMMFree.v, 26 uses) either vendored (Simp.v 126 lines + invert_hyp) or the
    file moves with the Examples (2.6).
    Estimate 1 day total.

2.4 Bitwidth and Zmod literals

Copy coqutil Word/Bitwidth.v (60 lines, stdlib-only after blia -> lia) to riscv.Utility.Bitwidth. This is
the one non-map change that downstream must follow, because the Bitwidth class identity
is threaded through every bedrock2 compiler lemma (Context {BW: Bitwidth width},
FlatToRiscvCommon.v:78); bedrock2 would simply take it from riscv.Utility.Utility, which
it already imports (33 Require lines). Wrinkle: the Number Notation for Zmod literals in that
file should exist in exactly one place; if coqutil keeps its copy, importing both prints a
notation-override warning (not tested).

2.5 Little-endian bytes

Stdlib has nothing for list byte <-> Z. Vendor le_combine/le_split and the four
lemmas used (le_combine_split, le_split_mod, le_combine_bound, length_le_split),
~80 lines, using the vendored prover. Because bedrock2 also uses coqutil's le_split (for
Z32s_to_bytes-shaped program loading and Kami memory init) the copies must stay
definitionally identical so reflexivity bridges them. Estimate 0.5 day.

2.6 Sets and Examples

valid_machine in MinimalMMIO(_Post).v is the only user of PropSet/ListSet. Restating it
as (forall a, In a xAddrs -> ~ isMMIOAddr a) and undef_on from the riscv map class
removes the dependency without vendoring 1 000 lines of PropSet/ListSet/List; the three
endswith lemmas are 10 lines. bedrock2's MMIO.v and KamiRiscv.v (which Require coqutil.Datatypes.PropSet, KamiRiscv.v:24) adapt at ~5 sites. Estimate 0.5 day.

Examples (Fib.v, Example64Literal.v use Zkeyed_map; WMMFree.v uses OfFunc,
Simp, the prover; SMTVerif.v uses EqDecider): either port them to the function map
and the vendored tactics (~1 day) or split them out of the default target with an optional
coqutil dependency. Nothing downstream imports them.

3. What breaks downstream

bedrock2 447b97df: 37 files under compiler/src, 3 under processor/src, 2 under end2end/src
require riscv.*. The key coupling is that bedrock2 uses one mem: map.map word byte
both as its source-language memory and as riscv-coq's Mem
(compiler/FlatToRiscvCommon.v:85, GoFlatToRiscv.v:39, RunInstruction.v:102, Pipeline.v:67
with mem_ok at Pipeline.v:141), and Registers: map.map Z word with map.ok
(Pipeline.v:148,153; RunInstruction.v:101; GoFlatToRiscv.v:38; processor/KamiRiscv.v:76,
KamiRiscvStep.v:452, Consistency.v:292; end2end/End2EndPipeline.v:70-73). Across
compiler+processor+end2end there are 120 distinct map.* names (306 map.get, 110
map.split, 24 map.fold); the files that touch getRegs/getMem use 92 of them.
The compiler relates program memory to riscv-coq's loads through coqutil's
SeparationMemory lemmas stated about riscv-coq's Memory.load_Z/store_bytes
(load_Z_of_sep x7, uncurried_store_bytes_of_sep x5, load_bytes_of_sep x3,
store_bytes_preserves_domain x2, sep_of_load_bytes x2) and unfolds those definitions at
19 sites (e.g. GoFlatToRiscv.v:602, MMIO.v:177,197, FlatToRiscvFunctions.v:1823, Spilling.v:2106).
Kami: riscvRegsInit is a map.put chain (KamiRiscv.v:270-276), riscvMemInit is
map.of_list with Properties.map.get_of_list_In_NoDup (KamiRiscv.v:336-386); end2end
instantiates memory with SortedListWord.map (Bedrock2SemanticsForKami.v:13-14) and
registers with Zkeyed_map (End2EndLightbulb.v:188).

Under a bare function design bedrock2 would have to carry a relation between its coqutil
memory and riscv-coq's function memory through every spec_* lemma and every one of those
sites: effectively a rewrite of GoFlatToRiscv/RunInstruction/FlatToRiscvCommon and the
Kami step proof. I do not recommend it.

Under the riscv-owned class design bedrock2 needs: (i) the one-line instance from
coqutil maps (Exp5.v shows it) and Registers_ok/mem_ok mapped to rmap.ok; (ii) a small
bridge file proving riscv.Memory.load_bytes (rmap_of_coqutil mem) = coqutil.Map.Memory.load_bytes
etc. (by unfolding, if riscv-coq copies the definitions verbatim; unchecked_store_bytes
needs one map_ext lemma because coqutil goes through of_list_word_at); (iii) undef_on
and the restated valid_machine in MMIO.v/KamiRiscv.v; (iv) Bitwidth and le_split taken
from riscv-coq. The 19 unfold sites and the ~30 sep-lemma sites then need
rewrite riscv_load_Z_eq or change. Estimate 1-1.5 weeks for someone who knows the
compiler proofs, plus 1-2 days for processor/ and 0.5 day for end2end. The Kami-side
processor proof is otherwise untouched: it never sees riscv-coq's memory representation,
only map.get riscvMemInit addr facts.

4. Effort and plan

Step Scope riscv-coq effort Downstream Independent PR?
1 drop Z.Lia, sanity, Byte, Option, Word.Properties, Decidable; move tactics (destr, rdelta, Tactics.*, fwd use) into Utility/Tactics.v; rewrite 5 record updates in MinimalCSRs.v 1 day none yes
2 vendor bitwise prover (Utility/{ZLib,BitOps,prove_Zeq_bitwise}.v) and point Proofs/ at it 1 day none (bedrock2 only imports the resulting lemmas) yes
3 Utility/Bitwidth.v + Utility/LittleEndianList.v 0.5 day bedrock2 switches 2 Require lines, must match class identity: coordinated bump yes, but paired with a bedrock2 bump
4 Utility/Map.v, rewrite Memory.v, CSRFile, DefaultMemImpl*, all Context lines, restate valid_machine (PropSet gone) 2-3 days bedrock2 compiler 1-1.5 weeks, processor 1-2 days, end2end 0.5 day coordinated with bedrock2 + processor
5 Examples on the function map + vendored simp, or optional-dependency target 1 day none yes
6 remove coq-coqutil from coq-riscv.opam, DEPFLAGS_COQUTIL from Makefile, CI 0.5 day bedrock2 build scripts last

Totals: riscv-coq ~1.5 weeks; downstream ~2 weeks; ~1.3k lines vendored (map class 60,
memory 60, little-endian 80, Bitwidth 60, prover ~600, tactics ~100, misc ~30).

"Keep a tiny coqutil subset vendored" and "depend only on stdlib + a small
riscv.Utility.Map" are the same plan: the subset above is what riscv-coq uses. The
alternative of splitting coqutil into a stdlib-only core package that riscv-coq depends on
would avoid the copies and the class-identity coordination, but is a coqutil decision.

Recommendation: do steps 1, 2, 5 now on the option-A branch (no downstream effect, removes
coqutil from Proofs/ and Examples/ entirely and from all but the map-typed Platform files);
do step 3 together with the next bedrock2 bump; schedule step 4 only if the goal is a
coqutil-free coq-riscv package, since it costs ~2 weeks of bedrock2 work for no proof
benefit. If step 4 is wanted, use the riscv-owned class (Exp5.v), not bare functions.

GitHub-ready summary

I looked at what it would take to drop coqutil from riscv-coq, on master and on the
fable/littleendian-bits branch (which already removes HList, PrimitivePair and the tuple
LittleEndian, but leans harder on coqutil's Map.Memory).

Inventory (53 of 102 files): maps (map.map/get/put/empty/undef_on/ok,
coqutil's load_Z/store_bytes memory model, sorted-list instances), the bitwise prover
prove_Zeq_bitwise (16 files in Proofs/), Bitwidth, le_split/le_combine, a handful of
tactics (destruct_one_match, ssplit, destr, rdelta, simp), PropSet in the MMIO
valid_machine, and trivia (blia, byte notation, option_map2, sanity).

Findings:

  • Maps: riscv-coq itself only needs get/put/empty and three lemmas. A 20-line riscv-owned
    class works, with instances from any coqutil map (3 lines) or from plain functions (no
    funext). Bare functions are not viable for memory because bedrock2 uses one coqutil map
    object as both its source memory and riscv-coq's Mem, with sep-logic (map.split,
    map.fold) and coqutil's SeparationMemory lemmas about riscv-coq's load_Z; a total
    Register -> word would also change spec_getRegister's uninitialised-register clause.
  • Bitwise: stdlib Zbitwise is a lemma library, not a prover; bits_inj'+btauto fails on
    all 5 representative encode/decode goals, and lia/nia after bitSlice_alt only handle
    concrete-width arithmetic. But prove_Zeq_bitwise and its deps only need stdlib: a
    vendored copy (917 lines, trimmable to ~600) compiles without coqutil and proves the same
    goals at the same speed (0.1-11 s each).
  • lia is already enough everywhere except 15 blia in BitSlice.v. Bitwidth,
    little-endian and the tactics are ~300 stdlib-only lines to copy.

Downstream: steps that do not touch the map type are invisible to bedrock2. The map step
costs bedrock2 an instance plus bridge lemmas and edits at ~50 sites in the compiler,
processor and end2end (~2 weeks), and the Bitwidth move needs a coordinated bump.

Estimate: ~1.5 weeks in riscv-coq, ~2 weeks downstream, ~1.3k lines vendored.
Recommendation: do the coqutil-free Proofs/Examples/tactics/prover steps now on the
littleendian-bits branch; move Bitwidth/le_split with the next bedrock2 bump; only take
on the map interface if a coqutil-free coq-riscv package is the goal, and then with a
riscv-owned map class rather than bare functions.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

@JasonGross

Copy link
Copy Markdown
Author

Yes to both. coqutil's always (Semantics/OmniSmallstepCombinators.v) is an inductive over an
omni-semantics step that packages the establish/preserve/use triple the Kami connection takes, and GarageDoor's top theorem is initial_conditions mach -> always run1 (eventually run1 (io_spec ∘ getLog)) mach over MetricRiscvMachine with the FE310 MMIO ranges. The variant is:

Theorem granite_always : forall P g0 m0,
  related g0 m0 -> always run1 P m0 ->
  always granite_step (fun g => exists m, related g m /\ P m) g0.

where granite_step quantifies over one clock cycle's admissible inputs (no interrupts) and the
granite state carries its abstracted MMIO log (as Kami's KState). It is proved by mk_always
with invariant "related to a riscv-coq state satisfying the riscv-coq invariant".
Composing with GarageDoor needs only:
garagedoor_correct as is; granite_always; a riscv-coq-only lemma that eventually (io_spec ∘ getLog) gives "the current log is a prefix of a good trace" (append-only log); the log component
of related; and one initial-state lemma building the riscv-coq start state from granite's. The
result is granite_initial s0 -> always granite_step (fun g => exists ext, io_spec (ext ++ log g)) (s0, []), transported to the Quartz core by the existing trace equivalence. Every implication
except the initial-state one goes from riscv-coq to granite; no fairness is needed.

What blocks it: the compiled GarageDoor program has 6514 instructions of 27 kinds (plus 8 data
words). Granite covers 12 kinds and 84% of the instructions; the missing 14 kinds (1063
instructions: sltu, mulhu, jal, xori, and, sb, or, lbu, sub, andi, bgeu,
srl, ori, sltiu) are all on the hot path; lbu/sb need a byte-granular memory path and
mulhu an upper product that granite's hardware lacks. The MMIO mismatch (atomic versus
asynchronous) and the memory layout are handled inside the relation. Leakage: garagedoor_correct states nothing about the leakage trace, so the
composition is functional only; if a constant-time statement is added on the riscv-coq side, the
early-out multiplier's zero-operand leakage (521 multiplies on secret limbs) breaks the security
composition until the multiplier is constant-time.

Bridge size after the ISA gap: 2.5-3.5k lines. The ISA growth is the real cost.

Full section (always definition, theorem, composition chain, instruction histogram, MMIO/memory/leakage)

6. Addendum: an always variant, and composing with fiat-crypto's GarageDoor proof

Andres (17:48Z): "could we state a variant of granite_always_related for always properties as
defined in coqutil right now? could this updated theorem compose with the fiat-crypto Garagedoor
proof to make a End2EndLightbulb-like hardware-software connection by only composing implications
from riscv-coq postconditions to granite executions?"

Sources: coqutil 4b19efb3 (/data/jason/fiat-crypto-worktrees/fu-b/coqutil), fiat-crypto a5ee22098
(wp-f1/fiat-crypto, src/Bedrock/End2End/X25519/GarageDoor{,Top}.v), bedrock2 447b97df
(compiler/src/compiler/CompilerInvariant.v, end2end/src/end2end/End2EndLightbulb.v). The
instruction histogram in 6.3 was computed in scratch (fu-e/gd/CountInsns.v, rocq compile from
the rocq-9.2 switch against the clone's prebuilt .vo, nothing written into the clone).

6.1 coqutil's always, and how GarageDoor uses it

coqutil/Semantics/OmniSmallstepCombinators.v is parameterised by an omni-semantics step
step : State -> (State -> Prop) -> Prop (line 3) and defines

Inductive eventually(P: State -> Prop)(initial: State): Prop :=            (* :5-12 *)
  | eventually_done: P initial -> eventually P initial
  | eventually_step: forall midset, step initial midset ->
      (forall mid, midset mid -> eventually P mid) -> eventually P initial.

Inductive always(P: State -> Prop)(initial: State): Prop :=                (* :46-51 *)
  | mk_always (invariant: State -> Prop)
      (Establish: invariant initial)
      (Preserve: forall s, invariant s -> step s invariant)
      (Use: forall s, invariant s -> P s).

with hd_always/tl_always/always_unfold1 (:55-86, needing step_weaken) and a coinductive
always' proven equivalent (:90-100). eventually is runsTo (CompilerInvariant.v:21-23,
runsTo_is_eventually). So always P m0 is the establish/preserve/use triple that
riscv_to_kamiImplProcessor takes (KamiRiscv.v:519-545), packaged as a proposition.

The compiler specialises both to mcomp_sat (run1 iset) on MetricRiscvMachine
(CompilerInvariant.v:231-234) and proves always_eventually_good_trace : initial_conditions initial -> always (eventually good_trace) initial (:236-248) with mk_always and invariant
ll_inv. fiat-crypto's GarageDoor top theorem is that instance:

Theorem garagedoor_correct : forall mach : RiscvMachine, initial_conditions mach ->
  always run1 (eventually run1 (fun mach' => io_spec mach'.(getLog))) mach.   (* GarageDoorTop.v:365-366 *)

where run1 := mcomp_sat (run1 Decode.RV32IM) over MetricRiscvMachine (GarageDoorTop.v:261-262),
the platform is MetricMinimalMMIO with the FE310 MMIOSpec (compiler/MMIO.v:18-19, 32;
riscv/Platform/FE310ExtSpec.v:14-24: OTP/PRCI/GPIO0/UART0/SPI1 ranges, isMMIOAligned n a := n = 4 /\ a mod 4 = 0, MMIOReadOK := True) and DefaultRiscvState (identity translate,
CompilerInvariant.v:25). initial_conditions (GarageDoorTop.v:270-279): pc = 0x20400000,
getLog = [], getTrace = Some [], nextPc = pc+4, all registers initialised, XAddrs covers
the code range 0x20400000..0x21400000, valid_machine, and memory = code (garagedoor_insns) +
heap 0x80000000..0x80002000 + stack ..0x80004000 (ml, :127-134). io_spec (:169-176) is
only_mmio_satisfying (boot_seq +++ protocol_spec): the riscv-coq getLog (a list of
LogItems) is abstracted by mmio_trace_abstraction_relation (bedrock2Examples/SPI.v:57-64:
("st",a,v) ↔ MMIOWRITE [a;v], ("ld",a,v) ↔ MMIOREAD [a] -> [v]) into `mmios : list (string

  • word * word), and that list must be a LAN9250-over-SPI boot sequence followed by protocol_steptransitions.garagedoor_invariant_proof (:349-362) exposes the triple directly, in exactly the shape riscv_to_kamiImplProcessor` consumes.

End2EndLightbulb.v:169-176 is the model to imitate: bytes_at (instrencode lightbulb_insts) 0 mem0 -> Behavior (p4mm mem0) state t -> exists t', KamiLabelSeqR t t' /\ prefix_of t' goodHlTrace,
obtained from end2end (End2EndPipeline.v:274-345), which feeds ll_inv to
riscv_to_kamiImplProcessor and rewrites the two MMIO abstractions into each other
(kami_and_lightbulb_abstract_bedrockTrace_the_same_way, End2EndLightbulb.v:148).

6.2 The always variant and the composition

Granite's spec machine M := semantics.machine defaultMachine pub_init sec_init (Spec.v:758-765)
has a deterministic Machine.step : St -> input -> St * output. To use coqutil's combinators it
becomes an omni step by quantifying over the admissible inputs of one clock cycle, and, as Kami
does with KState := KamiMachine * list LabelT (KamiRiscv.v:144-149), the state is paired with the
MMIO events abstracted so far, since St keeps no history (Spec.v:306-318, MemTrace is
commented out):

Definition GState := St * list (string * bits 32 * bits 32).           (* granite state + abstracted MMIO log *)

Definition admissible (i : IFC.Input * IFC.DriverOut) : Prop :=
  (fst (fst i)).(PubInput_interruptValid) = false.                     (* riscv-coq has no interrupts *)

(* MMIO events of one cycle, read off the handshake: a request leaves when valid && ready
   (Spec.v:560-570), a load's value arrives when the response is accepted (Spec.v:547-558) *)
Definition cycle_mmio (s : St) (i : IFC.Input * IFC.DriverOut) : list (string * bits 32 * bits 32).

Definition granite_step (g : GState) (P : GState -> Prop) : Prop :=
  forall i, admissible i ->
    let '(s', _) := Machine.step M (fst g) i in P (s', cycle_mmio (fst g) i ++ snd g).

(* the state relation of §1.2/§5.2, now also relating the abstracted logs *)
Inductive related : GState -> MetricRiscvMachine -> Prop :=
  | ... (idle / leaked / mmio_wait / done as before) ...
      mmio_trace_abstraction_relation (snd g) m.(getLog) -> ...         (* SPI.v:63-64 *)

(* per-cycle simulation, the same content as instr_sim in §5.2 *)
Lemma cycle_sim : forall g m (inv : MetricRiscvMachine -> Prop) i,
    related g m -> inv m -> mcomp_sat (run1 RV32IM) m (fun _ => inv) -> admissible i ->
    let g' := (fst (Machine.step M (fst g) i), cycle_mmio (fst g) i ++ snd g) in
    exists m', related g' m' /\ inv m'.
(* silent cycle: m' = m; retiring cycle: m' from the postcondition *)

Theorem granite_always : forall (P : MetricRiscvMachine -> Prop) g0 m0,
    related g0 m0 ->
    always (mcomp_sat (run1 RV32IM)) P m0 ->
    always granite_step (fun g => exists m, related g m /\ P m) g0.
Proof. (* destruct the hypothesis as (inv, E, Pres, U); apply mk_always with
          invariant := fun g => exists m, related g m /\ inv m; Preserve is cycle_sim. *)

This is granite_always_related of §5.2 restated on coqutil's always: the riscv-coq invariant is
carried across unchanged, and the granite invariant is "related to a riscv-coq state satisfying
it". Leakage rides inside related (leak_related (granite_leaks g) m.(getTrace), §5.5) and is
not needed for GarageDoor's functional statement.

The composition for GarageDoor, spelled out as implications:

  1. garagedoor_correct (riscv-coq, given): initial_conditions m0 -> always run1 (eventually run1 (fun m' => io_spec m'.(getLog))) m0.
  2. granite_always (bridge, riscv-coq ⇒ granite): with P := eventually run1 (io_spec ∘ getLog).
  3. eventually_log_prefix (riscv-coq only): eventually run1 (fun m' => io_spec (abstract m'.(getLog))) m -> exists ext, io_spec (ext ++ abstract m.(getLog)), because getLog is append-only under
    run1 (Primitives.v:67-73, mcomp_sane; this is ll_inv_implies_prefix_of_good,
    CompilerInvariant.v:228, restated).
  4. related_log (bridge, part of related): related g m -> abstract m.(getLog) = snd g (the
    abstraction relation is functional in both directions, SPI.v:57-62).
  5. granite_initial (bridge, granite ⇒ riscv-coq existence, the only lemma not of the form
    "riscv-coq ⇒ granite"): PubInit_imem holds garagedoor_bytes at 0x20400000, PubInit_pc = 0x20400000, SecInit_dmem agrees with Imem on the code range, isMMIOAddr_g = the FE310
    ranges ⇒ exists m0, initial_conditions m0 /\ related (s0, []) m0 (build m0 with
    riscvRegsInit-style all-zero registers, KamiRiscv.v:276-311, XAddrs = the code range,
    memory from Imem/Dmem, valid_machine from the MMIO ranges being outside both).

Chaining 1-5:

Theorem garagedoor_on_granite_spec : forall s0,
    granite_initial s0 ->
    always granite_step (fun g => exists ext, io_spec (ext ++ snd g)) (s0, []).

and Machine.equivalent (SingleCycleRefines.v:1321, TopLevelSpec.v:731-757) turns a property of
the spec machine's I/O traces into the same property of the Quartz core's I/O traces (equal
inputs give equal outputs, Machine.v:95-96, 319-350), which gives the End2EndLightbulb analogue:

Theorem garagedoor_on_quartz : forall s0 tr,
    granite_initial s0 -> Machine.in_traces (QuartzTop.machine' pub_init sec_init) tr ->
    Forall admissible (map Machine.Input tr) ->
    exists ext, io_spec (ext ++ mmio_of_trace tr).

So yes: apart from the initial-state lemma (5), every implication goes from a riscv-coq
postcondition/invariant to a granite execution, and the riscv-coq proof (garagedoor_correct) is
used as is. always on the granite side is over clock cycles with inputs universally quantified
(subject to admissible), which is stronger than the Kami statement (Kami has no external inputs
other than MMIO responses, KamiRiscvStep.v:554-570).

6.3 What blocks it today

  1. ISA. The compiled GarageDoor program (garagedoor_insns, GarageDoorTop.v:152) has 6522
    entries: 6514 instructions of 27 kinds and 8 InvalidInstruction words, which are the 32-byte
    garageowner public key embedded by memconst_pk (GarageDoor.v:35-36, GarageDoorTop.v:38;
    data, never executed). Counts:

    supported by granite (12 kinds, 5451 instrs, 84%) not supported (14 kinds, 1063 instrs)
    Lw 1659, Add 1223, Sw 997, Addi 741, Mul 346, Lui 164, Srli 125, Slli 100, Beq 44, Jalr 37, Xor 11, Bne 4 Sltu 200, Mulhu 175, Jal 169, Xori 166, And 98, Sb 49, Or 48, Lbu 48, Sub 44, Andi 39, Bgeu 13, Srl 9, Ori 3, Sltiu 2

    (granite's Csrrw and InvalidInstr are unused.) Every missing kind is executed on the hot
    path (Sltu/Mulhu/Sub are the field arithmetic's carries and high products; Jal is every
    call). Lbu/Sb need a byte-granular memory path that granite's word-only mem_req_t
    (Common.v:237-241) and LoadWord/StoreWord (Memory.v:355-358) do not have; Mulhu needs
    the upper product from the multiplier (app/MultiplierSpec.v). Growing granite means touching
    Riscv.v, Spec.v, IsaParams.v, SingleCycle.v, Pipelined.v, the Quartz decoder/ALU
    (quartz/examples/Processor.v:533-1000), StaticAnalysis.v and all refinement proofs; the
    existing 14-instruction development is 23k lines in isaSpec/. This is granite work, not
    bridge work, and it is the gate.

  2. MMIO model. Addresses are not a problem: isMMIOAddr is a parameter (Riscv.v:196-210,
    TopLevelSpec.v:709), set it to the FE310 ranges. GarageDoor only issues word-sized aligned
    MMIO (MMIOWRITE/MMIOREAD, FE310CSemantics.v:33-46), which matches granite's word-only
    requests. The mismatch is temporal: riscv-coq completes a load inside run1 with any value
    (MMIOReadOK := True), granite raises a request, waits an unbounded number of cycles in
    StepWaitMMIOResp (Spec.v:592-610) and takes the value from a secret input. cycle_sim
    handles it with the in-flight constructor and by appending the abstracted event only when the
    response is accepted, so that snd g and getLog stay in step; no fairness assumption is
    needed for the always form (a stalled MMIO just means the granite invariant keeps the same
    riscv-coq state).

  3. Interrupts. GarageDoor uses none; admissible excludes them on the granite side.

  4. Memory. Code at 0x20400000, heap and stack at 0x80000000, no overlap, so the Harvard
    condition of §5.3 reduces to "SecInit_dmem equals PubInit_imem on the code range", and the
    compiler's XAddrs invariant guarantees no store hits the code range. Data accesses: the
    compiler's Lw/Sw are word-aligned by construction; Lbu/Sb are byte accesses and fall
    under item 1. valid_machine (MinimalMMIO.v:139-140) needs the FE310 ranges disjoint from
    the code range and from RAM, which they are.

  5. Leakage. garagedoor_correct says nothing about getTrace beyond the initial Some []
    (GarageDoorTop.v:273); neither GarageDoorTop.v nor MontgomeryLadderRISCV.v states a
    constant-time theorem. So the composition available today is functional: "the Quartz core
    running GarageDoor emits only LAN9250 MMIO traces allowed by io_spec". Granite's
    noninterference theorem would not be invoked. If a riscv-coq-side constant-time statement for
    GarageDoor is added (bedrock2's leakage compiler gives getTrace = Some (f ...) per call,
    Pipeline.v:790), §5.5 applies, and the mul gap becomes concrete: GarageDoor executes 346
    Mul and 175 Mulhu in X25519 field arithmetic on secret limbs, and granite's early-out
    multiplier leaks whether an operand is zero (Riscv.v:282-285). Composed with granite's
    contract, GarageDoor on granite is therefore not constant-time unless the multiplier is made
    constant-time or the software is shown never to multiply a secret zero.

  6. Metrics. GarageDoor's always is over MetricRiscvMachine; related ignores
    getMetrics, as Kami does (KamiRiscvStep.v:551).

Estimate for the bridge once the ISA gap is closed: the §5.4 bridge (1.4-2.3k lines, scaling with
the instruction count: with 26 instruction kinds, closer to 2.5-3.5k) plus GState/granite_step
plumbing and granite_always (~150), granite_initial (~200), the two-line composition file
(~100). The ISA growth itself is the large item and is measured in granite's own units (per
instruction: decoder, ALU/memory path, single-cycle and pipeline proofs, static analysis).

6.4 GitHub-ready reply (for #1)

Yes to both. coqutil's always (Semantics/OmniSmallstepCombinators.v) is an inductive over an
omni-semantics step that packages the establish/preserve/use triple the Kami connection takes, and GarageDoor's top theorem is initial_conditions mach -> always run1 (eventually run1 (io_spec ∘ getLog)) mach over MetricRiscvMachine with the FE310 MMIO ranges. The variant is:

Theorem granite_always : forall P g0 m0,
  related g0 m0 -> always run1 P m0 ->
  always granite_step (fun g => exists m, related g m /\ P m) g0.

where granite_step quantifies over one clock cycle's admissible inputs (no interrupts) and the
granite state carries its abstracted MMIO log (as Kami's KState). It is proved by mk_always
with invariant "related to a riscv-coq state satisfying the riscv-coq invariant".
Composing with GarageDoor needs only:
garagedoor_correct as is; granite_always; a riscv-coq-only lemma that eventually (io_spec ∘ getLog) gives "the current log is a prefix of a good trace" (append-only log); the log component
of related; and one initial-state lemma building the riscv-coq start state from granite's. The
result is granite_initial s0 -> always granite_step (fun g => exists ext, io_spec (ext ++ log g)) (s0, []), transported to the Quartz core by the existing trace equivalence. Every implication
except the initial-state one goes from riscv-coq to granite; no fairness is needed.

What blocks it: the compiled GarageDoor program has 6514 instructions of 27 kinds (plus 8 data
words). Granite covers 12 kinds and 84% of the instructions; the missing 14 kinds (1063
instructions: sltu, mulhu, jal, xori, and, sb, or, lbu, sub, andi, bgeu,
srl, ori, sltiu) are all on the hot path; lbu/sb need a byte-granular memory path and
mulhu an upper product that granite's hardware lacks. The MMIO mismatch (atomic versus
asynchronous) and the memory layout are handled inside the relation. Leakage: garagedoor_correct states nothing about the leakage trace, so the
composition is functional only; if a constant-time statement is added on the riscv-coq side, the
early-out multiplier's zero-operand leakage (521 multiplies on secret limbs) breaks the security
composition until the multiplier is constant-time.

Bridge size after the ISA gap: 2.5-3.5k lines. The ISA growth is the real cost.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

@andres-erbsen

Copy link
Copy Markdown

State the theorems we'd expect to be able to prove about riscv-coq omnisemantics and granite once all the issues above are resolved. sketch out the structure of the proof, but do not do any particularly heavy work such as adding missing instructions or aligning leakage, metrics, etc. Architect the proof so that much work can be shared between the corollaries for transferring "eventually" and "always" statements.

@JasonGross

Copy link
Copy Markdown
Author

Working on it: writing the target theorem statements (riscv-coq omnisemantics vs granite, eventually and always) as a Rocq skeleton with the proof structure sketched, sharing one simulation core between the two corollaries. Back here shortly.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

@JasonGross

Copy link
Copy Markdown
Author

Statements are in #4 (riscvConnection/RiscvCoqConnection.v, everything Admitted by design; it compiles against granite #3 plus coqutil and riscv-coq master through COQPATH).

The generic part is one section over two omnisemantics steps stepA (riscv-coq, run1 under any PrimitivesParams platform on MetricRiscvMachine) and stepB (granite, one clock cycle of Spec.v's semantics.machine over admissible inputs, paired with the abstracted MMIO log), a relation R and a measure. The single core assumption is a forward simulation of granite by riscv-coq up to measured stuttering:

Hypothesis core : forall b a Q,
  R b a -> stepA a Q ->
  stepB b (fun b' => (exists a', R b' a' /\ Q a') \/ (R b' a /\ measure b' < measure b)).

Definition lift P b := exists a, R b a /\ P a.
Lemma transfer_always     : R b a -> always stepA P a     -> always stepB (lift P) b.
Lemma transfer_eventually : R b a -> eventually stepA P a -> eventually stepB (lift P) b.
Lemma transfer_always_eventually :
  R b a -> always stepA (eventually stepA P) a -> always stepB (eventually stepB (lift P)) b.

Forward (granite step matched by a riscv-coq step) is the direction both transfers need: the riscv-coq hypothesis is a weakest precondition over all riscv-coq outcomes, so we have to show granite's outcome is one of them. always uses core with Q := the riscv-coq invariant and never needs the measure; eventually is an outer induction on the riscv-coq eventually and an inner one on the measure for the stuttering cycles. That section is all the shared work.

The instantiation states the relation (registers, pc, both memories through riscv-coq's executable-address set, MMIO log, leakage trace; no CSRs, no metrics), one lemma with content

Lemma cycle_sim : forall g m Q, related g m -> run1_step m Q ->
  granite_step g (fun g' => (exists m', related g' m' /\ Q m') \/ (related g' m /\ measure g' < measure g)).

and the corollaries granite_always, granite_eventually, granite_runsTo, granite_always_eventually and granite_io_spec (the always (eventually io_spec (getLog m)) shape of garagedoor_correct, transported to always (eventually io_spec (log g))) as two-line applications of the generic lemmas.

The open issues are named hypotheses so they can be discharged one at a time: admissible_no_interrupt; isa_coverage (every word riscv-coq executes decodes on the granite side); csr_primitives_stuck (the platform makes getCSRField/setCSRField impossible, as MinimalMMIO does, so no run in a hypothesis executes a CSR instruction or takes a trap; this stands in for MPIE, mtvec, mie); no_misaligned_access; leak_step (a placeholder for the leakage projection); and the progress measure, needed only by eventually. decode_agree is a lemma to prove, not an assumption. Not stated, because it needs fiat-crypto as a dependency: the initial-state lemma from pub_init/sec_init holding the compiled program to a riscv-coq state satisfying initial_conditions.


Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants