Repository navigation
Port from stdpp bitvectors to stdlib bits - #1
JasonGross wants to merge 3 commits into
Conversation
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
|
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
How is this coming along? Can we have a PR on top of the monomorphized cpu support? |
|
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 Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm). |
|
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. |
|
Ported: #3, stacked on #2 (the monomorphized CPU). Both gist files build unchanged on Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm). |
|
Granite's single-cycle processor specification is Differences from riscv-coq:
Options:
Recommendation: do 1 now as a small separate theory depending on both projects, file the Full reportFollow-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), Andres asked (#1): "investigate differences between the Granite single-cycle 1. Granite's processor specificationGranite has three ISA-level artifacts, not one, and "the single-cycle processor specification" is
"Single-cycle" therefore means: fetch, decode, execute and writeback of one instruction all happen ISA subsetRV32 encodings, 14 instructions plus
Missing from RV32I: Machine word, registers, CSRs
Memory and MMIO
Exceptions, interrupts, phases, driver
Leakage and the security theorem
Build and dependenciesdune ( 2. riscv-coq's specification
How bedrock2/processor connects Kami to riscv-coq
3. Difference table
4. Options for connecting them(a) Refinement proof: granite spec ⇒ riscv-coq
|
|
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.
for each one of these, investigate which repo is more more conformant with official informal specifications of risc-v. |
|
Relationship sketch. Relate granite's reference semantics ( Replacing Conformance of the four gaps (RISC-V ISA manual, riscv/riscv-isa-manual 2026-09-16):
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 Andres asked: "Please sketch what a relationship between riscv-coq and isaSpec/Spec.v would look 1. Sketch of a relationship between
|
| 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_agreeis used once pergstep_soundcase: granite'sStepLeakmicro-step calls
params.decode(Spec.v:578) and riscv-coq'srun1callsdecode iset (combine 4 inst)
(Run.v:28); withmem_relatedgivingcombine 4 (loadWord pc) = Zmod.unsigned (LoadWord pc Imem)
(granite'sLoadWordislittle_endian_to_bits,Memory.v:355-356; coqutil'scombineis
little-endian too).- The per-instruction cases are the 14 arms of
execStrt/execCtrl/execMem
(Spec.v:378-450, 342-376) againstExecuteI.execute/ExecuteM.execute/ExecuteCSR.execute
aftermcomp_satunfolding throughinterpret_action. Each is acbn/case_decide/Zmod
arithmetic obligation, not a Kamikinvert. - Exceptions: granite
handleExn'(Spec.v:456-462) versusraiseExceptionWithInfo
(Machine.v:112-123). Relatable for illegal instruction (code 2,mtval := encodingon 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 themtveclow-bits-zero andmie
restrictions of §3. Misalignedlw/sware not relatable under the defaulttranslate
(§3.1): exclude them by side condition, or instantiateRiscvMachine.translatein the bridge
platform with an alignment check (notetranslate_with_alignment_checkatMachine.v:130-134
raises code 4 for stores too, so it would need a store variant raising 6). - MMIO: granite's
StepWaitMMIORespphase spans cycles; the bridge relates the sequence
(request emitted, silent cycles, response consumed and written back,Spec.v:592-610) to one
run1whosenonmem_load(MinimalMMIO.v:66-73) picks the same value. That is the
related_mmio_waitconstructor. - Leakage: granite emits one
executeInstr raw instr leakper instruction (Spec.v:579,
Riscv.v:318-320); riscv-coq emitsfetchInstr pcthenexecuteInstr (decoded) leak
(Run.v:26-30).project_leakmapsRiscv.v:217-246constructors toLeakageOfInstr.v:112-152
ones, dropping theMul_leakage (zero_arg)bit (riscv-coqMul_leakagehas none,
LeakageOfInstr.v:55, 68) and mappingCsrrw_leakage*toNone(riscv-coq returnsNonefor
CSR instructions,LeakageOfInstr.v:223, which then makes the whole traceNone,
RiscvMachine.v:184-186). So the trace equation only holds up to the firstcsrrw; state it as
"getTrace = Some (...)while nocsrrwhas executed,Noneafterwards", or excludecsrrw.
1.4 Restrictions the theorem would carry
- no interrupts (
InterruptSt = None, i.e.PubInput_interruptValid = falsethroughout); - program never accesses CSR 0x304 (
mie), andmtvecis 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
Cdisjoint 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
- A
RiscvPrograminstance for granite's state. riscv-coq'sExecuteis written against
RiscvProgram M t(Machine.v:35-68). granite would provideM := free riscv_primitive primitive_resultinterpreted oversemantics.St, or a state monad overSt. The interpreter
must give meaning togetCSRField/setCSRFieldforMTVecBase/MTVecMode/MEPC/MCauseCode/ MCauseInterrupt/MTVal/MPP/MPIE/MIE(granite has five whole-word CSRs,RegisterFile.v:35-41),
toendCycleEarly(granite'sprog/evalProghas no early exit,core/Program.v:44-60), and
fail on reservations, privilege, fence, byte/half accesses. - The MMIO wait phase cannot be expressed inside
run1. riscv-coq'sloadWordreturns 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 runningrun1only 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 sorun1can be split at a
primitive (a coroutine interpretation of the free monad). This alone breaks
SingleCycleRefines.vandPipelineRefines.v, which case-split on the phases. - Interrupts. riscv-coq has none (
Machine.v:114). granite'sStepInterruptphase could stay
as a wrapper aroundrun1, 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. - Leakage. granite's security theorem needs the multiplier's zero-operand bit and the values
written tomtvec/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'sleakage_of_instrleaks nothing formulandNonefor CSR instructions
(LeakageOfInstr.v:68, 223), andNoneerases 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'sLeakageOfInstris parameterised or extended. - Semantic deltas granite would inherit (all listed in §3): misaligned data accesses no longer
trap;mtvecshifted;miebecomes a per-source register with no effect on granite's
interrupt input; trap entry writesMPIE := 0rather than clearing the global enable.
StaticAnalysis.v(1701 lines) mirrorsexecStrt/execCtrl/execMemcase by case and would
be rewritten against riscv-coq'sExecute. - Restating the proofs.
SingleCycleRefines.v(1336) becomes a proof that the
IsaParams-driven single-cycle program refinesrun1-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) referenceSpec.vonly
throughinstrs/leakagetypes andSingleCycle, 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 ifSem_machinekeeps its type. - Build. granite's
dune-projectwould addcoq-coqutilandcoq-riscv(both are opam
packages with Makefile builds;riscv-coq/coq-riscv.opamrequirescoq >= 8.18and
coq-coqutil >= 0.0.7; coqutil at bedrock2 447b97df requiresrocq-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'smap.*functions are fine; the twoNumber Notations onZmod_scope, granitecore/Bits.v:29-33and coqutilWord/Bitwidth.v:10-33,
collide and the last import wins). Granite would also inherit riscv-coq'sGeneralizable 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/swnever trap; misaligned ones raise a contained trap with
code 4 (load) or 6 (store) andmtval := 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/Swcalltranslate Load/Store 4 addr(ExecuteI.v:126-131, 158-164) and
the defaulttranslateisReturn(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 addressesMinimalMMIOrequires
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 unusedtranslate_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_excandnorm: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
mtvecregister 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
mtvecregister 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 setpcto BASE. 1 Vectored: Asynchronous interrupts setpcto
BASE+4×cause. ≥2 Reserved.
When MODE=Direct, all traps into machine mode cause thepcto be set to the address in the
BASE field. When MODE=Vectored, all synchronous exceptions into machine mode cause thepcto
be set to the address in the BASE field, whereas interrupts cause thepcto 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:
mtvecis an arbitrary 32-bit register (RegisterFile.v:29-30, 68-69); on an
exception or interruptpc := mtvecverbatim (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 toBASE+1/BASE+2/BASE+3and then fetches from a misaligned pc
without any check (Spec.v:577): wrong. Becausemtvecis WARL, the cheapest conformant fix
is to make bits 1:0 read-only zero inwriteCsr(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 writesmcause := srcon an interrupt without setting
the Interrupt bit (Spec.v:535, the comment acknowledges it), againstnorm:mcause_intr_op
(machine.adoc:1732). - riscv-coq:
mtvecis stored asMTVecBaseandMTVecModefields; a CSR read returns
base << 2 | modeand 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 := BASEis the specified behaviour in both Direct and Vectored mode.
Conformant. (MTVecMode ≥ 2is 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.
[...]mieis the corresponding MXLEN-bit read/write register containing interrupt enable bits.
Interrupt cause number i (as reported in CSRmcause) corresponds with bit i in bothmipand
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 themstatusregister is set, or the current privilege
mode has less privilege than M-mode; (b) bit i is set in bothmipandmie; and (c) if register
midelegexists, bit i is not set inmideleg.
(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 nomip. So granite usesmieas the global enable
and has no per-source enables. Wrong with respect to the register map: software that does
csrrw x0, 0x304, t0witht0 = 0x800(enable machine external interrupts) on a conformant
core additionally needsmstatus.MIE = 1to receive anything, and software that sets
mstatus.MIEon 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
mstatuswith MIE/MPIE (MPP hard-wired to 3), keepmieper-source, and take the interrupt iff
mstatus.MIE && mie[src] && mip[src]. - riscv-coq:
mstatus.MIE/MPIE/MPPare CSR fields (CSRField.v:48,CSRGetSet.v:85, 306-324),mie(0x304) is decomposed into per-source fields (CSRGetSet.v:261-264, 419),
andmretrestoresMIE := 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
(nomip, 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 asmstatus.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 nomret, so a handler cannot restore the previous enable
atomically; it mustcsrrwthe enable back andjalrthroughmepc(two instructions with an
interrupt window in between, the situation the note atmachine.adoc:422-430warns about). The
consistent reading is again "granite'smieis reallymstatus.MIE, with MPIE omitted". - riscv-coq:
raiseExceptionWithInfosetsMTVal,MPP := Machine,MPIE := 0,MEPC,
MCauseCode, and jumps (Machine.v:112-123); it does not copyMIEintoMPIEand does
not clearMIE. The source comment says the two writes exist "just so that Mret will succeed
at restoring them". So after trap +mret,MIEis 0 instead of the pre-trap value, and inside
the handlerMIEstill 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 addingmstatus.
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 withmip. 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 := 0and never touchesmie. Granite clears
mieand saves nothing: wrong. riscv-coq setsMPIE := 0and leavesMIE: also wrong, but a
two-line fix.
Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm).
|
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? |
|
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? |
|
Yes, and it is the direction bedrock2 already consumes: Why it is easier: with plain Size: about 1.4-2.3k lines, versus 4.8k for the Kami connection, which also bridged two word Leakage: for the security theorem to compose, granite's leakage must be a function of riscv-coq's Full addendum (theorem signatures, why easier/harder, Kami comparison, leakage)5. Addendum: the other direction (riscv-coq
|
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 leakspcand the decoded instruction.
raw = Imem[pc]andImemis public (PubInit_imem,IFC.v:67-70), sorawis a function of
the riscv-coq trace and the public program (riscv-coq'sDecode.decodeis 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).Gis the identity here.Mul_leakage (zero_arg : bool)(Riscv.v:282-285): riscv-coq'sMul_leakagecarries nothing
(LeakageOfInstr.v:55, 68).zero_argis 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 whosemuloperands 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_leakageand let the compiler's constant-time proof carry it (bedrock2 would then have to
provemuloperands 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,csrrwis
excluded by theMinimalMMIOhypothesis; if a CSR platform were used instead, riscv-coq'sNone
for CSR instructions (LeakageOfInstr.v:223) makesgetTrace = None, i.e. no guarantee, and
Gwould be undefined there (consistent: granite's leakage ofvis then "more than nothing").InvalidInstr_leakage: excluded (no traps).- riscv-coq's
fetchInstr pchas no granite counterpart, butpcis recoverable from the
granite trace (initial pc public, branch bits andjalrtargets leaked), so the two traces are
inter-definable except for themulbit.
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).
|
what about riscv-coq without coqutil? and could we state a variant of granite_always_related for |
|
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 Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm). |
|
riscv-coq without coqutil: I looked at what it would take to drop coqutil from riscv-coq, on master and on the Inventory (53 of 102 files): maps ( Findings:
Downstream: steps that do not touch the map type are invisible to bedrock2. The map step Estimate: ~1.5 weeks in riscv-coq, ~2 weeks downstream, ~1.3k lines vendored. Full report (inventory, experiments, downstream impact, plan)Follow-up H: removing the coqutil dependency from riscv-coqLane fu-h, 2026-09-17. Requested by Andres Erbsen (#1, 2026-09-17 17:37Z): Sources (read-only):
1. InventoryMaster: 54 of 102 Option A vs master: option A already removes Require lines by coqutil module (option A), with the names riscv-coq actually uses:
Build wiring: 2. Replacement per category, with what stdlib offers and what I measured2.1 Maps (the only structurally hard one)What riscv-coq itself needs from a map: Experiment Two caveats on going to raw functions rather than a riscv-owned class:
Cost inside riscv-coq: 2.2 Bitwise reasoningStdlib status on rocq-stdlib 9.1: Measured on 5 representative goals (
Conclusion: stdlib is not strong enough to replace 2.3 Lia, sanity, Byte, Option, Decidable, Word.Properties, TacticsAll mechanical:
2.4 Bitwidth and Zmod literalsCopy coqutil 2.5 Little-endian bytesStdlib has nothing for 2.6 Sets and Examples
Examples ( 3. What breaks downstreambedrock2 Under a bare function design bedrock2 would have to carry a relation between its coqutil Under the riscv-owned class design bedrock2 needs: (i) the one-line instance from 4. Effort and plan
Totals: riscv-coq ~1.5 weeks; downstream ~2 weeks; ~1.3k lines vendored (map class 60, "Keep a tiny coqutil subset vendored" and "depend only on stdlib + a small Recommendation: do steps 1, 2, 5 now on the option-A branch (no downstream effect, removes GitHub-ready summaryI looked at what it would take to drop coqutil from riscv-coq, on master and on the Inventory (53 of 102 files): maps ( Findings:
Downstream: steps that do not touch the map type are invisible to bedrock2. The map step Estimate: ~1.5 weeks in riscv-coq, ~2 weeks downstream, ~1.3k lines vendored. Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm). |
|
Yes to both. coqutil's 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 What blocks it: the compiled GarageDoor program has 6514 instructions of 27 kinds (plus 8 data 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
|
| 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.
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).
Interrupts. GarageDoor uses none; admissible excludes them on the granite side.
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.
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.
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).
|
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. |
|
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). |
|
Statements are in #4 ( The generic part is one section over two omnisemantics steps 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. 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 The open issues are named hypotheses so they can be discharged one at a time: Written by Claude Fable 5.1 via Claude Code (session https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm). |
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.noninterferencedepends 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 compareZmod.unsigned _ =? Zmod.unsigned _), plus auto-generated hypothesis names. Details in the commit message;core/Bits.vreplaces 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 Unificationmakes 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 intendednotation-overriddenpair for the 0/1 literals.Written by Claude Fable 5.1.
🤖 Generated with Claude Code
https://claude.ai/code/session_01YJbiRBkJtM7x6PvYV6hmEm