interplane.Get Omega
Read in your language

omega-gpu-driver

aien-dev/omega-gpu-driver

Brought by drakestapleton

GitHub aien-dev/omega-gpu-driver#3 (code only)

closed derived 9da57537159f26ed #3

Imported from GitHub aien-dev/omega-gpu-driver#3 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base f26c9385e5adcc5e09544486d700b1ffdb8cf769 · Head 31df36d13b0d490412d369ea8d531b6a145b2688

drakestapleton reviewed (COMMENTED) on 2026-10-30 13:12 UTC

Triage at d83122b: blocked.

  • Draft and stacking. This is a draft. The body says it is stacked on #1 (review/w0-reset-on-release), which is now merged, and the base is already main, mergeable clean. Please update the body.
  • Compiler pin. omc is pinned to draft omega-mv#890, which is stacked on omega-mv#878. Both have to land first.
  • CI. No check runs on this head, so all gate results are author-reported host runs.
  • Hardware. Window steps W1–W7 are NOT_RUN on GB10, and nothing ran on the Spark for this review.

— Grokbot

Fetch it

A git bundle of the pull request's head, 140679 bytes.

curl -fsSL https://interplane.io/drakestapleton/omega-gpu-driver/patches/9da57537159f26ed.bundle -o 9da57537159f26ed.bundle
git fetch 9da57537159f26ed.bundle refs/pull/3/head

Raw bundle · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/omega-gpu-driver
3
31df36d13b0d490412d369ea8d531b6a145b2688
{"kind":"github-import","owner":"aien-dev","repo":"omega-gpu-driver","number":3,"url":"https://github.com/aien-dev/omega-gpu-driver/pull/3","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:39:49Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/.crumb b/.crumb
index dd44b4f..6805525 100644
--- a/.crumb
+++ b/.crumb
@@ -3,14 +3,14 @@
     "generated": {
       "children": [],
       "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
-      "compiled_at": "2026-10-28T21:31:30Z",
+      "compiled_at": "2026-11-05T22:59:48Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:3744d81e46b7555795e7e293dcb4ad6a879aaee58a7b67b2d703f0bd1b7fc658",
+      "digest": "sha256:ecc0821a81d578d3a8db91d4523238a024836548718094a4c12865976f945ce1",
       "evidence_files": 0,
       "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
-      "files": 14,
-      "generated_at_commit": "bf98036d4d46d45b4ecb7d6157333bbc7ab74793",
-      "source_tree": "sha256:5afbb60c360650fc27ad12f5fe59b4c68499b9785c4e488a1ca7f8e2d6ab8620"
+      "files": 67,
+      "generated_at_commit": "0f0a2a576556c1bf8cd63c090040141fbd372a39",
+      "source_tree": "sha256:eb2c0635d43b9570b04a70a14e1c0433505a5da030d9fb8665794661388ee5eb"
     }
   },
   "layer": "driver",
diff --git a/DESIGN.md b/DESIGN.md
new file mode 100644
index 0000000..8fc8003
--- /dev/null
+++ b/DESIGN.md
@@ -0,0 +1,118 @@
+# omega-gpu-driver design notes
+
+Status: **PROPOSED.** None of this is implemented yet. Nothing here has run on the GB10.
+
+The bring-up design (GSP boot chain, RPC surface, the `ogd` launcher and manifest, the D2 window) is in the
+lane's design document and is summarised in `README.md` and `window/README.md`. This file holds the design
+decisions for the driver's isolation model and its userspace interface.
+
+Source: an accel-driver survey of 2026-10-27 (lessons 1-3). It read the two Linux accel NPU drivers at
+torvalds/linux `d135ab453a740`. All `drivers/accel/...` and `include/uapi/...` cites below are file:line in
+that tree. `NV:` cites are NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/sdk/nvidia/inc/class/`.
+
+## 1. Isolation: one private GPU address space per client, no pushbuffer parser
+
+**The two Linux models.** The two drivers protect the device in different ways:
+
+- **ethosu has no MMU**, so the kernel checks every command stream.
+  - It copies the stream into a buffer object marked no-mmap (`ethosu_drv.c:130`, enforced at
+    `ethosu_gem.c:26-27`), so userspace cannot change it after the check.
+  - It replays the stream in an interpreter (`ethosu_gem_cmdstream_copy_and_validate`, `ethosu_gem.c:385-707`).
+  - Submit refuses a region that does not fit its buffer (`ethosu_job.c:398-496`).
+- **rocket has an MMU** and never parses commands.
+  - `rocket_open` gives each open file its own IOMMU paging domain (`rocket_drv.c:72,89`; created at 38-56).
+  - Buffers are mapped into that domain (`rocket_gem.c:96`).
+  - The domain is attached to the core for each job and detached afterwards (`rocket_job.c:348`, 382, 406).
+
+**What we adopt.** The GB10 translates GPU virtual addresses through its GMMU, so OwnDriver follows rocket:
+
+- Every client gets its own GPU VA space (FERMI_VASPACE_A). That client's page tables come from local GMMU
+  code (`chan/gmmu.om`) and are installed with SET_PAGE_DIRECTORY.
+- A client's buffers are mapped only into its own VA space.
+- The driver does **not** parse or check pushbuffers or GPFIFO contents. Its job is address-space setup,
+  buffer bounds, fences and teardown.
+
+**Paths the GMMU may not translate.** On these paths ethosu-style copy-then-check still applies. The paths
+come from the docs and none has been checked on the chip (UNVERIFIED):
+
+1. **Copy-engine physical mode.** Ampere's copy class has `LAUNCH_DMA_SRC_TYPE_PHYSICAL` and
+   `DST_TYPE_PHYSICAL` (`NV:clc7b5.h:121-126`). The published Blackwell copy headers (`NV:clc9b5.h`,
+   `NV:clcab5.h`) list too few methods to say whether the mode still exists.
+2. **Structures the GPU reads by bus address.**
+   - These are the instance block, RAMFC, USERD and the GPFIFO ring, whose IOVAs travel in the channel alloc
+     RPC (lane design §3).
+   - ogd allocates and writes them itself; a client never supplies their contents. That is the copy-then-check
+     rule applied at allocation.
+3. **The SMMU.** It translates every device access (`iommu.passthrough=0`; the GPU is alone in IOMMU group 20).
+   But one VFIO container gives the whole device a single IOMMU domain. A physical-mode access is therefore
+   bounded by the union of all clients' DMA mappings, not by one client's mappings [INFERENCE]. Until (1) is
+   settled, either refuse physical-mode copy methods, or run only one client at a time.
+
+**Scope in v1.** In v1 the workload inherits the VFIO device fd (lane design §4), so it has BAR0 read/write
+access. v1 therefore has one trusted workload per `ogd` session and claims no isolation between clients. The
+per-client VA space model starts to protect something only once `ogd` serves more than one client and the
+workload no longer holds the VFIO fd. That is v2: a request pipe, plus a mapping of only the doorbell and
+USERD pages.
+
+## 2. Submit ABI
+
+The rules come from ethosu's job path and rocket's uapi. Each one is required from the first version of the ABI:
+
+- **Per-buffer read/write flags; the write fence goes only on outputs.**
+  - ethosu takes an implicit dependency for every buffer, marked as a write only for output regions
+    (`ethosu_job.c:91-99`).
+  - It attaches the done fence with `DMA_RESV_USAGE_WRITE` only to outputs (`ethosu_job.c:102-114`).
+  - It locks all buffers as one group (`drm_gem_lock_reservations`, `ethosu_job.c:122-142`).
+  - Each submit buffer entry in our ABI carries `READ`, `WRITE` or both. A read-only input never waits on
+    another reader.
+- **A watchdog that checks progress before resetting.**
+  - ethosu runs one job in flight (`credit_limit = 1`, `ethosu_job.c:327`).
+  - Its timeout handler reads the queue read pointer (`NPU_REG_QREAD`, `ethosu_job.c:280`). If the pointer
+    still moves, it lets the job run on (`ethosu_job.c:287-292`) and resets only after that (`ethosu_job.c:305`).
+  - Our counterpart is GPGet in USERD and the semaphore sequence. The watchdog reads one of them before it
+    tears a channel down. A timeout with that counter still advancing is not a hang.
+- **Reserved, pad and flags fields must be zero.** Refuse the call otherwise: ethosu `ethosu_drv.c:125`;
+  rocket `rocket_gem.c:143`, `rocket_gem.c:174` and `rocket_job.c:643`. An unknown flag bit is refused, never
+  ignored.
+- **Self-sized structs.**
+  - rocket's submit carries `job_struct_size` and `task_struct_size` (`rocket_accel.h:142-145`, 177-180).
+  - The kernel refuses sizes smaller than the struct it knows (`rocket_job.c:77`, 638-639) and steps through
+    the arrays by the size the caller declared (`rocket_job.c:95`, 656).
+  - Our records start with a byte size and a version. The ABI can then grow at the tail without breaking old
+    callers.
+
+## 3. Ordering and cache sync: fences, not cache-maintenance calls
+
+rocket brackets CPU access with explicit calls:
+
+- `PREP_BO` waits for the write fence with a timeout, then calls `dma_sync_sgtable_for_cpu`
+  (`rocket_gem.c:152-161`).
+- `FINI_BO` calls `dma_sync_sgtable_for_device` (`rocket_gem.c:186`).
+
+rocket needs these because the RK3588 NPU's DMA is not cache-coherent. That is the reason given in review; it
+was not checked against RK3588 documentation here. ethosu syncs implicitly when a buffer is waited on or mapped.
+
+The GB10 is a self-hosted part with a coherent C2C link. NVIDIA's RM treats it as such:
+
+- Local EGM is set up only when `gpuIsSelfHosted(pGpu)` and `PDB_PROP_KBIF_IS_C2C_LINK_UP` hold
+  (`NV2:mem_mgr.c:4022-4023`, with the comment "EGM can be enabled only in C2C path").
+- When `kbusIsBar1Disabled` (`NV2:mem_mgr_gm107.c:619`), BAR1 is reported as size 0, with the comment "When
+  coherent C2C path is enabled, BAR1 is disabled" (`NV2:mem_mgr_gm107.c:688-694`).
+
+`NV2:` is `src/nvidia/src/kernel/gpu/mem_mgr/` (with `arch/maxwell/` for the gm107 file) in the same
+580.173.02 tree. Neither function has been run on our chip. The lines say how RM treats a self-hosted C2C
+GPU, not that every GB10 access path is coherent.
+
+What this design takes from that:
+
+1. **The ordering model on GB10 is fences plus memory ordering.** There are no CPU/GPU cache-maintenance
+   ioctls.
+   - The CPU reads an output only after that job's write fence (§2) has signalled.
+   - The submit path keeps its barriers: ring write, `dsb sy`, GPPut, `dsb sy`, doorbell.
+   - Completion is a semaphore release that the CPU reads after the fence.
+   - `prep`/`fini` remain only as an ABI slot for non-coherent targets. On GB10 they check their arguments
+     (§2 rules) and do nothing else.
+2. **No BAR1 VRAM mapping.** BAR1 is off on this chip: RM reports it as size 0 (above), and sysfs shows BAR0
+   only (lane design §1).
+   - All buffers are sysmem: pinned pages, VFIO MAP_DMA, and GMMU PTEs with the snooped sysmem aperture.
+   - The CPU's view of a buffer is the CPU's own mapping of those pages.
diff --git a/README.md b/README.md
index 43af3f7..50ad413 100644
--- a/README.md
+++ b/README.md
@@ -1,12 +1,17 @@
 # omega-gpu-driver
 
-The GB10 GPU driver written in seeded Omega. Status: **W0 IMPLEMENTED and EXERCISED in QEMU only.
-Not run on GB10 hardware; nothing here is QUALIFIED.**
+The GB10 GPU driver written in seeded Omega. Status: **W0 IMPLEMENTED and EXERCISED in QEMU. The driver
+units below are IMPLEMENTED and EXERCISED on the host against C referees and simulators only. Nothing has
+run on GB10 hardware; nothing here is QUALIFIED. GSP boot (`gb10_gsp_boot.c`) is not ported.**
 
 Parent: [aien-dev/omega-mv](https://github.com/aien-dev/omega-mv), the seeded Omega compiler. This repo
 pins one omega-mv commit and the sha256 of the `omc` it births (`tools/omc.pin`). The pin is currently
-the draft branch `feat/vfio-device-calls` (commit `7ae2aef9b`), which adds the `vfioctl` and `vfiomap`
-words this driver needs; it moves to omega-mv main after that PR is reviewed and merged.
+the draft branch `feat/vfio-dma-bar` (omega-mv#890, commit `397e6704`, on #878 `feat/vfio-device-calls`).
+It adds the `vfioctl` and `vfiomap` words plus IOMMU_MAP_DMA/UNMAP_DMA and the writable `vfiomapw` this
+driver needs. The pin moves to omega-mv main after those PRs are reviewed and merged.
+
+`DESIGN.md` (PROPOSED, no code yet) records the isolation model, the submit ABI and the ordering model:
+one GPU VA space per client with no pushbuffer parser, per-buffer read/write fences, and no BAR1.
 
 ## W0: bind, read identity, release
 
@@ -48,7 +53,9 @@ traps. See omega-mv `seed/host/MAPPING.md`.
 
 ## Build and test
 
-    sh build.sh          # births the pinned omc from seed-0, checks its sha256, writes build/w0
+    sh build.sh          # births the pinned omc from seed-0, checks its sha256, writes build/w0, build/fwprep
+    OGKM=<open-gpu-kernel-modules 580.173.02 checkout> sh build.sh
+                         # also runs build/fwprep on the installed gsp_ga10x.bin into build/fw (fw.manifest)
     KERNEL=img/boot/vmlinuz-7.0.0-1019-nvidia sh qemu/test.sh
                          # QEMU virt + SMMUv3, edu device on vfio-pci, 9 commands, all results checked
     KERNEL=... DEVICES='-device pcie-root-port,id=rp1,chassis=1,slot=1 -device edu,bus=rp1' \
@@ -66,16 +73,37 @@ Every QEMU boot and test command runs under `nice -n 19 taskset -c "${AIEN_TEST_
 cores 10-14, which the shared Spark reserves for its live service; set it to use other cores,
 e.g. `AIEN_TEST_CPUS=0-3 KERNEL=... sh qemu/test.sh`.
 
-Host tools in the build and test path (disclosed; not part of the driver): `sh`, `git`, `sha256sum`,
-QEMU 8.2.2, busybox, zstd, cpio, gzip. The driver itself is `w0.om` only.
+## Driver units (host-exercised ports of aienux PR #441 C)
+
+Each unit is a `.om` port of one aienux reference file; each gate compares the `.om` output with the C
+reference byte for byte, and each mutant script changes one line at a time and requires the gate to fail.
+
+| Unit | Ported from | Gate | Mutants |
+|---|---|---|---|
+| `gsp/mmio.om`, `gsp/sim.om` (register-level GSP start-up via SEC2, runtime-PM gate, SEC2+GSP falcon simulator) | `gpu/gsp_mmio.c`, `gpu/gsp_sim.c` | `tests/mmio_diff.sh`, `tests/pm_gate.sh` | `tests/mutants-mmio.sh` |
+| `gsp/sysinfo.om` (GSP_SET_SYSTEM_INFO payload) | `tools/ck_gsp_sysinfo_encode.c` | `tests/sysinfo_diff.sh` | `tests/mutants-sysinfo.sh` |
+| `gsp/seq.om` (GSP_RUN_CPU_SEQUENCER, CPU side) | `gpu/gsp_seq.c` | `tests/seq_diff.sh` | `tests/mutants-seq.sh` |
+| `gsp/sha2.om`, `gsp/inflate.om`, `gsp/fw.om`, `gsp/bindata.om`, `fwprep.om` (firmware inputs) | `ck_gsp_fw_inspect.c`, `ck_gsp_bindata_extract.c`, `argus/sha256.c` | `tests/fw_diff.sh` | `tests/mutants-fw.sh` |
+| `chan/gmmu.om`, `chan/mem.om`, `chan/chan.om`, `chan/sim.om` (page tables, buffers, channels; simulator mode only) | `gpu/gmmu.c`, `gpu_mem.c`, `gpu_chan.c`, `gpu_sim.c` | `tests/chan_diff.sh` | `tests/mutants-chan.sh` |
+| `chan/params.om` (RM alloc/control records for GSP-RM, NVIDIA 580.173.02 layouts) | NVIDIA headers | `tests/params_diff.sh` | `tests/mutants-chan.sh` |
+
+`fwprep FWFILE OGKMSRC OUTDIR` reads the signed `gsp_ga10x.bin` (unchanged) and the NVIDIA open-source
+bindata tables, and writes `fmc.img`, `fmc.hash`, `fmc.pubkey`, `fmc.sig`, `bl.img` and, last,
+`fw.manifest`. Channel ops other than the simulator (mode 0) trap; on the GB10 they go through GSP RPC.
 
-## On the GB10 (operator-run, authorized window only)
+Test-only referees and harnesses (disclosed; never linked into the driver): `tests/seq_ref.c` and
+`tests/params_ref.c` (C), the aienux C tools built fresh by the diff scripts, and the shell scripts in
+`tests/`. Host tools in the build and test path: `sh`, `git`, `sha256sum`, `cc`, QEMU 8.2.2, busybox,
+zstd, cpio, gzip.
 
-Main binds the GPU to `vfio-pci` (000f:01:00.0, IOMMU group 20, alone in its group) and runs:
+## On the GB10 (authorized exclusive window only)
 
-    build/w0 000f:01:00.0 20
+`window/README.md` is the procedure: W0 read-only checks, W1 reboot with nvidia.ko held back, W2 bind to
+`vfio-pci`, W3 `build/w0 000f:01:00.0 20`, W7 release, then R restores nvidia.ko and the resident 35B.
+`tests/window_sim.sh` runs those scripts unchanged against a simulated machine, and
+`tests/mutants-window.sh` checks that it catches each removed safety step. None of it has run on the GB10.
 
-Expected: config vendor/device 0x2e1210de (lspci reports [10de:2e12]) and matching map and pread
+Expected from W3: config vendor/device 0x2e1210de (lspci reports [10de:2e12]) and matching map and pread
 values. The BOOT_0 architecture field (bits 28:24) is defined at nv_ref.h:129-136 (GB100 0x1A, GB200
 0x1B); which value the GB10 reports is what this run measures, not something this repo asserts.
 
diff --git a/build.sh b/build.sh
index d332ae6..ced002e 100644
--- a/build.sh
+++ b/build.sh
@@ -1,12 +1,33 @@
 #!/bin/sh
-# build.sh -- birth the pinned omc (tools/getomc.sh) and compile w0.om into build/w0.
-# A failed compile leaves no build/w0 behind.
+# build.sh -- birth the pinned omc (tools/getomc.sh) and compile w0.om into build/w0 and the firmware
+# input tool (gsp/sha2.om gsp/inflate.om gsp/fw.om gsp/bindata.om fwprep.om) into build/fwprep.
+# With OGKM=<open-gpu-kernel-modules-580.173.02 checkout>, it then runs build/fwprep on the installed
+# GSP firmware into build/fw (checked by window/d2-pre.sh against build/fw/fw.manifest).
+# A failed step leaves no output behind.
 set -eu
 R=$(CDPATH= cd -- "$(dirname "$0")" && pwd)
 cd "$R"
 sh tools/getomc.sh
-rm -f build/w0 build/w0.tmp
-if ! build/omc < w0.om > build/w0.tmp; then rm -f build/w0.tmp; exit 1; fi
-chmod +x build/w0.tmp
-mv build/w0.tmp build/w0
-echo build/w0
+# compile OUT SRC... : concatenate the units and compile them into build/OUT
+compile() {
+	out=build/$1; shift
+	rm -f "$out" "$out.tmp"
+	if ! cat "$@" | build/omc > "$out.tmp"; then rm -f "$out.tmp"; exit 1; fi
+	chmod +x "$out.tmp"
+	mv "$out.tmp" "$out"
+	echo "$out"
+}
+compile w0 w0.om
+compile fwprep gsp/sha2.om gsp/inflate.om gsp/fw.om gsp/bindata.om fwprep.om
+FW=${FW:-/lib/firmware/nvidia/580.173.02/gsp_ga10x.bin}
+if [ -n "${OGKM:-}" ]; then
+	rm -rf build/fw build/fw.tmp
+	mkdir build/fw.tmp
+	if ! build/fwprep "$FW" "$OGKM" build/fw.tmp > build/fwprep.log; then
+		rm -rf build/fw.tmp; cat build/fwprep.log >&2; exit 1
+	fi
+	mv build/fw.tmp build/fw
+	echo build/fw
+else
+	echo "build/fw not built: set OGKM to an open-gpu-kernel-modules 580.173.02 checkout" >&2
+fi
diff --git a/chan/chan.om b/chan/chan.om
new file mode 100644
index 0000000..01fc04a
--- /dev/null
+++ b/chan/chan.om
@@ -0,0 +1,292 @@
+note chan/chan.om: GPFIFO compute channel (ring, USERD, instance block, doorbell), ported from aienux
+note PR #441 native/kernel/gpu/gpu_chan.c and gpu_chan.h (branch pr441 @ c5bb3a4b). Library unit: no main.
+note Prefix ch / CH. Needs chan/gmmu.om and chan/mem.om before it, and chan/sim.om (mode 0 ops).
+note
+note A channel is a slot 0..3 (CHSLOTS); its buffers are chan/mem.om slots. The CPU writes the ring,
+note USERD GPPut and the instance block through mmwin; the doorbell goes through mmregwr.
+note
+note Channel ops (C: a function-pointer table): chbindop / chdisop / chidlop. mmmode 0 calls the
+note simulator (chan/sim.om gsbind / gsdisable / gsidle). On GB10 the channel is allocated, scheduled
+note and torn down by GSP-RM (RM_ALLOC BLACKWELL_CHANNEL_GPFIFO_A, encoded by chan/params.om), not by
+note register writes, so any other mode traps 9 here: the hardware ops are the GSP RPC path.
+note
+note API (state in globals; a global is never an argument):
+note   chinit -> void                         all slots closed and empty
+note   chcreate c chid rl ent -> long         ck_gpu_chan_create (chid, rl, ent uint)
+note   chsubmit c pb off n -> long            ck_gpu_chan_submit (pb a mem slot, off and n uint)
+note   chretire c upto -> void                ck_gpu_chan_retire (upto uint)
+note   chteardown c budget nx -> long         ck_gpu_chan_teardown; extras: the first nx slots of chx
+note                                          (GMNONE entries are skipped, as C null pointers)
+note   chtoken rl chid -> uint                ck_gpu_submit_token
+note   chrluserd pa -> long                   ck_gpu_rl_userd, the two words in chrlo
+note   chgpent va n -> ulong                  ck_gpu_gp_entry; chmthd: ck_gpu_mthd
+note   per slot: chchid chrl chtok chent chpdb chgpva chupa chipa chrl0 chrl1 (descriptor), chgp chud
+note   chin (ring, USERD, instance mem slots), chput chret (uint, wrap as uint32), chopen
+note codes (enum ck_gpu_chan_status): 0 CHOK, 1 CHEINVAL, 2 CHENOMEM, 3 CHESTATE, 4 CHEFULL, 5 CHEBIND,
+note 6 CHETIME
+const CHOK long 0
+const CHEINVAL long 1
+const CHENOMEM long 2
+const CHESTATE long 3
+const CHEFULL long 4
+const CHEBIND long 5
+const CHETIME long 6
+const CHSLOTS ulong 4
+note CHID_MAX 0xFFF, RUNLIST_INVALID 0x7F, GP length max 0x1FFFFF, GP VA limit 1<<40
+const CHIDMAX uint 4095
+const CHRLINV uint 127
+const CHLENMX uint 2097151
+const CHVALIM ulong 1099511627776
+note USERD 512 bytes, GPPut at 0x8C; instance block 4096 bytes, page directory at word 128 (byte 512)
+const CHUDSZ ulong 512
+const CHGPPUT ulong 140
+const CHINSZ ulong 4096
+const CHPDBW ulong 512
+note RAMIN PDB: target sysmem coherent 2, BIG_PAGE_SIZE_64K bit 11 (2048); low address mask 0xFFFFF000
+const CHTSYS uint 2
+const CHBIG64 uint 2048
+const CHLOM uint 4294963200
+note doorbell VF base 0xB80000 + 0x30090 = 0xBB0090
+const CHDBELL ulong 12255376
+note GP entry: va & ~3 (mask 2^64-4), LENGTH at bit 42, LEVEL bit 41 set as physics nvrm_gp_entry does
+const CHVAM ulong 18446744073709551612
+const CHGPB41 ulong 2199023255552
+note method header (nvrm_mthd, INC_METHOD): 2 << 28
+const CHNINC uint 536870912
+global chchid uint 4
+global chrl uint 4
+global chtok uint 4
+global chent uint 4
+global chpdb ulong 4
+global chgpva ulong 4
+global chupa ulong 4
+global chipa ulong 4
+global chrl0 uint 4
+global chrl1 uint 4
+global chgp ulong 4
+global chud ulong 4
+global chin ulong 4
+global chput uint 4
+global chret uint 4
+global chopen uchar 4
+global chrlo uint 2
+global chx ulong 8
+fn chtoken rl uint chid uint to uint
+ret or shl and rl CHRLINV 16 and chid CHIDMAX
+end
+fn chrluserd pa ulong to long
+if or ne and pa 255 0 ge pa MMPALIM
+ret CHEINVAL
+end
+put chrlo 0 and uint and pa 4294967295 4294967040
+put chrlo 1 and uint and shr pa 32 4294967295 1048575
+ret CHOK
+end
+fn chgpent va ulong n uint to ulong
+ret or or and va CHVAM shl and ulong n 2097151 42 CHGPB41
+end
+fn chmthd subc uint mthd uint count uint to uint
+ret or or or CHNINC shl count 16 shl subc 13 shr mthd 2
+end
+fn chbindop c ulong to long
+if ne get mmmode 0 0
+trap 9
+end
+ret gsbind get chchid c get chtok c get chent c get chgpva c get chupa c get chipa c
+end
+fn chdisop chid uint to long
+if ne get mmmode 0 0
+trap 9
+end
+ret gsdisable chid
+end
+fn chidlop chid uint to long
+if ne get mmmode 0 0
+trap 9
+end
+ret gsidle chid
+end
+fn chinit to void
+for c ulong CHSLOTS
+put chopen c 0
+put chgp c GMNONE
+put chud c GMNONE
+put chin c GMNONE
+put chput c 0
+put chret c 0
+end
+end
+note create's error path: free whichever of the three buffers exist, ENOMEM
+fn chnomem c ulong to long
+if ne get chin c GMNONE
+r = gmfree get chin c
+end
+if ne get chud c GMNONE
+r = gmfree get chud c
+end
+if ne get chgp c GMNONE
+r = gmfree get chgp c
+end
+put chgp c GMNONE
+put chud c GMNONE
+put chin c GMNONE
+ret CHENOMEM
+end
+fn chcreate c ulong chid uint rl uint ent uint to long
+if ge c CHSLOTS
+ret CHEINVAL
+end
+if or gt chid CHIDMAX ge rl CHRLINV
+ret CHEINVAL
+end
+if or or lt ent 2 gt ent 65536 ne and ent sub ent 1 0
+ret CHEINVAL
+end
+put chopen c 0
+put chput c 0
+put chret c 0
+put chgp c GMNONE
+put chud c GMNONE
+put chin c GMNONE
+if ne gmalloc mul ulong ent 8 1 GMGPURO GMOK
+ret chnomem c
+end
+put chgp c get gmout 0
+if ne gmalloc CHUDSZ 1 GMHPOLL GMOK
+ret chnomem c
+end
+put chud c get gmout 0
+if ne gmalloc CHINSZ 1 0 GMOK
+ret chnomem c
+end
+put chin c get gmout 0
+ret chfill c chid rl ent
+end
+note zero gpfifo, USERD and instance block; write the RAMIN page-directory words
+fn chzero c ulong to ulong
+g = get chgp c
+u = get chud c
+n = get chin c
+mmzero get gmbpa g get gmbsz g
+mmzero get gmbpa u get gmbsz u
+mmzero get gmbpa n get gmbsz n
+pdb = get mmroot 0
+ip = get gmbpa n
+mmwr32 add ip CHPDBW ulong or or and uint and pdb 4294967295 CHLOM CHBIG64 CHTSYS
+mmwr32 add ip add CHPDBW 4 shr pdb 32
+ret pdb
+end
+note fill the descriptor, the runlist entry, then bind through the channel ops
+fn chfill c ulong chid uint rl uint ent uint to long
+pdb = chzero c
+put chchid c chid
+put chrl c rl
+put chtok c chtoken rl chid
+put chent c ent
+put chpdb c pdb
+put chgpva c get gmbva get chgp c
+put chupa c get gmbpa get chud c
+put chipa c get gmbpa get chin c
+if ne chrluserd get gmbpa get chud c CHOK
+ret chnomem c
+end
+put chrl0 c get chrlo 0
+put chrl1 c get chrlo 1
+if ne chbindop c 0
+r = gmfree get chin c
+r = gmfree get chud c
+r = gmfree get chgp c
+ret CHEBIND
+end
+put chopen c 1
+ret CHOK
+end
+fn chsubmit c ulong pb ulong off uint n uint to long
+if or ge c CHSLOTS eq get chopen c 0
+ret CHESTATE
+end
+if not gmlive pb
+ret CHEINVAL
+end
+if or or ne and off 3 0 eq n 0 gt n CHLENMX
+ret CHEINVAL
+end
+span = mul ulong n 4
+sz = get gmbsz pb
+if or gt ulong off sz gt span sub sz ulong off
+ret CHEINVAL
+end
+va = add get gmbva pb ulong off
+if or ge va CHVALIM gt span sub CHVALIM va
+ret CHEINVAL
+end
+ret chpush c va n
+end
+note ring full check, GP entry at put % entries, GPPut in USERD, doorbell
+fn chpush c ulong va ulong n uint to long
+p = get chput c
+e = get chent c
+if ge sub p get chret c sub e 1
+ret CHEFULL
+end
+mmwr64 add get gmbpa get chgp c mul ulong rem p e 8 chgpent va n
+p = add p 1
+put chput c p
+mmwr32 add get gmbpa get chud c CHGPPUT ulong rem p e
+mmregwr CHDBELL ulong get chtok c
+ret CHOK
+end
+fn chretire c ulong upto uint to void
+if ge c CHSLOTS
+ret
+end
+r = get chret c
+if le sub upto r sub get chput c r
+put chret c upto
+end
+end
+fn chteardown c ulong budget uint nx ulong to long
+if or ge c CHSLOTS eq get chopen c 0
+ret CHESTATE
+end
+put chopen c 0
+chid = get chchid c
+d = chdisop chid
+idle = false
+for i uint budget
+if ne chidlop chid 0
+idle = true
+break
+end
+end
+rc = CHOK
+for k ulong 3
+b = get chin c
+if eq k 1
+b = get chud c
+end
+if eq k 2
+b = get chgp c
+end
+if not idle
+r = gmquar b
+else
+if ne gmfree b GMOK
+rc = CHETIME
+end
+end
+end
+if not idle
+for i ulong nx
+b = get chx i
+if gmlive b
+r = gmquar b
+end
+end
+rc = CHETIME
+end
+put chgp c GMNONE
+put chud c GMNONE
+put chin c GMNONE
+ret rc
+end
diff --git a/chan/gmmu.om b/chan/gmmu.om
new file mode 100644
index 0000000..5eb24b6
--- /dev/null
+++ b/chan/gmmu.om
@@ -0,0 +1,507 @@
+note chan/gmmu.om: GB10 (Blackwell, ver3) GPU page tables and TLB invalidate, ported from aienux PR #441
+note native/kernel/gpu/gmmu.c and gmmu.h (branch pr441 @ c5bb3a4b). Library unit: no main. Prefix mm / MM.
+note Concatenate with chan/mem.om, chan/chan.om, chan/sim.om (the mode 0 device) before a test or driver.
+note
+note Window: the C takes any caller window (cpu pointer, pa_base, size). Omega cannot hand out a pointer,
+note so the window is the one global mmwin (8 MiB), at bus address mmwb with mmws bytes in use; mmwinit
+note sets them. The page-table pool, the buffers of chan/mem.om and the channel's rings all live inside it,
+note and chan/sim.om reads GPU-visible memory from the same array (in the C the simulator's mem is the
+note window too). On hardware the integrator DMA-maps mmwin and passes its IOVA as mmwb.
+note
+note Register seam (as gsp/mmio.om gsprd / gspwr): mmmode 0 = simulator (chan/sim.om gsrd / gswr),
+note mmmode 1 = 4-byte mapget / mapset on the vfiomapw BAR0 handle in mmbar, any other mode traps 9.
+note
+note API (state in globals; a global is never an argument):
+note   mmwinit base size -> long      window at bus address base, size bytes (1..8388608)
+note   mmasinit pool pages -> long    ck_gmmu_as_init: page-table pool of pages 4 KiB pages at pool
+note   mmmap va pa size page ap pcf   ck_gmmu_map; mmunmap va size page: ck_gmmu_unmap
+note   mminval budget -> long         ck_gmmu_invalidate (poll the trigger register budget times)
+note   mmptfree -> ulong              ck_gmmu_pt_free
+note   mmpde mmdualb mmduals mmpte    the entry encoders; mmlvidx lv va: ck_gmmu_index
+note   mmrd64 mmwr64 mmrd32 mmwr32 mmwr8 mmzero: little-endian window access by bus address
+note   globals out: mmroot (root page directory PA), mmdead (1 after an invalidate timeout),
+note   mmptpa / mmptus / mmptn (pool), mmleaf (last walk's leaf PA)
+note codes (enum ck_gmmu_status): 0 MMOK, 1 MMEINVAL, 2 MMEALIGN, 3 MMERANGE, 4 MMEBUSY, 5 MMENOMEM,
+note 6 MMENOENT, 7 MMETIME (ETIMEDOUT), 8 MMEDEAD
+note Bounds this port adds: mminval polls at most 1000000 times (trap 4 past that; the C takes any
+note uint32 budget); mmzero takes at most 1000000 bytes per call (trap 4).
+const MMOK long 0
+const MMEINVAL long 1
+const MMEALIGN long 2
+const MMERANGE long 3
+const MMEBUSY long 4
+const MMENOMEM long 5
+const MMENOENT long 6
+const MMETIME long 7
+const MMEDEAD long 8
+note walk results: free, mapped, missing (create 0), conflict
+const MMWFREE ulong 0
+const MMWMAP ulong 1
+const MMWMISS ulong 2
+const MMWCONF ulong 3
+note VA limit 1<<57, PA limit 1<<52, PDE/PTE address mask 0x000FFFFFFFFFF000,
+note dual-PDE big-table mask 0x000FFFFFFFFFFF00
+const MMVALIM ulong 144115188075855872
+const MMPALIM ulong 4503599627370496
+const MMADDR ulong 4503599627366400
+const MMBIGM ulong 4503599627370240
+const MMSZ4K ulong 4096
+const MMSZ64K ulong 65536
+const MMSZ2M ulong 2097152
+const MMPTB ulong 4096
+const MMMAXPT ulong 64
+note aperture 2 = system memory coherent (PDE and PTE); PDE PCF 2 = cached, no ATS
+const MMAPSYS ulong 2
+const MMPDEPCF ulong 2
+note GB10 virtual-function MMU invalidate registers: VF base 0xB80000, PDB 0xB830A0, UPPER_PDB 0xB830A4,
+note INVALIDATE 0xB830B0; trigger bit 31, ALL_VA bit 0, PDB aperture sysmem 2
+const MMRPDB ulong 12071072
+const MMRUPR ulong 12071076
+const MMRINV ulong 12071088
+const MMTRIG ulong 2147483648
+const MMALLVA ulong 1
+const MMPDBAP ulong 2
+const MMWINMAX ulong 8388608
+global mmwin uchar 8388608
+global mmwb ulong 1
+global mmws ulong 1
+global mmmode ulong 1
+global mmbar long 1
+global mmptpa ulong 64
+global mmptus uchar 64
+global mmptn ulong 1
+global mmroot ulong 1
+global mmdead ulong 1
+global mmleaf ulong 1
+global mmmiss ulong 1
+global mmnpa ulong 1
+global mmkey ulong 7
+global mmwres ulong 1
+fn mmregrd off ulong to ulong
+m = get mmmode 0
+if eq m 0
+ret gsrd off
+end
+if ne m 1
+trap 9
+end
+ret mapget get mmbar 0 off 4
+end
+fn mmregwr off ulong v ulong to void
+m = get mmmode 0
+if eq m 0
+gswr off v
+ret
+end
+if ne m 1
+trap 9
+end
+r = mapset get mmbar 0 off 4 v
+if ne r 0
+trap 9
+end
+end
+fn mmwinit base ulong size ulong to long
+if or eq size 0 gt size MMWINMAX
+ret MMEINVAL
+end
+if lt add base size base
+ret MMERANGE
+end
+put mmwb 0 base
+put mmws 0 size
+ret MMOK
+end
+fn mmrd64 pa ulong to ulong
+o = sub pa get mmwb 0
+v = ulong 0
+for i ulong 8
+v = or shl v 8 ulong get mmwin add o sub 7 i
+end
+ret v
+end
+fn mmwr64 pa ulong v ulong to void
+o = sub pa get mmwb 0
+for i ulong 8
+put mmwin add o i uchar and shr v mul i 8 255
+end
+end
+fn mmrd32 pa ulong to ulong
+o = sub pa get mmwb 0
+v = ulong 0
+for i ulong 4
+v = or shl v 8 ulong get mmwin add o sub 3 i
+end
+ret v
+end
+fn mmwr32 pa ulong v ulong to void
+o = sub pa get mmwb 0
+for i ulong 4
+put mmwin add o i uchar and shr v mul i 8 255
+end
+end
+fn mmwr8 pa ulong v uchar to void
+put mmwin sub pa get mmwb 0 v
+end
+fn mmzero pa ulong n ulong to void
+o = sub pa get mmwb 0
+for i ulong n
+put mmwin add o i 0
+end
+end
+note entry encoders (gmmu.c ck_gmmu_pde / ck_gmmu_dual_pde / ck_gmmu_pte)
+fn mmpde pa ulong ap ulong to ulong
+ret or or and pa MMADDR shl MMPDEPCF 3 shl and ap 3 1
+end
+note dual PDE word 0 (big-page table, 64 KiB pages); 0 when the half is absent
+fn mmdualb pa ulong ap ulong to ulong
+if eq ap 0
+ret 0
+end
+ret or or and pa MMBIGM shl MMPDEPCF 3 shl and ap 3 1
+end
+note dual PDE word 1 (small-page table, 4 KiB pages)
+fn mmduals pa ulong ap ulong to ulong
+if eq ap 0
+ret 0
+end
+ret or or and pa MMADDR shl MMPDEPCF 3 shl and ap 3 1
+end
+fn mmpte pa ulong ap ulong pcf ulong kind ulong to ulong
+v = or 1 shl and ap 3 1
+v = or v shl and pcf 31 3
+v = or v shl and kind 15 8
+ret or v and pa MMADDR
+end
+note level bit ranges: PDE4..PDE0 = 0..4, big PT = 5, small PT = 6
+fn mmlvlo lv ulong to ulong
+if eq lv 0
+ret 56
+end
+if eq lv 1
+ret 47
+end
+if eq lv 2
+ret 38
+end
+if eq lv 3
+ret 29
+end
+if eq lv 4
+ret 21
+end
+if eq lv 5
+ret 16
+end
+ret 12
+end
+fn mmlvhi lv ulong to ulong
+if eq lv 0
+ret 56
+end
+if eq lv 1
+ret 55
+end
+if eq lv 2
+ret 46
+end
+if eq lv 3
+ret 37
+end
+if eq lv 4
+ret 28
+end
+ret 20
+end
+fn mmlvidx lv ulong va ulong to ulong
+lo = mmlvlo lv
+b = add sub mmlvhi lv lo 1
+ret and shr va lo sub shl 1 b 1
+end
+fn mminwin pa ulong size ulong to bool
+b = get mmwb 0
+s = get mmws 0
+if or eq size 0 lt pa b
+ret false
+end
+o = sub pa b
+if gt o s
+ret false
+end
+ret le size sub s o
+end
+fn mmptalloc to long
+n = get mmptn 0
+for i ulong n
+if eq get mmptus i 0
+put mmptus i 1
+p = get mmptpa i
+mmzero p MMPTB
+put mmnpa 0 p
+ret MMOK
+end
+end
+ret MMENOMEM
+end
+fn mmptfree to ulong
+c = ulong 0
+for i ulong get mmptn 0
+if eq get mmptus i 0
+c = add c 1
+end
+end
+ret c
+end
+fn mmasinit pool ulong pages ulong to long
+if or or eq get mmws 0 0 or lt pages 2 gt pages MMMAXPT ne and pool 4095 0
+ret MMEINVAL
+end
+ok = mminwin pool mul pages MMPTB
+if not ok
+ret MMERANGE
+end
+put mmptn 0 pages
+put mmdead 0 0
+for i ulong MMMAXPT
+if lt i pages
+put mmptpa i add pool mul i MMPTB
+else
+put mmptpa i 0
+end
+put mmptus i 0
+end
+r = mmptalloc
+if eq r MMOK
+put mmroot 0 get mmnpa 0
+end
+ret r
+end
+note PDE4..PDE1: the PD0 table PA when mmwres is MMWFREE; otherwise mmwres is MMWCONF, or MMWMISS with
+note the first missing level in mmmiss
+fn mmwalkup va ulong create bool to ulong
+put mmwres 0 MMWFREE
+tbl = get mmroot 0
+for lv ulong 4
+ea = add tbl mul mmlvidx lv va 8
+v = mmrd64 ea
+if ne and v 1 0
+put mmwres 0 MMWCONF
+ret 0
+end
+if eq and shr v 1 3 0
+if not create
+put mmmiss 0 add lv 1
+put mmwres 0 MMWMISS
+ret 0
+end
+r = mmptalloc
+if ne r MMOK
+put mmwres 0 MMWCONF
+ret 0
+end
+mmwr64 ea mmpde get mmnpa 0 MMAPSYS
+v = mmrd64 ea
+end
+tbl = and v MMADDR
+end
+ret tbl
+end
+note walk(va, page, create): MMWFREE / MMWMAP with the leaf PA in mmleaf, MMWMISS with the first missing
+note level in mmmiss, MMWCONF
+fn mmwalk va ulong page ulong create bool to ulong
+tbl = mmwalkup va create
+if ne get mmwres 0 MMWFREE
+ret get mmwres 0
+end
+d = add tbl mul mmlvidx 4 va 16
+w0 = mmrd64 d
+w1 = mmrd64 add d 8
+bap = and shr w0 1 3
+sap = and shr w1 1 3
+if eq page MMSZ2M
+put mmleaf 0 d
+if ne and w0 1 0
+ret MMWMAP
+end
+if ne or bap sap 0
+ret MMWCONF
+end
+ret MMWFREE
+end
+if ne and w0 1 0
+ret MMWCONF
+end
+big = eq page MMSZ64K
+if big
+if ne sap 0
+ret MMWCONF
+end
+else
+if ne bap 0
+ret MMWCONF
+end
+end
+ret mmwalkpt d va big create
+end
+note walk, last stage: the big (64 KiB) or small (4 KiB) page table under the dual PDE0 at d
+fn mmwalkpt d ulong va ulong big bool create bool to ulong
+w0 = mmrd64 d
+w1 = mmrd64 add d 8
+ap = and shr w1 1 3
+lvl = ulong 6
+pt = and w1 MMADDR
+if big
+ap = and shr w0 1 3
+lvl = 5
+pt = and w0 MMBIGM
+end
+if eq ap 0
+if not create
+put mmmiss 0 lvl
+ret MMWMISS
+end
+r = mmptalloc
+if ne r MMOK
+ret MMWCONF
+end
+pt = get mmnpa 0
+if big
+mmwr64 add d 8 mmduals 0 0
+mmwr64 d mmdualb pt MMAPSYS
+else
+mmwr64 add d 8 mmduals pt MMAPSYS
+mmwr64 d mmdualb 0 0
+end
+end
+p = add pt mul mmlvidx lvl va 8
+put mmleaf 0 p
+if ne and mmrd64 p 1 0
+ret MMWMAP
+end
+ret MMWFREE
+end
+fn mmchk va ulong size ulong page ulong to long
+if ne get mmdead 0 0
+ret MMEDEAD
+end
+if and and ne page MMSZ4K ne page MMSZ64K ne page MMSZ2M
+ret MMEINVAL
+end
+if eq size 0
+ret MMEINVAL
+end
+if ne and or va size sub page 1 0
+ret MMEALIGN
+end
+if or ge va MMVALIM gt size sub MMVALIM va
+ret MMERANGE
+end
+ret MMOK
+end
+note dry run of map: page tables still needed, or 2^64-1 when a page is mapped or conflicts. The window
+note bounds a map to 2048 pages, so the loop bound is never reached.
+fn mmneed va ulong size ulong page ulong to ulong
+for j ulong 7
+put mmkey j 18446744073709551615
+end
+last = ulong 6
+if eq page MMSZ2M
+last = 4
+end
+if eq page MMSZ64K
+last = 5
+end
+need = ulong 0
+off = ulong 0
+while lt off size bound 999999
+w = mmwalk add va off page false
+if or eq w MMWMAP eq w MMWCONF
+ret 18446744073709551615
+end
+if eq w MMWMISS
+j = get mmmiss 0
+while le j last bound 8
+k = shr add va off add mmlvhi j 1
+if ne k get mmkey j
+put mmkey j k
+need = add need 1
+end
+if and eq j 4 eq last 6
+j = 5
+end
+j = add j 1
+end
+end
+off = add off page
+end
+ret need
+end
+fn mmmap va ulong pa ulong size ulong page ulong ap ulong pcf ulong to long
+rc = mmchk va size page
+if ne rc MMOK
+ret rc
+end
+if or gt ap 3 gt pcf 31
+ret MMEINVAL
+end
+if ne and pa sub page 1 0
+ret MMEALIGN
+end
+ok = mminwin pa size
+if or ge pa MMPALIM not ok
+ret MMERANGE
+end
+need = mmneed va size page
+if eq need 18446744073709551615
+ret MMEBUSY
+end
+if gt need mmptfree
+ret MMENOMEM
+end
+off = ulong 0
+while lt off size bound 999999
+w = mmwalk add va off page true
+if ne w MMWFREE
+ret MMEBUSY
+end
+mmwr64 get mmleaf 0 mmpte add pa off ap pcf 0
+off = add off page
+end
+ret MMOK
+end
+fn mmunmap va ulong size ulong page ulong to long
+rc = mmchk va size page
+if ne rc MMOK
+ret rc
+end
+off = ulong 0
+while lt off size bound 999999
+if ne mmwalk add va off page false MMWMAP
+ret MMENOENT
+end
+off = add off page
+end
+off = 0
+while lt off size bound 999999
+w = mmwalk add va off page false
+mmwr64 get mmleaf 0 0
+off = add off page
+end
+ret MMOK
+end
+fn mminval budget ulong to long
+if ne get mmdead 0 0
+ret MMEDEAD
+end
+pdb = shr get mmroot 0 12
+mmregwr MMRPDB or shl and pdb 268435455 4 MMPDBAP
+mmregwr MMRUPR and shr pdb 28 1048575
+mmregwr MMRINV or MMALLVA MMTRIG
+for i ulong budget
+if eq and mmregrd MMRINV MMTRIG 0
+ret MMOK
+end
+end
+put mmdead 0 1
+ret MMETIME
+end
diff --git a/chan/mem.om b/chan/mem.om
new file mode 100644
index 0000000..5c48aec
--- /dev/null
+++ b/chan/mem.om
@@ -0,0 +1,228 @@
+note chan/mem.om: GPU buffer allocator over chan/gmmu.om, ported from aienux PR #441
+note native/kernel/gpu/gpu_mem.c and gpu_mem.h (branch pr441 @ c5bb3a4b). Library unit: no main.
+note Prefix gm / GM. Needs chan/gmmu.om before it.
+note
+note A buffer is a slot index 0..63 (the C hands out struct pointers into the same 64-slot table);
+note GMNONE (64) is "no buffer". Any index past 63 is a foreign pointer and is refused like one.
+note The allocator serves the address space of chan/gmmu.om (one per program; the C takes it as an arg).
+note
+note API (state in globals; a global is never an argument):
+note   gminit poll pab pages vab -> long   ck_gmem_init: pages 4 KiB pages at bus address pab (inside the
+note                                         window, clear of the page-table pool), mapped at GPU VA vab
+note   gmalloc size cache flags -> long    ck_gmem_alloc; the new slot in gmout (GMNONE on refusal)
+note   gmfree b / gmquar b -> long          ck_gmem_free / ck_gmem_quarantine
+note   gmcount st -> ulong                  ck_gmem_count (pages in state st)
+note   gmlive b -> bool                     slot b is a buffer in state LIVE
+note   per slot: gmbpa (bus address; the CPU view is mmwin at gmbpa - mmwb), gmbva (GPU VA), gmbsz,
+note   gmbca, gmbfl, gmbst, gmbgen (uint, wraps as the C uint32)
+note codes (enum ck_gmem_status): 0 GMOK, 1 GMEINVAL, 2 GMENOMEM, 3 GMESTATE, 4 GMEMAP, 5 GMETIME
+note cache: 0 cached, 1 uncached; flags: 1 host polled (needs uncached), 2 GPU read-only
+note states: 0 free, 1 live, 2 quarantined (never handed out again)
+const GMOK long 0
+const GMEINVAL long 1
+const GMENOMEM long 2
+const GMESTATE long 3
+const GMEMAP long 4
+const GMETIME long 5
+const GMFREE uchar 0
+const GMLIVE uchar 1
+const GMQUAR uchar 2
+const GMHPOLL ulong 1
+const GMGPURO ulong 2
+const GMMAXB ulong 64
+const GMMAXP ulong 1024
+const GMNONE ulong 64
+global gmpoll ulong 1
+global gmpab ulong 1
+global gmvab ulong 1
+global gmpages ulong 1
+global gmpgst uchar 1024
+global gmbpa ulong 64
+global gmbva ulong 64
+global gmbsz ulong 64
+global gmbca ulong 64
+global gmbfl ulong 64
+global gmbst uchar 64
+global gmbgen uint 64
+global gmout ulong 1
+fn gminit poll ulong pab ulong pages ulong vab ulong to long
+if or eq get mmptn 0 0 eq get mmws 0 0
+ret GMEINVAL
+end
+if or or or eq pages 0 gt pages GMMAXP ne and pab 4095 0 ne and vab sub MMSZ2M 1 0
+ret GMEINVAL
+end
+if eq poll 0
+ret GMEINVAL
+end
+if ne gmrange pab mul pages 4096 vab GMOK
+ret GMEINVAL
+end
+put gmpoll 0 poll
+put gmpab 0 pab
+put gmvab 0 vab
+put gmpages 0 pages
+for i ulong GMMAXP
+put gmpgst i GMFREE
+end
+for i ulong GMMAXB
+put gmbst i GMFREE
+put gmbgen i 0
+end
+ret GMOK
+end
+note gminit's range checks: n bytes at pab inside the window, at vab inside the 57-bit VA space, and
+note clear of every page-table page
+fn gmrange pab ulong n ulong vab ulong to long
+b = get mmwb 0
+s = get mmws 0
+if or or lt pab b gt sub pab b s gt n sub s sub pab b
+ret GMEINVAL
+end
+if or ge vab MMVALIM gt n sub MMVALIM vab
+ret GMEINVAL
+end
+ret gmptclr pab n
+end
+fn gmptclr pab ulong n ulong to long
+for i ulong get mmptn 0
+p = get mmptpa i
+if and gt add p MMPTB pab lt p add pab n
+ret GMEINVAL
+end
+end
+ret GMOK
+end
+fn gmlive b ulong to bool
+if ge b GMMAXB
+ret false
+end
+ret eq get gmbst b GMLIVE
+end
+fn gmsetpg b ulong st uchar to void
+first = div sub get gmbpa b get gmpab 0 4096
+n = div get gmbsz b 4096
+for i ulong n
+put gmpgst add first i st
+end
+end
+fn gmalloc size ulong cache ulong flags ulong to long
+note flags & ~3 != 0 is flags > 3 for an unsigned value
+if or or or eq size 0 gt size mul GMMAXP 4096 gt cache 1 gt flags 3
+ret GMEINVAL
+end
+if and ne and flags GMHPOLL 0 ne cache 1
+ret GMEINVAL
+end
+put gmout 0 GMNONE
+n = div add size 4095 4096
+b = gmslot
+if eq b GMNONE
+ret GMENOMEM
+end
+st = gmfit n
+if eq st GMMAXP
+ret GMENOMEM
+end
+ret gmplace b st n cache flags
+end
+note first free buffer slot, GMNONE when all 64 are taken
+fn gmslot to ulong
+for i ulong GMMAXB
+if eq get gmbst i GMFREE
+ret i
+end
+end
+ret GMNONE
+end
+note first fit: the first page of the first run of n FREE pages, GMMAXP when there is none
+fn gmfit n ulong to ulong
+run = ulong 0
+st = ulong 0
+for i ulong get gmpages 0
+if ne get gmpgst i GMFREE
+run = 0
+continue
+end
+if eq run 0
+st = i
+end
+run = add run 1
+if eq run n
+ret st
+end
+end
+ret GMMAXP
+end
+note map n pages from page st into slot b (the slot stays FREE, so its fields stay unused, until the
+note map succeeds)
+fn gmplace b ulong st ulong n ulong cache ulong flags ulong to long
+put gmbpa b add get gmpab 0 mul st 4096
+put gmbva b add get gmvab 0 mul st 4096
+put gmbsz b mul n 4096
+pcf = gmpcf cache flags
+r = mmmap get gmbva b get gmbpa b get gmbsz b MMSZ4K MMAPSYS pcf
+if ne r MMOK
+ret GMEMAP
+end
+put gmbca b cache
+put gmbfl b flags
+put gmbst b GMLIVE
+put gmbgen b add get gmbgen b 1
+gmsetpg b GMLIVE
+put gmout 0 b
+ret GMOK
+end
+note PTE PCF: uncached 1 (GPU read-only 5), cached 0 (GPU read-only 4)
+fn gmpcf cache ulong flags ulong to ulong
+ro = ne and flags GMGPURO 0
+if eq cache 1
+if ro
+ret 5
+end
+ret 1
+end
+if ro
+ret 4
+end
+ret 0
+end
+fn gmretire b ulong reuse bool to long
+if not gmlive b
+ret GMESTATE
+end
+um = mmunmap get gmbva b get gmbsz b MMSZ4K
+iv = um
+if eq um MMOK
+iv = mminval get gmpoll 0
+end
+if and reuse eq iv MMOK
+gmsetpg b GMFREE
+put gmbst b GMFREE
+ret GMOK
+end
+gmsetpg b GMQUAR
+put gmbst b GMFREE
+if not reuse
+ret GMOK
+end
+if or eq iv MMETIME eq iv MMEDEAD
+ret GMETIME
+end
+ret GMEMAP
+end
+fn gmfree b ulong to long
+ret gmretire b true
+end
+fn gmquar b ulong to long
+ret gmretire b false
+end
+fn gmcount st uchar to ulong
+c = ulong 0
+for i ulong get gmpages 0
+if eq get gmpgst i st
+c = add c 1
+end
+end
+ret c
+end
diff --git a/chan/params.om b/chan/params.om
new file mode 100644
index 0000000..f32dce4
--- /dev/null
+++ b/chan/params.om
@@ -0,0 +1,300 @@
+note chan/params.om: the RM-alloc and RM-control parameter records the W5 "hello" chain forwards
+note to GSP-RM (GSP_RM_ALLOC 103 / GSP_RM_CONTROL 76 carry them verbatim: rpcRmApiAlloc_GSP and
+note rpcRmApiControl_GSP memcpy the caller's params) plus the two page-directory RPC bodies.
+note Layout source of record: NVIDIA open-gpu-kernel-modules 580.173.02 (MIT), struct offsets and
+note sizes printed by tests/params_ref.c from offsetof/sizeof on the NVIDIA headers and compared
+note byte for byte by tests/params_diff.sh. Library unit, no main. Prefix pa.
+note Every encoder zeroes pabuf, writes one record little-endian, sets palen and returns its size,
+note or a negative error and leaves pabuf untouched: PAEFIT a value does not fit its field,
+note PAERANGE a value outside the field's legal set, PAELEN a reply of the wrong length.
+const PAOK long 0
+const PAEFIT long -1
+const PAERANGE long -2
+const PAELEN long -3
+note 0xFFFFFFFF
+const PAU32 ulong 4294967295
+note channel ids are 12 bits (0xFFF)
+const PACHMAX ulong 4095
+note RPC function numbers (nvidia/inc/kernel/vgpu/rpc_global_enums.h:64,86,89,113)
+const PARSETPD ulong 54
+const PARCTRL ulong 76
+const PARUNSPD ulong 79
+const PARALLOC ulong 103
+note classes: NV01_ROOT 0x0, NV01_DEVICE_0 0x80, NV20_SUBDEVICE_0 0x2080, FERMI_VASPACE_A 0x90f1,
+note KEPLER_CHANNEL_GROUP_A 0xa06c, FERMI_CONTEXT_SHARE_A 0x9067, BLACKWELL_CHANNEL_GPFIFO_A 0xc96f,
+note BLACKWELL_COMPUTE_B 0xcec0
+const PACROOT ulong 0
+const PACDEV ulong 128
+const PACSUB ulong 8320
+const PACVAS ulong 37105
+const PACTSG ulong 41068
+const PACCTX ulong 36967
+const PACGPF ulong 51567
+const PACCMP ulong 52928
+note controls: NVA06C_CTRL_CMD_GPFIFO_SCHEDULE 0xa06c0101 (ctrla06c.h:97),
+note NV2080_CTRL_CMD_INTERNAL_STATIC_KGR_GET_INFO 0x20800a2a (ctrl2080internal.h:422)
+const PACMSCH ulong 2691432705
+const PACMGRI ulong 545262122
+note NV2080_ENGINE_TYPE_GRAPHICS 0x1, NV_CTXSHARE_ALLOCATION_FLAGS_SUBCONTEXT_ASYNC 0x1
+const PAENGGR ulong 1
+const PACTXAS ulong 1
+note record sizes (sizeof on the 580.173.02 headers)
+const PASZROOT ulong 120
+const PASZDEV ulong 56
+const PASZSUB ulong 4
+const PASZVAS ulong 56
+const PASZTSG ulong 20
+const PASZCTX ulong 12
+const PASZCHAN ulong 368
+const PASZSCH ulong 3
+const PASZSPD ulong 48
+const PASZUPD ulong 16
+note GR info reply: 8 engines x 0x3a entries x 8 bytes = 3712; one engine is 58 x 8 = 464 bytes;
+note SM_VERSION is index 0xC, its data word at 12 x 8 + 4 = 100
+const PAGRSZ ulong 3712
+const PAGRENG ulong 464
+const PAGRMAX ulong 8
+const PASMOFF ulong 100
+note NVOS04 channel flags: clear USERD_INDEX_VALUE 10:8, USERD_INDEX_FIXED 11, USERD_INDEX_PAGE_VALUE
+note 20:12 and USERD_INDEX_PAGE_FIXED 21 (mask 0xFFC000FF), then set PAGE_FIXED (1 << 21)
+const PAFLMSK ulong 4290773247
+const PAPGFIX ulong 2097152
+text PANAME "aien-ogd"
+global pabuf uchar 4096
+global palen ulong 1
+global pain ulong 48
+global pareply uchar 4096
+fn paclr n ulong to void
+for i ulong 4096
+put pabuf i 0
+end
+put palen 0 n
+end
+fn paput32 o ulong v ulong to void
+for i ulong 4
+put pabuf add o i uchar and shr v mul i 8 255
+end
+end
+fn paput64 o ulong v ulong to void
+for i ulong 8
+put pabuf add o i uchar and shr v mul i 8 255
+end
+end
+fn paget32 o ulong to ulong
+v = ulong 0
+for i ulong 4
+v = or shl v 8 ulong get pareply add o sub 3 i
+end
+ret v
+end
+fn paf4 a ulong b ulong c ulong d ulong to bool
+ret and and le a PAU32 le b PAU32 and le c PAU32 le d PAU32
+end
+note NV0000_ALLOC_PARAMETERS: hClient 0, processID 4, processName[100] 8 ("aien-ogd", NUL padded),
+note pOsPidInfo 112 (0)
+fn paroot hcli ulong pid ulong to long
+if not paf4 hcli pid 0 0
+ret PAEFIT
+end
+paclr PASZROOT
+paput32 0 hcli
+paput32 4 pid
+for i ulong len PANAME
+put pabuf add 8 i get PANAME i
+end
+ret long PASZROOT
+end
+note NV0080_ALLOC_PARAMETERS: deviceId 0, hClientShare 4, hTargetClient 8 (0), hTargetDevice 12 (0),
+note flags 16, vaSpaceSize 24, vaStartInternal 32 (0), vaLimitInternal 40 (0), vaMode 48
+fn padevice devid ulong hshare ulong flags ulong vamode ulong vasize ulong to long
+if not paf4 devid hshare flags vamode
+ret PAEFIT
+end
+paclr PASZDEV
+paput32 0 devid
+paput32 4 hshare
+paput32 16 flags
+paput64 24 vasize
+paput32 48 vamode
+ret long PASZDEV
+end
+note NV2080_ALLOC_PARAMETERS: subDeviceId 0
+fn pasubdev subid ulong to long
+if gt subid PAU32
+ret PAEFIT
+end
+paclr PASZSUB
+paput32 0 subid
+ret long PASZSUB
+end
+note NV_VASPACE_ALLOCATION_PARAMETERS: index 0, flags 4, vaSize 8, vaStartInternal 16 (0),
+note vaLimitInternal 24 (0), bigPageSize 32, vaBase 40, pasid 48 (0)
+fn pavaspace index ulong flags ulong vasize ulong vabase ulong bigpg ulong to long
+if not paf4 index flags bigpg 0
+ret PAEFIT
+end
+paclr PASZVAS
+paput32 0 index
+paput32 4 flags
+paput64 8 vasize
+paput32 32 bigpg
+paput64 40 vabase
+ret long PASZVAS
+end
+note NV_CHANNEL_GROUP_ALLOCATION_PARAMETERS: hObjectError 0, hObjectEccError 4, hVASpace 8,
+note engineType 12, bIsCallingContextVgpuPlugin 16 (NV_FALSE)
+fn patsg herr ulong hecc ulong hvas ulong eng ulong to long
+if not paf4 herr hecc hvas eng
+ret PAEFIT
+end
+paclr PASZTSG
+paput32 0 herr
+paput32 4 hecc
+paput32 8 hvas
+paput32 12 eng
+ret long PASZTSG
+end
+note NV_CTXSHARE_ALLOCATION_PARAMETERS: hVASpace 0, flags 4, subctxId 8
+fn pactxsh hvas ulong flags ulong subctx ulong to long
+if not paf4 hvas flags subctx 0
+ret PAEFIT
+end
+paclr PASZCTX
+paput32 0 hvas
+paput32 4 flags
+paput32 8 subctx
+ret long PASZCTX
+end
+note pain indices that hold NvU64 fields in the channel layout: gpFifoOffset 1, userdOffset[0] 7,
+note base/size of the six NV_MEMORY_DESC_PARAMS (16,17 20,21 24,25 28,29 32,33 38,39)
+fn pawide k ulong to bool
+if or eq k 1 eq k 7
+ret true
+end
+if and ge k 16 le k 35
+ret lt rem sub k 16 4 2
+end
+ret or eq k 38 eq k 39
+end
+note NV_MEMORY_DESC_PARAMS at o from pain[k..k+3]: base 0, size 8, addressSpace 16, cacheAttrib 20
+fn pamd o ulong k ulong to void
+paput64 o get pain k
+paput64 add o 8 get pain add k 1
+paput32 add o 16 get pain add k 2
+paput32 add o 20 get pain add k 3
+end
+note the GSP-client flag rewrite of kernel_channel.c:2814-2821: USERD_INDEX_FIXED false,
+note USERD_INDEX_PAGE_FIXED true, USERD_INDEX_VALUE = chid % 8, USERD_INDEX_PAGE_VALUE = chid / 8
+fn pachfl fl ulong chid ulong to ulong
+v = or and fl PAFLMSK PAPGFIX
+ret or v or shl rem chid 8 8 shl and div chid 8 511 12
+end
+note NV_CHANNEL_ALLOC_PARAMS (368 bytes) from pain:
+note 0 hObjectError, 1 gpFifoOffset, 2 gpFifoEntries, 3 client flags, 4 hContextShare, 5 hVASpace,
+note 6 hUserdMemory[0], 7 userdOffset[0], 8 engineType, 9 subDeviceId, 10 hObjectEccError,
+note 11 hPhysChannelGroup, 12 error notifier type, 13 ECC error notifier type, 14 privilege level,
+note 15 chid, 16-19 instanceMem, 20-23 userdMem, 24-27 ramfcMem, 28-31 mthdbufMem,
+note 32-35 errorNotifierMem, 36 ProcessID, 37 SubProcessID, 38-41 eccErrorNotifierMem.
+note hObjectBuffer, cid, hUserdMemory[1..7], userdOffset[1..7], the IVs, hmacNonce and tpcConfigID
+note are 0. internalFlags = PRIVILEGE 1:0 | ERROR_NOTIFIER_TYPE 3:2 | ECC_ERROR_NOTIFIER_TYPE 5:4.
+fn pachan to long
+for k ulong 42
+if and not pawide k gt get pain k PAU32
+ret PAEFIT
+end
+end
+if or or gt get pain 12 3 gt get pain 13 3 gt get pain 14 3
+ret PAERANGE
+end
+chid = get pain 15
+if gt chid PACHMAX
+ret PAERANGE
+end
+paclr PASZCHAN
+paput32 0 get pain 0
+paput64 8 get pain 1
+paput32 16 get pain 2
+paput32 20 pachfl get pain 3 chid
+paput32 24 get pain 4
+paput32 28 get pain 5
+paput32 32 get pain 6
+paput64 64 get pain 7
+paput32 128 get pain 8
+paput32 136 get pain 9
+paput32 140 get pain 10
+pamd 144 16
+pamd 168 20
+pamd 192 24
+pamd 216 28
+paput32 240 get pain 11
+paput32 244 or or get pain 14 shl get pain 12 2 shl get pain 13 4
+pamd 248 32
+pamd 272 38
+paput32 296 get pain 36
+paput32 300 get pain 37
+ret long PASZCHAN
+end
+note NVA06C_CTRL_GPFIFO_SCHEDULE_PARAMS: bEnable 0, bSkipSubmit 1, bSkipEnable 2 (NvBool each)
+fn pasched en ulong skipsub ulong skipen ulong to long
+if or or gt en 1 gt skipsub 1 gt skipen 1
+ret PAERANGE
+end
+paclr PASZSCH
+put pabuf 0 uchar en
+put pabuf 1 uchar skipsub
+put pabuf 2 uchar skipen
+ret long PASZSCH
+end
+note NV2080_CTRL_INTERNAL_STATIC_GR_GET_INFO_PARAMS request: all zero, GSP-RM fills the reply
+fn pagrinfo to long
+paclr PAGRSZ
+ret long PAGRSZ
+end
+note SM_VERSION of engine eng from a GR_GET_INFO reply of n bytes copied into pareply:
+note engineInfo[eng].infoList[0xC].data
+fn pasmver eng ulong n ulong to long
+if ne n PAGRSZ
+ret PAELEN
+end
+if ge eng PAGRMAX
+ret PAERANGE
+end
+ret long paget32 add mul eng PAGRENG PASMOFF
+end
+note rpc_set_page_directory_v1E_05 (48 bytes) from pain: 0 hClient 0, 1 hDevice 4, 2 pasid 8,
+note params at 16: 3 physAddress 16, 4 numEntries 24, flags 28 = 5 APERTURE 1:0 (0..2) |
+note 6 PRESERVE_PDES 2:2 (0..1), 7 hVASpace 32, 8 chId 36, 9 subDeviceId 40, 10 params.pasid 44
+fn pasetpd to long
+for k ulong 11
+if and ne k 3 gt get pain k PAU32
+ret PAEFIT
+end
+end
+if or gt get pain 5 2 gt get pain 6 1
+ret PAERANGE
+end
+paclr PASZSPD
+paput32 0 get pain 0
+paput32 4 get pain 1
+paput32 8 get pain 2
+paput64 16 get pain 3
+paput32 24 get pain 4
+paput32 28 or get pain 5 shl get pain 6 2
+paput32 32 get pain 7
+paput32 36 get pain 8
+paput32 40 get pain 9
+paput32 44 get pain 10
+ret long PASZSPD
+end
+note rpc_unset_page_directory_v1E_05: hClient 0, hDevice 4, params at 8: hVASpace 8, subDeviceId 12
+fn paunsetpd hcli ulong hdev ulong hvas ulong subdev ulong to long
+if not paf4 hcli hdev hvas subdev
+ret PAEFIT
+end
+paclr PASZUPD
+paput32 0 hcli
+paput32 4 hdev
+paput32 8 hvas
+paput32 12 subdev
+ret long PASZUPD
+end
diff --git a/chan/sim.om b/chan/sim.om
new file mode 100644
index 0000000..a5a40fa
--- /dev/null
+++ b/chan/sim.om
@@ -0,0 +1,537 @@
+note chan/sim.om: host simulator of the GB10 pieces the channel path touches, ported from aienux PR #441
+note native/kernel/gpu/gpu_sim.c and gpu_sim.h (branch pr441 @ c5bb3a4b). Library unit: no main.
+note Prefix gs / GS (never gsp). It is the mode 0 device of chan/gmmu.om mmregrd / mmregwr and of the
+note channel ops in chan/chan.om. Needs chan/gmmu.om (the window array mmwin) before it.
+note
+note It models: the VF MMU invalidate registers (a request completes after gsi[4] polls of INVALIDATE,
+note never when gsi[5] "stuck" is set), a 16-entry TLB filled by its own ver3 page walker, the fault log,
+note the doorbell (a submit token consumes that channel's ring: USERD GPPut, GP entries, push buffer
+note words, all through the GPU MMU, so a missing mapping or a write to read-only memory faults) and the
+note channel bind / disable / idle protocol. Every register access is logged (512 entries, then counted
+note as dropped). The walker, offsets and bit fields are this file's own copies, not chan/gmmu.om's, so
+note a wrong driver constant shows up as a wrong access or a fault.
+note
+note State (the fields of struct ck_gsim):
+note   gsmem 0 base, 1 size of the memory the GPU sees (inside mmwin, at bus address gsmem 0)
+note   gsi   0 pdb_lo, 1 pdb_hi, 2 pending, 3 polls left, 4 latency (3), 5 stuck, 6 done, 7 all
+note   gslogo / gslogv / gslogw, gsnlog, gsldrop: the register log
+note   gstv gstpdb gstva gstpa gstpg gstlo, gstn (next), gsthits: the TLB
+note   gsfva gsfpdb gsfkind gsfw, gsnf: faults (16 kept, all counted)
+note   per channel slot (4): gscb bound, gscid, gsctok, gscent, gscgpva, gscupa, gscipa, gscpdb,
+note   gscget gp_get, gscwr words_read, gscflt faulted, gscdis disabled
+note   gsdb doorbells, gsdbunk doorbell_unknown, gshang (set by a test: the engine never idles),
+note   gsidlep idle_polls
+note fault kinds: 1 unmapped, 2 bad PDE (a PTE above PDE2), 3 aperture, 4 write to read-only, 5 outside
+note memory
+const GSRPDB ulong 12071072
+const GSRUPR ulong 12071076
+const GSRINV ulong 12071088
+const GSDBELL ulong 12255376
+const GSTRIG ulong 2147483648
+const GSADDR ulong 4503599627366400
+const GSBIGM ulong 4503599627370240
+const GSUDPUT ulong 140
+const GSLOGMX ulong 512
+const GSNONE ulong 4
+note gshalf's "try the other half" result; fault kinds are 1..5, so 255 never collides
+const GSNEXT ulong 255
+note gspdbof's refusal: 2^64-1, never a page-aligned PDB
+const GSBADPD ulong 18446744073709551615
+global gsmem ulong 2
+global gsi ulong 8
+global gslogo uint 512
+global gslogv uint 512
+global gslogw uchar 512
+global gsnlog ulong 1
+global gsldrop ulong 1
+global gstv uchar 16
+global gstpdb ulong 16
+global gstva ulong 16
+global gstpa ulong 16
+global gstpg ulong 16
+global gstlo ulong 16
+global gstn ulong 1
+global gsthits ulong 1
+global gsfva ulong 16
+global gsfpdb ulong 16
+global gsfkind ulong 16
+global gsfw ulong 16
+global gsnf ulong 1
+global gscb uchar 4
+global gscid uint 4
+global gsctok uint 4
+global gscent uint 4
+global gscgpva ulong 4
+global gscupa ulong 4
+global gscipa ulong 4
+global gscpdb ulong 4
+global gscget uint 4
+global gscwr uint 4
+global gscflt uchar 4
+global gscdis uchar 4
+global gsdb ulong 1
+global gsdbunk ulong 1
+global gshang ulong 1
+global gsidlep ulong 1
+note walk / translate results: 0 pa, 1 page size, 2 pte low 12 bits, 3 the word read
+global gsw ulong 4
+fn gsinit base ulong size ulong to void
+put gsmem 0 base
+put gsmem 1 size
+for i ulong 8
+put gsi i 0
+end
+put gsi 4 3
+for i ulong GSLOGMX
+put gslogo i 0
+put gslogv i 0
+put gslogw i 0
+end
+put gsnlog 0 0
+put gsldrop 0 0
+for i ulong 16
+put gstv i 0
+put gstpdb i 0
+put gstva i 0
+put gstpa i 0
+put gstpg i 0
+put gstlo i 0
+put gsfva i 0
+put gsfpdb i 0
+put gsfkind i 0
+put gsfw i 0
+end
+put gstn 0 0
+put gsthits 0 0
+put gsnf 0 0
+for i ulong 4
+put gscb i 0
+put gscid i 0
+put gsctok i 0
+put gscent i 0
+put gscgpva i 0
+put gscupa i 0
+put gscipa i 0
+put gscpdb i 0
+put gscget i 0
+put gscwr i 0
+put gscflt i 0
+put gscdis i 0
+end
+put gsdb 0 0
+put gsdbunk 0 0
+put gshang 0 0
+put gsidlep 0 0
+for i ulong 4
+put gsw i 0
+end
+end
+fn gslog off ulong v ulong w uchar to void
+n = get gsnlog 0
+if lt n GSLOGMX
+put gslogo n uint off
+put gslogv n uint v
+put gslogw n w
+put gsnlog 0 add n 1
+else
+put gsldrop 0 add get gsldrop 0 1
+end
+end
+fn gsinmem pa ulong n ulong to bool
+b = get gsmem 0
+s = get gsmem 1
+if lt pa b
+ret false
+end
+o = sub pa b
+if gt o s
+ret false
+end
+ret le n sub s o
+end
+fn gsrd64 pa ulong to ulong
+o = add sub pa get gsmem 0 sub get gsmem 0 get mmwb 0
+v = ulong 0
+for i ulong 8
+v = or shl v 8 ulong get mmwin add o sub 7 i
+end
+ret v
+end
+fn gsrd32 pa ulong to ulong
+o = add sub pa get gsmem 0 sub get gsmem 0 get mmwb 0
+v = ulong 0
+for i ulong 4
+v = or shl v 8 ulong get mmwin add o sub 3 i
+end
+ret v
+end
+fn gslo lv ulong to ulong
+if eq lv 0
+ret 56
+end
+if eq lv 1
+ret 47
+end
+if eq lv 2
+ret 38
+end
+if eq lv 3
+ret 29
+end
+ret 21
+end
+fn gshi lv ulong to ulong
+if eq lv 0
+ret 56
+end
+if eq lv 1
+ret 55
+end
+if eq lv 2
+ret 46
+end
+if eq lv 3
+ret 37
+end
+ret 28
+end
+fn gschkpte pte ulong wf ulong to ulong
+ap = and shr pte 1 3
+pcf = and shr pte 3 31
+if or eq ap 0 eq ap 1
+ret 3
+end
+if and ne wf 0 ne and pcf 4 0
+ret 4
+end
+ret 0
+end
+note a valid PTE of page size psz: translation into gsw 0..2; 5 when the target is outside memory
+fn gsleaf e ulong psz ulong va ulong to ulong
+pa = add and and e GSADDR not sub psz 1 and va sub psz 1
+put gsw 0 pa
+put gsw 1 psz
+put gsw 2 and e 4095
+if gsinmem pa 4
+ret 0
+end
+ret 5
+end
+note the dual PDE0 at tbl + idx*16: small half (4 KiB pages) first, then big half (64 KiB)
+fn gsdual tbl ulong idx ulong e ulong va ulong wf ulong to ulong
+e1 = gsrd64 add add tbl mul idx 16 8
+f = gshalf and shr e1 1 3 and e1 GSADDR 12 va wf
+if ne f GSNEXT
+ret f
+end
+f = gshalf and shr e 1 3 and e GSBIGM 16 va wf
+if ne f GSNEXT
+ret f
+end
+ret 1
+end
+note one half of the dual PDE0: aperture ap, page table pt, page shift sh; GSNEXT means try the next half
+fn gshalf ap ulong pt ulong sh ulong va ulong wf ulong to ulong
+if eq ap 0
+ret GSNEXT
+end
+if eq ap 1
+ret 3
+end
+a = add pt mul and shr va sh sub shl 1 sub 21 sh 1 8
+if not gsinmem a 8
+ret 5
+end
+pte = gsrd64 a
+if eq and pte 1 0
+ret GSNEXT
+end
+f = gschkpte pte wf
+if ne f 0
+ret f
+end
+ret gsleaf pte shl 1 sh va
+end
+fn gswalk pdb ulong va ulong wf ulong to ulong
+if ne shr va 57 0
+ret 1
+end
+tbl = pdb
+for lv ulong 5
+esz = ulong 8
+if eq lv 4
+esz = 16
+end
+lo = gslo lv
+idx = and shr va lo sub shl 1 add sub gshi lv lo 1 1
+ea = add tbl mul idx esz
+if not gsinmem ea esz
+ret 5
+end
+e = gsrd64 ea
+if ne and e 1 0
+if lt lv 2
+ret 2
+end
+f = gschkpte e wf
+if ne f 0
+ret f
+end
+ret gsleaf e shl 1 lo va
+end
+if lt lv 4
+ap = and shr e 1 3
+if eq ap 0
+ret 1
+end
+if eq ap 1
+ret 3
+end
+tbl = and e GSADDR
+continue
+end
+ret gsdual tbl idx e va wf
+end
+ret 1
+end
+fn gsfault pdb ulong va ulong kind ulong wf ulong to void
+n = get gsnf 0
+if lt n 16
+put gsfva n va
+put gsfpdb n pdb
+put gsfkind n kind
+put gsfw n wf
+end
+put gsnf 0 add n 1
+end
+fn gsxlate pdb ulong va ulong wf ulong to ulong
+i = gstlbhit pdb va
+if lt i 16
+f = gschkpte get gstlo i wf
+if ne f 0
+gsfault pdb va f wf
+ret f
+end
+put gsthits 0 add get gsthits 0 1
+put gsw 0 add get gstpa i sub va get gstva i
+ret 0
+end
+f = gswalk pdb va wf
+if ne f 0
+gsfault pdb va f wf
+ret f
+end
+gstfill pdb va
+ret 0
+end
+note the first valid TLB slot covering (pdb, va), 16 when none
+fn gstlbhit pdb ulong va ulong to ulong
+for i ulong 16
+if and ne get gstv i 0 eq get gstpdb i pdb
+if lt sub va get gstva i get gstpg i
+ret i
+end
+end
+end
+ret 16
+end
+note fill TLB slot gstn % 16 from the walk result in gsw (pa, page, pte_lo)
+fn gstfill pdb ulong va ulong to void
+n = rem get gstn 0 16
+put gstn 0 add get gstn 0 1
+pg = get gsw 1
+vp = and va not sub pg 1
+put gstv n 1
+put gstpdb n pdb
+put gstpg n pg
+put gstva n vp
+put gstpa n sub get gsw 0 sub va vp
+put gstlo n get gsw 2
+end
+note a GPU read of 4 bytes at va: fault kind, the word in gsw 3
+fn gsgrd32 pdb ulong va ulong to ulong
+f = gsxlate pdb va 0
+if ne f 0
+ret f
+end
+put gsw 3 gsrd32 get gsw 0
+ret 0
+end
+fn gschan chid uint to ulong
+for i ulong 4
+if and ne get gscb i 0 eq get gscid i chid
+ret i
+end
+end
+ret GSNONE
+end
+fn gsconsume c ulong to void
+if or or ne get gscflt c 0 ne get gscdis c 0 ne get gshang 0 0
+ret
+end
+upa = add get gscupa c GSUDPUT
+if not gsinmem upa 4
+put gscflt c 1
+ret
+end
+pv = uint gsrd32 upa
+ent = get gscent c
+if ge pv ent
+put gscflt c 1
+ret
+end
+pdb = get gscpdb c
+while ne get gscget c pv bound 999999
+if not gsent c pdb add get gscgpva c mul ulong get gscget c 8
+put gscflt c 1
+ret
+end
+put gscget c rem add get gscget c 1 ent
+end
+end
+note one GP entry at eva: read both words, then every pushbuffer word; false on a fault
+fn gsent c ulong pdb ulong eva ulong to bool
+if ne gsgrd32 pdb eva 0
+ret false
+end
+lo = get gsw 3
+if ne gsgrd32 pdb add eva 4 0
+ret false
+end
+hi = get gsw 3
+ret gspb c pdb or and lo 4294967292 shl and hi 255 32 and shr hi 10 2097151
+end
+note read the n pushbuffer words at pbva (counted in gscwr); false on a fault
+fn gspb c ulong pdb ulong pbva ulong n ulong to bool
+for a ulong div add n 1023 1024
+for b ulong 1024
+w = add mul a 1024 b
+if ge w n
+break
+end
+if ne gsgrd32 pdb add pbva mul w 4 0
+ret false
+end
+put gscwr c add get gscwr c 1
+end
+end
+ret true
+end
+fn gsrd off ulong to ulong
+v = ulong 0
+if eq off GSRINV
+if and ne get gsi 2 0 eq get gsi 5 0
+if eq get gsi 3 0
+pdb = shl or and shr get gsi 0 4 268435455 shl and get gsi 1 1048575 28 12
+for i ulong 16
+if or ne get gsi 7 0 eq get gstpdb i pdb
+put gstv i 0
+end
+end
+put gsi 2 0
+put gsi 6 add get gsi 6 1
+else
+put gsi 3 sub get gsi 3 1
+end
+end
+if ne get gsi 2 0
+v = GSTRIG
+end
+end
+gslog off v 0
+ret v
+end
+fn gswr off ulong v ulong to void
+gslog off v 1
+if eq off GSRPDB
+put gsi 0 v
+ret
+end
+if eq off GSRUPR
+put gsi 1 v
+ret
+end
+if and eq off GSRINV ne and v GSTRIG 0
+put gsi 2 1
+put gsi 3 get gsi 4
+put gsi 7 0
+if ne and v 2 0
+put gsi 7 1
+end
+ret
+end
+if eq off GSDBELL
+put gsdb 0 add get gsdb 0 1
+for i ulong 4
+if and ne get gscb i 0 eq ulong get gsctok i v
+gsconsume i
+ret
+end
+end
+put gsdbunk 0 add get gsdbunk 0 1
+end
+end
+note bind: the channel's page directory comes from its instance block (RAMIN word 128/129), as the
+note hardware reads it; target must be sysmem (2 coherent, 3 non-coherent), bit 10 (VOL) clear
+fn gsbind chid uint tok uint ent uint gpva ulong upa ulong ipa ulong to long
+if ne gschan chid GSNONE
+ret -1
+end
+pdb = gspdbof ipa
+if eq pdb GSBADPD
+ret -1
+end
+for i ulong 4
+if eq get gscb i 0
+put gscid i chid
+put gsctok i tok
+put gscent i ent
+put gscgpva i gpva
+put gscupa i upa
+put gscipa i ipa
+put gscpdb i pdb
+put gscget i 0
+put gscwr i 0
+put gscflt i 0
+put gscdis i 0
+put gscb i 1
+ret 0
+end
+end
+ret -1
+end
+note the page directory from RAMIN word 128/129 of the instance block at ipa; GSBADPD when the words
+note are outside memory, the target is not sysmem or VOL is set (a real PDB has its low 12 bits clear)
+fn gspdbof ipa ulong to ulong
+a = add ipa 512
+if not gsinmem a 8
+ret GSBADPD
+end
+w = gsrd64 a
+lo = and w 4294967295
+t = and lo 3
+if or and ne t 2 ne t 3 ne and lo 1024 0
+ret GSBADPD
+end
+ret or shl shr w 32 32 and lo 4294963200
+end
+fn gsdisable chid uint to long
+c = gschan chid
+if eq c GSNONE
+ret -1
+end
+put gscdis c 1
+ret 0
+end
+fn gsidle chid uint to long
+put gsidlep 0 add get gsidlep 0 1
+c = gschan chid
+if eq c GSNONE
+ret 1
+end
+if or ne get gshang 0 0 eq get gscdis c 0
+ret 0
+end
+put gscb c 0
+ret 1
+end
diff --git a/fwprep.om b/fwprep.om
new file mode 100644
index 0000000..635bb2f
--- /dev/null
+++ b/fwprep.om
@@ -0,0 +1,545 @@
+note fwprep.om: the GB10 firmware inputs for the bring-up chain, from files only (OM-1 seeded omc).
+note Usage: fwprep FWFILE OGKMSRC OUTDIR
+note   FWFILE  gsp_ga10x.bin (580.173.02), inspected as ck_gsp_fw_inspect inspect does
+note   OGKMSRC open-gpu-kernel-modules-580.173.02 tree; its two GB10B bindata files are read as
+note           ck_gsp_bindata_extract extract does (src/nvidia/generated/g_bindata_kgspGetBinArchive*)
+note   OUTDIR  gets fmc.img fmc.hash fmc.pubkey fmc.sig bl.img, then fw.manifest (written to
+note           fw.manifest.tmp and renamed; fw.manifest is unlinked first, so a refused or failed run
+note           never leaves a manifest behind; consumers read the outputs only through it)
+note stdout: the inspect report, the FMC extract report, the boot extract report (the C tools' exact
+note bytes, without --out), then "fwprep ..." lines. Exit 0 ok, 1 usage or FWFILE open/read error
+note (stderr), 2 refused, 3 output write failure.
+note Build: cat gsp/sha2.om gsp/inflate.om gsp/fw.om gsp/bindata.om fwprep.om | build/omc > fwprep
+note Prefix fwp. Host only: reads files, writes OUTDIR; no device.
+global fwpok ulong 1
+global fwpsgb ulong 80
+global fwpsgl ulong 80
+global fwpst uchar 128
+global fwpsrc uchar 4096
+global fwpsrcn ulong 1
+global fwpout uchar 4096
+global fwpoutn ulong 1
+global fwpp uchar 4096
+global fwppn ulong 1
+global fwprn uchar 8200
+global fwpoo ulong 5
+global fwpon ulong 5
+global fwpoh uchar 320
+global fwpdo ulong 1
+global fwpsz ulong 2
+global fwpsh uchar 128
+note FWPTXT segments: 1 "fwprep ", 2 usage, 3..5 bindata paths, 6..7 functions, 8..13 labels,
+note 14..20 output names, 21.. messages, 33.. manifest pieces, 43..63 the 21 RM_RISCV_UCODE_DESC
+note words in struct order (C riscv_desc), 64.. more pieces
+text FWPTXT "|fwprep |usage: fwprep FWFILE OGKMSRC OUTDIR|/src/nvidia/generated/|g_bindata_kgspGetBinArchiveGspRmFmcGfwProdSigned_GB10B.c|g_bindata_kgspGetBinArchiveGspRmBoot_GB10B.c|kgspGetBinArchiveGspRmFmcGfwProdSigned_GB10B|kgspGetBinArchiveGspRmBoot_GB10B|UCODE_IMAGE|UCODE_HASH|UCODE_PKEY|UCODE_SIG|UCODE_IMAGE_PROD|UCODE_DESC_PROD|fmc.img|fmc.hash|fmc.pubkey|fmc.sig|bl.img|fw.manifest|fw.manifest.tmp|REFUSED unexpected function | in |REFUSED missing label |wrote | bytes=| sha256=|RESULT OK|FAILED |makedir |write |rename |: |fwmanifest 1|fwversion |build_id |fw_file bytes=|fwimage offset=| size=|fwsignature .fwsignature_gb10y offset=|fmc_src |boot_src |bl_desc UCODE_DESC_PROD| version=| bootloader_off=| bootloader_size=| bl_param_off=| bl_param_size=| elf_off=| elf_size=| app_version=| manifest_off=| manifest_size=| mdata_off=| mdata_size=| mcode_off=| mcode_size=| monitor_enabled=| swbrom_code_off=| swbrom_code_size=| swbrom_data_off=| swbrom_data_size=| fb_reserved=| signed_as_code=|out |end|open |short read|REFUSED firmware|REFUSED bindata |"
+fn fwpsetup to void
+if eq get fwpok 0 1
+ret
+end
+put fwpok 0 1
+seg = ulong 0
+for i ulong len FWPTXT
+c = get FWPTXT i
+if eq c 124
+seg = add seg 1
+put fwpsgb seg add i 1
+put fwpsgl seg 0
+else
+put fwpsgl seg add get fwpsgl seg 1
+end
+end
+end
+fn fwpos k ulong to void
+b = get fwpsgb k
+for i ulong get fwpsgl k
+fwoc get FWPTXT add b i
+end
+end
+fn fwppath to void
+for i ulong get fwppn 0
+fwoc get fwpp i
+end
+end
+note fwpp = OUTDIR "/" segment k
+fn fwpmk k ulong to void
+n = get fwpoutn 0
+for i ulong n
+put fwpp i get fwpout i
+end
+put fwpp n 47
+n = add n 1
+b = get fwpsgb k
+for i ulong get fwpsgl k
+put fwpp n get FWPTXT add b i
+n = add n 1
+end
+put fwppn 0 n
+end
+note bdpath = OGKMSRC "/src/nvidia/generated/" segment k
+fn fwpbdp k ulong to void
+n = get fwpsrcn 0
+for i ulong n
+put bdpath i get fwpsrc i
+end
+for s ulong 2
+g = ulong 3
+if eq s 1
+g = k
+end
+b = get fwpsgb g
+for i ulong get fwpsgl g
+put bdpath n get FWPTXT add b i
+n = add n 1
+end
+end
+put bdpathn 0 n
+end
+note one line to stderr: segment k, then the path in fwpath (when wp 1), then ": " strerror e (e > 0)
+fn fwperr k ulong wp ulong e ulong to void
+z = fwoflush
+put fwofd 0 2
+fwpos k
+if eq wp 1
+fwopath
+end
+if gt e 0
+fwpos 32
+fwoerrno e
+end
+fwoc 10
+z = fwoflush
+put fwofd 0 1
+end
+note arguments into fwpath (FWFILE), fwpsrc, fwpout: 0, or 1 on a usage error
+fn fwpargs to ulong
+if ne argcnt 4
+ret 1
+end
+a = argread 1 fwpath 0 4096
+if lt a 1
+ret 1
+end
+put fwpathn 0 ulong a
+b = argread 2 fwpsrc 0 4000
+if lt b 1
+ret 1
+end
+put fwpsrcn 0 ulong b
+c = argread 3 fwpout 0 4000
+if lt c 1
+ret 1
+end
+put fwpoutn 0 ulong c
+ret 0
+end
+note C cmd_inspect on FWFILE: 0 OK, 2 refused, 1 open or read error (C stderr wording)
+fn fwpfw to ulong
+fd = fopen fwpath 0 get fwpathn 0 524288 0
+if lt fd 0
+fwperr 66 1 ulong neg fd
+ret 1
+end
+s = fstat int fd fwpst 0 128
+if lt s 0
+c = fclose int fd
+fwperr 66 1 ulong neg s
+ret 1
+end
+sz = ulong 0
+for i ulong 8
+sz = or sz shl ulong get fwpst add 48 i mul i 8
+end
+md = ulong 0
+for i ulong 4
+md = or md shl ulong get fwpst add 16 i mul i 8
+end
+note S_IFMT 0170000 = 61440, S_IFDIR 0040000 = 16384: a directory is "Is a directory" (21)
+if eq and md 61440 16384
+c = fclose int fd
+fwperr 66 1 21
+ret 1
+end
+e = fwinsp int fd sz
+c = fclose int fd
+if eq e 1
+fwperr 67 0 0
+ret 1
+end
+ret e
+end
+note does the label of block i equal FWPTXT segment k?
+fn fwpleq i ulong k ulong to ulong
+b = get fwpsgb k
+l = get fwpsgl k
+if ne get bdlbl i l
+ret 0
+end
+a = mul i 64
+m = ulong 1
+for j ulong l
+if ne get bdlb add a j get FWPTXT add b j
+m = 0
+end
+end
+ret m
+end
+note block whose label equals FWPTXT segment k, or BDNONE
+fn fwpfind k ulong to ulong
+for i ulong get bdn 0
+if eq fwpleq i k 1
+ret i
+end
+end
+ret BDNONE
+end
+note "fwprep REFUSED missing label L in FILE"
+fn fwpmiss k ulong f ulong to ulong
+fwpos 1
+fwpos 23
+fwpos k
+fwpos 22
+fwpos f
+fwoc 10
+ret 2
+end
+note record block for label segment k as output slot o; 2 (refused) when it is missing
+fn fwpslot k ulong f ulong o ulong to ulong
+i = fwpfind k
+if eq i BDNONE
+ret fwpmiss k f
+end
+put fwpoo o get bdpo i
+put fwpon o get bdpn i
+ret 0
+end
+note extract bindata file f (segment 4 FMC or 5 boot) whose function must be segment fn
+fn fwpbd f ulong fs ulong w ulong to ulong
+fwpbdp f
+e = bdfile
+put fwpsz w get bdfsz 0
+for i ulong 64
+put fwpsh add mul w 64 i get bdfsh i
+end
+if ne e 0
+fwpos 1
+fwpos 69
+fwpos f
+fwoc 10
+ret 2
+end
+b = get fwpsgb fs
+l = get fwpsgl fs
+m = ulong 1
+if ne get bdfnl 0 l
+m = 0
+else
+for j ulong l
+if ne get bdfn j get FWPTXT add b j
+m = 0
+end
+end
+end
+if eq m 0
+fwpos 1
+fwpos 21
+bdofn 0
+fwpos 22
+fwpos f
+fwoc 10
+ret 2
+end
+ret 0
+end
+fn fwpfmc to ulong
+e = fwpbd 4 6 0
+if ne e 0
+ret e
+end
+e = fwpslot 8 4 0
+if ne e 0
+ret e
+end
+e = fwpslot 9 4 1
+if ne e 0
+ret e
+end
+e = fwpslot 10 4 2
+if ne e 0
+ret e
+end
+ret fwpslot 11 4 3
+end
+fn fwpboot to ulong
+e = fwpbd 5 7 1
+if ne e 0
+ret e
+end
+e = fwpslot 12 5 4
+if ne e 0
+ret e
+end
+i = fwpfind 13
+if eq i BDNONE
+ret fwpmiss 13 5
+end
+put fwpdo 0 get bdpo i
+ret 0
+end
+note "fwprep FAILED <what> <path in fwpp>: <strerror e>" on stdout
+fn fwpfail k ulong e ulong to ulong
+fwpos 1
+fwpos 28
+fwpos k
+fwppath
+fwpos 32
+fwoerrno e
+fwoc 10
+ret 3
+end
+note write bdpl[o..o+n) to OUTDIR/segment k: 0 or a positive errno (5 for a zero-byte write)
+fn fwpwf k ulong o ulong n ulong to ulong
+fwpmk k
+fd = fopen fwpp 0 get fwppn 0 524865 420
+if lt fd 0
+ret ulong neg fd
+end
+q = ulong 0
+while lt q n bound 999999
+r = write int fd bdpl add o q sub n q
+if lt r 1
+c = fclose int fd
+if lt r 0
+ret ulong neg r
+end
+ret 5
+end
+q = add q ulong r
+end
+c = fclose int fd
+if lt c 0
+ret ulong neg c
+end
+ret 0
+end
+note write output slot o as segment k and print its line; 0 or 3
+fn fwpput o ulong k ulong to ulong
+e = fwpwf k get fwpoo o get fwpon o
+if ne e 0
+ret fwpfail 30 e
+end
+bdsh256 get fwpoo o get fwpon o
+shhex 32
+for i ulong 64
+put fwpoh add mul o 64 i get shhx i
+end
+fwpos 1
+fwpos 24
+fwpos k
+fwpos 25
+fwodec get fwpon o
+fwpos 26
+fwohx 32
+fwoc 10
+ret 0
+end
+fn fwpohx o ulong to void
+for i ulong 64
+fwoc get fwpoh add mul o 64 i
+end
+end
+note little-endian u32 word w of the boot UCODE_DESC_PROD plain bytes
+fn fwpw32 w ulong to ulong
+p = add get fwpdo 0 mul w 4
+v = ulong 0
+for k ulong 4
+v = or v shl ulong get bdpl add p k mul k 8
+end
+ret v
+end
+note manifest lines 1..6: the firmware and the two bindata inputs
+fn fwpman1 to void
+fwpos 33
+fwoc 10
+fwpos 34
+for i ulong get fwvern 0
+fwoc get fwver i
+end
+fwoc 10
+fwpos 35
+for i ulong get fwbidn 0
+fwoc get fwbidh i
+end
+fwoc 10
+fwpos 36
+fwodec get fwlen 0
+fwpos 26
+for i ulong 64
+fwoc get fwhxf i
+end
+fwoc 10
+fwpos 37
+fwodec get fwsof get fwimx 0
+fwpos 38
+fwodec get fwssz get fwimx 0
+fwpos 26
+for i ulong 64
+fwoc get fwhxi i
+end
+fwoc 10
+fwpos 39
+fwodec get fwsof get fwsx 0
+fwpos 38
+fwodec get fwssz get fwsx 0
+fwpos 26
+for i ulong 64
+fwoc get fwhxs i
+end
+fwoc 10
+for w ulong 2
+fwpos add 40 w
+fwpos add 4 w
+fwpos 25
+fwodec get fwpsz w
+fwpos 26
+for i ulong 64
+fwoc get fwpsh add mul w 64 i
+end
+fwoc 10
+end
+end
+note manifest: the descriptor words, the outputs, "end"
+fn fwpman2 to void
+fwpos 42
+for w ulong 21
+fwpos add 43 w
+fwodec fwpw32 w
+end
+fwoc 10
+for o ulong 5
+fwpos 64
+fwpos add 14 o
+fwpos 25
+fwodec get fwpon o
+fwpos 26
+fwpohx o
+fwoc 10
+end
+fwpos 65
+fwoc 10
+end
+note write fw.manifest.tmp through the fw.om writer, then rename it to fw.manifest; 0 or 3
+fn fwpman to ulong
+z = fwoflush
+oe = get fwoerr 0
+fwpmk 20
+fd = fopen fwpp 0 get fwppn 0 524865 420
+if lt fd 0
+ret fwpfail 30 ulong neg fd
+end
+put fwofd 0 int fd
+put fwoerr 0 0
+fwpman1
+fwpman2
+z = fwoflush
+we = get fwoerr 0
+put fwofd 0 1
+put fwoerr 0 oe
+c = fclose int fd
+if eq we 1
+ret fwpfail 30 5
+end
+if lt c 0
+ret fwpfail 30 ulong neg c
+end
+ret fwpren
+end
+note rename fw.manifest.tmp to fw.manifest (renameat2 packed list: u16 count, then u16 len + bytes)
+fn fwpren to ulong
+put fwprn 0 2
+put fwprn 1 0
+n = ulong 2
+for s ulong 2
+fwpmk sub 20 s
+l = get fwppn 0
+put fwprn n uchar rem l 256
+put fwprn add n 1 uchar div l 256
+n = add n 2
+for i ulong l
+put fwprn add n i get fwpp i
+end
+n = add n l
+end
+r = renames fwprn 0 n 0
+if lt r 0
+ret fwpfail 31 ulong neg r
+end
+fwpos 1
+fwpos 24
+fwpos 19
+fwoc 10
+ret 0
+end
+note make OUTDIR (an existing one is fine) and write every output, the manifest last
+fn fwpwrite to ulong
+r = makedir fwpout 0 get fwpoutn 0 493
+if lt r 0
+if ne r -17
+for i ulong get fwpoutn 0
+put fwpp i get fwpout i
+end
+put fwppn 0 get fwpoutn 0
+ret fwpfail 29 ulong neg r
+end
+end
+for o ulong 5
+e = fwpput o add 14 o
+if ne e 0
+ret e
+end
+end
+ret fwpman
+end
+fn fwprun to ulong
+e = fwpfw
+if eq e 2
+fwpos 1
+fwpos 68
+fwoc 10
+end
+if ne e 0
+ret e
+end
+e = fwpfmc
+if ne e 0
+ret e
+end
+e = fwpboot
+if ne e 0
+ret e
+end
+e = fwpwrite
+if ne e 0
+ret e
+end
+fwpos 1
+fwpos 27
+fwoc 10
+ret 0
+end
+fn main to int
+fwsetup
+bdsetup
+fwpsetup
+if ne fwpargs 0
+fwperr 2 0 0
+ret 1
+end
+fwpmk 19
+u = unlink fwpp 0 get fwppn 0
+e = fwprun
+z = fwoflush
+if and eq e 0 eq get fwoerr 0 1
+ret 3
+end
+ret int e
+end
diff --git a/gsp/bindata.om b/gsp/bindata.om
new file mode 100644
index 0000000..986331f
--- /dev/null
+++ b/gsp/bindata.om
@@ -0,0 +1,1526 @@
+note gsp/bindata.om: the NVIDIA generated bindata reader in seeded Omega (OM-1). Ports the extract path
+note of aienux PR #441 native/kernel/tools/ck_gsp_bindata_extract.c: refuse, next_line, after,
+note parse_u32, copy_field, parse_hex_array, parse_pvt, parse_archive, parse_file, find_label,
+note decode_desc, region_ok, check_semantics, report (stdout lines; no --out writing) and the read
+note step of cmd_extract. Every refusal text is the C's, "line N: " prefix included.
+note Library unit: no main. Prefix bd. Needs gsp/sha2.om, gsp/inflate.om and gsp/fw.om first
+note (SHA-256/384, DEFLATE + CRC-32 + ISIZE, and the fwo* stdout writer).
+note The text is read through a 1 MiB pread window (the C reads the whole file, at most 64 MiB, first;
+note this port hashes the whole file first, so a read failure is still reported before any parse).
+note Deviations (documented): arrays live in two 16 MiB pools, bdraw for compressed arrays as stored and
+note bdpl for plain bytes (uncompressed arrays are parsed straight into bdpl). Running out of a pool is
+note the C's own "out of memory for LABEL" refusal; the C would malloc up to MAX_ARRAY per array and
+note DATA SIZE per inflated array. A directory path is refused as "File too large", the text the C
+note prints on this host (glibc ftell on a directory).
+const BDMAXB ulong 16
+const BDPOOL ulong 16777216
+const BDMAXA ulong 8388608
+const BDNONE ulong 999
+const BDUNS ulong 4294967295
+const BDWIN ulong 1048576
+global bdok ulong 1
+global bdsgb ulong 160
+global bdsgl ulong 160
+global bdpath uchar 4096
+global bdpathn ulong 1
+global bdfd int 1
+global bdst uchar 128
+global bdfsz ulong 1
+global bdfpos ulong 1
+global bdtp ulong 1
+global bdte ulong 1
+global bdtx uchar 1048576
+global bdln uchar 520
+global bdll ulong 1
+global bdlno ulong 1
+global bdrs uchar 256
+global bdrsn ulong 1
+global bdn ulong 1
+global bdarc ulong 1
+global bdcmp ulong 16
+global bdds ulong 16
+global bdcs ulong 16
+global bdhh ulong 16
+global bdhd ulong 16
+global bdhp ulong 16
+global bdnb ulong 16
+global bdbo ulong 16
+global bdpo ulong 16
+global bdpn ulong 16
+global bdfn uchar 1536
+global bdfnl ulong 16
+global bdlb uchar 1024
+global bdlbl ulong 16
+global bdfm uchar 2560
+global bdfml ulong 16
+global bdid uchar 3072
+global bdidl ulong 16
+global bdraw uchar 16777216
+global bdrtop ulong 1
+global bdpl uchar 16777216
+global bdptop ulong 1
+global bdimg uchar 64
+global bdimgn ulong 1
+global bdfsh uchar 64
+note segment k of BDTXT is the text between the k-th and (k+1)-th '|': 1..76 refusal pieces in C
+note wording, 77..114 the C's line prefixes and tokens, 115.. report pieces
+text BDTXT "|line |: |line longer than 511 characters|array size out of range for |expected '{' after the array declaration of |out of memory for |file ends inside the array of |non-hex token in the array of |byte token without a trailing comma in |more bytes than the declared size in |fewer bytes than the declared size in |expected '{' in the storage record of |storage record: bad uncompressed size for |storage record: uncompressed size differs from DATA SIZE for |storage record: bad compressed size for |storage record: compressed size differs from the header for |storage record: missing pointer line for |storage record: data pointer is not the array of |storage record: missing compressed flag for |storage record: bad compressed flag for |storage record: compressed flag disagrees with COMPRESSION for |second archive table|archive table name is not the file's function|expected '{' after the archive declaration|archive: bad entryNum|archive: entryNum differs from the number of arrays|archive: expected entries block|archive: expected the entries comment|archive: missing entry |archive: malformed entry for |archive: entry order or label differs from the arrays at |archive: entry without a storage index for |archive: storage index is not this array for |archive: expected end of entries|archive: expected end of table|array | has no data or no storage record|more than 16 arrays|FUNCTION line without a BINDATA_LABEL|FUNCTION line not terminated|bad function name|bad label|array belongs to a different function: |duplicate label |function is not a kgspGetBinArchive function: |identifier too long for |data before the first FUNCTION header|bad file name for |FILE TYPE is not BINARY for |COMPRESSION is neither YES nor NO for |COMPLEX_STRUCT is not NO for |bad DATA SIZE for |bad COMPRESSED SIZE for |second array for |array header incomplete for |COMPRESSED SIZE missing with COMPRESSION YES for |COMPRESSED SIZE given with COMPRESSION NO for |array identifier is not the expected one for |storage record before the array of |second storage record for |no arrays found|no archive table|descriptor is not 84 bytes: |descriptor version is not 5: |descriptor monitor not enabled: |descriptor without a matching image: |descriptor manifest region outside the image or unaligned: |descriptor monitor-data region outside the image or unaligned: |descriptor monitor-code region outside the image or unaligned: |hash array is not 48 bytes|hash array without UCODE_IMAGE|UCODE_HASH is not SHA-384 of UCODE_IMAGE| is not 384 bytes|unknown label | (|)|// FUNCTION: |(\"BINDATA_LABEL_|\")|kgspGetBinArchive|kgspBinArchive|_BINDATA_LABEL_|_data|// FILE NAME: |// FILE TYPE: |BINARY|// COMPRESSION: |YES|NO|// COMPLEX_STRUCT: |// DATA SIZE (bytes): |// COMPRESSED SIZE (bytes): |N/A|static BINDATA_CONST NvU8 |[] = |#if defined(BINDATA_INCLUDE_STORAGE_PVT_DEFN)|static const BINDATA_ARCHIVE __|static BINDATA_CONST|static const BINDATA_ARCHIVE|{|};|NV_TRUE,|NV_FALSE,| =|// entries[]|{ BINDATA_LABEL_|&g_bindata_pvt[__idx_|}|UCODE_DESC|UCODE_IMAGE|UCODE_HASH|UCODE_SIG|UCODE_PKEY|//|function | arrays=|desc | version=| manifest=0x|+0x| monitor_data=0x| monitor_code=0x| monitor_enabled=| fb_reserved=0x| signed_as_code=| app_version=| image=|/|hash384 UCODE_HASH equals sha384(UCODE_IMAGE)| file=| stored=| compressed=|yes|no| size=| sha256=|RESULT OK arrays=|REFUSED: |REFUSED: cannot read | |"
+note build the segment table and reset the pools (call once per program)
+fn bdsetup to void
+if eq get bdok 0 1
+ret
+end
+put bdok 0 1
+fwsetup
+infsetup
+seg = ulong 0
+for i ulong len BDTXT
+c = get BDTXT i
+if eq c 124
+seg = add seg 1
+put bdsgb seg add i 1
+put bdsgl seg 0
+else
+put bdsgl seg add get bdsgl seg 1
+end
+end
+put bdrtop 0 0
+put bdptop 0 0
+end
+note ---- printing through the fw.om writer ----
+fn bdos k ulong to void
+b = get bdsgb k
+for i ulong get bdsgl k
+fwoc get BDTXT add b i
+end
+end
+fn bdolab i ulong to void
+b = mul i 64
+for j ulong get bdlbl i
+fwoc get bdlb add b j
+end
+end
+fn bdofn i ulong to void
+b = mul i 96
+for j ulong get bdfnl i
+fwoc get bdfn add b j
+end
+end
+fn bdofm i ulong to void
+b = mul i 160
+for j ulong get bdfml i
+fwoc get bdfm add b j
+end
+end
+fn bdopath to void
+for i ulong get bdpathn 0
+fwoc get bdpath i
+end
+end
+note ---- the refusal reason (C f->reason, 256 bytes: at most 255 characters kept) ----
+fn bdrc c uchar to void
+n = get bdrsn 0
+if lt n 255
+put bdrs n c
+put bdrsn 0 add n 1
+end
+end
+fn bdrseg k ulong to void
+b = get bdsgb k
+for i ulong get bdsgl k
+bdrc get BDTXT add b i
+end
+end
+fn bdrlab i ulong to void
+b = mul i 64
+for j ulong get bdlbl i
+bdrc get bdlb add b j
+end
+end
+fn bdrfn i ulong to void
+b = mul i 96
+for j ulong get bdfnl i
+bdrc get bdfn add b j
+end
+end
+note "line N: " (C refuse: N is the cursor's line count, 0 when the cursor is NULL)
+fn bdrhd ln ulong to void
+put bdrsn 0 0
+bdrseg 1
+d = new uchar 24 0
+n = ulong 0
+x = ln
+while lt n 24 bound 24
+put d n add uchar rem x 10 48
+n = add n 1
+x = div x 10
+if eq x 0
+break
+end
+end
+while gt n 0 bound 24
+n = sub n 1
+bdrc get d n
+end
+bdrseg 2
+end
+note refuse at the current line with reason k, then the label of block b unless b is BDNONE
+fn bdrl k ulong b ulong to ulong
+bdrhd get bdlno 0
+bdrseg k
+if ne b BDNONE
+bdrlab b
+end
+ret 2
+end
+note refuse at the current line with reason k and the function name of block b
+fn bdrf k ulong b ulong to ulong
+bdrhd get bdlno 0
+bdrseg k
+bdrfn b
+ret 2
+end
+note refuse with line 0 (semantic checks) with reason k, then the label of b unless BDNONE
+fn bdr0 k ulong b ulong to ulong
+bdrhd 0
+bdrseg k
+if ne b BDNONE
+bdrlab b
+end
+ret 2
+end
+note "array LABEL has no data or no storage record" at the current line
+fn bdrnd b ulong to ulong
+bdrhd get bdlno 0
+bdrseg 36
+bdrlab b
+bdrseg 37
+ret 2
+end
+note ---- the text window and C next_line ----
+note keep at least 512 unread bytes in bdtx unless the file is used up: 0, or 3 on a read error
+fn bdfill to ulong
+tp = get bdtp 0
+av = sub get bdte 0 tp
+if ge av 512
+ret 0
+end
+fp = get bdfpos 0
+if ge fp get bdfsz 0
+ret 0
+end
+for i ulong av
+put bdtx i get bdtx add tp i
+end
+put bdtp 0 0
+put bdte 0 av
+w = sub BDWIN av
+lf = sub get bdfsz 0 fp
+if lt lf w
+w = lf
+end
+q = ulong 0
+while lt q w bound 999999
+r = pread get bdfd 0 bdtx add av q sub w q long add fp q
+if lt r 1
+ret 3
+end
+q = add q ulong r
+end
+put bdte 0 add av w
+put bdfpos 0 add fp w
+ret 0
+end
+note C next_line into bdln[0..bdll): 1 = a line, 0 = end of text, 2 = longer than 511 characters
+note (reason set, line count advanced), 3 = read error. A trailing CR is dropped and the line ends
+note at its first NUL (the C's string view of its buffer).
+fn bdnext to ulong
+e = bdfill
+if ne e 0
+ret 3
+end
+tp = get bdtp 0
+te = get bdte 0
+if ge tp te
+ret 0
+end
+lim = add tp 512
+if gt lim te
+lim = te
+end
+j = tp
+nl = ulong 0
+while lt j lim bound 600
+if eq get bdtx j 10
+nl = 1
+break
+end
+j = add j 1
+end
+put bdlno 0 add get bdlno 0 1
+n = sub j tp
+if ge n 512
+bdrhd get bdlno 0
+bdrseg 3
+ret 2
+end
+for i ulong n
+put bdln i get bdtx add tp i
+end
+if gt n 0
+if eq get bdln sub n 1 13
+n = sub n 1
+end
+end
+k = ulong 0
+while lt k n bound 600
+if eq get bdln k 0
+break
+end
+k = add k 1
+end
+put bdln k 0
+put bdll 0 k
+if eq nl 1
+put bdtp 0 add j 1
+else
+put bdtp 0 te
+end
+ret 1
+end
+note ---- string helpers over the line ----
+fn bdlc i ulong to uchar
+if ge i get bdll 0
+ret 0
+end
+ret get bdln i
+end
+note does the line at p start with segment k (C after / strncmp)?
+fn bdpre p ulong k ulong to ulong
+b = get bdsgb k
+l = get bdsgl k
+if gt add p l get bdll 0
+ret 0
+end
+for i ulong l
+if ne get bdln add p i get BDTXT add b i
+ret 0
+end
+end
+ret 1
+end
+note is the line from p to its end exactly segment k (C strcmp)?
+fn bdeqs p ulong k ulong to ulong
+L = get bdll 0
+if gt p L
+ret 0
+end
+if ne sub L p get bdsgl k
+ret 0
+end
+ret bdpre p k
+end
+note C strspn(line + p, " ")
+fn bdsp p ulong to ulong
+q = p
+L = get bdll 0
+while lt q L bound 600
+if ne get bdln q 32
+break
+end
+q = add q 1
+end
+ret q
+end
+note first position at or after p where segment k occurs (C strstr), BDNONE if none
+fn bdfind p ulong k ulong to ulong
+q = p
+L = get bdll 0
+while le q L bound 600
+if eq bdpre q k 1
+ret q
+end
+q = add q 1
+end
+ret BDNONE
+end
+note first '(' at or after p (C strchr), BDNONE if none
+fn bdfpar p ulong to ulong
+q = p
+L = get bdll 0
+while lt q L bound 600
+if eq get bdln q 40
+ret q
+end
+q = add q 1
+end
+ret BDNONE
+end
+note C parse_u32 at p: decimal at most 4294967295, then spaces, commas or tabs, then the end or "//"
+fn bdu32 p ulong to long
+c = bdlc p
+if lt c 48
+ret -1
+end
+if gt c 57
+ret -1
+end
+acc = ulong 0
+q = p
+while lt q get bdll 0 bound 600
+c = get bdln q
+if lt c 48
+break
+end
+if gt c 57
+break
+end
+acc = add mul acc 10 sub ulong c 48
+if gt acc BDUNS
+ret -1
+end
+q = add q 1
+end
+while lt q get bdll 0 bound 600
+c = get bdln q
+if and and ne c 32 ne c 44 ne c 9
+break
+end
+q = add q 1
+end
+if lt q get bdll 0
+if eq bdpre q 114 0
+ret -1
+end
+end
+ret long acc
+end
+note does the line at p hold the first n characters of block i's identifier?
+fn bdlnid p ulong i ulong n ulong to ulong
+if gt add p n get bdll 0
+ret 0
+end
+b = mul i 192
+for j ulong n
+if ne get bdln add p j get bdid add b j
+ret 0
+end
+end
+ret 1
+end
+note does the line at p start with block i's label?
+fn bdlnlb p ulong i ulong to ulong
+n = get bdlbl i
+if gt add p n get bdll 0
+ret 0
+end
+b = mul i 64
+for j ulong n
+if ne get bdln add p j get bdlb add b j
+ret 0
+end
+end
+ret 1
+end
+note does the line at p start with block i's function name?
+fn bdlnfn p ulong i ulong to ulong
+n = get bdfnl i
+if gt add p n get bdll 0
+ret 0
+end
+b = mul i 96
+for j ulong n
+if ne get bdln add p j get bdfn add b j
+ret 0
+end
+end
+ret 1
+end
+note labels of blocks i and j equal?
+fn bdlbeq i ulong j ulong to ulong
+n = get bdlbl i
+if ne n get bdlbl j
+ret 0
+end
+a = mul i 64
+b = mul j 64
+for k ulong n
+if ne get bdlb add a k get bdlb add b k
+ret 0
+end
+end
+ret 1
+end
+note function names of blocks i and j equal?
+fn bdfneq i ulong j ulong to ulong
+n = get bdfnl i
+if ne n get bdfnl j
+ret 0
+end
+a = mul i 96
+b = mul j 96
+for k ulong n
+if ne get bdfn add a k get bdfn add b k
+ret 0
+end
+end
+ret 1
+end
+note label of block i starts with segment k (sw 0) or equals it (sw 1)?
+fn bdlbsg i ulong k ulong sw ulong to ulong
+n = get bdlbl i
+l = get bdsgl k
+if lt n l
+ret 0
+end
+if eq sw 1
+if ne n l
+ret 0
+end
+end
+a = mul i 64
+b = get bdsgb k
+for j ulong l
+if ne get bdlb add a j get BDTXT add b j
+ret 0
+end
+end
+ret 1
+end
+note function name of block i starts with segment k?
+fn bdfnsg i ulong k ulong to ulong
+n = get bdfnl i
+l = get bdsgl k
+if lt n l
+ret 0
+end
+a = mul i 96
+b = get bdsgb k
+for j ulong l
+if ne get bdfn add a j get BDTXT add b j
+ret 0
+end
+end
+ret 1
+end
+note C find_label for the name in bdimg[0..bdimgn): block index or BDNONE
+fn bdfimg to ulong
+for i ulong get bdn 0
+n = get bdlbl i
+if eq n get bdimgn 0
+a = mul i 64
+m = ulong 1
+for j ulong n
+if ne get bdlb add a j get bdimg j
+m = 0
+end
+end
+if eq m 1
+ret i
+end
+end
+end
+ret BDNONE
+end
+note C find_label for segment k: block index or BDNONE
+fn bdfseg k ulong to ulong
+for i ulong get bdn 0
+if eq bdlbsg i k 1 1
+ret i
+end
+end
+ret BDNONE
+end
+note ---- C copy_field into the block's fields (len checked by the caller) ----
+fn bdsetfn i ulong p ulong n ulong to void
+b = mul i 96
+for j ulong n
+put bdfn add b j get bdln add p j
+end
+put bdfnl i n
+end
+fn bdsetlb i ulong p ulong n ulong to void
+b = mul i 64
+for j ulong n
+put bdlb add b j get bdln add p j
+end
+put bdlbl i n
+end
+fn bdsetfm i ulong p ulong n ulong to void
+b = mul i 160
+for j ulong n
+put bdfm add b j get bdln add p j
+end
+put bdfml i n
+end
+note append segment k to block i's identifier at q; returns the new end
+fn bdidsg i ulong q ulong k ulong to ulong
+b = mul i 192
+s = get bdsgb k
+for j ulong get bdsgl k
+put bdid add b add q j get BDTXT add s j
+end
+ret add q get bdsgl k
+end
+note identifier kgspBinArchive<stem>_BINDATA_LABEL_<label>_data (caller checked its length)
+fn bdmkid i ulong to void
+b = mul i 192
+q = bdidsg i 0 81
+fb = mul i 96
+note stem = function name after "kgspGetBinArchive" (17 characters)
+for j ulong sub get bdfnl i 17
+put bdid add b q get bdfn add add fb 17 j
+q = add q 1
+end
+q = bdidsg i q 82
+lb = mul i 64
+for j ulong get bdlbl i
+put bdid add b q get bdlb add lb j
+q = add q 1
+end
+q = bdidsg i q 83
+put bdidl i q
+end
+note ---- C parse_file: one "// FUNCTION: " line ----
+fn bdfunc to ulong
+n = get bdn 0
+if gt n 0
+b = sub n 1
+if eq and eq get bdhd b 1 eq get bdhp b 1 false
+ret bdrnd b
+end
+end
+if ge n BDMAXB
+ret bdrl 38 BDNONE
+end
+v = get bdsgl 77
+lp = bdfpar v
+if eq lp BDNONE
+ret bdrl 39 BDNONE
+end
+if eq bdpre lp 78 0
+ret bdrl 39 BDNONE
+end
+pe = bdfind add lp 16 79
+if eq pe BDNONE
+ret bdrl 40 BDNONE
+end
+if ne add pe 2 get bdll 0
+ret bdrl 40 BDNONE
+end
+put bdn 0 add n 1
+fl = sub lp v
+if or eq fl 0 ge fl 96
+ret bdrl 41 BDNONE
+end
+bdsetfn n v fl
+ll = sub sub pe lp 16
+if or eq ll 0 ge ll 64
+ret bdrl 42 BDNONE
+end
+bdsetlb n add lp 16 ll
+ret bdfunc2 n
+end
+note the rest of the FUNCTION header: same function, unique label, stem, identifier
+fn bdfunc2 n ulong to ulong
+if gt n 0
+if eq bdfneq 0 n 0
+ret bdrf 43 n
+end
+end
+for j ulong n
+if eq bdlbeq j n 1
+ret bdrl 44 n
+end
+end
+put bdcs n BDUNS
+put bdcmp n 2
+put bdds n 0
+put bdhh n 0
+put bdhd n 0
+put bdhp n 0
+put bdnb n 0
+put bdfml n 0
+if eq bdfnsg n 80 0
+ret bdrf 45 n
+end
+note 14 + (funclen - 17) + 15 + labellen + 5 characters must stay below 192
+t = add sub get bdfnl n 17 34
+t = add t get bdlbl n
+if ge t 192
+ret bdrl 46 n
+end
+bdmkid n
+ret 0
+end
+note "static BINDATA_CONST NvU8 " line of block b
+fn bdarrhd b ulong to ulong
+if eq get bdhd b 1
+ret bdrl 54 b
+end
+c = get bdcmp b
+m = ulong 0
+if eq c 2
+m = 1
+end
+if eq get bdds b 0
+m = 1
+end
+if eq get bdcs b BDUNS
+m = 1
+end
+if eq get bdfml b 0
+m = 1
+end
+if eq m 1
+ret bdrl 55 b
+end
+if and eq c 1 eq get bdcs b 0
+ret bdrl 56 b
+end
+if and eq c 0 ne get bdcs b 0
+ret bdrl 57 b
+end
+v = get bdsgl 94
+il = get bdidl b
+if eq bdlnid v b il 0
+ret bdrl 58 b
+end
+if eq bdeqs add v il 95 0
+ret bdrl 58 b
+end
+put bdhh b 1
+ret bdhex b
+end
+fn bdhexd c uchar to ulong
+if and ge c 48 le c 57
+ret sub ulong c 48
+end
+if and ge c 97 le c 102
+ret sub ulong c 87
+end
+if and ge c 65 le c 70
+ret sub ulong c 55
+end
+ret 16
+end
+note C parse_hex_array: the "{" line, the byte lines, "};"
+fn bdhex b ulong to ulong
+want = get bdds b
+if eq get bdcmp b 1
+want = get bdcs b
+end
+if or eq want 0 gt want BDMAXA
+ret bdrl 4 b
+end
+r = bdnext
+if eq r 3
+ret 3
+end
+if ne r 1
+ret bdrl 5 b
+end
+if eq bdeqs 0 100 0
+ret bdrl 5 b
+end
+if eq get bdcmp b 1
+t = get bdrtop 0
+if gt add t want BDPOOL
+ret bdrl 6 b
+end
+put bdbo b t
+put bdrtop 0 add t want
+else
+t = get bdptop 0
+if gt add t want BDPOOL
+ret bdrl 6 b
+end
+put bdbo b t
+put bdpo b t
+put bdpn b want
+put bdptop 0 add t want
+end
+put bdnb b 0
+go = ulong 1
+while eq go 1 bound 100
+while eq go 1 bound 999999
+r = bdnext
+if eq r 3
+ret 3
+end
+if eq r 2
+ret 2
+end
+if eq r 0
+ret bdrl 7 b
+end
+if eq bdeqs 0 101 1
+go = 0
+else
+e = bdhexln b want
+if ne e 0
+ret e
+end
+end
+end
+end
+if ne get bdnb b want
+ret bdrl 11 b
+end
+put bdhd b 1
+ret 0
+end
+note one line of "0xHH," tokens of block b
+fn bdhexln b ulong want ulong to ulong
+p = ulong 0
+L = get bdll 0
+cm = get bdcmp b
+base = get bdbo b
+while lt p L bound 600
+while lt p L bound 600
+c = get bdln p
+if and ne c 32 ne c 9
+break
+end
+p = add p 1
+end
+if ge p L
+break
+end
+if ne bdlc p 48
+ret bdrl 8 b
+end
+if ne bdlc add p 1 120
+ret bdrl 8 b
+end
+h = bdhexd bdlc add p 2
+if eq h 16
+ret bdrl 8 b
+end
+l = bdhexd bdlc add p 3
+if eq l 16
+ret bdrl 8 b
+end
+if ne bdlc add p 4 44
+ret bdrl 9 b
+end
+nb = get bdnb b
+if ge nb want
+ret bdrl 10 b
+end
+v = uchar add mul h 16 l
+if eq cm 1
+put bdraw add base nb v
+else
+put bdpl add base nb v
+end
+put bdnb b add nb 1
+p = add p 5
+end
+ret 0
+end
+note C parse_pvt: the storage record after "#if defined(BINDATA_INCLUDE_STORAGE_PVT_DEFN)"
+fn bdpvt b ulong to ulong
+r = bdnext
+if eq r 3
+ret 3
+end
+if ne r 1
+ret bdrl 12 b
+end
+if eq bdeqs 0 100 0
+ret bdrl 12 b
+end
+r = bdnext
+if eq r 3
+ret 3
+end
+if ne r 1
+ret bdrl 13 b
+end
+v = bdu32 bdsp 0
+if lt v 0
+ret bdrl 13 b
+end
+if ne ulong v get bdds b
+ret bdrl 14 b
+end
+r = bdnext
+if eq r 3
+ret 3
+end
+if ne r 1
+ret bdrl 15 b
+end
+v = bdu32 bdsp 0
+if lt v 0
+ret bdrl 15 b
+end
+w = get bdds b
+if eq get bdcmp b 1
+w = get bdcs b
+end
+if ne ulong v w
+ret bdrl 16 b
+end
+ret bdpvt2 b
+end
+note the pointer and flag lines of the storage record
+fn bdpvt2 b ulong to ulong
+r = bdnext
+if eq r 3
+ret 3
+end
+if ne r 1
+ret bdrl 17 b
+end
+p = bdsp 0
+il = get bdidl b
+if eq bdlnid p b il 0
+ret bdrl 18 b
+end
+if ne bdlc add p il 44
+ret bdrl 18 b
+end
+r = bdnext
+if eq r 3
+ret 3
+end
+if ne r 1
+ret bdrl 19 b
+end
+p = bdsp 0
+fl = ulong 2
+if eq bdpre p 102 1
+fl = 1
+else
+if eq bdpre p 103 1
+fl = 0
+end
+end
+if eq fl 2
+ret bdrl 20 b
+end
+if ne fl get bdcmp b
+ret bdrl 21 b
+end
+put bdhp b 1
+ret 0
+end
+note C parse_archive (the declaration is the current line)
+fn bdarch to ulong
+if eq get bdarc 0 1
+ret bdrl 22 BDNONE
+end
+p = get bdsgl 97
+if eq bdlnfn p 0 0
+ret bdrl 23 BDNONE
+end
+if eq bdeqs add p get bdfnl 0 104 0
+ret bdrl 23 BDNONE
+end
+r = bdnext
+if eq r 3
+ret 3
+end
+if ne r 1
+ret bdrl 24 BDNONE
+end
+if eq bdeqs 0 100 0
+ret bdrl 24 BDNONE
+end
+r = bdnext
+if eq r 3
+ret 3
+end
+if ne r 1
+ret bdrl 25 BDNONE
+end
+v = bdu32 bdsp 0
+if lt v 0
+ret bdrl 25 BDNONE
+end
+if ne ulong v get bdn 0
+ret bdrl 26 BDNONE
+end
+ret bdarch2
+end
+note the entries block of the archive table
+fn bdarch2 to ulong
+r = bdnext
+if eq r 3
+ret 3
+end
+if ne r 1
+ret bdrl 27 BDNONE
+end
+if eq bdeqs bdsp 0 100 0
+ret bdrl 27 BDNONE
+end
+r = bdnext
+if eq r 3
+ret 3
+end
+if ne r 1
+ret bdrl 28 BDNONE
+end
+if eq bdpre bdsp 0 105 0
+ret bdrl 28 BDNONE
+end
+for i ulong get bdn 0
+e = bdarent i
+if ne e 0
+ret e
+end
+end
+r = bdnext
+if eq r 3
+ret 3
+end
+if ne r 1
+ret bdrl 34 BDNONE
+end
+if eq bdeqs bdsp 0 108 0
+ret bdrl 34 BDNONE
+end
+r = bdnext
+if eq r 3
+ret 3
+end
+if ne r 1
+ret bdrl 35 BDNONE
+end
+if eq bdeqs 0 101 0
+ret bdrl 35 BDNONE
+end
+put bdarc 0 1
+ret 0
+end
+note one archive entry, for block i
+fn bdarent i ulong to ulong
+r = bdnext
+if eq r 3
+ret 3
+end
+if ne r 1
+ret bdrl 29 i
+end
+p = bdsp 0
+if eq bdpre p 106 0
+ret bdrl 30 i
+end
+lab = add p get bdsgl 106
+if eq bdlnlb lab i 0
+ret bdrl 31 i
+end
+c = bdlc add lab get bdlbl i
+if and ne c 32 ne c 44
+ret bdrl 31 i
+end
+x = bdfind lab 107
+if eq x BDNONE
+ret bdrl 32 i
+end
+x = add x get bdsgl 107
+il = sub get bdidl i 5
+if eq bdlnid x i il 0
+ret bdrl 33 i
+end
+if ne bdlc add x il 93
+ret bdrl 33 i
+end
+ret 0
+end
+note C parse_file: one line after the FUNCTION check (b = current block)
+fn bdline to ulong
+if eq bdpre 0 77 1
+ret bdfunc
+end
+n = get bdn 0
+if eq n 0
+if or eq bdpre 0 98 1 eq bdpre 0 99 1
+ret bdrl 47 BDNONE
+end
+ret 0
+end
+b = sub n 1
+if eq bdpre 0 84 1
+v = get bdsgl 84
+l = sub get bdll 0 v
+if or eq l 0 ge l 160
+ret bdrl 48 b
+end
+bdsetfm b v l
+ret 0
+end
+if eq bdpre 0 85 1
+if eq bdeqs get bdsgl 85 86 0
+ret bdrl 49 b
+end
+ret 0
+end
+if eq bdpre 0 87 1
+v = get bdsgl 87
+if eq bdeqs v 88 1
+put bdcmp b 1
+else
+if eq bdeqs v 89 1
+put bdcmp b 0
+else
+ret bdrl 50 b
+end
+end
+ret 0
+end
+ret bdline2 b
+end
+note the remaining header comments and the three record kinds
+fn bdline2 b ulong to ulong
+if eq bdpre 0 90 1
+if eq bdeqs get bdsgl 90 89 0
+ret bdrl 51 b
+end
+ret 0
+end
+if eq bdpre 0 91 1
+x = bdu32 get bdsgl 91
+if lt x 0
+ret bdrl 52 b
+end
+put bdds b ulong x
+ret 0
+end
+if eq bdpre 0 92 1
+v = get bdsgl 92
+if eq bdeqs v 93 1
+put bdcs b 0
+else
+x = bdu32 v
+if lt x 0
+ret bdrl 53 b
+end
+put bdcs b ulong x
+end
+ret 0
+end
+if eq bdpre 0 94 1
+ret bdarrhd b
+end
+if eq bdeqs 0 96 1
+if eq get bdhd b 0
+ret bdrl 59 b
+end
+if eq get bdhp b 1
+ret bdrl 60 b
+end
+ret bdpvt b
+end
+if eq bdpre 0 97 1
+if eq and eq get bdhd b 1 eq get bdhp b 1 false
+ret bdrnd b
+end
+ret bdarch
+end
+ret 0
+end
+note copy bdraw[o..o+n) to infin[0..n), n <= 8 MiB, in chunks below the 1,000,000-pass limit
+fn bdcpin o ulong n ulong to void
+p = ulong 0
+while lt p n bound 64
+k = sub n p
+if gt k 524288
+k = 524288
+end
+for j ulong k
+put infin add p j get bdraw add add o p j
+end
+p = add p k
+end
+end
+note copy infout[0..n) to bdpl[o..o+n)
+fn bdcpout o ulong n ulong to void
+p = ulong 0
+while lt p n bound 64
+k = sub n p
+if gt k 524288
+k = 524288
+end
+for j ulong k
+put bdpl add add o p j get infout add p j
+end
+p = add p k
+end
+end
+note inflate block i (C unpack_gz_body) into the plain pool
+fn bdunpk i ulong to ulong
+ds = get bdds i
+t = get bdptop 0
+if gt add t ds BDPOOL
+ret bdrl 6 i
+end
+nb = get bdnb i
+bdcpin get bdbo i nb
+e = infgz nb ds
+if ne e 0
+infmsg e
+bdrhd 0
+for j ulong get infmn 0
+bdrc get infm j
+end
+bdrseg 75
+bdrlab i
+bdrseg 76
+ret 2
+end
+bdcpout t ds
+put bdpo i t
+put bdpn i ds
+put bdptop 0 add t ds
+ret 0
+end
+note C parse_file: the whole text, then the end checks and the inflation; 0, 2 refused, 3 read error
+fn bdparse to ulong
+put bdn 0 0
+put bdarc 0 0
+put bdlno 0 0
+put bdtp 0 0
+put bdte 0 0
+put bdfpos 0 0
+go = ulong 1
+while eq go 1 bound 100
+while eq go 1 bound 999999
+r = bdnext
+if eq r 3
+ret 3
+end
+if eq r 2
+ret 2
+end
+if eq r 0
+go = 0
+else
+e = bdline
+if ne e 0
+ret e
+end
+end
+end
+end
+if eq get bdn 0 0
+ret bdrl 61 BDNONE
+end
+if eq get bdarc 0 0
+ret bdrl 62 BDNONE
+end
+for i ulong get bdn 0
+if eq and eq get bdhd i 1 eq get bdhp i 1 false
+ret bdrnd i
+end
+if eq get bdcmp i 1
+e = bdunpk i
+if ne e 0
+ret e
+end
+end
+end
+ret 0
+end
+note ---- C check_semantics ----
+note little-endian u32 word w of block i's plain bytes
+fn bdw32 i ulong w ulong to ulong
+p = add get bdpo i mul w 4
+v = ulong 0
+for k ulong 4
+v = or v shl ulong get bdpl add p k mul k 8
+end
+ret v
+end
+note C region_ok: size != 0, off % 256 == 0, off + size <= image
+fn bdreg off ulong size ulong img ulong to ulong
+if eq size 0
+ret 0
+end
+if ne rem off 256 0
+ret 0
+end
+if gt add off size img
+ret 0
+end
+ret 1
+end
+note a UCODE_DESC* block
+fn bddesc i ulong to ulong
+if ne get bdpn i 84
+ret bdr0 63 i
+end
+if ne bdw32 i 0 5
+ret bdr0 64 i
+end
+if ne bdw32 i 14 1
+ret bdr0 65 i
+end
+note img = "UCODE_IMAGE" + label suffix after "UCODE_DESC", cut to 63 characters (C char img[64])
+n = ulong 0
+s = get bdsgb 110
+for j ulong get bdsgl 110
+put bdimg n get BDTXT add s j
+n = add n 1
+end
+a = mul i 64
+j = ulong 10
+while lt j get bdlbl i bound 64
+if lt n 63
+put bdimg n get bdlb add a j
+n = add n 1
+end
+j = add j 1
+end
+put bdimgn 0 n
+ib = bdfimg
+if eq ib BDNONE
+ret bdr0 66 i
+end
+ret bddesc2 i ib
+end
+note the three regions, then the desc line
+fn bddesc2 i ulong ib ulong to ulong
+il = get bdpn ib
+if eq bdreg bdw32 i 8 bdw32 i 9 il 0
+ret bdr0 67 i
+end
+if eq bdreg bdw32 i 10 bdw32 i 11 il 0
+ret bdr0 68 i
+end
+if eq bdreg bdw32 i 12 bdw32 i 13 il 0
+ret bdr0 69 i
+end
+bdos 117
+bdolab i
+bdos 118
+fwodec bdw32 i 0
+bdos 119
+fwohex bdw32 i 8
+bdos 120
+fwohex bdw32 i 9
+bdos 121
+fwohex bdw32 i 10
+bdos 120
+fwohex bdw32 i 11
+bdos 122
+fwohex bdw32 i 12
+bdos 120
+fwohex bdw32 i 13
+bdos 123
+fwodec bdw32 i 14
+bdos 124
+fwohex bdw32 i 19
+bdos 125
+fwodec bdw32 i 20
+bdos 126
+fwodec bdw32 i 7
+bdos 127
+for j ulong get bdimgn 0
+fwoc get bdimg j
+end
+bdos 128
+fwodec il
+fwoc 10
+ret 0
+end
+note SHA-384 of bdpl[o..o+n) into shout[0..48)
+fn bdsh384 o ulong n ulong to void
+sh5init
+p = ulong 0
+while lt p n bound 64
+k = sub n p
+if gt k SHWIN
+k = SHWIN
+end
+for j ulong k
+put shin j get bdpl add add o p j
+end
+sh5upd 0 k
+p = add p k
+end
+sh5fin
+end
+note SHA-256 (context 4) of bdpl[o..o+n) into shout[0..32)
+fn bdsh256 o ulong n ulong to void
+sh2init 4
+p = ulong 0
+while lt p n bound 64
+k = sub n p
+if gt k SHWIN
+k = SHWIN
+end
+for j ulong k
+put shin j get bdpl add add o p j
+end
+sh2upd 4 0 k
+p = add p k
+end
+sh2fin 4
+end
+note the UCODE_HASH block
+fn bdhash i ulong to ulong
+if ne get bdpn i 48
+ret bdr0 70 BDNONE
+end
+ib = bdfseg 110
+if eq ib BDNONE
+ret bdr0 71 BDNONE
+end
+bdsh384 get bdpo ib get bdpn ib
+o = get bdpo i
+for j ulong 48
+if ne get shout j get bdpl add o j
+ret bdr0 72 BDNONE
+end
+end
+bdos 129
+fwoc 10
+ret 0
+end
+fn bdsem to ulong
+for i ulong get bdn 0
+e = ulong 0
+if eq bdlbsg i 109 0 1
+e = bddesc i
+else
+if eq bdlbsg i 111 1 1
+e = bdhash i
+else
+if or eq bdlbsg i 112 1 1 eq bdlbsg i 113 1 1
+if ne get bdpn i 384
+bdrhd 0
+bdrlab i
+bdrseg 73
+e = 2
+end
+else
+if eq bdlbsg i 110 0 0
+e = bdr0 74 i
+end
+end
+end
+end
+if ne e 0
+ret e
+end
+end
+ret 0
+end
+note C report without --out: one array line per block
+fn bdreport to void
+for i ulong get bdn 0
+bdos 36
+bdofn i
+bdos 140
+bdolab i
+bdos 130
+bdofm i
+bdos 131
+fwodec get bdnb i
+bdos 132
+if eq get bdcmp i 1
+bdos 133
+else
+bdos 134
+end
+bdos 135
+fwodec get bdpn i
+bdos 136
+bdsh256 get bdpo i get bdpn i
+shhex 32
+fwohx 32
+fwoc 10
+end
+end
+note "REFUSED: cannot read PATH: <strerror e>"
+fn bdcantrd e ulong to ulong
+bdos 139
+bdopath
+fwos 64
+fwoerrno e
+fwoc 10
+ret 2
+end
+note C cmd_extract (no --out) for the path in bdpath[0..bdpathn). Prints the C's stdout bytes
+note through the fw.om writer. Returns 0 = RESULT OK, 2 = REFUSED. bdfsh gets the file's SHA-256
+note hex, bdfsz its size; the blocks stay in bd* for the caller (bdpl keeps the plain bytes across
+note calls: the pools are only reset by bdsetup).
+fn bdfile to ulong
+bdsetup
+fd = fopen bdpath 0 get bdpathn 0 524288 0
+if lt fd 0
+ret bdcantrd ulong neg fd
+end
+put bdfd 0 int fd
+s = fstat int fd bdst 0 128
+if lt s 0
+c = fclose int fd
+ret bdcantrd ulong neg s
+end
+sz = ulong 0
+for i ulong 8
+sz = or sz shl ulong get bdst add 48 i mul i 8
+end
+md = ulong 0
+for i ulong 4
+md = or md shl ulong get bdst add 16 i mul i 8
+end
+note S_IFMT 0170000 = 61440, S_IFDIR 0040000 = 16384; 64 MiB = 67108864 (the C's read_file limit)
+if or eq and md 61440 16384 gt sz 67108864
+c = fclose int fd
+ret bdcantrd 27
+end
+put bdfsz 0 sz
+sh2init 3
+r = sh2file 3 int fd 0 sz
+if ne r 0
+c = fclose int fd
+ret bdcantrd 5
+end
+sh2fin 3
+shhex 32
+for i ulong 64
+put bdfsh i get shhx i
+end
+ret bdfile2 int fd
+end
+fn bdfile2 fd int to ulong
+e = bdparse
+c = fclose fd
+if eq e 3
+ret bdcantrd 5
+end
+if eq e 2
+bdos 138
+for i ulong get bdrsn 0
+fwoc get bdrs i
+end
+fwoc 10
+ret 2
+end
+bdos 115
+for i ulong get bdfnl 0
+fwoc get bdfn i
+end
+bdos 116
+fwodec get bdn 0
+fwoc 10
+e = bdsem
+if eq e 2
+bdos 138
+for i ulong get bdrsn 0
+fwoc get bdrs i
+end
+fwoc 10
+ret 2
+end
+bdreport
+bdos 137
+fwodec get bdn 0
+fwoc 10
+ret 0
+end
diff --git a/gsp/fw.om b/gsp/fw.om
new file mode 100644
index 0000000..e928068
--- /dev/null
+++ b/gsp/fw.om
@@ -0,0 +1,749 @@
+note gsp/fw.om: GSP firmware container inspection in seeded Omega (OM-1). Ports the inspect path of
+note aienux PR #441 native/kernel/tools/ck_gsp_fw_inspect.c (in_bounds, inspect_buf, print_report,
+note cmd_inspect) for the fixed pins family gb10y and version 580.173.02. Library unit: no main.
+note Prefix fw. Needs gsp/sha2.om concatenated first. The file is read with pread from an open fd,
+note never mapped and never a device. Also holds the shared stdout writer (fwo*) that gsp/bindata.om
+note and fwprep.om print through, and the strerror texts the C prints.
+note Deviation (documented): the section string table is copied into a 16 MiB global; a larger one is
+note refused with reason 29 after the C's bounds check and before its NUL check. The C keeps the whole
+note file in memory; this port preads only the header, the section table, the string table, the
+note version and note bytes, and streams the three SHA-256 digests (same results).
+const FWOCAP ulong 65536
+const FWSTMX ulong 16777216
+const FWNONE ulong 999
+global fwob uchar 65536
+global fwon ulong 1
+global fwofd int 1
+global fwoerr ulong 1
+global fwsgb ulong 80
+global fwsgl ulong 80
+global fwok ulong 1
+global fwpath uchar 4096
+global fwpathn ulong 1
+global fwhd uchar 64
+global fwsh uchar 16384
+global fwst uchar 16777216
+global fwstn ulong 1
+global fwbuf uchar 128
+global fwshn ulong 1
+global fwnsec ulong 1
+global fwsn ulong 256
+global fwsty ulong 256
+global fwsof ulong 256
+global fwssz ulong 256
+global fwlen ulong 1
+global fwimx ulong 1
+global fwvx ulong 1
+global fwbx ulong 1
+global fwsx ulong 1
+global fwver uchar 64
+global fwvern ulong 1
+global fwbidh uchar 128
+global fwbidn ulong 1
+global fwhxf uchar 64
+global fwhxi uchar 64
+global fwhxs uchar 64
+note segment k of FWTXT is the text between the k-th and (k+1)-th '|' (segment 0 is empty).
+note 1..28 are the C refusal reasons in check order, 29 the deviation reason, 30.. report pieces,
+note 54.. strerror texts (glibc wording); 68..70 more strerror texts for fwprep's write paths.
+text FWTXT "|short header: file smaller than an ELF64 header|ELF magic missing|not ELF64 (EI_CLASS)|not little-endian (EI_DATA)|EI_VERSION is not 1|e_type is not ET_REL (the pinned container is a relocatable object)|e_machine is not RISC-V (243)|e_shentsize is not 64|e_shnum is 0: no section header table|e_shnum above this tool's limit (256)|e_shstrndx out of range|section header table outside the file|section string table outside the file or empty|section string table not NUL-terminated|section name index outside the string table|section bounds: offset+size outside the file|missing section .fwimage|.fwimage empty|missing section .fwversion|missing section .note.gnu.build-id|missing section: no signature section for this chip family|signature section empty|version section size not in 1..63|version string not NUL-terminated|version mismatch against the pinned driver version|build-id note too short|build-id note is not an NT_GNU_BUILD_ID note|build-id note descriptor size out of range|section string table above this port's 16 MiB buffer|file | bytes=| family=| expect_version=|section | type=| offset=| size=|(null)|fwversion |build_id |signature_section |sha256_file |sha256_fwimage |sha256_signature |RESULT OK|RESULT REFUSED |.fwimage|.fwversion|.note.gnu.build-id|.fwsignature_gb10y|580.173.02|gb10y|GNU|No such file or directory|Permission denied|Is a directory|File too large|Input/output error|Not a directory|Too many levels of symbolic links|File name too long|Unknown error |open |: |short read|Too many open files|Cannot allocate memory|File exists|No space left on device|Read-only file system|"
+text FWHEXD "0123456789abcdef"
+note build the segment table once
+fn fwsetup to void
+if eq get fwok 0 1
+ret
+end
+put fwok 0 1
+seg = ulong 0
+put fwsgb 0 0
+put fwsgl 0 0
+for i ulong len FWTXT
+c = get FWTXT i
+if eq c 124
+seg = add seg 1
+put fwsgb seg add i 1
+put fwsgl seg 0
+else
+put fwsgl seg add get fwsgl seg 1
+end
+end
+put fwon 0 0
+put fwofd 0 1
+put fwoerr 0 0
+end
+note ---- buffered writer: fwob[0..fwon) goes to fd fwofd; a failed write sets fwoerr 1 ----
+fn fwoflush to long
+n = get fwon 0
+p = ulong 0
+while lt p n bound 999999
+r = write get fwofd 0 fwob p sub n p
+if le r 0
+put fwoerr 0 1
+put fwon 0 0
+ret -5
+end
+p = add p ulong r
+end
+put fwon 0 0
+ret 0
+end
+fn fwoc c uchar to void
+if ge get fwon 0 FWOCAP
+z = fwoflush
+end
+n = get fwon 0
+put fwob n c
+put fwon 0 add n 1
+end
+note print segment k of FWTXT
+fn fwos k ulong to void
+b = get fwsgb k
+for i ulong get fwsgl k
+fwoc get FWTXT add b i
+end
+end
+note print v in decimal
+fn fwodec v ulong to void
+d = new uchar 24 0
+n = ulong 0
+x = v
+while lt n 24 bound 24
+put d n add uchar rem x 10 48
+n = add n 1
+x = div x 10
+if eq x 0
+break
+end
+end
+while gt n 0 bound 24
+n = sub n 1
+fwoc get d n
+end
+end
+note print v in lowercase hex without leading zeros (C %x)
+fn fwohex v ulong to void
+d = new uchar 24 0
+n = ulong 0
+x = v
+while lt n 24 bound 24
+put d n get FWHEXD rem x 16
+n = add n 1
+x = div x 16
+if eq x 0
+break
+end
+end
+while gt n 0 bound 24
+n = sub n 1
+fwoc get d n
+end
+end
+note print shhx[0..2n) (call shhex n first)
+fn fwohx n ulong to void
+for i ulong mul n 2
+fwoc get shhx i
+end
+end
+fn fwopath to void
+for i ulong get fwpathn 0
+fwoc get fwpath i
+end
+end
+note print the strerror text of errno e (positive)
+fn fwoerrno e ulong to void
+k = ulong 0
+if eq e 2
+k = 54
+end
+if eq e 13
+k = 55
+end
+if eq e 21
+k = 56
+end
+if eq e 27
+k = 57
+end
+if eq e 5
+k = 58
+end
+if eq e 20
+k = 59
+end
+if eq e 40
+k = 60
+end
+if eq e 36
+k = 61
+end
+if eq e 24
+k = 66
+end
+if eq e 12
+k = 67
+end
+if eq e 17
+k = 68
+end
+if eq e 28
+k = 69
+end
+if eq e 30
+k = 70
+end
+if eq k 0
+fwos 62
+fwodec e
+ret
+end
+fwos k
+end
+note ---- pread loops, one per destination global: 0, -errno, or -5 when the file ends early ----
+fn fwrdhd fd int off ulong n ulong to long
+q = ulong 0
+while lt q n bound 999999
+r = pread fd fwhd q sub n q long add off q
+if lt r 0
+ret r
+end
+if eq r 0
+ret -5
+end
+q = add q ulong r
+end
+ret 0
+end
+fn fwrdsh fd int off ulong n ulong to long
+q = ulong 0
+while lt q n bound 999999
+r = pread fd fwsh q sub n q long add off q
+if lt r 0
+ret r
+end
+if eq r 0
+ret -5
+end
+q = add q ulong r
+end
+ret 0
+end
+fn fwrdst fd int off ulong n ulong to long
+q = ulong 0
+while lt q n bound 999999
+r = pread fd fwst q sub n q long add off q
+if lt r 0
+ret r
+end
+if eq r 0
+ret -5
+end
+q = add q ulong r
+end
+ret 0
+end
+fn fwrdbf fd int off ulong n ulong to long
+q = ulong 0
+while lt q n bound 999999
+r = pread fd fwbuf q sub n q long add off q
+if lt r 0
+ret r
+end
+if eq r 0
+ret -5
+end
+q = add q ulong r
+end
+ret 0
+end
+note ---- little-endian readers (C rd16/rd32/rd64) over fwhd, fwsh, fwbuf ----
+fn fwh16 p ulong to ulong
+ret or ulong get fwhd p shl ulong get fwhd add p 1 8
+end
+fn fwh64 p ulong to ulong
+v = ulong 0
+for i ulong 8
+v = or v shl ulong get fwhd add p i mul i 8
+end
+ret v
+end
+fn fws32 p ulong to ulong
+v = ulong 0
+for i ulong 4
+v = or v shl ulong get fwsh add p i mul i 8
+end
+ret v
+end
+fn fws64 p ulong to ulong
+v = ulong 0
+for i ulong 8
+v = or v shl ulong get fwsh add p i mul i 8
+end
+ret v
+end
+fn fwb32 p ulong to ulong
+v = ulong 0
+for i ulong 4
+v = or v shl ulong get fwbuf add p i mul i 8
+end
+ret v
+end
+note C in_bounds: off + size <= len without overflow
+fn fwinb off ulong size ulong flen ulong to ulong
+if gt off flen
+ret 0
+end
+if le size sub flen off
+ret 1
+end
+ret 0
+end
+note does the NUL-terminated name at fwst[off] equal segment k?
+fn fwnmeq off ulong k ulong to ulong
+b = get fwsgb k
+l = get fwsgl k
+n = get fwstn 0
+for i ulong l
+p = add off i
+if ge p n
+ret 0
+end
+if ne get fwst p get FWTXT add b i
+ret 0
+end
+end
+p2 = add off l
+if ge p2 n
+ret 0
+end
+if ne get fwst p2 0
+ret 0
+end
+ret 1
+end
+note checks 1..12 (C inspect_buf lines 123-138): returns 0, a reason, or 1000 on an I/O error
+fn fwchk1 fd int flen ulong to ulong
+if lt flen 64
+ret 1
+end
+r = fwrdhd fd 0 64
+if ne r 0
+ret 1000
+end
+note magic 0x7f 'E' 'L' 'F' = 127 69 76 70
+m = ulong 0
+if ne get fwhd 0 127
+m = 1
+end
+if ne get fwhd 1 69
+m = 1
+end
+if ne get fwhd 2 76
+m = 1
+end
+if ne get fwhd 3 70
+m = 1
+end
+if eq m 1
+ret 2
+end
+if ne get fwhd 4 2
+ret 3
+end
+if ne get fwhd 5 1
+ret 4
+end
+if ne get fwhd 6 1
+ret 5
+end
+if ne fwh16 16 1
+ret 6
+end
+if ne fwh16 18 243
+ret 7
+end
+if ne fwh16 58 64
+ret 8
+end
+n = fwh16 60
+if eq n 0
+ret 9
+end
+if gt n 256
+ret 10
+end
+if ge fwh16 62 n
+ret 11
+end
+if eq fwinb fwh64 40 mul n 64 flen 0
+ret 12
+end
+put fwshn 0 n
+r = fwrdsh fd fwh64 40 mul n 64
+if ne r 0
+ret 1000
+end
+ret 0
+end
+note checks 13..16 (C lines 139-154): string table, then every section header in order
+fn fwchk2 fd int flen ulong to ulong
+si = mul fwh16 62 64
+so = fws64 add si 24
+ss = fws64 add si 32
+if eq ss 0
+ret 13
+end
+if eq fwinb so ss flen 0
+ret 13
+end
+if gt ss FWSTMX
+ret 29
+end
+r = fwrdst fd so ss
+if ne r 0
+ret 1000
+end
+if ne get fwst sub ss 1 0
+ret 14
+end
+put fwstn 0 ss
+ret fwsecs flen
+end
+note C lines 145-154: every section header in order; records each before checking the next
+fn fwsecs flen ulong to ulong
+for i ulong get fwshn 0
+b = mul i 64
+nm = fws32 b
+ty = fws32 add b 4
+of = fws64 add b 24
+sz = fws64 add b 32
+if ge nm get fwstn 0
+ret 15
+end
+if ne ty 8
+if gt sz 0
+if eq fwinb of sz flen 0
+ret 16
+end
+end
+end
+k = get fwnsec 0
+put fwsn k nm
+put fwsty k ty
+put fwsof k of
+put fwssz k sz
+put fwnsec 0 add k 1
+end
+ret 0
+end
+note checks 17..22 (C lines 155-168): the strcmp chain, last match wins
+fn fwchk3 to ulong
+put fwimx 0 FWNONE
+put fwvx 0 FWNONE
+put fwbx 0 FWNONE
+put fwsx 0 FWNONE
+for i ulong get fwnsec 0
+o = get fwsn i
+if eq fwnmeq o 47 1
+put fwimx 0 i
+else
+if eq fwnmeq o 48 1
+put fwvx 0 i
+else
+if eq fwnmeq o 49 1
+put fwbx 0 i
+else
+if eq fwnmeq o 50 1
+put fwsx 0 i
+end
+end
+end
+end
+end
+x = get fwimx 0
+if eq x FWNONE
+ret 17
+end
+if eq get fwsty x 8
+ret 18
+end
+if eq get fwssz x 0
+ret 18
+end
+if eq get fwvx 0 FWNONE
+ret 19
+end
+if eq get fwbx 0 FWNONE
+ret 20
+end
+x = get fwsx 0
+if eq x FWNONE
+ret 21
+end
+if eq get fwsty x 8
+ret 22
+end
+if eq get fwssz x 0
+ret 22
+end
+ret 0
+end
+note checks 23..25 (C lines 170-175): .fwversion size, NUL, equality with the pin "580.173.02"
+fn fwchk4 fd int to ulong
+x = get fwvx 0
+sz = get fwssz x
+if eq get fwsty x 8
+ret 23
+end
+if eq sz 0
+ret 23
+end
+if ge sz 64
+ret 23
+end
+r = fwrdbf fd get fwsof x sz
+if ne r 0
+ret 1000
+end
+if ne get fwbuf sub sz 1 0
+ret 24
+end
+n = ulong 0
+while lt n sz bound 64
+if eq get fwbuf n 0
+break
+end
+put fwver n get fwbuf n
+n = add n 1
+end
+put fwvern 0 n
+if ne sz add get fwsgl 51 1
+ret 25
+end
+b = get fwsgb 51
+for i ulong get fwsgl 51
+if ne get fwbuf i get FWTXT add b i
+ret 25
+end
+end
+ret 0
+end
+note checks 26..28 (C lines 177-185): the NT_GNU_BUILD_ID note, then its hex
+fn fwchk5 fd int to ulong
+x = get fwbx 0
+sz = get fwssz x
+if eq get fwsty x 8
+ret 26
+end
+if lt sz 16
+ret 26
+end
+n = sz
+if gt n 80
+n = 80
+end
+r = fwrdbf fd get fwsof x n
+if ne r 0
+ret 1000
+end
+m = ulong 0
+if ne fwb32 0 4
+m = 1
+end
+note "GNU\0" = 71 78 85 0
+if ne get fwbuf 12 71
+m = 1
+end
+if ne get fwbuf 13 78
+m = 1
+end
+if ne get fwbuf 14 85
+m = 1
+end
+if ne get fwbuf 15 0
+m = 1
+end
+if ne fwb32 8 3
+m = 1
+end
+if eq m 1
+ret 27
+end
+d = fwb32 4
+if eq d 0
+ret 28
+end
+if gt d 64
+ret 28
+end
+if gt add 16 d sz
+ret 28
+end
+fwbidhx d
+ret 0
+end
+note lowercase hex of the d note descriptor bytes fwbuf[16..16+d) into fwbidh (C hex)
+fn fwbidhx d ulong to void
+for i ulong d
+c = get fwbuf add 16 i
+put fwbidh mul i 2 get FWHEXD shr c 4
+put fwbidh add mul i 2 1 get FWHEXD and c 15
+end
+put fwbidn 0 mul d 2
+end
+note the three SHA-256 digests as lowercase hex in fwhxf / fwhxi / fwhxs; 0 or 1000 on an I/O error
+fn fwdig fd int flen ulong to ulong
+sh2init 0
+sh2init 1
+sh2init 2
+r = sh2file 0 fd 0 flen
+if ne r 0
+ret 1000
+end
+x = get fwimx 0
+r = sh2file 1 fd get fwsof x get fwssz x
+if ne r 0
+ret 1000
+end
+x = get fwsx 0
+r = sh2file 2 fd get fwsof x get fwssz x
+if ne r 0
+ret 1000
+end
+sh2fin 0
+shhex 32
+for i ulong 64
+put fwhxf i get shhx i
+end
+sh2fin 1
+shhex 32
+for i ulong 64
+put fwhxi i get shhx i
+end
+sh2fin 2
+shhex 32
+for i ulong 64
+put fwhxs i get shhx i
+end
+ret 0
+end
+note all checks in the C order: 0 = every check passed, 1..29 = refusal reason, 1000 = I/O error
+fn fwcheck fd int flen ulong to ulong
+put fwnsec 0 0
+put fwlen 0 flen
+e = fwchk1 fd flen
+if ne e 0
+ret e
+end
+e = fwchk2 fd flen
+if ne e 0
+ret e
+end
+e = fwchk3
+if ne e 0
+ret e
+end
+e = fwchk4 fd
+if ne e 0
+ret e
+end
+e = fwchk5 fd
+if ne e 0
+ret e
+end
+ret fwdig fd flen
+end
+note print the NUL-terminated name at fwst[off], or (null) when it is empty
+fn fwoname off ulong to void
+if eq get fwst off 0
+fwos 38
+ret
+end
+note the string table is NUL-terminated (check 14), so the name ends inside it; chunked for the
+note 999999 bound (a name may run up to 16 MiB)
+p = off
+go = ulong 1
+while eq go 1 bound 20
+while ne get fwst p 0 bound 999999
+fwoc get fwst p
+p = add p 1
+end
+if eq get fwst p 0
+go = 0
+end
+end
+end
+note C cmd_inspect + print_report for an open fd of flen bytes, path in fwpath[0..fwpathn).
+note Returns 0 = RESULT OK, 2 = RESULT REFUSED, 1 = I/O error (the C prints "short read" on
+note stderr and nothing on stdout; here the buffered file line is dropped and the caller reports).
+fn fwinsp fd int flen ulong to ulong
+fwsetup
+mk = get fwon 0
+fwos 30
+fwopath
+fwos 31
+fwodec flen
+fwos 32
+fwos 52
+fwos 33
+fwos 51
+fwoc 10
+e = fwcheck fd flen
+if eq e 1000
+put fwon 0 mk
+ret 1
+end
+for i ulong get fwnsec 0
+fwos 34
+fwodec i
+fwoc 32
+fwoname get fwsn i
+fwos 35
+fwodec get fwsty i
+fwos 36
+fwodec get fwsof i
+fwos 37
+fwodec get fwssz i
+fwoc 10
+end
+if ne e 0
+fwos 46
+fwos e
+fwoc 10
+ret 2
+end
+fwos 39
+for i ulong get fwvern 0
+fwoc get fwver i
+end
+fwoc 10
+fwos 40
+for i ulong get fwbidn 0
+fwoc get fwbidh i
+end
+fwoc 10
+fwos 41
+fwos 50
+fwos 37
+fwodec get fwssz get fwsx 0
+fwoc 10
+fwos 42
+for i ulong 64
+fwoc get fwhxf i
+end
+fwoc 10
+fwos 43
+for i ulong 64
+fwoc get fwhxi i
+end
+fwos 37
+fwodec get fwssz get fwimx 0
+fwoc 10
+fwos 44
+for i ulong 64
+fwoc get fwhxs i
+end
+fwoc 10
+fwos 45
+fwoc 10
+ret 0
+end
diff --git a/gsp/inflate.om b/gsp/inflate.om
new file mode 100644
index 0000000..7401341
--- /dev/null
+++ b/gsp/inflate.om
@@ -0,0 +1,562 @@
+note gsp/inflate.om -- raw DEFLATE (RFC 1951) plus the bindata trailer (CRC-32, ISIZE), in OM-1.
+note Port of inf_bits, huff_construct, huff_decode, inf_codes, inf_stored, inf_fixed, inf_dynamic,
+note inflate_raw, crc32_bytes, get32le and unpack_gz_body from aienux pr441 @ c5bb3a4b
+note native/kernel/tools/ck_gsp_bindata_extract.c lines 199-389 (puff-style canonical Huffman).
+note Library unit: no main. Every name starts with inf. No dependency on any other unit.
+note
+note Caller contract: put the stored bytes in infin[0..inlen), call infsetup once, then
+note infgz inlen outlen. The plain bytes land in infout[0..outlen). Result 0 = ok, else a reason
+note code 1..22; infmsg code copies its text into infm[0..infmn).
+note Codes 1..20 are the C reasons word for word. 21 and 22 are this port's buffer bounds
+note (outlen above 16 MiB, inlen above 8 MiB); the C has no such limit (documented deviation).
+note
+note 8388608 = 8 MiB, 16777216 = 16 MiB (Wolfram 8*2^20, 16*2^20)
+const INFINMAX ulong 8388608
+const INFOUTMX ulong 16777216
+global infin uchar 8388608
+global infout uchar 16777216
+note bit reader and stream state, one element each
+global infil ulong 1
+global infip ulong 1
+global infbb ulong 1
+global infbc ulong 1
+global infol ulong 1
+global infop ulong 1
+global inferr ulong 1
+note Huffman tables: table t (0 = lencode, 1 = distcode) has counts infcnt[t*16 + len] and
+note symbols infsym[t*320 + i]; inflen holds the code lengths being built from
+global infcnt ulong 32
+global infsym ulong 640
+global inflen ulong 320
+global infor ulong 19
+global inflb ulong 29
+global infle ulong 29
+global infdb ulong 30
+global infde ulong 30
+global infm uchar 128
+global infmn ulong 1
+text INFMSGS "|inflate: input exhausted|inflate: invalid Huffman code|inflate: output longer than declared size|inflate: invalid length symbol|inflate: invalid distance symbol|inflate: distance before start of output|inflate: stored block length check failed|inflate: bad code counts|inflate: bad code-length code|inflate: repeat with no previous length|inflate: too many lengths|inflate: no end-of-block code|inflate: bad literal/length code|inflate: bad distance code|inflate: invalid block type 3|inflate: output shorter than declared size|inflate: trailing bytes after the final block|compressed array shorter than a deflate block plus its 8-byte trailer|compressed trailer: ISIZE differs from DATA SIZE|compressed trailer: CRC-32 mismatch|inflate: declared size above this port's 16 MiB buffer|compressed array above this port's 8 MiB buffer"
+note fill the constant tables (C: order[19], lbase/lext[29], dbase/dext[30])
+fn infsetup to void
+put infor 0 16
+put infor 1 17
+put infor 2 18
+put infor 3 0
+put infor 4 8
+put infor 5 7
+put infor 6 9
+put infor 7 6
+put infor 8 10
+put infor 9 5
+put infor 10 11
+put infor 11 4
+put infor 12 12
+put infor 13 3
+put infor 14 13
+put infor 15 2
+put infor 16 14
+put infor 17 1
+put infor 18 15
+put inflb 0 3
+put inflb 1 4
+put inflb 2 5
+put inflb 3 6
+put inflb 4 7
+put inflb 5 8
+put inflb 6 9
+put inflb 7 10
+put inflb 8 11
+put inflb 9 13
+put inflb 10 15
+put inflb 11 17
+put inflb 12 19
+put inflb 13 23
+put inflb 14 27
+put inflb 15 31
+put inflb 16 35
+put inflb 17 43
+put inflb 18 51
+put inflb 19 59
+put inflb 20 67
+put inflb 21 83
+put inflb 22 99
+put inflb 23 115
+put inflb 24 131
+put inflb 25 163
+put inflb 26 195
+put inflb 27 227
+put inflb 28 258
+for i ulong 29
+note lext: 0 for 0..7, then (i-4)/4 for 8..27, 0 for 28
+put infle i 0
+if and ge i 8 lt i 28
+put infle i div sub i 4 4
+end
+end
+put infdb 0 1
+put infdb 1 2
+put infdb 2 3
+put infdb 3 4
+put infdb 4 5
+put infdb 5 7
+put infdb 6 9
+put infdb 7 13
+put infdb 8 17
+put infdb 9 25
+put infdb 10 33
+put infdb 11 49
+put infdb 12 65
+put infdb 13 97
+put infdb 14 129
+put infdb 15 193
+put infdb 16 257
+put infdb 17 385
+put infdb 18 513
+put infdb 19 769
+put infdb 20 1025
+put infdb 21 1537
+put infdb 22 2049
+put infdb 23 3073
+put infdb 24 4097
+put infdb 25 6145
+put infdb 26 8193
+put infdb 27 12289
+put infdb 28 16385
+put infdb 29 24577
+for j ulong 30
+note dext: 0 for 0..3, then (j-2)/2 for 4..29
+put infde j 0
+if ge j 4
+put infde j div sub j 2 2
+end
+end
+end
+note copy reason code k (1..22) into infm[0..infmn)
+fn infmsg k ulong to void
+seg = ulong 0
+n = ulong 0
+for i ulong len INFMSGS
+c = get INFMSGS i
+if eq c 124
+seg = add seg 1
+else
+if eq seg k
+put infm n c
+n = add n 1
+end
+end
+end
+put infmn 0 n
+end
+note C inf_bits: next need bits (LSB first); -1 with inferr = 1 when the input runs out
+fn infbits need ulong to long
+while lt get infbc 0 need bound 64
+p = get infip 0
+if ge p get infil 0
+put inferr 0 1
+ret -1
+end
+put infbb 0 or get infbb 0 shl ulong get infin p get infbc 0
+put infip 0 add p 1
+put infbc 0 add get infbc 0 8
+end
+b = get infbb 0
+v = and b sub shl ulong 1 need 1
+put infbb 0 shr b need
+put infbc 0 sub get infbc 0 need
+ret long v
+end
+note C huff_construct over inflen[base..base+n) into table t: 0 = complete, -1 = over-subscribed,
+note else the number of unused codes
+fn infbuild t ulong base ulong n ulong to long
+offs = new ulong 16 0
+co = mul t 16
+for i ulong 16
+put infcnt add co i 0
+end
+for j ulong n
+l = get inflen add base j
+put infcnt add co l add get infcnt add co l 1
+end
+if eq get infcnt co n
+ret 0
+end
+left = long 1
+for k ulong 15
+left = shl left 1
+left = sub left long get infcnt add add co k 1
+if lt left 0
+ret -1
+end
+end
+put offs 1 0
+for m ulong 14
+l = add m 1
+put offs add l 1 add get offs l get infcnt add co l
+end
+so = mul t 320
+for q ulong n
+l = get inflen add base q
+if ne l 0
+put infsym add so get offs l q
+put offs l add get offs l 1
+end
+end
+ret left
+end
+note C huff_decode with table t: the symbol, or -1 (inferr 1 = input exhausted, 2 = invalid code)
+fn infdec t ulong to long
+code = long 0
+first = long 0
+index = long 0
+co = mul t 16
+for k ulong 15
+b = infbits 1
+if lt b 0
+ret -1
+end
+code = or code b
+count = long get infcnt add add co k 1
+if lt sub code count first
+x = ulong add index sub code first
+x = add x mul t 320
+ret long get infsym x
+end
+index = add index count
+first = shl add first count 1
+code = shl code 1
+end
+put inferr 0 2
+ret -1
+end
+note one literal/length symbol of C inf_codes: 0 = go on, 1 = end of block, 2 = error (inferr)
+fn infsym1 to ulong
+s = infdec 0
+if lt s 0
+ret 2
+end
+if lt s 256
+p = get infop 0
+if ge p get infol 0
+put inferr 0 3
+ret 2
+end
+put infout p uchar s
+put infop 0 add p 1
+ret 0
+end
+if eq s 256
+ret 1
+end
+y = ulong sub s 257
+if ge y 29
+put inferr 0 4
+ret 2
+end
+e = infbits get infle y
+if lt e 0
+ret 2
+end
+ln = add get inflb y ulong e
+s = infdec 1
+if lt s 0
+ret 2
+end
+y = ulong s
+if ge y 30
+put inferr 0 5
+ret 2
+end
+e = infbits get infde y
+if lt e 0
+ret 2
+end
+dist = add get infdb y ulong e
+p = get infop 0
+if gt dist p
+put inferr 0 6
+ret 2
+end
+if gt add p ln get infol 0
+put inferr 0 3
+ret 2
+end
+for i ulong ln
+put infout add p i get infout sub add p i dist
+end
+put infop 0 add p ln
+ret 0
+end
+note C inf_codes: symbols until end of block; every pass but the last writes at least one byte,
+note so the 999998 x 999998 pass budget can never be the limit for a 16 MiB output
+fn infcodes to ulong
+o = ulong 0
+while lt o 999998 bound 999999
+i = ulong 0
+while lt i 999998 bound 999999
+r = infsym1
+if eq r 1
+ret 0
+end
+if eq r 2
+ret get inferr 0
+end
+i = add i 1
+end
+o = add o 1
+end
+ret 3
+end
+note C inf_stored
+fn infstored to ulong
+put infbb 0 0
+put infbc 0 0
+p = get infip 0
+if gt add p 4 get infil 0
+ret 1
+end
+ln = or ulong get infin p shl ulong get infin add p 1 8
+nl = or ulong get infin add p 2 shl ulong get infin add p 3 8
+p = add p 4
+put infip 0 p
+note 65535 = 0xffff (Wolfram FromDigits["ffff",16])
+if ne xor ln 65535 nl
+ret 7
+end
+if gt add p ln get infil 0
+ret 1
+end
+o = get infop 0
+if gt add o ln get infol 0
+ret 3
+end
+for i ulong ln
+put infout add o i get infin add p i
+end
+put infip 0 add p ln
+put infop 0 add o ln
+ret 0
+end
+note C inf_fixed: lengths 8 (0..143), 9 (144..255), 7 (256..279), 8 (280..287); distances 30 x 5
+fn inffixed to ulong
+for i ulong 288
+put inflen i 8
+if and ge i 144 lt i 256
+put inflen i 9
+end
+if and ge i 256 lt i 280
+put inflen i 7
+end
+end
+b = infbuild 0 0 288
+for j ulong 30
+put inflen j 5
+end
+b = infbuild 1 0 30
+ret infcodes
+end
+note C inf_dynamic
+fn infdyn to ulong
+v = infbits 5
+if lt v 0
+ret 1
+end
+nlen = add ulong v 257
+v = infbits 5
+if lt v 0
+ret 1
+end
+ndist = add ulong v 1
+v = infbits 4
+if lt v 0
+ret 1
+end
+ncode = add ulong v 4
+if or gt nlen 286 gt ndist 30
+ret 8
+end
+for k ulong 19
+put inflen get infor k 0
+if lt k ncode
+v = infbits 3
+if lt v 0
+ret 1
+end
+put inflen get infor k ulong v
+end
+end
+if ne infbuild 0 0 19 0
+ret 9
+end
+tot = add nlen ndist
+i = ulong 0
+while lt i tot bound 400
+s = infdec 0
+if lt s 0
+ret get inferr 0
+end
+if lt s 16
+put inflen i ulong s
+i = add i 1
+continue
+end
+rep = ulong 0
+cnt = ulong 0
+if eq s 16
+if eq i 0
+ret 10
+end
+rep = get inflen sub i 1
+v = infbits 2
+if lt v 0
+ret 1
+end
+cnt = add 3 ulong v
+else
+if eq s 17
+v = infbits 3
+if lt v 0
+ret 1
+end
+cnt = add 3 ulong v
+else
+v = infbits 7
+if lt v 0
+ret 1
+end
+cnt = add 11 ulong v
+end
+end
+if gt add i cnt tot
+ret 11
+end
+for r ulong cnt
+put inflen add i r rep
+end
+i = add i cnt
+end
+if eq get inflen 256 0
+ret 12
+end
+e = infbuild 0 0 nlen
+if or lt e 0 and gt e 0 ne sub nlen get infcnt 0 1
+ret 13
+end
+e = infbuild 1 nlen ndist
+if or lt e 0 and gt e 0 ne sub ndist get infcnt 16 1
+ret 14
+end
+ret infcodes
+end
+note one block of C inflate_raw: 0 = more blocks follow, 1 = that was the final block,
+note else 100 + reason code
+fn infblk to ulong
+last = infbits 1
+if lt last 0
+ret 101
+end
+ty = infbits 2
+if lt ty 0
+ret 101
+end
+r = ulong 0
+if eq ty 0
+r = infstored
+else
+if eq ty 1
+r = inffixed
+else
+if eq ty 2
+r = infdyn
+else
+ret 115
+end
+end
+end
+if ne r 0
+ret add 100 r
+end
+ret ulong last
+end
+note C inflate_raw over infin[0..infil) into infout[0..infol); every block takes at least 3 bits,
+note so 999998 x 999998 blocks is far above any 8 MiB input
+fn infraw to ulong
+put infip 0 0
+put infbb 0 0
+put infbc 0 0
+put infop 0 0
+put inferr 0 0
+o = ulong 0
+done = ulong 0
+while and eq done 0 lt o 999998 bound 999999
+i = ulong 0
+while and eq done 0 lt i 999998 bound 999999
+r = infblk
+if ge r 100
+ret sub r 100
+end
+done = r
+i = add i 1
+end
+o = add o 1
+end
+if ne get infop 0 get infol 0
+ret 16
+end
+if ne get infip 0 get infil 0
+ret 17
+end
+ret 0
+end
+note C crc32_bytes over infout[0..n): init and final xor 4294967295 (0xffffffff), reflected poly
+note 3988292384 (0xedb88320) (Wolfram FromDigits); chunked so no loop passes 1000000 times
+fn infcrc n ulong to ulong
+c = ulong 4294967295
+p = ulong 0
+while lt p n bound 999999
+k = sub n p
+if gt k 524288
+k = 524288
+end
+for i ulong k
+c = xor c ulong get infout add p i
+for b ulong 8
+m = sub 0 and c 1
+c = xor shr c 1 and 3988292384 m
+end
+end
+p = add p k
+end
+ret and xor c 4294967295 4294967295
+end
+note C get32le of infin[p..p+4)
+fn infle32 p ulong to ulong
+v = or ulong get infin p shl ulong get infin add p 1 8
+v = or v shl ulong get infin add p 2 16
+ret or v shl ulong get infin add p 3 24
+end
+note C unpack_gz_body: deflate body + CRC-32 + ISIZE in infin[0..inlen), outlen plain bytes
+fn infgz inlen ulong outlen ulong to ulong
+if lt inlen 9
+ret 18
+end
+if gt outlen INFOUTMX
+ret 21
+end
+if gt inlen INFINMAX
+ret 22
+end
+put infil 0 sub inlen 8
+put infol 0 outlen
+e = infraw
+if ne e 0
+ret e
+end
+if ne infle32 sub inlen 4 outlen
+ret 19
+end
+if ne infle32 sub inlen 8 infcrc outlen
+ret 20
+end
+ret 0
+end
diff --git a/gsp/mmio.om b/gsp/mmio.om
new file mode 100644
index 0000000..f620f2e
--- /dev/null
+++ b/gsp/mmio.om
@@ -0,0 +1,288 @@
+note gsp/mmio.om: the register-level GSP start-up on GB10B in seeded Omega, a port of
+note aien-dev/aienux PR #441 native/kernel/gpu/gsp_mmio.{h,c} (ck_gsp_mmio_boot, ck_gsp_mmio_notify).
+note GB10B has no FSP: SEC2 boots the GSP-FMC (open-gpu-kernel-modules 580.173.02, kgspBootstrap_GH100,
+note kernel_gsp_gh100.c:833-995, SEC2 branch :868-872). The eleven steps:
+note  1 wait until SEC2 EMEM channel 0 is empty, QUEUE_HEAD(0) == QUEUE_TAIL(0), HEAD read first
+note    (ksec2CanSendPacket_GB10B kernel_sec2_gb10b.c:343-357, _ksec2GetQueueHeadTail_GB10B :103-104)
+note  2 EMEMC(0) = offset 0 with auto-increment on write (AINCW bit 24) (:118-154, :723)
+note  3 EMEMD(0) = the packet one dword at a time, a short tail zero-padded (:166-213)
+note  4 EMEMC(0) read back: the write pointer moved by exactly the dwords written (:204-210)
+note  5 QUEUE_TAIL(0) = padded size - 4, THEN QUEUE_HEAD(0) = 0, which interrupts SEC2 (:72-84, :730)
+note  6 wait until SEC2 MAILBOX0 no longer reads 0xc001cafe (:285-311, :640)
+note  7 wait until GSP HWCFG2 is non-zero and not 0xBADF41xx (target mask released) (:264-283, :367-379)
+note  8 wait until HWCFG2 bit 13 (RISCV_BR_PRIV_LOCKDOWN) is clear or GSP MAILBOX0 is non-zero; MAILBOX0:1
+note    equal to the FMC boot-argument address means not read yet (kernel_gsp_gh100.c:492-533)
+note  9 GSP MAILBOX0 non-zero after that is an FMC error code (:940-946)
+note 10 GSP FALCON_OS = GspRmBoot appVersion (:954-956)
+note 11 RISC-V CPUCTL bit 7 ACTIVE_STAT must read ACTIVE (kernel_falcon_ga102.c:47-55)
+note Notify (kgspSetCmdQueueHead_TU102, kernel_gsp_tu102.c:343-355): GSP QUEUE_HEAD(0) = 0.
+note Library unit: no main. Build after it gsp/sim.om (the mode 0 device) and a driver with main.
+note Register seam: every device access is gsprd / gspwr. gspmode 0 = the in-.om simulator (simrd/simwr),
+note gspmode 1 = BAR0 through a vfiomapw handle in gspbar (mapget/mapset, 4 bytes). Mode 1 runs only in a
+note hardware window; host tests never set it. Nothing here has run on the chip.
+note BAR0 offsets, GB10B (dev_sec_pri.h:27-56, dev_gsp.h:27, dev_falcon_v4.h, dev_riscv_pri.h:58,68),
+note written in decimal because OM-1 has no hex literal: 0x840040 0x840044 0x840ac0 0x840ac4 0x840c00
+note 0x840c04 0x110040 0x110044 0x110080 0x1100f4 0x110c00 0x111388.
+const S2MB0 ulong 8650816
+const S2MB1 ulong 8650820
+const S2EMC ulong 8653504
+const S2EMD ulong 8653508
+const S2QH ulong 8653824
+const S2QT ulong 8653828
+const GMB0 ulong 1114176
+const GMB1 ulong 1114180
+const GOS ulong 1114240
+const GHWCFG2 ulong 1114356
+const GQH ulong 1117184
+const GCPUCTL ulong 1119112
+note EMEMC AINCW 1<<24; 64 dwords per EMEM block; channel 1024 bytes; SEC2 busy 0xc001cafe;
+note target locked 0xBADF4100 under mask 0xFFFFFF00; HWCFG2 lockdown 1<<13; CPUCTL active 1<<7.
+const AINCW ulong 16777216
+const DWBLK ulong 64
+const CHBYTES ulong 1024
+const CMDBUSY ulong 3221342974
+const PRIVLCK ulong 3135193344
+const PRIVMSK ulong 4294967040
+const LOCKDN ulong 8192
+const CPUACT ulong 128
+const M32 ulong 4294967295
+note stage codes (enum ck_gsp_mmio_err)
+const EOK long 0
+const EARG long -1
+const EBUSY long -2
+const EEMEM long -3
+const ESEC2 long -4
+const EMASK long -5
+const ELOCK long -6
+const EFMC long -7
+const ERISCV long -8
+note -9: the device is not runtime-active (arm64: a BAR read of a D3 device is an external abort);
+note checked before the first register access, so a refused start makes no access at all
+const EPM long -9
+note runtime PM: mode 0 asks the simulator (spm 0 = active); mode 1 reads the sysfs file whose path
+note the caller puts in gpmp[0..gpmn) (.../power/runtime_status) and requires exactly "active\n"
+text pmact "active\n"
+global gpmp uchar 128
+global gpmn ulong 1
+global gpmb uchar 16
+note seam state: mode, BAR0 handle (mode 1), pause between polls in nanoseconds (mode 1)
+global gspmode ulong 1
+global gspbar long 1
+global gsppns long 1
+note input (struct ck_gsp_mmio_in): the packet bytes, then gin 0 len, 1 fmc_args_pa, 2 app_version,
+note 3..6 poll budgets of steps 1, 6, 7, 8 (0 = check once)
+global gpkt uchar 1024
+global gin ulong 7
+note output (struct ck_gsp_mmio_out): gstage, then gout 0..3 polls of steps 1, 6, 7, 8, 4 dwords,
+note 5 ememc_after, 6 sec2_mb0, 7 sec2_mb1, 8 hwcfg2, 9 gsp_mb0, 10 gsp_mb1, 11 cpuctl
+global gstage long 1
+global gout ulong 12
+fn gsprd off ulong to ulong
+m = get gspmode 0
+if eq m 0
+ret simrd off
+end
+if ne m 1
+trap 9
+end
+ret mapget get gspbar 0 off 4
+end
+fn gspwr off ulong v ulong to void
+m = get gspmode 0
+if eq m 0
+simwr off v
+ret
+end
+if ne m 1
+trap 9
+end
+r = mapset get gspbar 0 off 4 v
+if ne r 0
+trap 9
+end
+end
+fn gsppause to void
+if eq get gspmode 0 1
+r = sleepns get gsppns 0
+end
+end
+fn ememdw c ulong to ulong
+ret add mul and shr c 8 255 DWBLK and shr c 2 63
+end
+fn maskrel h ulong to bool
+if eq h 0
+ret false
+end
+ret ne and h PRIVMSK PRIVLCK
+end
+fn gsppm to bool
+if eq get gspmode 0 0
+ret simpmok
+end
+fd = fopen gpmp 0 get gpmn 0 524288 0
+if lt fd 0
+ret false
+end
+n = read int fd gpmb ulong 0 16
+r = fclose int fd
+if ne n long len pmact
+ret false
+end
+for i ulong len pmact
+if ne get gpmb i get pmact i
+ret false
+end
+end
+ret true
+end
+note step 8 condition: MAILBOX0, MAILBOX1 only when MAILBOX0 is the argument address, then HWCFG2
+fn lockdone to bool
+m0 = gsprd GMB0
+put gout 9 m0
+pa = get gin 1
+if ne m0 0
+if eq m0 and pa M32
+m1 = gsprd GMB1
+put gout 10 m1
+if eq m1 shr pa 32
+ret false
+end
+end
+end
+h = gsprd GHWCFG2
+put gout 8 h
+ret or eq and h LOCKDN 0 ne m0 0
+end
+note one check of wait k (0 step 1, 1 step 6, 2 step 7, 3 step 8): true when it is over
+fn pollonce k ulong to bool
+if eq k 0
+hd = gsprd S2QH
+ret eq hd gsprd S2QT
+end
+if eq k 1
+mb = gsprd S2MB0
+put gout 6 mb
+ret ne mb CMDBUSY
+end
+if eq k 2
+hw = gsprd GHWCFG2
+put gout 8 hw
+ret maskrel hw
+end
+ret lockdone
+end
+note wait k with budget gin 3+k (a uint32): checks, then budget, then pause, as the C loop; the polls
+note used go to gout k. Inner loops stop themselves at 999998 passes, so no loop reaches its bound.
+fn pollstep k ulong to bool
+b = get gin add 3 k
+n = ulong 0
+ok = false
+stop = false
+while not stop bound 4400
+c = ulong 0
+while true bound 999999
+if pollonce k
+ok = true
+stop = true
+break
+end
+if ge n b
+stop = true
+break
+end
+gsppause
+n = add n 1
+c = add c 1
+if eq c 999998
+break
+end
+end
+end
+put gout k n
+ret ok
+end
+note step 3: whole dwords little-endian, then a short tail zero-padded
+fn ememput ln ulong to void
+i = ulong 0
+while le add i 4 ln bound 300
+v = or ulong get gpkt i shl ulong get gpkt add i 1 8
+v = or v or shl ulong get gpkt add i 2 16 shl ulong get gpkt add i 3 24
+gspwr S2EMD v
+i = add i 4
+end
+if lt i ln
+t = ulong 0
+k = ulong 0
+while lt add i k ln bound 4
+t = or t shl ulong get gpkt add i k mul 8 k
+k = add k 1
+end
+gspwr S2EMD t
+end
+end
+fn gspfail e long to long
+put gstage 0 e
+ret e
+end
+note steps 1-11; returns the stage (also in gstage). Budgets and app_version are uint32 in the C
+note struct: a value above that range is refused as an argument error.
+fn gspboot to long
+for i ulong 12
+put gout i 0
+end
+put gstage 0 EARG
+ln = get gin 0
+if or eq ln 0 gt ln CHBYTES
+ret EARG
+end
+for j ulong 5
+if gt get gin add 2 j M32
+ret EARG
+end
+end
+if not gsppm
+ret gspfail EPM
+end
+if not pollstep 0
+ret gspfail EBUSY
+end
+gspwr S2EMC AINCW
+st = ememdw gsprd S2EMC
+ememput ln
+dw = div add ln 3 4
+put gout 4 dw
+ea = gsprd S2EMC
+put gout 5 ea
+if ne and sub ememdw ea st M32 dw
+ret gspfail EEMEM
+end
+gspwr S2QT sub mul dw 4 4
+gspwr S2QH 0
+if not pollstep 1
+put gout 7 gsprd S2MB1
+ret gspfail ESEC2
+end
+if not pollstep 2
+ret gspfail EMASK
+end
+if not pollstep 3
+put gout 10 gsprd GMB1
+ret gspfail ELOCK
+end
+m0 = gsprd GMB0
+put gout 9 m0
+if ne m0 0
+ret gspfail EFMC
+end
+gspwr GOS get gin 2
+cp = gsprd GCPUCTL
+put gout 11 cp
+if eq and cp CPUACT 0
+ret gspfail ERISCV
+end
+ret gspfail EOK
+end
+note announce new command-queue elements to GSP-RM (after the ring write and its fence)
+fn gspnotify to void
+gspwr GQH 0
+end
diff --git a/gsp/seq.om b/gsp/seq.om
new file mode 100644
index 0000000..7d3a6df
--- /dev/null
+++ b/gsp/seq.om
@@ -0,0 +1,200 @@
+note gsp/seq.om: the CPU side of GSP_RUN_CPU_SEQUENCER (event 0x1002) in seeded Omega, a port of
+note aien-dev/aienux PR #441 native/kernel/gpu/gsp_seq.{h,c} (gsp_seq_run, payload_dwords), which replaces
+note NVIDIA's kgspExecuteSequencerBuffer_IMPL (open-gpu-kernel-modules 580.173.02,
+note src/nvidia/src/kernel/gpu/gsp/kernel_gsp.c:5297-5432, called from the 0x1002 handler at :442).
+note Opcodes and payload sizes (rmgspseq.h src/nvidia/arch/nvalloc/common/inc/rmgspseq.h:78-101, :215):
+note   0 REG_WRITE  2 dwords  addr val              BAR0[addr] = val                       kernel_gsp.c:5331
+note   1 REG_MODIFY 3 dwords  addr mask val         BAR0[addr] = (old & ~mask) | val        :5341
+note   2 REG_POLL   5 dwords  addr mask val tmo err wait until (BAR0[addr] & mask) == val   :5356
+note   3 DELAY_US   1 dword   us                    wait us microseconds                   :5383
+note   4 REG_STORE  2 dwords  addr index            save[index] = BAR0[addr], index < 8     :5392, :5397
+note   5 CORE_RESET 6 CORE_START 7 CORE_WAIT_FOR_HALT 8 CORE_RESUME: 0 dwords              :5403 :5412 :5420
+note All nine are here; none is missing. The four core opcodes are falcon HALs in NVIDIA (kflcnReset,
+note kflcnStartCpu, kflcnWaitForHalt; on GB10B CORE_RESUME goes to kgspExecuteSequencerCommand_GA102,
+note g_kernel_gsp_nvoc.c:1028-1047 -> kernel_gsp_ga102.c:136-200). They restart the chip, so, as in the C,
+note they are not guessed at register level: the build supplies fn sqcorefn op ulong to long (0 done,
+note anything else failed) and sets sqcore 1; with sqcore 0 every core opcode is refused.
+note The walk is the C's: nwords (bufferSizeDWord) > 0, ci (cmdIndex) < nwords, stop at ci; an unknown
+note opcode or a payload that runs past ci is refused before anything of it is done. REG_POLL's timeout
+note and error dwords are not used: a poll gets sqbud extra reads (0 counts as 1), as in the C.
+note Library unit: no main. Build after gsp/mmio.om (gsprd, gspwr, gsppause, gspmode, M32) and, for host
+note tests, gsp/sim.om. Register I/O is only gsprd/gspwr; mode 0 is the simulator, mode 1 BAR0.
+note Name prefix sq / SQ only. Nothing here has run on the chip.
+note
+note API: put the dwords in sqbuf[0..nwords), set sqbud (poll budget), sqcore (0/1), clear sqsave and sqdly
+note if wanted, then r = sqrun nwords cmdindex. sqrun returns 0 or a code below; sqwhy r puts the C's why text
+note into sqwb[0..sqwl). sqsave[0..8) gets REG_STORE values; sqdly[0] counts DELAY_US opcodes, sqdly[1]
+note adds their microseconds (mode 1 also sleeps them).
+note Codes: -1 empty buffer; -2 cmdIndex not inside the buffer; -3 unknown opcode; -4 opcode overruns
+note cmdIndex; -5 poll timed out; -6 save index out of range; -7 core opcode with no core callback;
+note -8 core opcode failed; .om only: -9 nwords over 16384 (sqbuf, the 64 KiB GSP message limit,
+note message_queue_priv.h:91-96, as dwords); -10 the mode 1 sleep failed; -11 poll budget over 999998
+note (the OM-1 loop bound). The C's "null argument" has no counterpart: nothing here can be null.
+const SQMAX ulong 16384
+const SQSAVE ulong 8
+const SQBMAX ulong 999998
+note opcode numbers (rmgspseq.h:78-101)
+const SQWR ulong 0
+const SQMOD ulong 1
+const SQPOLL ulong 2
+const SQDLY ulong 3
+const SQSTO ulong 4
+const SQCRST ulong 5
+const SQCRES ulong 8
+const SQEEMP long -1
+const SQEIDX long -2
+const SQEOP long -3
+const SQEOVR long -4
+const SQEPOLL long -5
+const SQESAVE long -6
+const SQENOC long -7
+const SQECORE long -8
+const SQECAP long -9
+const SQESLP long -10
+const SQEBUD long -11
+text sqwt "empty buffer|cmdIndex not inside the buffer|unknown opcode|opcode overruns cmdIndex|poll timed out|save index out of range|core opcode with no core callback|core opcode failed|nwords over 16384|delay sleep failed|poll budget over 999998|"
+global sqbuf uint 16384
+global sqsave ulong 8
+global sqbud ulong 1
+global sqcore ulong 1
+global sqdly ulong 2
+global sqwb uchar 64
+global sqwl ulong 1
+note payload dwords of op, M32 for an unknown opcode (GSP_SEQUENCER_PAYLOAD_SIZE_DWORDS)
+fn sqpay op ulong to ulong
+if or eq op SQWR eq op SQSTO
+ret 2
+end
+if eq op SQMOD
+ret 3
+end
+if eq op SQPOLL
+ret 5
+end
+if eq op SQDLY
+ret 1
+end
+if and ge op SQCRST le op SQCRES
+ret 0
+end
+ret M32
+end
+fn sqw i ulong to ulong
+ret ulong get sqbuf i
+end
+fn sqpoll a0 ulong a1 ulong a2 ulong to long
+left = get sqbud 0
+if eq left 0
+left = 1
+end
+v = and gsprd a0 M32
+while ne and v a1 a2 bound 999999
+if eq left 0
+ret SQEPOLL
+end
+left = sub left 1
+gsppause
+v = and gsprd a0 M32
+end
+ret 0
+end
+note one opcode whose payload starts at sqbuf[i]
+fn sqone op ulong i ulong to long
+if eq op SQWR
+gspwr sqw i sqw add i 1
+ret 0
+end
+if eq op SQMOD
+a = sqw i
+v = and gsprd a M32
+gspwr a or and v xor sqw add i 1 M32 sqw add i 2
+ret 0
+end
+if eq op SQPOLL
+r = sqpoll sqw i sqw add i 1 sqw add i 2
+ret r
+end
+if eq op SQDLY
+us = sqw i
+put sqdly 0 add get sqdly 0 1
+put sqdly 1 add get sqdly 1 us
+if eq get gspmode 0 1
+s = sleepns long mul us 1000
+if lt s 0
+ret SQESLP
+end
+end
+ret 0
+end
+if eq op SQSTO
+k = sqw add i 1
+if ge k SQSAVE
+ret SQESAVE
+end
+put sqsave k and gsprd sqw i M32
+ret 0
+end
+if eq get sqcore 0 0
+ret SQENOC
+end
+c = sqcorefn op
+if ne c 0
+ret SQECORE
+end
+ret 0
+end
+fn sqrun nw ulong ci ulong to long
+put sqwl 0 0
+if eq nw 0
+ret SQEEMP
+end
+if ge ci nw
+ret SQEIDX
+end
+if gt nw SQMAX
+ret SQECAP
+end
+if gt get sqbud 0 SQBMAX
+ret SQEBUD
+end
+i = ulong 0
+while lt i ci bound 999999
+op = sqw i
+i = add i 1
+n = sqpay op
+if eq n M32
+ret SQEOP
+end
+if gt add i n ci
+ret SQEOVR
+end
+r = sqone op i
+if ne r 0
+ret r
+end
+i = add i n
+end
+ret 0
+end
+note the why text of code e into sqwb[0..sqwl); 0 leaves it empty
+fn sqwhy e long to void
+put sqwl 0 0
+if ge e 0
+ret
+end
+k = ulong sub 0 add e 1
+w = ulong 0
+o = ulong 0
+for j ulong len sqwt
+c = get sqwt j
+if eq c 124
+w = add w 1
+else
+if eq w k
+put sqwb o c
+o = add o 1
+end
+end
+end
+put sqwl 0 o
+end
diff --git a/gsp/sha2.om b/gsp/sha2.om
new file mode 100644
index 0000000..bb3446e
--- /dev/null
+++ b/gsp/sha2.om
@@ -0,0 +1,518 @@
+note gsp/sha2.om: SHA-256 and SHA-384 (FIPS 180-4) in seeded Omega (OM-1), for the GB10 firmware
+note inputs. Ports the digests the aienux PR #441 tools use: argus/sha256.c (sha256_init/update/final,
+note used by ck_gsp_fw_inspect.c and ck_gsp_bindata_extract.c) and the SHA-384 of
+note ck_gsp_bindata_extract.c lines 84-197 (sha512_block, sha384). Library unit: no main.
+note Prefix sh. Input is always the window shin[off..off+n), n <= SHWIN; callers copy or pread into it.
+note SHA-256: eight independent streaming contexts cx 0..7 (shh, shtot, shbn, shbf), so one pass over a
+note file can feed several digests. SHA-384: one streaming context (sh5h, sh5t, sh5n, sh5b).
+note A digest lands in shout (32 or 48 bytes); shhex n writes its lowercase hex into shhx[0..2n).
+note Constants: K256 = first 32 bits of the fractional parts of the cube roots of the first 64 primes,
+note K512 = first 64 bits for the first 80 primes, IV256 = square roots of the first 8 primes (32 bits),
+note IV384 = square roots of primes 9..16 (64 bits). All decimal, computed by WolframLanguageEvaluator:
+note Table[Floor[FractionalPart[N[CubeRoot[Prime[i]],120]]*2^64],{i,80}] (and the 2^32 / Sqrt forms);
+note spot checks against the C hex: K512[0] 0x428a2f98d728ae22, K512[79] 0x6c44198c4a475817,
+note IV384[0] 0xcbbb9d5dc1059ed8, IV384[7] 0x47b5481dbefa4fa4, K256[63] 0xc67178f2.
+const SHWIN ulong 524288
+global shin uchar 524288
+global shok ulong 1
+global shk uint 64
+global shk5 ulong 80
+global shh uint 64
+global shv uint 8
+global shtot ulong 8
+global shbn ulong 8
+global shbf uchar 512
+global shw uint 64
+global sh5h ulong 8
+global sh5t ulong 1
+global sh5n ulong 1
+global sh5b uchar 128
+global sh5w ulong 80
+global shout uchar 64
+global shhx uchar 128
+fn shsetup to void
+if eq get shok 0 1
+ret
+end
+put shk 0 1116352408
+put shk 1 1899447441
+put shk 2 3049323471
+put shk 3 3921009573
+put shk 4 961987163
+put shk 5 1508970993
+put shk 6 2453635748
+put shk 7 2870763221
+put shk 8 3624381080
+put shk 9 310598401
+put shk 10 607225278
+put shk 11 1426881987
+put shk 12 1925078388
+put shk 13 2162078206
+put shk 14 2614888103
+put shk 15 3248222580
+put shk 16 3835390401
+put shk 17 4022224774
+put shk 18 264347078
+put shk 19 604807628
+put shk 20 770255983
+put shk 21 1249150122
+put shk 22 1555081692
+put shk 23 1996064986
+put shk 24 2554220882
+put shk 25 2821834349
+put shk 26 2952996808
+put shk 27 3210313671
+put shk 28 3336571891
+put shk 29 3584528711
+put shk 30 113926993
+put shk 31 338241895
+put shk 32 666307205
+put shk 33 773529912
+put shk 34 1294757372
+put shk 35 1396182291
+put shk 36 1695183700
+put shk 37 1986661051
+put shk 38 2177026350
+put shk 39 2456956037
+put shk 40 2730485921
+put shk 41 2820302411
+put shk 42 3259730800
+put shk 43 3345764771
+put shk 44 3516065817
+put shk 45 3600352804
+put shk 46 4094571909
+put shk 47 275423344
+put shk 48 430227734
+put shk 49 506948616
+put shk 50 659060556
+put shk 51 883997877
+put shk 52 958139571
+put shk 53 1322822218
+put shk 54 1537002063
+put shk 55 1747873779
+put shk 56 1955562222
+put shk 57 2024104815
+put shk 58 2227730452
+put shk 59 2361852424
+put shk 60 2428436474
+put shk 61 2756734187
+put shk 62 3204031479
+put shk 63 3329325298
+put shk5 0 4794697086780616226
+put shk5 1 8158064640168781261
+put shk5 2 13096744586834688815
+put shk5 3 16840607885511220156
+put shk5 4 4131703408338449720
+put shk5 5 6480981068601479193
+put shk5 6 10538285296894168987
+put shk5 7 12329834152419229976
+put shk5 8 15566598209576043074
+put shk5 9 1334009975649890238
+put shk5 10 2608012711638119052
+put shk5 11 6128411473006802146
+put shk5 12 8268148722764581231
+put shk5 13 9286055187155687089
+put shk5 14 11230858885718282805
+put shk5 15 13951009754708518548
+put shk5 16 16472876342353939154
+put shk5 17 17275323862435702243
+put shk5 18 1135362057144423861
+put shk5 19 2597628984639134821
+put shk5 20 3308224258029322869
+put shk5 21 5365058923640841347
+put shk5 22 6679025012923562964
+put shk5 23 8573033837759648693
+put shk5 24 10970295158949994411
+put shk5 25 12119686244451234320
+put shk5 26 12683024718118986047
+put shk5 27 13788192230050041572
+put shk5 28 14330467153632333762
+put shk5 29 15395433587784984357
+put shk5 30 489312712824947311
+put shk5 31 1452737877330783856
+put shk5 32 2861767655752347644
+put shk5 33 3322285676063803686
+put shk5 34 5560940570517711597
+put shk5 35 5996557281743188959
+put shk5 36 7280758554555802590
+put shk5 37 8532644243296465576
+put shk5 38 9350256976987008742
+put shk5 39 10552545826968843579
+put shk5 40 11727347734174303076
+put shk5 41 12113106623233404929
+put shk5 42 14000437183269869457
+put shk5 43 14369950271660146224
+put shk5 44 15101387698204529176
+put shk5 45 15463397548674623760
+put shk5 46 17586052441742319658
+put shk5 47 1182934255886127544
+put shk5 48 1847814050463011016
+put shk5 49 2177327727835720531
+put shk5 50 2830643537854262169
+put shk5 51 3796741975233480872
+put shk5 52 4115178125766777443
+put shk5 53 5681478168544905931
+put shk5 54 6601373596472566643
+put shk5 55 7507060721942968483
+put shk5 56 8399075790359081724
+put shk5 57 8693463985226723168
+put shk5 58 9568029438360202098
+put shk5 59 10144078919501101548
+put shk5 60 10430055236837252648
+put shk5 61 11840083180663258601
+put shk5 62 13761210420658862357
+put shk5 63 14299343276471374635
+put shk5 64 14566680578165727644
+put shk5 65 15097957966210449927
+put shk5 66 16922976911328602910
+put shk5 67 17689382322260857208
+put shk5 68 500013540394364858
+put shk5 69 748580250866718886
+put shk5 70 1242879168328830382
+put shk5 71 1977374033974150939
+put shk5 72 2944078676154940804
+put shk5 73 3659926193048069267
+put shk5 74 4368137639120453308
+put shk5 75 4836135668995329356
+put shk5 76 5532061633213252278
+put shk5 77 6448918945643986474
+put shk5 78 6902733635092675308
+put shk5 79 7801388544844847127
+put shok 0 1
+end
+note SHA-256 context cx (0..7): chaining value shh[8cx..8cx+8), bytes absorbed shtot[cx], pending
+note block shbf[64cx..64cx+shbn[cx])
+fn sh2init cx ulong to void
+shsetup
+b = mul cx 8
+put shh b 1779033703
+put shh add b 1 3144134277
+put shh add b 2 1013904242
+put shh add b 3 2773480762
+put shh add b 4 1359893119
+put shh add b 5 2600822924
+put shh add b 6 528734635
+put shh add b 7 1541459225
+put shtot cx 0
+put shbn cx 0
+end
+note the 64 rounds over the schedule in shw, folded into the chaining value in shv (16 registers:
+note the state lives in a..h, the sums are built one term at a time)
+fn sh2rnd to void
+a = get shv 0
+b = get shv 1
+c = get shv 2
+d = get shv 3
+e = get shv 4
+f = get shv 5
+g = get shv 6
+h = get shv 7
+for t ulong 64
+x = or shr e 6 shl e 26
+x = xor x or shr e 11 shl e 21
+x = xor x or shr e 25 shl e 7
+x = add x h
+x = add x xor and e f and not e g
+x = add x get shk t
+x = add x get shw t
+h = g
+g = f
+f = e
+e = add d x
+d = c
+c = b
+b = a
+y = or shr b 2 shl b 30
+y = xor y or shr b 13 shl b 19
+y = xor y or shr b 22 shl b 10
+x = add x y
+y = xor and b c and b d
+y = xor y and c d
+a = add x y
+end
+put shv 0 add get shv 0 a
+put shv 1 add get shv 1 b
+put shv 2 add get shv 2 c
+put shv 3 add get shv 3 d
+put shv 4 add get shv 4 e
+put shv 5 add get shv 5 f
+put shv 6 add get shv 6 g
+put shv 7 add get shv 7 h
+end
+note one 64-byte block: src 0 = shin[off..off+64), src 1 = shbf[off..off+64)
+fn sh2comp cx ulong src ulong off ulong to void
+for t ulong 16
+p = add off mul t 4
+if eq src 0
+v = or shl uint get shin p 24 shl uint get shin add p 1 16
+v = or v or shl uint get shin add p 2 8 uint get shin add p 3
+put shw t v
+else
+v = or shl uint get shbf p 24 shl uint get shbf add p 1 16
+v = or v or shl uint get shbf add p 2 8 uint get shbf add p 3
+put shw t v
+end
+end
+for u ulong 48
+i = add u 16
+x = get shw sub i 2
+s = or shr x 17 shl x 15
+s = xor s or shr x 19 shl x 13
+s = xor s shr x 10
+y = get shw sub i 15
+r = or shr y 7 shl y 25
+r = xor r or shr y 18 shl y 14
+r = xor r shr y 3
+s = add s get shw sub i 7
+r = add r get shw sub i 16
+put shw i add s r
+end
+bs = mul cx 8
+for j ulong 8
+put shv j get shh add bs j
+end
+sh2rnd
+for j2 ulong 8
+put shh add bs j2 get shv j2
+end
+end
+note absorb shin[off..off+n) into context cx; n <= SHWIN
+fn sh2upd cx ulong off ulong n ulong to void
+if gt n SHWIN
+trap 3
+end
+bo = mul cx 64
+i = ulong 0
+while lt i n bound 999999
+bn = get shbn cx
+if and eq bn 0 le add i 64 n
+sh2comp cx 0 add off i
+i = add i 64
+else
+put shbf add bo bn get shin add off i
+bn = add bn 1
+i = add i 1
+if eq bn 64
+sh2comp cx 1 bo
+bn = ulong 0
+end
+put shbn cx bn
+end
+end
+put shtot cx add get shtot cx n
+end
+note pad and finish context cx: the 32-byte digest goes to shout[0..32)
+fn sh2fin cx ulong to void
+bo = mul cx 64
+bits = mul get shtot cx 8
+bn = get shbn cx
+put shbf add bo bn 128
+bn = add bn 1
+if gt bn 56
+while lt bn 64 bound 64
+put shbf add bo bn 0
+bn = add bn 1
+end
+sh2comp cx 1 bo
+bn = ulong 0
+end
+while lt bn 56 bound 64
+put shbf add bo bn 0
+bn = add bn 1
+end
+for k ulong 8
+bn = and shr bits mul sub 7 k 8 255
+put shbf add bo add 56 k uchar bn
+end
+sh2comp cx 1 bo
+put shbn cx 0
+bo = mul cx 8
+for j ulong 8
+bits = ulong get shh add bo j
+bn = mul j 4
+put shout bn uchar and shr bits 24 255
+put shout add bn 1 uchar and shr bits 16 255
+put shout add bn 2 uchar and shr bits 8 255
+put shout add bn 3 uchar and bits 255
+end
+end
+note hash bytes [off, off+n) of the open file fd into context cx through shin; returns 0, the negative
+note errno of a failed pread, or -5 (EIO) when the file ends early
+fn sh2file cx ulong fd int off ulong n ulong to long
+p = ulong 0
+while lt p n bound 999999
+k = sub n p
+if gt k SHWIN
+k = SHWIN
+end
+q = ulong 0
+while lt q k bound 999999
+r = pread fd shin q sub k q long add add off p q
+if lt r 0
+ret r
+end
+if eq r 0
+ret -5
+end
+q = add q ulong r
+end
+sh2upd cx 0 k
+p = add p k
+end
+ret 0
+end
+note SHA-384 (one context)
+fn sh5init to void
+shsetup
+put sh5h 0 14680500436340154072
+put sh5h 1 7105036623409894663
+put sh5h 2 10473403895298186519
+put sh5h 3 1526699215303891257
+put sh5h 4 7436329637833083697
+put sh5h 5 10282925794625328401
+put sh5h 6 15784041429090275239
+put sh5h 7 5167115440072839076
+put sh5t 0 0
+put sh5n 0 0
+end
+fn sh5rnd to void
+a = get sh5h 0
+b = get sh5h 1
+c = get sh5h 2
+d = get sh5h 3
+e = get sh5h 4
+f = get sh5h 5
+g = get sh5h 6
+h = get sh5h 7
+for t ulong 80
+x = or shr e 14 shl e 50
+x = xor x or shr e 18 shl e 46
+x = xor x or shr e 41 shl e 23
+x = add x h
+x = add x xor and e f and not e g
+x = add x get shk5 t
+x = add x get sh5w t
+h = g
+g = f
+f = e
+e = add d x
+d = c
+c = b
+b = a
+y = or shr b 28 shl b 36
+y = xor y or shr b 34 shl b 30
+y = xor y or shr b 39 shl b 25
+x = add x y
+y = xor and b c and b d
+y = xor y and c d
+a = add x y
+end
+put sh5h 0 add get sh5h 0 a
+put sh5h 1 add get sh5h 1 b
+put sh5h 2 add get sh5h 2 c
+put sh5h 3 add get sh5h 3 d
+put sh5h 4 add get sh5h 4 e
+put sh5h 5 add get sh5h 5 f
+put sh5h 6 add get sh5h 6 g
+put sh5h 7 add get sh5h 7 h
+end
+note one 128-byte block: src 0 = shin[off..off+128), src 1 = sh5b
+fn sh5comp src ulong off ulong to void
+for t ulong 16
+v = ulong 0
+for k ulong 8
+if eq src 0
+v = or shl v 8 ulong get shin add add off mul t 8 k
+else
+v = or shl v 8 ulong get sh5b add mul t 8 k
+end
+end
+put sh5w t v
+end
+for u ulong 64
+i = add u 16
+x = get sh5w sub i 2
+s = or shr x 19 shl x 45
+s = xor s or shr x 61 shl x 3
+s = xor s shr x 6
+y = get sh5w sub i 15
+r = or shr y 1 shl y 63
+r = xor r or shr y 8 shl y 56
+r = xor r shr y 7
+s = add s get sh5w sub i 7
+r = add r get sh5w sub i 16
+put sh5w i add s r
+end
+sh5rnd
+end
+fn sh5upd off ulong n ulong to void
+if gt n SHWIN
+trap 3
+end
+i = ulong 0
+while lt i n bound 999999
+bn = get sh5n 0
+if and eq bn 0 le add i 128 n
+sh5comp 0 add off i
+i = add i 128
+else
+put sh5b bn get shin add off i
+bn = add bn 1
+i = add i 1
+if eq bn 128
+sh5comp 1 0
+bn = ulong 0
+end
+put sh5n 0 bn
+end
+end
+put sh5t 0 add get sh5t 0 n
+end
+note pad and finish: the 48-byte digest goes to shout[0..48) (message length below 2^61 bytes)
+fn sh5fin to void
+bits = mul get sh5t 0 8
+bn = get sh5n 0
+put sh5b bn 128
+bn = add bn 1
+if gt bn 112
+while lt bn 128 bound 128
+put sh5b bn 0
+bn = add bn 1
+end
+sh5comp 1 0
+bn = ulong 0
+end
+while lt bn 120 bound 128
+put sh5b bn 0
+bn = add bn 1
+end
+for k ulong 8
+bn = and shr bits mul sub 7 k 8 255
+put sh5b add 120 k uchar bn
+end
+sh5comp 1 0
+put sh5n 0 0
+for j ulong 48
+bits = get sh5h div j 8
+bn = and shr bits mul sub 7 rem j 8 8 255
+put shout j uchar bn
+end
+end
+note lowercase hex of shout[0..n) into shhx[0..2n), n <= 64
+fn shhex n ulong to void
+for i ulong n
+b = get shout i
+hi = shr b 4
+lo = and b 15
+if lt hi 10
+put shhx mul i 2 add hi 48
+else
+put shhx mul i 2 add hi 87
+end
+if lt lo 10
+put shhx add mul i 2 1 add lo 48
+else
+put shhx add mul i 2 1 add lo 87
+end
+end
+end
diff --git a/gsp/sim.om b/gsp/sim.om
new file mode 100644
index 0000000..4dc8620
--- /dev/null
+++ b/gsp/sim.om
@@ -0,0 +1,325 @@
+note gsp/sim.om: a simulated GB10B SEC2 + GSP falcon for host tests of gsp/mmio.om. NOT the chip.
+note Port of aien-dev/aienux PR #441 native/kernel/gpu/gsp_sim.{h,c}. Models only what the driver source
+note says the host sees on BAR0 during GSP start-up: SEC2 EMEM channel 0 (1 KiB, EMEMC/EMEMD with write
+note auto-increment), its queue HEAD/TAIL and MAILBOX0/1, and the GSP falcon's MAILBOX0/1, HWCFG2
+note (target-mask pattern, lockdown bit 13), FALCON_OS, RISC-V CPUCTL and QUEUE_HEAD(0). Time is counted
+note in reads of the polled register. Every access is logged in order (first 1024 kept, all counted);
+note accesses the driver never makes, and orders it never uses, are violations. SIM-CHOICE marks what
+note the source does not settle. The offsets are this file's own copies (not the driver's), so a wrong
+note driver constant shows up as a wrong access instead of moving the simulator with it.
+note Library unit: no main. simrd / simwr are the mode 0 device of gsprd / gspwr.
+const XS2MB0 ulong 8650816
+const XS2MB1 ulong 8650820
+const XS2EMC ulong 8653504
+const XS2EMD ulong 8653508
+const XS2QH ulong 8653824
+const XS2QT ulong 8653828
+const XGMB0 ulong 1114176
+const XGMB1 ulong 1114180
+const XGOS ulong 1114240
+const XGHWCF2 ulong 1114356
+const XGQH ulong 1117184
+const XGCPUCT ulong 1119112
+note AINCW 1<<24, busy 0xc001cafe, lockdown 1<<13, active 1<<7, a wait that never ends 0xFFFFFFFF
+const XAINCW ulong 16777216
+const XBUSY ulong 3221342974
+const XLOCK ulong 8192
+const XACT ulong 128
+const XM32 ulong 4294967295
+const NOEND ulong 4294967295
+const LOGMAX ulong 1024
+note config (struct ck_gspsim_cfg), set by the caller before siminit: scfg
+note 0 busy_reads, 1 cmd_reads, 2 mask_reads, 3 args_reads, 4 lockdown_reads, 5 fmc_error, 6 riscv_dead,
+note 7 emem_no_inc, 8 fmc_args_pa, 9 hwcfg2_zero_reads
+global scfg ulong 10
+global semem ulong 256
+note runtime PM state of the simulated device, set by the caller: 0 active, 1 suspended (D3).
+note siminit leaves it alone. Any access while suspended counts as a violation.
+global spm ulong 1
+fn simpmok to bool
+ret eq get spm 0 0
+end
+note state words: ss[i]
+const SEMEMC ulong 0
+const SQHEAD ulong 1
+const SQTAIL ulong 2
+const SS2MB0 ulong 3
+const SS2MB1 ulong 4
+const SGMB0 ulong 5
+const SGMB1 ulong 6
+const SHWCFG2 ulong 7
+const SOS ulong 8
+const SCPUCTL ulong 9
+const SGQHW ulong 10
+note phase: 0 idle, 1 command posted, 2 handled (mask), 3 FMC running (lockdown), 4 released, 9 rejected
+const SPHASE ulong 11
+const SLEFT ulong 12
+const SZLEFT ulong 13
+const SPKTOK ulong 14
+const SOSPH ulong 15
+const SNLOG ulong 16
+const SVIOL ulong 17
+global ss ulong 18
+global slogo ulong 1024
+global slogv ulong 1024
+global slogw uchar 1024
+fn sg i ulong to ulong
+ret get ss i
+end
+fn sp i ulong v ulong to void
+put ss i v
+end
+fn sviol to void
+sp SVIOL add sg SVIOL 1
+end
+note a countdown word: 0 stays (the caller acts on 0), NOEND stays, anything else drops by one
+fn sdec i ulong to void
+l = sg i
+if and ne l 0 ne l NOEND
+sp i sub l 1
+end
+end
+fn slog off ulong v ulong w uchar to void
+n = sg SNLOG
+if lt n LOGMAX
+put slogo n off
+put slogv n v
+put slogw n w
+end
+sp SNLOG add n 1
+end
+fn siminit to void
+for i ulong 18
+sp i 0
+end
+for j ulong 256
+put semem j 0
+end
+note an old message in the channel: HEAD != TAIL until busy_reads HEAD reads have passed
+if ne get scfg 0 0
+sp SQHEAD 0
+sp SQTAIL 16
+end
+note SIM-CHOICE: target locked to SEC2, low byte 0xA7 (0xBADF41A7); idle SEC2 MAILBOX0 0
+sp SHWCFG2 3135193511
+sp SS2MB0 0
+sp SLEFT get scfg 0
+end
+note SEC2 checks the packet: MCTP SOM|EOM 0xC0000000, NVDM 0x1410DE7E, payload version 1, size 860,
+note TAIL 864. Anything else (SIM-CHOICE): consumed, the target mask is never released.
+fn simpkt to bool
+a = and eq sg SQTAIL 864 eq get semem 0 3221225472
+b = and eq get semem 1 336649854 eq and get semem 2 65535 1
+ret and and a b eq shr get semem 2 16 860
+end
+fn srqh to ulong
+if and eq sg SPHASE 0 ne sg SQHEAD sg SQTAIL
+if eq sg SLEFT 0
+sp SQHEAD sg SQTAIL
+else
+sdec SLEFT
+end
+end
+ret sg SQHEAD
+end
+fn srmb0 to ulong
+if eq sg SPHASE 1
+if eq sg SLEFT 0
+sp SS2MB0 0
+sp SQHEAD sg SQTAIL
+if ne sg SPKTOK 0
+sp SPHASE 2
+sp SLEFT get scfg 2
+sp SZLEFT get scfg 9
+else
+sp SPHASE 9
+end
+else
+sdec SLEFT
+end
+end
+ret sg SS2MB0
+end
+fn srfmc to void
+if eq sg SLEFT 0
+if ne get scfg 5 0
+sp SGMB0 get scfg 5
+else
+sp SHWCFG2 and sg SHWCFG2 not XLOCK
+sp SPHASE 4
+if eq get scfg 6 0
+sp SCPUCTL XACT
+end
+end
+else
+sdec SLEFT
+end
+end
+fn srhw to ulong
+ph = sg SPHASE
+if and eq ph 2 ne sg SZLEFT 0
+sdec SZLEFT
+ret 0
+end
+if eq ph 2
+if eq sg SLEFT 0
+sp SPHASE 3
+note SIM-CHOICE: other HWCFG2 bits 0x5, so HWCFG2 = 0x2005
+sp SHWCFG2 or XLOCK 5
+pa = get scfg 8
+sp SGMB0 and pa XM32
+sp SGMB1 shr pa 32
+sp SLEFT get scfg 4
+else
+sdec SLEFT
+end
+else
+if and eq ph 3 ne sg SGMB0 and get scfg 8 XM32
+srfmc
+end
+end
+ret sg SHWCFG2
+end
+fn srgmb0 to ulong
+if and eq sg SPHASE 3 eq sg SGMB0 and get scfg 8 XM32
+a = get scfg 3
+if ne a NOEND
+if eq a 0
+sp SGMB0 0
+sp SGMB1 0
+else
+put scfg 3 sub a 1
+end
+end
+end
+ret sg SGMB0
+end
+fn simrd off ulong to ulong
+if ne get spm 0 0
+sviol
+end
+v = ulong 0
+if eq off XS2QH
+v = srqh
+else
+if eq off XS2QT
+v = sg SQTAIL
+else
+if eq off XS2EMC
+v = sg SEMEMC
+else
+if eq off XS2EMD
+e = sg SEMEMC
+v = get semem and add mul and shr e 8 255 64 and shr e 2 63 255
+else
+if eq off XS2MB0
+v = srmb0
+else
+if eq off XS2MB1
+v = sg SS2MB1
+else
+if eq off XGHWCF2
+v = srhw
+else
+if eq off XGMB0
+v = srgmb0
+else
+if eq off XGMB1
+v = sg SGMB1
+else
+if eq off XGOS
+v = sg SOS
+else
+if eq off XGCPUCT
+v = sg SCPUCTL
+else
+sviol
+end
+end
+end
+end
+end
+end
+end
+end
+end
+end
+end
+slog off v 0
+ret v
+end
+fn swememd val ulong to void
+e = sg SEMEMC
+dw = add mul and shr e 8 255 64 and shr e 2 63
+if or or eq and e XAINCW 0 ge dw 256 ne sg SPHASE 0
+sviol
+ret
+end
+put semem dw val
+if eq get scfg 7 0
+dw = add dw 1
+note EMEMC keeps all but bits 2..15 (mask ~0xFFFC = 0xFFFF0003), then block << 8 | offset << 2
+sp SEMEMC or or and e 4294901763 shl and div dw 64 255 8 shl rem dw 64 2
+end
+end
+fn swqh val ulong to void
+ph = sg SPHASE
+note the doorbell: TAIL must already point at the last dword of a message starting at 0
+if or or ne ph 0 ne val 0 eq sg SQTAIL sg SQHEAD
+sviol
+end
+sp SQHEAD val
+if eq ph 0
+if simpkt
+sp SPKTOK 1
+else
+sp SPKTOK 0
+end
+sp SPHASE 1
+sp SS2MB0 XBUSY
+sp SLEFT get scfg 1
+end
+end
+fn simwr off ulong val ulong to void
+if ne get spm 0 0
+sviol
+end
+slog off val 1
+if eq off XS2EMC
+sp SEMEMC val
+ret
+end
+if eq off XS2EMD
+swememd val
+ret
+end
+if eq off XS2QT
+note the driver writes only into an empty channel
+if or ne sg SPHASE 0 ne sg SQHEAD sg SQTAIL
+sviol
+end
+sp SQTAIL val
+ret
+end
+if eq off XS2QH
+swqh val
+ret
+end
+if eq off XGOS
+sp SOS val
+sp SOSPH sg SPHASE
+note FALCON_OS before lockdown release
+if ne sg SPHASE 4
+sviol
+end
+ret
+end
+if eq off XGQH
+sp SGQHW add sg SGQHW 1
+if ne val 0
+sviol
+end
+ret
+end
+sviol
+end
diff --git a/gsp/sysinfo.om b/gsp/sysinfo.om
new file mode 100644
index 0000000..cd445a5
--- /dev/null
+++ b/gsp/sysinfo.om
@@ -0,0 +1,709 @@
+note gsp/sysinfo.om: the GspSystemInfo payload of GSP_SET_SYSTEM_INFO (RPC 72, 936 bytes) in seeded Omega.
+note Port of aien-dev/aienux PR #441 native/kernel/tools/ck_gsp_sysinfo_encode.c (encode, the fields
+note table, the slurped-text rules). The 72 field offsets and sizes are that tool's table, which its
+note nvhdr gate checks against NVIDIA's GspSystemInfo (open-gpu-kernel-modules 580.173.02,
+note src/nvidia/generated/g_rpc-structures.h via gsp_static_config.h). Little endian, every byte not set is 0.
+note Library unit: no main. Name prefix si / SI only.
+note
+note API (all state is in globals; a global can never be an argument):
+note   sireset            load the table, clear values, seen marks, set order and siout. Call first.
+note   siseti k v         set field k (0..71, the order below) to v; long code
+note   sisetn v           set the field named sinam[0..sinl) to v; long code
+note   sitext n           parse sitxt[0..n) as the C tool's "field value" lines; long code; the set
+note                      order (siord[0..sinord)) lets a caller echo each accepted line
+note   siencode           build siout[0..936) from every accepted field
+note   sinmk k            copy field k's name into sinam/sinl
+note   siwhy e            put the refusal text of code e into siwb[0..siwl) (the C tool's why string;
+note                      for siseti/sisetn refusals the "line N: " prefix is left out)
+note codes: 0 SIEOK; -1 SIEIDX index past 71 (API only); -2 SIEREP field repeated; -3 SIEFIT value
+note does not fit the field; -4 SIEUNK unknown field; -5 SIENUM not a number; -6 SIEWANT line is not
+note "field value"; -7 SIELONG line of 512 bytes or more; -8 SIEBIG text over 65536 bytes (.om only, the
+note C slurps any size); -9 SIENIT sireset not called (.om only).
+note A refused set leaves the field unset; a refused sitext ends at the refused line (lines before it
+note stay set, as the C tool's partial echo shows), and the caller must not send siout then.
+note
+note Field sources for ogd on GB10 (VFIO userspace; nvidia.ko fill sites in open-gpu-kernel-modules
+note 580.173.02; every NVIDIA path below is under src/nvidia/ unless it starts with kernel-open/). All
+note fields are written by rpcGspSetSystemInfo_v17_00, src/kernel/vgpu/rpc.c:10493-10658. Window-1
+note values (hex) and their DOCUMENTED/OBSERVED/INFERRED/ASSUMED tags are in aienux
+note evidence/own-gpu-driver/rung2/system_info.txt. Source classes:
+note   CFG   = the GPU's own PCI config space, read through the VFIO config region (index 7)
+note   RP    = the upstream root port's config space (outside the VFIO group: sysfs config, read-only)
+note   CONST = fixed for GB10B / this host build, documented in the NVIDIA source
+note   OS    = host kernel constant
+note   DRV   = ogd's own allocation
+note   LIVE  = only a live read on the running GPU gives it
+note field                             src    nvidia.ko fill site                            GB10 value
+note gpuPhysAddr                       CFG    rpc.c:10525 <- gpu_mgr.c:1967 <- osinit.c:738     0x24000000
+note                                          (nv->regs->cpu_address, BAR0 start, nv-pci.c:1500-1502);
+note                                          ogd: BAR0/BAR1 dwords 0x10/0x14 of the config region or the
+note                                          sysfs resource file. LIVE per boot (PCI assignment).
+note gpuPhysFbAddr                     CONST  rpc.c:10526 <- osinit.c:739 (nv->fb, no FB BAR)       0
+note gpuPhysInstAddr                   CFG    rpc.c:10527 <- gpu_mgr.c:1994 (BAR0 + 0x700000)      0x24700000
+note gpuPhysIoAddr                     CONST  rpc.c:10528                                           0
+note nvDomainBusDeviceFunc             CFG    rpc.c:10529 <- osinit.c:764, osinit.c:144-147,         0xf00000100
+note                                          g_gpu_nvoc.h:502-507; ogd: the BDF it opened (000f:01:00.0)
+note simAccessBufPhysAddr              CONST  rpc.c:10562-10569 (0 outside simulation)              0
+note notifyOpSharedSurfacePhysAddr     DRV    rpc.c:10571-10578, kernel_gsp.c:3489-3526; ogd's IOVA of its
+note                                          notify-op page (IOMMU_MAP_DMA). LIVE per boot.
+note pcieAtomicsOpMask                 RP     rpc.c:10579 <- kernel_bif_gh100.c:620-642 (root port      0x7
+note                                          DevCap2 AtomicOp completer bits). INFERRED, needs RP read.
+note consoleMemSize                    CONST  rpc.c:10583 (no console reservation on GB10, UNKNOWN)   0
+note maxUserVa                         OS     rpc.c:10584 <- os.c:720 <- os-interface.c:1128-1131    0x1000000000000
+note                                          (TASK_SIZE; 48-bit VA arm64 kernel)
+note pciConfigMirrorBase               CONST  rpc.c:10540 <- kernel_bif_gh100.c:593-604, bound to      0x92000
+note                                          GB10B at g_kernel_bif_nvoc.c:965-968
+note pciConfigMirrorSize               CONST  same                                                   0x1000
+note PCIDeviceID                       CFG    rpc.c:10533 <- kern_gpu_gb100.c:967 (config 0x00)        0x2e1210de
+note PCISubDeviceID                    CFG    rpc.c:10534 <- kern_gpu_gb100.c:959 (config 0x2c)        0x10de
+note PCIRevisionID                     CFG    rpc.c:10535 <- kern_gpu_gb100.c:950 (config 0x08)        0xa1
+note pcieAtomicsCplDeviceCapMask       CFG    rpc.c:10581 <- kernel_bif_gb10b.c:30-60 (GPU DevCap2)    0
+note oorArch                           CONST  rpc.c:10530 <- gpu_mgr.c:1539 (OOR_ARCH_AARCH64)        3
+note clPdbProperties                   RP     rpc.c:10590 clSyncWithGsp, chipset.c:765               0x1088020c1
+note                                          (properties set while probing the root port). INFERRED.
+note Chipset                           RP     chipset.c:812 (nvcst.h:300, 0x22d1 -> CS_NVIDIA_T254)   0x106d
+note bGpuBehindBridge                  RP     rpc.c:10600-10604                                      0
+note bFlrSupported                     CFG    rpc.c:10555 <- kbifCacheFlrSupport_GH100               1
+note                                          kernel_bif_gh100.c:1099 (config 0x64 DevCap bit 28)
+note b64bBar0Supported                 CFG    rpc.c:10556 <- kbifCache64bBar0Support_GH100           1
+note                                          kernel_bif_gh100.c:1131 (BAR0 type bits)
+note bMnocAvailable                    CONST  rpc.c:10549                                           0
+note chipsetL1ssEnable                 RP     rpc.c:10552 (root port L1 PM substates)                0
+note bUpstreamL0sUnsupported           RP     rpc.c:10600-10604                                      0
+note bUpstreamL1Unsupported            RP     rpc.c:10600-10604                                      0
+note bUpstreamL1PorSupported           RP     rpc.c:10600-10604                                      0
+note bUpstreamL1PorMobileOnly          RP     rpc.c:10600-10604                                      0
+note bSystemHasMux                     CONST  rpc.c:10597                                           0
+note upstreamAddressValid              RP     rpc.c:10605                                           1
+note FHBBusInfo.deviceID .. revisionID RP     chipset.c:813 (bus info chipset.c:335-338)            0x22d1, 0x10de
+note chipsetIDInfo.deviceID .. rev     RP     chipset.c:814                                         0x22d1, 0x10de
+note acpiMethodData.bValid             CONST  rpc.c:10596 <- acpi_common.c:1131                      1
+note acpiMethodData.dodMethodData.*    CONST  acpi_common.c:1134-1136 (_DOD absent: status 0xffff,  0xffff, 64
+note                                          acpiIdListLen = sizeof list)
+note acpiMethodData.jt/capsMethodData  CONST  acpi_common.c (status of absent methods)              0x56, 0x56
+note hypervisorType                    CONST  rpc.c:10607 <- hypervisor.c:51,58 (OS_HYPERVISOR_UNKNOWN) 4
+note virtualConfigBits, bIsPassthru    CONST  rpc.c:10608-10609                                      0
+note sysTimerOffsetNs                  LIVE   rpc.c:10622 <- timer_gb10b.c:52-77 (OS ns - PTIMER ns)  0 (UNKNOWN)
+note                                          needs a PTIMER read in the window, just before the send
+note gspVFInfo.*                       CFG    rpc.c:10612-10619 (no SR-IOV capability)               0
+note bIsPrimary                        CONST  rpc.c:10624 (UNKNOWN; console owner)                   0
+note bIsUnixHdmiFrlComplianceEnabled   CONST  rpc.c:10625 <- g_gpu_nvoc.c:350                       1
+note isGridBuild, gridBuildCsp         CONST  rpc.c:10629, :10631                                   0
+note pcieConfigReg.linkCap             CFG    rpc.c:10559 (config 0x6c, PCIe Link Capabilities)       0x457901
+note bPreserveVideoMemoryAllocations   CONST  rpc.c:10632                                           0
+note bTdrEventSupported                CONST  rpc.c:10635                                           0
+note bFeatureStretchVblankCapable      CONST  rpc.c:10640                                           0
+note bEnableDynamicGranularityPageArrays CONST rpc.c:10585                                          0
+note bClockBoostSupported              CONST  rpc.c:10647                                           0
+note hostPageSize                      OS     rpc.c:10593 <- os.c:4421 (os_page_size)                4096
+note bIsCmcBasedHws                    CONST  never assigned in 580.173.02 (stays 0)                 0
+note bGspNocatEnabled                  CONST  rpc.c:10649-10652 (Windows only)                       0
+note bS0ixSupport                      CONST  rpc.c:10627                                           0
+note bWindowChannelAlwaysMapped        CONST  rpc.c:10641 <- g_kern_disp_nvoc.c:305                  1
+note Values only a live read gives: gpuPhysAddr/gpuPhysInstAddr (BAR assignment), the CFG ids, linkCap,
+note FLR and BAR0-64-bit bits (config region), the RP fields (root-port config), sysTimerOffsetNs (PTIMER
+note at send time) and notifyOpSharedSurfacePhysAddr (ogd's own DMA mapping). Nothing here reads them:
+note the caller supplies every value. Nothing here has run on the chip.
+const SINF ulong 72
+const SISIZE ulong 936
+note a line of 512 bytes or more is refused (the C tool's char buf[512])
+const SILINE ulong 512
+note the text buffer: 65536 bytes (the C tool slurps any size; .om refuses more, SIEBIG)
+const SITXMAX ulong 65536
+const SIMAX64 ulong 18446744073709551615
+const SIEOK long 0
+const SIEIDX long -1
+const SIEREP long -2
+const SIEFIT long -3
+const SIEUNK long -4
+const SIENUM long -5
+const SIEWANT long -6
+const SIELONG long -7
+const SIEBIG long -8
+const SIENIT long -9
+note the 72 field names in table order, each followed by one space
+text sinames "gpuPhysAddr gpuPhysFbAddr gpuPhysInstAddr gpuPhysIoAddr nvDomainBusDeviceFunc simAccessBufPhysAddr notifyOpSharedSurfacePhysAddr pcieAtomicsOpMask consoleMemSize maxUserVa pciConfigMirrorBase pciConfigMirrorSize PCIDeviceID PCISubDeviceID PCIRevisionID pcieAtomicsCplDeviceCapMask oorArch clPdbProperties Chipset bGpuBehindBridge bFlrSupported b64bBar0Supported bMnocAvailable chipsetL1ssEnable bUpstreamL0sUnsupported bUpstreamL1Unsupported bUpstreamL1PorSupported bUpstreamL1PorMobileOnly bSystemHasMux upstreamAddressValid FHBBusInfo.deviceID FHBBusInfo.vendorID FHBBusInfo.subdeviceID FHBBusInfo.subvendorID FHBBusInfo.revisionID chipsetIDInfo.deviceID chipsetIDInfo.vendorID chipsetIDInfo.subdeviceID chipsetIDInfo.subvendorID chipsetIDInfo.revisionID acpiMethodData.bValid acpiMethodData.dodMethodData.status acpiMethodData.dodMethodData.acpiIdListLen acpiMethodData.jtMethodData.status acpiMethodData.capsMethodData.status hypervisorType virtualConfigBits bIsPassthru sysTimerOffsetNs gspVFInfo.totalVFs gspVFInfo.firstVFOffset gspVFInfo.FirstVFBar0Address gspVFInfo.FirstVFBar1Address gspVFInfo.FirstVFBar2Address gspVFInfo.b64bitBar0 gspVFInfo.b64bitBar1 gspVFInfo.b64bitBar2 bIsPrimary bIsUnixHdmiFrlComplianceEnabled isGridBuild pcieConfigReg.linkCap gridBuildCsp bPreserveVideoMemoryAllocations bTdrEventSupported bFeatureStretchVblankCapable bEnableDynamicGranularityPageArrays bClockBoostSupported hostPageSize bIsCmcBasedHws bGspNocatEnabled bS0ixSupport bWindowChannelAlwaysMapped "
+note refusal fragments, each ended by | (124): 0 "line " 1 " too long" 2 ": " 3 want 4 unknown field
+note 5 "field " 6 " repeated" 7 " is not a number" 8 " does not fit " 9 " (" 10 " bytes)" 11 index
+note 12 too big 13 not reset
+text siwt "line | too long|: |want \"field value\"|unknown field |field | repeated| is not a number| does not fit | (| bytes)|field index out of range|text over 65536 bytes|sireset not called|"
+global sioff ulong 72
+global sisz ulong 72
+global sival ulong 72
+global siseen uchar 72
+global siord ulong 72
+global sinord ulong 1
+global siout uchar 936
+global sitxt uchar 65536
+note name and value tokens of the current line (or of the last siseti/sisetn call)
+global sinam uchar 128
+global sinl ulong 1
+global sivb uchar 128
+global sivl ulong 1
+note line number of the last refusal (0 = an API call), field index of the current line, parser cursor
+global siline ulong 1
+global sifld ulong 1
+global sipos ulong 1
+global sinv ulong 1
+global siwb uchar 256
+global siwl ulong 1
+fn sireset to void
+put sioff 0 0
+put sisz 0 8
+put sioff 1 8
+put sisz 1 8
+put sioff 2 16
+put sisz 2 8
+put sioff 3 24
+put sisz 3 8
+put sioff 4 32
+put sisz 4 8
+put sioff 5 40
+put sisz 5 8
+put sioff 6 48
+put sisz 6 8
+put sioff 7 56
+put sisz 7 8
+put sioff 8 64
+put sisz 8 8
+put sioff 9 72
+put sisz 9 8
+put sioff 10 80
+put sisz 10 4
+put sioff 11 84
+put sisz 11 4
+put sioff 12 88
+put sisz 12 4
+put sioff 13 92
+put sisz 13 4
+put sioff 14 96
+put sisz 14 4
+put sioff 15 100
+put sisz 15 4
+put sioff 16 104
+put sisz 16 1
+put sioff 17 112
+put sisz 17 8
+put sioff 18 120
+put sisz 18 4
+put sioff 19 124
+put sisz 19 1
+put sioff 20 125
+put sisz 20 1
+put sioff 21 126
+put sisz 21 1
+put sioff 22 127
+put sisz 22 1
+put sioff 23 128
+put sisz 23 4
+put sioff 24 132
+put sisz 24 1
+put sioff 25 133
+put sisz 25 1
+put sioff 26 134
+put sisz 26 1
+put sioff 27 135
+put sisz 27 1
+put sioff 28 136
+put sisz 28 1
+put sioff 29 137
+put sisz 29 1
+put sioff 30 138
+put sisz 30 2
+put sioff 31 140
+put sisz 31 2
+put sioff 32 142
+put sisz 32 2
+put sioff 33 144
+put sisz 33 2
+put sioff 34 146
+put sisz 34 1
+put sioff 35 148
+put sisz 35 2
+put sioff 36 150
+put sisz 36 2
+put sioff 37 152
+put sisz 37 2
+put sioff 38 154
+put sisz 38 2
+put sioff 39 156
+put sisz 39 1
+put sioff 40 160
+put sisz 40 1
+put sioff 41 164
+put sisz 41 4
+put sioff 42 168
+put sisz 42 4
+put sioff 43 236
+put sisz 43 4
+put sioff 44 828
+put sisz 44 4
+put sioff 45 836
+put sisz 45 4
+put sioff 46 840
+put sisz 46 2
+put sioff 47 842
+put sisz 47 1
+put sioff 48 848
+put sisz 48 8
+put sioff 49 856
+put sisz 49 4
+put sioff 50 860
+put sisz 50 4
+put sioff 51 864
+put sisz 51 8
+put sioff 52 872
+put sisz 52 8
+put sioff 53 880
+put sisz 53 8
+put sioff 54 888
+put sisz 54 1
+put sioff 55 889
+put sisz 55 1
+put sioff 56 890
+put sisz 56 1
+put sioff 57 896
+put sisz 57 1
+put sioff 58 897
+put sisz 58 1
+put sioff 59 898
+put sisz 59 1
+put sioff 60 900
+put sisz 60 4
+put sioff 61 904
+put sisz 61 4
+put sioff 62 908
+put sisz 62 1
+put sioff 63 909
+put sisz 63 1
+put sioff 64 910
+put sisz 64 1
+put sioff 65 911
+put sisz 65 1
+put sioff 66 912
+put sisz 66 1
+put sioff 67 920
+put sisz 67 8
+put sioff 68 928
+put sisz 68 1
+put sioff 69 929
+put sisz 69 1
+put sioff 70 930
+put sisz 70 1
+put sioff 71 931
+put sisz 71 1
+for k ulong SINF
+put sival k 0
+put siseen k 0
+put siord k 0
+end
+for i ulong SISIZE
+put siout i 0
+end
+put sinord 0 0
+put siline 0 0
+put sinl 0 0
+put sivl 0 0
+put siwl 0 0
+end
+note the field's value fits its size (8-byte fields take any value)
+fn sifits k ulong v ulong to bool
+sz = get sisz k
+if lt sz 8
+ret eq shr v mul sz 8 0
+end
+ret true
+end
+fn sistore k ulong v ulong to long
+if ge k SINF
+ret SIEIDX
+end
+if ne get siseen k 0
+ret SIEREP
+end
+if not sifits k v
+ret SIEFIT
+end
+put siseen k 1
+put sival k v
+n = get sinord 0
+put siord n k
+put sinord 0 add n 1
+ret SIEOK
+end
+note name k into sinam/sinl
+fn sinmk k ulong to void
+w = ulong 0
+o = ulong 0
+for i ulong len sinames
+c = get sinames i
+if eq c 32
+w = add w 1
+else
+if eq w k
+put sinam o c
+o = add o 1
+end
+end
+end
+put sinl 0 o
+end
+fn sieqat s ulong n ulong to bool
+for j ulong n
+if ne get sinames add s j get sinam j
+ret false
+end
+end
+ret true
+end
+note index of the field named sinam[0..sinl), SINF when none
+fn silook to ulong
+k = ulong 0
+s = ulong 0
+n = get sinl 0
+for i ulong len sinames
+if eq get sinames i 32
+if eq sub i s n
+if sieqat s n
+ret k
+end
+end
+k = add k 1
+s = add i 1
+end
+end
+ret SINF
+end
+note sivb[0..sivl) as "%#llx" of v (API path only)
+fn sihexv v ulong to void
+put sivb 0 48
+if eq v 0
+put sivl 0 1
+ret
+end
+put sivb 1 120
+nd = ulong 0
+t = v
+while ne t 0 bound 17
+nd = add nd 1
+t = shr t 4
+end
+for i ulong nd
+d = and shr v mul sub sub nd i 1 4 15
+if lt d 10
+put sivb add i 2 uchar add d 48
+else
+put sivb add i 2 uchar add d 87
+end
+end
+put sivl 0 add nd 2
+end
+fn siseti k ulong v ulong to long
+put siline 0 0
+if eq get sisz 0 0
+ret SIENIT
+end
+if lt k SINF
+sinmk k
+put sifld 0 k
+end
+sihexv v
+r = sistore k v
+ret r
+end
+fn sisetn v ulong to long
+put siline 0 0
+if eq get sisz 0 0
+ret SIENIT
+end
+k = silook
+if eq k SINF
+sihexv v
+ret SIEUNK
+end
+r = siseti k v
+ret r
+end
+fn siencode to void
+for i ulong SISIZE
+put siout i 0
+end
+for k ulong SINF
+if ne get siseen k 0
+v = get sival k
+o = get sioff k
+for b ulong get sisz k
+put siout add o b uchar and shr v mul b 8 255
+end
+end
+end
+end
+note C isspace: \t \n \v \f \r (9..13) and space (32)
+fn siws c uchar to bool
+ret or eq c 32 and ge c 9 le c 13
+end
+fn siskip b ulong to void
+p = get sipos 0
+while lt p b bound 600
+if not siws get sitxt p
+break
+end
+p = add p 1
+end
+put sipos 0 p
+end
+note one sscanf %127s token from sipos (which 0 = sinam, 1 = sivb, 2 = dropped); returns its length
+fn sitk which ulong b ulong to ulong
+p = get sipos 0
+n = ulong 0
+while and lt p b lt n 127 bound 600
+c = get sitxt p
+if siws c
+break
+end
+if eq which 0
+put sinam n c
+end
+if eq which 1
+put sivb n c
+end
+n = add n 1
+p = add p 1
+end
+put sipos 0 p
+ret n
+end
+note strtoull digit value, 99 for a non-digit
+fn sidig c uchar to ulong
+if and ge c 48 le c 57
+ret sub ulong c 48
+end
+if and ge c 97 le c 102
+ret sub ulong c 87
+end
+if and ge c 65 le c 70
+ret sub ulong c 55
+end
+ret 99
+end
+note sivb[0..sivl) as strtoull(val, &end, 0) with errno == 0, *end == 0 and val[0] != '-' -> sinv
+fn sinum to bool
+n = get sivl 0
+if eq get sivb 0 45
+ret false
+end
+i = ulong 0
+if eq get sivb 0 43
+i = 1
+end
+base = ulong 10
+if lt i n
+if eq get sivb i 48
+base = 8
+if lt add i 2 n
+x = get sivb add i 1
+if or eq x 120 eq x 88
+if lt sidig get sivb add i 2 16
+base = 16
+i = add i 2
+end
+end
+end
+end
+end
+v = ulong 0
+nd = ulong 0
+ovf = false
+while lt i n bound 200
+d = sidig get sivb i
+if ge d base
+break
+end
+if gt v div sub SIMAX64 d base
+ovf = true
+else
+v = add mul v base d
+end
+nd = add nd 1
+i = add i 1
+end
+put sinv 0 v
+ret and and gt nd 0 eq i n not ovf
+end
+note one line sitxt[a..b) after the # cut: 1 blank, else a code
+fn sidoln a ulong b ulong to long
+put sipos 0 a
+siskip b
+if eq get sipos 0 b
+ret 1
+end
+put sinl 0 sitk 0 b
+siskip b
+if eq get sipos 0 b
+ret SIEWANT
+end
+put sivl 0 sitk 1 b
+siskip b
+if ne get sipos 0 b
+ret SIEWANT
+end
+k = silook
+put sifld 0 k
+if eq k SINF
+ret SIEUNK
+end
+if ne get siseen k 0
+ret SIEREP
+end
+if not sinum
+ret SIENUM
+end
+r = sistore k get sinv 0
+ret r
+end
+fn sieol p ulong m ulong to ulong
+e = p
+while lt e m bound 70000
+if eq get sitxt e 10
+break
+end
+e = add e 1
+end
+ret e
+end
+fn sihash p ulong e ulong to ulong
+h = p
+while lt h e bound 600
+if eq get sitxt h 35
+break
+end
+h = add h 1
+end
+ret h
+end
+fn sitext n ulong to long
+put siline 0 0
+if eq get sisz 0 0
+ret SIENIT
+end
+if gt n SITXMAX
+ret SIEBIG
+end
+note the C tool reads a NUL-terminated string: the text ends at the first NUL byte
+m = n
+for i ulong n
+if eq get sitxt i 0
+m = i
+break
+end
+end
+p = ulong 0
+ln = ulong 0
+while lt p m bound 70000
+ln = add ln 1
+put siline 0 ln
+e = sieol p m
+if ge sub e p SILINE
+ret SIELONG
+end
+r = sidoln p sihash p e
+if lt r 0
+ret r
+end
+p = add e 1
+end
+put siline 0 0
+ret SIEOK
+end
+fn siwc c uchar to void
+n = get siwl 0
+if lt n 256
+put siwb n c
+put siwl 0 add n 1
+end
+end
+note fragment k of siwt
+fn siwfr k ulong to void
+w = ulong 0
+for i ulong len siwt
+c = get siwt i
+if eq c 124
+w = add w 1
+else
+if eq w k
+siwc c
+end
+end
+end
+end
+fn siwdec v ulong to void
+d = ulong 1
+while le d div v 10 bound 20
+d = mul d 10
+end
+while ne d 0 bound 20
+siwc uchar add rem div v d 10 48
+d = div d 10
+end
+end
+fn siwnam mx ulong to void
+for i ulong get sinl 0
+if lt i mx
+siwc get sinam i
+end
+end
+end
+fn siwval mx ulong to void
+for i ulong get sivl 0
+if lt i mx
+siwc get sivb i
+end
+end
+end
+note the refusal text of e (the C tool's why string) into siwb[0..siwl)
+fn siwhy e long to void
+put siwl 0 0
+ln = get siline 0
+if ne ln 0
+siwfr 0
+siwdec ln
+if eq e SIELONG
+siwfr 1
+ret
+end
+siwfr 2
+end
+if eq e SIEWANT
+siwfr 3
+end
+if eq e SIEUNK
+siwfr 4
+siwnam 128
+end
+if eq e SIEREP
+siwfr 5
+siwnam 128
+siwfr 6
+end
+if eq e SIENUM
+siwval 128
+siwfr 7
+end
+if eq e SIEFIT
+siwval 40
+siwfr 8
+siwnam 60
+siwfr 9
+siwdec get sisz get sifld 0
+siwfr 10
+end
+if eq e SIEIDX
+siwfr 11
+end
+if eq e SIEBIG
+siwfr 12
+end
+if eq e SIENIT
+siwfr 13
+end
+end
diff --git a/tests/chan_diff.sh b/tests/chan_diff.sh
new file mode 100755
index 0000000..b4ef7a6
--- /dev/null
+++ b/tests/chan_diff.sh
@@ -0,0 +1,66 @@
+#!/bin/sh
+# chan_diff.sh: builds the .om channel trace (chan/gmmu.om + chan/mem.om + chan/chan.om + chan/sim.om +
+# tests/chan_trace.om) and the C reference trace (aienux PR #441 tests/gpu_chan_trace.c + gpu/gmmu.c +
+# gpu/gpu_mem.c + gpu/gpu_chan.c + gpu/gpu_sim.c, compiled fresh into a temp dir as a test-only referee)
+# and requires byte-identical stdout. Host only: the trace runs on the simulator (mmmode 0).
+# Env: AIENUX (aienux checkout), OMC (pinned omc), GMMU_OM / MEM_OM / CHAN_OM / GSIM_OM (unit files to
+# test; mutants use these), CHAN_REF (a C trace already produced by this script's referee build, so a
+# mutant run skips the rebuild; the file must be non-empty).
+set -u
+here=$(cd "$(dirname "$0")/.." && pwd)
+AIENUX=${AIENUX:-/home/drakestapleton/work/OwnDriver/aienux}
+OMC=${OMC:-$here/build/omc}
+GMMU_OM=${GMMU_OM:-$here/chan/gmmu.om}
+MEM_OM=${MEM_OM:-$here/chan/mem.om}
+CHAN_OM=${CHAN_OM:-$here/chan/chan.om}
+GSIM_OM=${GSIM_OM:-$here/chan/sim.om}
+CHAN_REF=${CHAN_REF:-}
+OMC_SHA=$(sed -n 's/^OMC_SHA256=//p' "$here/tools/omc.pin")
+run() { nice -n 19 taskset -c "${AIEN_TEST_CPUS:-0-9,15-19}" "$@"; }
+
+got=$(sha256sum "$OMC" | cut -d' ' -f1)
+if [ "$got" != "$OMC_SHA" ]; then
+  echo "chan_diff: FAIL omc sha256 $got, pinned $OMC_SHA"; exit 2
+fi
+# The host trace must stay on the simulator: mode 0 only, no device words in the test driver,
+# while the BAR0 (mode 1) branch stays present in the register seam.
+if grep -n 'mmmode [0-9]* [1-9]\|mmbar\|vfio\|mapnew\|/dev/\|/sys/' "$here/tests/chan_trace.om"; then
+  echo "chan_diff: FAIL test driver leaves simulator mode or names a device"; exit 2
+fi
+for w in 'ret mapget get mmbar 0 off 4' 'r = mapset get mmbar 0 off 4 v'; do
+  if ! grep -qxF "$w" "$GMMU_OM"; then
+    echo "chan_diff: FAIL BAR0 branch line missing from chan/gmmu.om: $w"; exit 2
+  fi
+done
+
+t=$(mktemp -d /tmp/chan_diff.XXXXXX) || exit 2
+trap 'rm -rf "$t"' EXIT
+if [ -n "$CHAN_REF" ]; then
+  [ -s "$CHAN_REF" ] || { echo "chan_diff: FAIL CHAN_REF $CHAN_REF missing or empty"; exit 2; }
+  cp "$CHAN_REF" "$t/c.txt" || exit 2
+else
+  k=$AIENUX/native/kernel
+  if ! run cc -std=c11 -O1 -Wall -Werror -I"$k/gpu" -o "$t/ctrace" \
+      "$k/tests/gpu_chan_trace.c" "$k/gpu/gmmu.c" "$k/gpu/gpu_mem.c" "$k/gpu/gpu_chan.c" "$k/gpu/gpu_sim.c"; then
+    echo "chan_diff: FAIL C reference build"; exit 2
+  fi
+  run "$t/ctrace" > "$t/c.txt" || { echo "chan_diff: FAIL C reference run"; exit 2; }
+fi
+if ! cat "$GMMU_OM" "$MEM_OM" "$CHAN_OM" "$GSIM_OM" "$here/tests/chan_trace.om" | run "$OMC" > "$t/omtrace"; then
+  echo "chan_diff: FAIL omc build"; exit 3
+fi
+chmod +x "$t/omtrace"
+run "$t/omtrace" > "$t/om.txt"
+rc=$?
+if [ "$rc" -ne 0 ]; then
+  echo "chan_diff: FAIL om trace exit $rc"; exit 1
+fi
+n=$(wc -l < "$t/c.txt")
+if [ "$n" -eq 0 ]; then
+  echo "chan_diff: FAIL empty C trace"; exit 2
+fi
+if ! cmp -s "$t/c.txt" "$t/om.txt"; then
+  echo "chan_diff: FAIL traces differ ($(diff "$t/c.txt" "$t/om.txt" | grep -c '^[<>]') differing lines; C $n lines, om $(wc -l < "$t/om.txt"))"
+  exit 1
+fi
+echo "chan_diff: PASS ($n lines identical, .om vs C reference)"
diff --git a/tests/chan_trace.om b/tests/chan_trace.om
new file mode 100644
index 0000000..a5270e5
--- /dev/null
+++ b/tests/chan_trace.om
@@ -0,0 +1,264 @@
+note tests/chan_trace.om: the differential trace driver for the channel port. It replays aienux PR #441
+note native/kernel/tests/gpu_chan_trace.c (branch pr441 @ c5bb3a4b) line for line on chan/sim.om and
+note prints the same text: after every operation its rc, every register access the simulator logged
+note since the last line, the doorbell count and FNV-1a 64 of the whole 8 MiB simulated memory.
+note Build: cat chan/gmmu.om chan/mem.om chan/chan.om chan/sim.om tests/chan_trace.om | omc > prog.
+note Prefix ct. Host only: mmmode is 0 (the simulator) for the whole run.
+note memory: 8 MiB at bus address 0x80000000, page-table pool there (64 pages), data at 0x80040000
+note (128 pages), GPU VA base 0x200000000
+const CTPA ulong 2147483648
+const CTMEM ulong 8388608
+const CTDATA ulong 2147745792
+const CTVA ulong 8589934592
+note FNV-1a 64 offset basis 0xcbf29ce484222325 and prime 0x100000001b3
+const CTFNVO ulong 14695981039346656037
+const CTFNVP ulong 1099511628211
+const CTFOR ulong 1000
+text ctt "setup|create chid>max|create runlist=0x7f|create entries=24|create entries=1|create|alloc pb|alloc sem|submit off=2|submit nwords=0|submit past end|submit foreign buf|submit |retire put=| ret=|retire past put ret=|teardown idle|teardown again|submit after close|create (hung run)|teardown hung| rc=| doorbells=| mem=|token=| rl=|quarantined_pages=| free_pages=|setup failed\n"
+global ctob uchar 262144
+global ctpos ulong 1
+global ctcnt ulong 1
+global ctlab ulong 1
+global ctdig uchar 24
+global ctstep ulong 1
+global ctseen ulong 1
+fn ctflush to void
+n = get ctpos 0
+if gt n 0
+r = write 1 ctob 0 n
+if ne r long n
+exit 1
+end
+end
+put ctpos 0 0
+end
+fn ctch c uchar to void
+p = get ctpos 0
+put ctob p c
+put ctpos 0 add p 1
+put ctcnt 0 add get ctcnt 0 1
+if ge add p 1 262000
+ctflush
+end
+end
+note the k-th '|'-separated fragment of ctt
+fn ctfrag k ulong to void
+w = ulong 0
+for i ulong len ctt
+c = get ctt i
+if eq c 124
+w = add w 1
+else
+if eq w k
+ctch c
+end
+end
+end
+end
+note %u, and %0Nu with w > 0
+fn ctdecw v ulong w ulong to void
+n = ulong 0
+x = v
+while true bound 24
+put ctdig n uchar add rem x 10 48
+n = add n 1
+x = div x 10
+if eq x 0
+break
+end
+end
+while lt n w bound 24
+put ctdig n 48
+n = add n 1
+end
+for i ulong n
+ctch get ctdig sub sub n 1 i
+end
+end
+fn ctdec v ulong to void
+ctdecw v 0
+end
+fn ctsdec v long to void
+if lt v 0
+ctch 45
+ctdec ulong neg v
+ret
+end
+ctdec ulong v
+end
+note lowercase hex, zero-padded to w digits
+fn cthex v ulong w ulong to void
+n = ulong 0
+x = v
+while true bound 24
+d = uchar rem x 16
+if lt d 10
+put ctdig n add d 48
+else
+put ctdig n add d 87
+end
+n = add n 1
+x = div x 16
+if eq x 0
+break
+end
+end
+while lt n w bound 24
+put ctdig n 48
+n = add n 1
+end
+for i ulong n
+ctch get ctdig sub sub n 1 i
+end
+end
+fn ctfnv to ulong
+h = CTFNVO
+for a ulong 8192
+o = mul a 1024
+for b ulong 1024
+h = mul xor h ulong get mmwin add o b CTFNVP
+end
+end
+ret h
+end
+note "%04u " then the label (printed by the caller); ctend pads it to 24 (%-24s) and ends the line
+fn ctbeg to void
+ctdecw get ctstep 0 4
+put ctstep 0 add get ctstep 0 1
+ctch 32
+put ctlab 0 get ctcnt 0
+end
+fn ctend rc long to void
+while lt sub get ctcnt 0 get ctlab 0 24 bound 64
+ctch 32
+end
+ctfrag 21
+ctsdec rc
+s = get ctseen 0
+n = get gsnlog 0
+while lt s n bound 600
+ctch 32
+if ne get gslogw s 0
+ctch 87
+else
+ctch 82
+end
+cthex ulong get gslogo s 6
+ctch 61
+cthex ulong get gslogv s 8
+s = add s 1
+end
+put ctseen 0 s
+ctfrag 22
+ctdec get gsdb 0
+ctfrag 23
+cthex ctfnv 16
+ctch 10
+ctflush
+end
+fn ctline k ulong rc long to void
+ctbeg
+ctfrag k
+ctend rc
+end
+fn ctfresh to void
+for a ulong 8192
+o = mul a 1024
+for b ulong 1024
+put mmwin add o b 165
+end
+end
+r = mmwinit CTPA CTMEM
+gsinit CTPA CTMEM
+put mmmode 0 0
+put ctseen 0 0
+r1 = mmasinit CTPA 64
+r2 = long 1
+if eq r1 MMOK
+r2 = gminit 10 CTDATA 128 CTVA
+end
+if or ne r MMOK or ne r1 MMOK ne r2 GMOK
+ctfrag 28
+ctflush
+exit 1
+end
+ctline 0 0
+end
+fn main to int
+chinit
+ctfresh
+ctline 1 chcreate 0 4096 1 16
+ctline 2 chcreate 0 3 127 16
+ctline 3 chcreate 0 3 1 24
+ctline 4 chcreate 0 3 1 1
+ctline 5 chcreate 0 3 1 16
+ctfrag 24
+cthex ulong get chtok 0 8
+ctfrag 25
+cthex ulong get chrl0 0 8
+ctch 44
+cthex ulong get chrl1 0 8
+ctch 10
+r = gmalloc 8192 0 GMGPURO
+pb = get gmout 0
+ctline 6 r
+r = gmalloc 4096 1 GMHPOLL
+sem = get gmout 0
+ctline 7 r
+base = get gmbpa pb
+for i ulong 4096
+mmwr8 add base i uchar and mul i 7 255
+end
+ctline 8 chsubmit 0 pb 2 4
+ctline 9 chsubmit 0 pb 0 0
+ctline 10 chsubmit 0 pb 8188 2
+ctline 11 chsubmit 0 CTFOR 0 4
+for i uint 300
+rc = chsubmit 0 pb mul rem i 64 64 add 1 rem i 16
+ctbeg
+ctfrag 12
+ctdec ulong i
+ctend rc
+if or eq rc CHEFULL eq rem i 5 4
+chretire 0 sub get chput 0 rem i 3
+ctbeg
+ctfrag 13
+ctdec ulong get chput 0
+ctfrag 14
+ctdec ulong get chret 0
+ctend 0
+end
+end
+chretire 0 add get chput 0 5
+ctbeg
+ctfrag 15
+ctdec ulong get chret 0
+ctend 0
+put chx 0 pb
+put chx 1 sem
+ctline 16 chteardown 0 4 2
+ctline 17 chteardown 0 4 2
+ctline 18 chsubmit 0 pb 0 4
+ctfresh
+ctline 19 chcreate 0 7 2 8
+r = gmalloc 4096 0 GMGPURO
+pb = get gmout 0
+ctline 6 r
+for i uint 9
+rc = chsubmit 0 pb 0 8
+ctbeg
+ctfrag 12
+ctdec ulong i
+ctend rc
+end
+put gshang 0 1
+put chx 0 pb
+ctline 20 chteardown 0 6 1
+ctfrag 26
+ctdec gmcount GMQUAR
+ctfrag 27
+ctdec gmcount GMFREE
+ctch 10
+ctflush
+ret 0
+end
diff --git a/tests/fw_diff.sh b/tests/fw_diff.sh
new file mode 100755
index 0000000..fe7b188
--- /dev/null
+++ b/tests/fw_diff.sh
@@ -0,0 +1,234 @@
+#!/bin/sh
+# fw_diff.sh: builds fwprep (gsp/sha2.om gsp/inflate.om gsp/fw.om gsp/bindata.om fwprep.om) with the
+# pinned omc and the two C referees from aienux PR #441 (kernel/tools/ck_gsp_fw_inspect.c and
+# kernel/tools/ck_gsp_bindata_extract.c with argus/sha256.c, compiled fresh into a temp dir as
+# test-only referees, never linked into the product), then requires:
+#   - fwprep stdout = C inspect stdout + C FMC extract stdout + C boot extract stdout + the fwprep
+#     lines expected from the C --out files, byte for byte, exit 0;
+#   - every output cmp-identical to the C --out file it comes from, fw.manifest identical to one
+#     rebuilt here from the C outputs (od/wc/sha256sum), and the pinned digests and descriptor;
+#   - negative controls refused by the C and by fwprep (exit 2, C stdout prefix identical, no
+#     fw.manifest left, a stale one removed): truncated firmware, .fwsignature_gb10y renamed,
+#     a flipped compressed byte (CRC-32), a flipped deflate body byte, a flipped UCODE_HASH byte;
+#     plus fwprep's own refusals: wrong function, missing FWFILE (C stderr wording, exit 1),
+#     OUTDIR not a directory (exit 3), usage (exit 1).
+# Host only: reads the firmware and bindata files, writes a temp dir; no device.
+# Env: AIENUX, OMC, FW (gsp_ga10x.bin), OGKM (open-gpu-kernel-modules-580.173.02 tree),
+#      SHA2_OM INFL_OM FW_OM BD_OM FWPREP_OM (units to test; mutants use these).
+# Exit 0 PASS, 1 differ, 2 setup, 3 omc failure.
+set -u
+here=$(cd "$(dirname "$0")/.." && pwd)
+AIENUX=${AIENUX:-/home/drakestapleton/work/OwnDriver/aienux}
+OMC=${OMC:-$here/build/omc}
+FW=${FW:-/lib/firmware/nvidia/580.173.02/gsp_ga10x.bin}
+OGKM=${OGKM:-/home/drakestapleton/workspace/_ext/open-gpu-kernel-modules-580.173.02}
+SHA2_OM=${SHA2_OM:-$here/gsp/sha2.om}
+INFL_OM=${INFL_OM:-$here/gsp/inflate.om}
+FW_OM=${FW_OM:-$here/gsp/fw.om}
+BD_OM=${BD_OM:-$here/gsp/bindata.om}
+FWPREP_OM=${FWPREP_OM:-$here/fwprep.om}
+OMC_SHA=$(sed -n 's/^OMC_SHA256=//p' "$here/tools/omc.pin")
+run() { nice -n 19 taskset -c "${AIEN_TEST_CPUS:-0-9,15-19}" "$@"; }
+fail() { echo "fw_diff: FAIL $2"; exit "$1"; }
+
+FW_SHA=32cb7cf3e77f97e92f6e92135939ccb3ba382748144569c0dfccf3338d43d963
+FMC_C=g_bindata_kgspGetBinArchiveGspRmFmcGfwProdSigned_GB10B.c
+BOOT_C=g_bindata_kgspGetBinArchiveGspRmBoot_GB10B.c
+FMC_F=kgspGetBinArchiveGspRmFmcGfwProdSigned_GB10B
+BOOT_F=kgspGetBinArchiveGspRmBoot_GB10B
+FMC_C_SHA=2861be1864befa21e4fe4a5d088dae816de8cd8f03359de9f7d35cff910c8957
+BOOT_C_SHA=c9c0c0073837b8e38ef6fc94c3c531d6f03b22003fe084b0f9066631f4a0397b
+FMC_IMG_SHA=b13ead4b9a6b8a0d268f3094cc4f4521d6be8a9a525edbc9a8f3f397c86f1f2e
+BL_IMG_SHA=427a691d8453f02548d395f40ac900eb0d5b8ea864e8f14f958eef890ba400a2
+# 0xa00 = 2560, 0xa600 = 42496, 0xb000 = 45056, 0x24d00 = 150784
+DESC_PIN='version=5 bootloader_off=0 bootloader_size=0 bl_param_off=0 bl_param_size=0 elf_off=0 elf_size=0 app_version=0 manifest_off=0 manifest_size=2560 mdata_off=2560 mdata_size=42496 mcode_off=45056 mcode_size=150784 monitor_enabled=1'
+G=$OGKM/src/nvidia/generated
+
+got=$(sha256sum "$OMC" | cut -d' ' -f1)
+[ "$got" = "$OMC_SHA" ] || fail 2 "omc sha256 $got, pinned $OMC_SHA"
+[ "$(sha256sum < "$FW" | cut -d' ' -f1)" = "$FW_SHA" ] || fail 2 "firmware sha256 differs from the 580.173.02 pin: $FW"
+[ "$(sha256sum < "$G/$FMC_C" | cut -d' ' -f1)" = "$FMC_C_SHA" ] || fail 2 "FMC bindata sha256 differs from the pin"
+[ "$(sha256sum < "$G/$BOOT_C" | cut -d' ' -f1)" = "$BOOT_C_SHA" ] || fail 2 "boot bindata sha256 differs from the pin"
+if grep -n 'vfio\|mapnew\|mapget\|mapset\|/dev/\|/sys/' "$SHA2_OM" "$INFL_OM" "$FW_OM" "$BD_OM" "$FWPREP_OM"; then
+  fail 2 "a firmware unit names a device"
+fi
+
+t=$(mktemp -d /tmp/fw_diff.XXXXXX) || exit 2
+trap 'rm -rf "$t"' EXIT
+k=$AIENUX/native
+for tool in ck_gsp_fw_inspect ck_gsp_bindata_extract; do
+  run cc -std=c11 -O1 -Wall -Werror -I"$k/argus" -o "$t/$tool" "$k/kernel/tools/$tool.c" "$k/argus/sha256.c" \
+    || fail 2 "C referee build $tool"
+done
+cat "$SHA2_OM" "$INFL_OM" "$FW_OM" "$BD_OM" "$FWPREP_OM" | run "$OMC" > "$t/fwprep" || fail 3 "omc build"
+chmod +x "$t/fwprep"
+
+# ---- positive run on the real inputs ----
+run "$t/ck_gsp_fw_inspect" inspect "$FW" > "$t/insp.txt" || fail 2 "C inspect refused the real firmware"
+run "$t/ck_gsp_bindata_extract" extract "$G/$FMC_C" > "$t/fmc.txt" || fail 2 "C extract refused FMC"
+run "$t/ck_gsp_bindata_extract" extract "$G/$BOOT_C" > "$t/boot.txt" || fail 2 "C extract refused boot"
+mkdir "$t/cfmc" "$t/cboot"
+run "$t/ck_gsp_bindata_extract" extract "$G/$FMC_C" --out "$t/cfmc" > /dev/null || fail 2 "C extract --out FMC"
+run "$t/ck_gsp_bindata_extract" extract "$G/$BOOT_C" --out "$t/cboot" > /dev/null || fail 2 "C extract --out boot"
+cf=$t/cfmc/$FMC_F
+cb=$t/cboot/$BOOT_F
+cat "$t/insp.txt" "$t/fmc.txt" "$t/boot.txt" > "$t/want.txt"
+set -- fmc.img "$cf.UCODE_IMAGE.bin" fmc.hash "$cf.UCODE_HASH.bin" fmc.pubkey "$cf.UCODE_PKEY.bin" \
+  fmc.sig "$cf.UCODE_SIG.bin" bl.img "$cb.UCODE_IMAGE_PROD.bin"
+outs=
+while [ $# -ge 2 ]; do
+  [ -f "$2" ] || fail 2 "C output missing: $2"
+  printf 'fwprep wrote %s bytes=%s sha256=%s\n' "$1" "$(wc -c < "$2")" "$(sha256sum < "$2" | cut -d' ' -f1)" >> "$t/want.txt"
+  printf 'out %s bytes=%s sha256=%s\n' "$1" "$(wc -c < "$2")" "$(sha256sum < "$2" | cut -d' ' -f1)" >> "$t/outs.txt"
+  outs="$outs $1:$2"
+  shift 2
+done
+printf 'fwprep wrote fw.manifest\nfwprep RESULT OK\n' >> "$t/want.txt"
+
+sec() { sed -n "s/^section [0-9]* $1 type=[0-9]* offset=\([0-9]*\) size=\([0-9]*\)\$/offset=\1 size=\2/p" "$t/insp.txt"; }
+names='version bootloader_off bootloader_size bl_param_off bl_param_size elf_off elf_size app_version manifest_off manifest_size mdata_off mdata_size mcode_off mcode_size monitor_enabled swbrom_code_off swbrom_code_size swbrom_data_off swbrom_data_size fb_reserved signed_as_code'
+words=$(od -An -v -tu4 "$cb.UCODE_DESC_PROD.bin")
+[ "$(echo $words | wc -w)" -eq 21 ] || fail 2 "C descriptor is not 21 words"
+desc=$(set -- $words; for n in $names; do printf ' %s=%s' "$n" "$1"; shift; done)
+{
+  echo "fwmanifest 1"
+  echo "fwversion $(sed -n 's/^fwversion //p' "$t/insp.txt")"
+  echo "build_id $(sed -n 's/^build_id //p' "$t/insp.txt")"
+  echo "fw_file bytes=$(wc -c < "$FW") sha256=$(sed -n 's/^sha256_file //p' "$t/insp.txt")"
+  echo "fwimage $(sec '\.fwimage') sha256=$(sed -n 's/^sha256_fwimage \([0-9a-f]*\) .*/\1/p' "$t/insp.txt")"
+  echo "fwsignature .fwsignature_gb10y $(sec '\.fwsignature_gb10y') sha256=$(sed -n 's/^sha256_signature //p' "$t/insp.txt")"
+  echo "fmc_src $FMC_C bytes=$(wc -c < "$G/$FMC_C") sha256=$FMC_C_SHA"
+  echo "boot_src $BOOT_C bytes=$(wc -c < "$G/$BOOT_C") sha256=$BOOT_C_SHA"
+  echo "bl_desc UCODE_DESC_PROD$desc"
+  cat "$t/outs.txt"
+  echo end
+} > "$t/manifest.want"
+
+o=$t/out
+mkdir "$o"
+echo stale > "$o/fw.manifest"
+run "$t/fwprep" "$FW" "$OGKM" "$o" > "$t/om.txt" 2> "$t/om.err"
+rc=$?
+[ "$rc" -eq 0 ] || { cat "$t/om.err"; tail -n 3 "$t/om.txt"; fail 1 "fwprep exit $rc on the real inputs"; }
+[ -s "$t/om.err" ] && fail 1 "fwprep wrote to stderr on success"
+n=$(wc -l < "$t/want.txt")
+if ! cmp -s "$t/want.txt" "$t/om.txt"; then
+  diff "$t/want.txt" "$t/om.txt" | head -n 6
+  fail 1 "stdout differs ($(diff "$t/want.txt" "$t/om.txt" | grep -c '^[<>]') differing lines; want $n)"
+fi
+for p in $outs; do
+  cmp -s "${p#*:}" "$o/${p%%:*}" || fail 1 "${p%%:*} differs from the C output"
+done
+if ! cmp -s "$t/manifest.want" "$o/fw.manifest"; then
+  diff "$t/manifest.want" "$o/fw.manifest" | head -n 6
+  fail 1 "fw.manifest differs from the one rebuilt from the C outputs"
+fi
+[ "$(ls "$o" | wc -l)" -eq 6 ] || fail 1 "OUTDIR holds other files: $(ls "$o" | tr '\n' ' ')"
+[ "$(sha256sum < "$o/fmc.img" | cut -d' ' -f1)" = "$FMC_IMG_SHA" ] || fail 1 "fmc.img sha256 pin"
+[ "$(wc -c < "$o/fmc.img")" -eq 195912 ] || fail 1 "fmc.img size pin"
+[ "$(sha256sum < "$o/bl.img" | cut -d' ' -f1)" = "$BL_IMG_SHA" ] || fail 1 "bl.img sha256 pin"
+[ "$(wc -c < "$o/bl.img")" -eq 196608 ] || fail 1 "bl.img size pin"
+grep -qF "bl_desc UCODE_DESC_PROD $DESC_PIN " "$o/fw.manifest" || fail 1 "descriptor pin"
+echo "fw_diff: positive PASS ($n stdout lines, 5 outputs and fw.manifest identical to the C referees)"
+
+# ---- negative controls ----
+# edit_line SRC LINE OLD NEW DST: replace line LINE (which must read OLD) with NEW; exactly once
+edit_line() {
+  awk -v n="$2" -v a="$3" -v b="$4" 'NR == n && $0 == a { print b; c++; next } { print } END { exit c == 1 ? 0 : 1 }' \
+    "$1" > "$5" || fail 2 "control edit did not apply at $1:$2"
+}
+# tree NAME FMCFILE BOOTFILE: a minimal OGKMSRC holding the two bindata files
+tree() {
+  mkdir -p "$t/$1/src/nvidia/generated"
+  cp "$2" "$t/$1/src/nvidia/generated/$FMC_C"
+  cp "$3" "$t/$1/src/nvidia/generated/$BOOT_C"
+}
+neg=0
+# refused NAME FWFILE OGKMSRC WANTPREFIXFILE LASTLINE: fwprep exits 2, prints the C prefix then LASTLINE,
+# leaves no fw.manifest (a stale one is removed)
+refused() {
+  d=$t/o_$1
+  mkdir -p "$d"
+  echo stale > "$d/fw.manifest"
+  run "$t/fwprep" "$2" "$3" "$d" > "$t/$1.om" 2> "$t/$1.err"
+  r=$?
+  [ "$r" -eq 2 ] || fail 1 "control $1: fwprep exit $r, want 2"
+  { cat "$4"; echo "$5"; } > "$t/$1.want"
+  cmp -s "$t/$1.want" "$t/$1.om" || { diff "$t/$1.want" "$t/$1.om" | head -n 4; fail 1 "control $1: stdout differs"; }
+  [ -e "$d/fw.manifest" ] && fail 1 "control $1: fw.manifest left behind"
+  neg=$((neg + 1))
+  echo "fw_diff: control $1 refused (exit 2): $(grep -h 'REFUSED' "$t/$1.want" | tail -n 2 | tr '\n' ' ')"
+}
+# cref NAME TOOLARGS...: the C referee must refuse (exit 2); its stdout goes to $t/NAME.c
+cref() {
+  nm=$1; shift
+  run "$@" > "$t/$nm.c"
+  r=$?
+  [ "$r" -eq 2 ] || fail 1 "control $nm: C referee exit $r, want 2"
+}
+
+# 1 truncated firmware (ends inside .fwsignature_gb10y)
+head -c 74985600 "$FW" > "$t/trunc.bin"
+cref trunc "$t/ck_gsp_fw_inspect" inspect "$t/trunc.bin"
+refused trunc "$t/trunc.bin" "$OGKM" "$t/trunc.c" "fwprep REFUSED firmware"
+rm -f "$t/trunc.bin"
+# 2 .fwsignature_gb10y renamed to .fwsignature_gb10x in the section string table
+off=$(grep -obaF .fwsignature_gb10y "$FW" | cut -d: -f1)
+[ "$(echo "$off" | wc -l)" -eq 1 ] && [ -n "$off" ] || fail 2 "section name not found once"
+cp "$FW" "$t/ren.bin"
+printf x | dd of="$t/ren.bin" bs=1 seek=$((off + 17)) conv=notrunc 2> /dev/null
+cref ren "$t/ck_gsp_fw_inspect" inspect "$t/ren.bin"
+grep -q 'no signature section' "$t/ren.c" || fail 1 "control ren: C refused for another reason"
+refused ren "$t/ren.bin" "$OGKM" "$t/ren.c" "fwprep REFUSED firmware"
+rm -f "$t/ren.bin"
+# 3 CRC-32: UCODE_DESC_PROD trailer byte 0xb7 -> 0xb6
+edit_line "$G/$BOOT_C" 24717 '    0x78, 0xf4, 0x01, 0x00, 0xb7, 0x2b, 0xc9, 0xc2, 0x54, 0x00, 0x00, 0x00,' \
+  '    0x78, 0xf4, 0x01, 0x00, 0xb6, 0x2b, 0xc9, 0xc2, 0x54, 0x00, 0x00, 0x00,' "$t/crc.c.in"
+tree crc "$G/$FMC_C" "$t/crc.c.in"
+cref crcb "$t/ck_gsp_bindata_extract" extract "$t/crc/src/nvidia/generated/$BOOT_C"
+grep -q 'CRC-32 mismatch' "$t/crcb.c" || fail 1 "control crc: C refused for another reason"
+cat "$t/insp.txt" "$t/fmc.txt" "$t/crcb.c" > "$t/crc.c"
+refused crc "$FW" "$t/crc" "$t/crc.c" "fwprep REFUSED bindata $BOOT_C"
+# 4 deflate body: UCODE_DESC_PROD compressed byte 0x20 -> 0x30
+edit_line "$G/$BOOT_C" 24716 '    0x63, 0x65, 0x20, 0x02, 0x70, 0x41, 0xf1, 0x32, 0x20, 0xde, 0x00, 0xc4, 0xbe, 0x4c, 0x0c, 0x8c,' \
+  '    0x63, 0x65, 0x30, 0x02, 0x70, 0x41, 0xf1, 0x32, 0x20, 0xde, 0x00, 0xc4, 0xbe, 0x4c, 0x0c, 0x8c,' "$t/body.c.in"
+tree body "$G/$FMC_C" "$t/body.c.in"
+cref bodyb "$t/ck_gsp_bindata_extract" extract "$t/body/src/nvidia/generated/$BOOT_C"
+grep -q 'inflate' "$t/bodyb.c" || fail 1 "control body: C refused for another reason"
+cat "$t/insp.txt" "$t/fmc.txt" "$t/bodyb.c" > "$t/body.c"
+refused body "$FW" "$t/body" "$t/body.c" "fwprep REFUSED bindata $BOOT_C"
+# 5 hash mismatch: first UCODE_HASH byte 0x2f -> 0x2e
+edit_line "$G/$FMC_C" 12319 '    0x2f, 0xb0, 0x24, 0x61, 0x26, 0x9a, 0x45, 0xd3, 0xd4, 0x6c, 0x7b, 0x01, 0x88, 0x07, 0xff, 0x06,' \
+  '    0x2e, 0xb0, 0x24, 0x61, 0x26, 0x9a, 0x45, 0xd3, 0xd4, 0x6c, 0x7b, 0x01, 0x88, 0x07, 0xff, 0x06,' "$t/hash.c.in"
+tree hash "$t/hash.c.in" "$G/$BOOT_C"
+cref hashf "$t/ck_gsp_bindata_extract" extract "$t/hash/src/nvidia/generated/$FMC_C"
+grep -q 'UCODE_HASH is not SHA-384 of UCODE_IMAGE' "$t/hashf.c" || fail 1 "control hash: C refused for another reason"
+cat "$t/insp.txt" "$t/hashf.c" > "$t/hash.c"
+refused hash "$FW" "$t/hash" "$t/hash.c" "fwprep REFUSED bindata $FMC_C"
+# 6 wrong function: the boot file in the FMC slot (the C accepts it; fwprep's own check refuses)
+tree swap "$G/$BOOT_C" "$G/$BOOT_C"
+cat "$t/insp.txt" "$t/boot.txt" > "$t/swap.c"
+refused swap "$FW" "$t/swap" "$t/swap.c" "fwprep REFUSED unexpected function $BOOT_F in $FMC_C"
+# 7 missing FWFILE: exit 1 with the C's stderr line, nothing on stdout
+run "$t/ck_gsp_fw_inspect" inspect "$t/nofile" > /dev/null 2> "$t/nofile.cerr"
+run "$t/fwprep" "$t/nofile" "$OGKM" "$t/o_nofile" > "$t/nofile.om" 2> "$t/nofile.err"
+r=$?
+[ "$r" -eq 1 ] || fail 1 "control nofile: fwprep exit $r, want 1"
+[ -s "$t/nofile.om" ] && fail 1 "control nofile: stdout not empty"
+cmp -s "$t/nofile.cerr" "$t/nofile.err" || fail 1 "control nofile: stderr differs from the C"
+neg=$((neg + 1))
+# 8 OUTDIR is a regular file: every check passes, the first output write fails, exit 3, no manifest
+echo x > "$t/notdir"
+run "$t/fwprep" "$FW" "$OGKM" "$t/notdir" > "$t/notdir.om" 2> /dev/null
+r=$?
+[ "$r" -eq 3 ] || fail 1 "control notdir: fwprep exit $r, want 3"
+tail -n 1 "$t/notdir.om" | grep -q "^fwprep FAILED makedir $t/notdir: File exists\$\|^fwprep FAILED write $t/notdir/fmc.img: Not a directory\$" \
+  || fail 1 "control notdir: $(tail -n 1 "$t/notdir.om")"
+neg=$((neg + 1))
+# 9 usage
+run "$t/fwprep" "$FW" "$OGKM" > /dev/null 2> "$t/usage.err"
+r=$?
+[ "$r" -eq 1 ] || fail 1 "control usage: fwprep exit $r, want 1"
+grep -qx 'usage: fwprep FWFILE OGKMSRC OUTDIR' "$t/usage.err" || fail 1 "control usage: stderr"
+neg=$((neg + 1))
+echo "fw_diff: PASS ($n stdout lines and 6 files identical to the C referees; $neg/9 negative controls refused)"
diff --git a/tests/mmio_diff.sh b/tests/mmio_diff.sh
new file mode 100755
index 0000000..d686cf7
--- /dev/null
+++ b/tests/mmio_diff.sh
@@ -0,0 +1,54 @@
+#!/bin/sh
+# mmio_diff.sh: builds the .om GSP start-up trace (gsp/mmio.om + gsp/sim.om + tests/mmio_trace.om) and the
+# C reference trace (aienux PR #441 tests/gsp_boot_trace.c + gpu/gsp_mmio.c + gpu/gsp_sim.c, compiled
+# fresh into a temp dir as a test-only referee) and requires byte-identical stdout. Host only.
+# Env: AIENUX (aienux checkout), OMC (pinned omc), MMIO_OM (driver file to test; mutants use this).
+set -u
+here=$(cd "$(dirname "$0")/.." && pwd)
+AIENUX=${AIENUX:-/home/drakestapleton/work/OwnDriver/aienux}
+OMC=${OMC:-$here/build/omc}
+MMIO_OM=${MMIO_OM:-$here/gsp/mmio.om}
+OMC_SHA=$(sed -n 's/^OMC_SHA256=//p' "$here/tools/omc.pin")
+run() { nice -n 19 taskset -c "${AIEN_TEST_CPUS:-0-9,15-19}" "$@"; }
+
+got=$(sha256sum "$OMC" | cut -d' ' -f1)
+if [ "$got" != "$OMC_SHA" ]; then
+  echo "mmio_diff: FAIL omc sha256 $got, pinned $OMC_SHA"; exit 2
+fi
+# The host trace must stay on the simulator: mode 0 only, no device words in the test driver,
+# while the BAR0 (mode 1) branch stays present in the driver.
+if grep -n 'gspmode [0-9]* [1-9]\|gspbar\|vfio\|mapnew\|/dev/\|/sys/' "$here/tests/mmio_trace.om"; then
+  echo "mmio_diff: FAIL test driver leaves simulator mode or names a device"; exit 2
+fi
+for w in 'ret mapget get gspbar 0 off 4' 'r = mapset get gspbar 0 off 4 v' 'r = sleepns get gsppns 0'; do
+  if ! grep -qxF "$w" "$here/gsp/mmio.om"; then
+    echo "mmio_diff: FAIL BAR0 branch line missing from gsp/mmio.om: $w"; exit 2
+  fi
+done
+
+t=$(mktemp -d /tmp/mmio_diff.XXXXXX) || exit 2
+trap 'rm -rf "$t"' EXIT
+k=$AIENUX/native/kernel
+if ! run cc -std=c11 -O1 -Wall -Werror -I"$k/gpu" -o "$t/ctrace" \
+    "$k/tests/gsp_boot_trace.c" "$k/gpu/gsp_mmio.c" "$k/gpu/gsp_sim.c"; then
+  echo "mmio_diff: FAIL C reference build"; exit 2
+fi
+run "$t/ctrace" > "$t/c.txt" || { echo "mmio_diff: FAIL C reference run"; exit 2; }
+if ! cat "$MMIO_OM" "$here/gsp/sim.om" "$here/tests/mmio_trace.om" | run "$OMC" > "$t/omtrace"; then
+  echo "mmio_diff: FAIL omc build"; exit 3
+fi
+chmod +x "$t/omtrace"
+run "$t/omtrace" > "$t/om.txt"
+rc=$?
+if [ "$rc" -ne 0 ]; then
+  echo "mmio_diff: FAIL om trace exit $rc"; exit 1
+fi
+n=$(wc -l < "$t/c.txt")
+if [ "$n" -eq 0 ]; then
+  echo "mmio_diff: FAIL empty C trace"; exit 2
+fi
+if ! cmp -s "$t/c.txt" "$t/om.txt"; then
+  echo "mmio_diff: FAIL traces differ ($(diff "$t/c.txt" "$t/om.txt" | grep -c '^[<>]') differing lines; C $n lines, om $(wc -l < "$t/om.txt"))"
+  exit 1
+fi
+echo "mmio_diff: PASS ($n lines identical, $(grep -c '^==' "$t/c.txt") scenarios, .om vs C reference)"
diff --git a/tests/mmio_trace.om b/tests/mmio_trace.om
new file mode 100644
index 0000000..1cc884a
--- /dev/null
+++ b/tests/mmio_trace.om
@@ -0,0 +1,325 @@
+note tests/mmio_trace.om: every register access gspboot and gspnotify make against the simulated SEC2 + GSP
+note (gsp/sim.om, mode 0) in a fixed list of scenarios, one per line. Port of aien-dev/aienux PR #441
+note native/kernel/tests/gsp_boot_trace.c: same scenarios, same printf bytes (%d, %u, %#x with 0 as `0`,
+note %06x, %08x), so tests/mmio_diff.sh can cmp the two outputs. Host only; never touches a device.
+note Build: cat gsp/mmio.om gsp/sim.om tests/mmio_trace.om | omc
+const ARGSPA ulong 4886716416
+const APPVER ulong 390049
+text tnames "happy busy3 busy-forever sec2-never mask-never hwcfg2-zero2 args-never lockdown-never fmc-error riscv-dead emem-stuck bad-header odd-7 full-1024 too-long budget0 "
+text th1 "== "
+text th2 " rc="
+text th3 " stage="
+text th4 " polls="
+text th5 " dwords="
+text th6 " ememc="
+text th7 " sec2="
+text th8 " hwcfg2="
+text th9 " gsp="
+text th10 " cpuctl="
+text th11 " nlog="
+text th12 " violations="
+text th13 " phase="
+global tob uchar 262144
+global tpos ulong 1
+global tdig uchar 24
+fn tflush to void
+n = get tpos 0
+if gt n 0
+r = write 1 tob 0 n
+if ne r long n
+exit 1
+end
+end
+put tpos 0 0
+end
+fn tch c uchar to void
+p = get tpos 0
+put tob p c
+put tpos 0 add p 1
+if ge add p 1 262000
+tflush
+end
+end
+fn ttext k ulong to void
+if eq k 1
+for i ulong len th1
+tch get th1 i
+end
+end
+if eq k 2
+for i ulong len th2
+tch get th2 i
+end
+end
+if eq k 3
+for i ulong len th3
+tch get th3 i
+end
+end
+if eq k 4
+for i ulong len th4
+tch get th4 i
+end
+end
+if eq k 5
+for i ulong len th5
+tch get th5 i
+end
+end
+if eq k 6
+for i ulong len th6
+tch get th6 i
+end
+end
+if eq k 7
+for i ulong len th7
+tch get th7 i
+end
+end
+if eq k 8
+for i ulong len th8
+tch get th8 i
+end
+end
+if eq k 9
+for i ulong len th9
+tch get th9 i
+end
+end
+if eq k 10
+for i ulong len th10
+tch get th10 i
+end
+end
+if eq k 11
+for i ulong len th11
+tch get th11 i
+end
+end
+if eq k 12
+for i ulong len th12
+tch get th12 i
+end
+end
+if eq k 13
+for i ulong len th13
+tch get th13 i
+end
+end
+end
+note the k-th space-separated name of tnames
+fn tname k ulong to void
+w = ulong 0
+for i ulong len tnames
+c = get tnames i
+if eq c 32
+w = add w 1
+else
+if eq w k
+tch c
+end
+end
+end
+end
+note %u
+fn tdec v ulong to void
+n = ulong 0
+x = v
+while true bound 24
+put tdig n uchar add rem x 10 48
+n = add n 1
+x = div x 10
+if eq x 0
+break
+end
+end
+for i ulong n
+tch get tdig sub sub n 1 i
+end
+end
+note %d
+fn tsdec v long to void
+if lt v 0
+tch 45
+tdec ulong neg v
+ret
+end
+tdec ulong v
+end
+note lowercase hex, at least w digits, zero-padded (%0Nx)
+fn thex v ulong w ulong to void
+n = ulong 0
+x = v
+while true bound 24
+d = uchar rem x 16
+if lt d 10
+put tdig n add d 48
+else
+put tdig n add d 87
+end
+n = add n 1
+x = div x 16
+if eq x 0
+break
+end
+end
+while lt n w bound 24
+put tdig n 48
+n = add n 1
+end
+for i ulong n
+tch get tdig sub sub n 1 i
+end
+end
+note %#x: 0 alone, otherwise 0x and the digits
+fn talt v ulong to void
+if eq v 0
+tch 48
+ret
+end
+tch 48
+tch 120
+thex v 1
+end
+fn tbase to void
+put scfg 0 0
+put scfg 1 3
+put scfg 2 4
+put scfg 3 2
+put scfg 4 5
+put scfg 5 0
+put scfg 6 0
+put scfg 7 0
+put scfg 8 ARGSPA
+put scfg 9 0
+end
+fn tput32 o ulong v ulong to void
+put gpkt o uchar and v 255
+put gpkt add o 1 uchar and shr v 8 255
+put gpkt add o 2 uchar and shr v 16 255
+put gpkt add o 3 uchar and shr v 24 255
+end
+fn thead k ulong rc long to void
+ttext 1
+tname k
+ttext 2
+tsdec rc
+ttext 3
+tsdec get gstage 0
+ttext 4
+tdec get gout 0
+tch 44
+tdec get gout 1
+tch 44
+tdec get gout 2
+tch 44
+tdec get gout 3
+ttext 5
+tdec get gout 4
+ttext 6
+talt get gout 5
+ttext 7
+talt get gout 6
+tch 44
+talt get gout 7
+ttext 8
+talt get gout 8
+ttext 9
+talt get gout 9
+tch 44
+talt get gout 10
+ttext 10
+talt get gout 11
+ttext 11
+tdec get ss SNLOG
+ttext 12
+tdec get ss SVIOL
+ttext 13
+tdec get ss SPHASE
+tch 10
+end
+note one scenario: the caller has set scfg; k names it
+fn tscen k ulong ln ulong budget ulong hdrok bool to void
+for i ulong 1024
+put gpkt i uchar and add mul i 13 5 255
+end
+if hdrok
+tput32 0 3221225472
+tput32 4 336649854
+tput32 8 56360961
+end
+put gin 0 ln
+put gin 1 ARGSPA
+put gin 2 APPVER
+for j ulong 4
+put gin add 3 j budget
+end
+put gspmode 0 0
+siminit
+rc = gspboot
+if eq rc 0
+gspnotify
+end
+thead k rc
+n = get ss SNLOG
+for e ulong n
+if lt e LOGMAX
+if eq get slogw e 1
+tch 87
+else
+tch 82
+end
+tch 32
+thex get slogo e 6
+tch 32
+thex get slogv e 8
+tch 10
+end
+end
+end
+fn main to int
+tbase
+tscen 0 868 100 true
+tbase
+put scfg 0 3
+tscen 1 868 100 true
+tbase
+put scfg 0 NOEND
+tscen 2 868 5 true
+tbase
+put scfg 1 NOEND
+tscen 3 868 5 true
+tbase
+put scfg 2 NOEND
+tscen 4 868 5 true
+tbase
+put scfg 9 2
+tscen 5 868 100 true
+tbase
+put scfg 3 NOEND
+tscen 6 868 6 true
+tbase
+put scfg 4 NOEND
+tscen 7 868 6 true
+tbase
+put scfg 5 35
+tscen 8 868 100 true
+tbase
+put scfg 6 1
+tscen 9 868 100 true
+tbase
+put scfg 7 1
+tscen 10 868 100 true
+tbase
+tscen 11 868 3 false
+tbase
+tscen 12 7 3 true
+tbase
+tscen 13 1024 3 true
+tbase
+tscen 14 1025 3 true
+tbase
+tscen 15 868 0 true
+tflush
+ret 0
+end
diff --git a/tests/mutants-chan.sh b/tests/mutants-chan.sh
new file mode 100755
index 0000000..e0309b9
--- /dev/null
+++ b/tests/mutants-chan.sh
@@ -0,0 +1,97 @@
+#!/bin/sh
+# mutants-chan.sh: single-line mutants of the channel port (chan/gmmu.om, chan/mem.om, chan/chan.om;
+# each must turn tests/chan_diff.sh red) and of chan/params.om (each must turn tests/params_diff.sh
+# red). The simulator chan/sim.om and the test drivers are never mutated. A mutant must change exactly
+# the named line(s) and still compile; otherwise it is INVALID and the run fails. Also runs the two
+# negative controls of the comparison itself: a C trace with one corrupted byte must fail chan_diff.
+set -u
+here=$(cd "$(dirname "$0")/.." && pwd)
+t=$(mktemp -d /tmp/mutants-chan.XXXXXX) || exit 2
+trap 'rm -rf "$t"' EXIT
+k=${AIENUX:-/home/drakestapleton/work/OwnDriver/aienux}/native/kernel
+run() { nice -n 19 taskset -c "${AIEN_TEST_CPUS:-0-9,15-19}" "$@"; }
+
+if ! sh "$here/tests/chan_diff.sh" > "$t/base.log" 2>&1; then
+  cat "$t/base.log"; echo "mutants-chan: FAIL chan baseline is not green"; exit 2
+fi
+if ! sh "$here/tests/params_diff.sh" > "$t/pbase.log" 2>&1; then
+  cat "$t/pbase.log"; echo "mutants-chan: FAIL params baseline is not green"; exit 2
+fi
+# the C channel trace, built once and handed to every mutant run (CHAN_REF)
+if ! run cc -std=c11 -O1 -Wall -Werror -I"$k/gpu" -o "$t/ctrace" \
+    "$k/tests/gpu_chan_trace.c" "$k/gpu/gmmu.c" "$k/gpu/gpu_mem.c" "$k/gpu/gpu_chan.c" "$k/gpu/gpu_sim.c"; then
+  echo "mutants-chan: FAIL C reference build"; exit 2
+fi
+run "$t/ctrace" > "$t/cref.txt" || { echo "mutants-chan: FAIL C reference run"; exit 2; }
+# negative control: one corrupted byte in the reference must make chan_diff exit 1
+sed '1s/rc=0/rc=1/' "$t/cref.txt" > "$t/cbad.txt"
+CHAN_REF=$t/cbad.txt sh "$here/tests/chan_diff.sh" > "$t/neg.log" 2>&1
+rc=$?
+if [ "$rc" -ne 1 ]; then
+  cat "$t/neg.log"; echo "mutants-chan: FAIL negative control (corrupted C trace) exit $rc, want 1"; exit 2
+fi
+echo "negative control refused: corrupted C trace -> chan_diff exit 1"
+
+# unit|desc|old line|new line[|old line 2|new line 2]  (whole-line matches, each exactly once)
+cat > "$t/list" <<'EOF'
+gmmu|PTE aperture at bit 2 instead of 1|v = or 1 shl and ap 3 1|v = or 1 shl and ap 3 2
+gmmu|PTE PCF at bit 4 instead of 3|v = or v shl and pcf 31 3|v = or v shl and pcf 31 4
+gmmu|PDE PCF 0 instead of 2|const MMPDEPCF ulong 2|const MMPDEPCF ulong 0
+gmmu|invalidate drops ALL_VA|mmregwr MMRINV or MMALLVA MMTRIG|mmregwr MMRINV MMTRIG
+gmmu|PDB register address shifted 8 not 4|mmregwr MMRPDB or shl and pdb 268435455 4 MMPDBAP|mmregwr MMRPDB or shl and pdb 268435455 8 MMPDBAP
+chan|work-submit token runlist at bit 17|ret or shl and rl CHRLINV 16 and chid CHIDMAX|ret or shl and rl CHRLINV 17 and chid CHIDMAX
+chan|GP_PUT at USERD 0x88 instead of 0x8c|const CHGPPUT ulong 140|const CHGPPUT ulong 136
+chan|doorbell register one word up|const CHDBELL ulong 12255376|const CHDBELL ulong 12255380
+chan|GP entry length at bit 43|ret or or and va CHVAM shl and ulong n 2097151 42 CHGPB41|ret or or and va CHVAM shl and ulong n 2097151 43 CHGPB41
+chan|ring full one slot late|if ge sub p get chret c sub e 1|if gt sub p get chret c sub e 1
+chan|retire refuses upto == put|if le sub upto r sub get chput c r|if lt sub upto r sub get chput c r
+chan|chid max 4096|const CHIDMAX uint 4095|const CHIDMAX uint 4096
+chan|RAMIN big-page 64K bit dropped|const CHBIG64 uint 2048|const CHBIG64 uint 0
+chan|RAMIN PDB high word shift 31|mmwr32 add ip add CHPDBW 4 shr pdb 32|mmwr32 add ip add CHPDBW 4 shr pdb 31
+chan|hung teardown skips the extra buffers|if gmlive b|if not gmlive b
+mem|uncached GPU-RO PCF 5 becomes 4|ret 5|ret 4
+params|channel record 360 bytes|const PASZCHAN ulong 368|const PASZCHAN ulong 360
+params|subDeviceId written at cid (132)|paput32 136 get pain 9|paput32 132 get pain 9
+params|USERD index bits not cleared|const PAFLMSK ulong 4290773247|const PAFLMSK ulong 4294967295
+params|USERD_INDEX_PAGE_FIXED not set|const PAPGFIX ulong 2097152|const PAPGFIX ulong 0
+params|internalFlags error/ECC notifier fields swapped|paput32 244 or or get pain 14 shl get pain 12 2 shl get pain 13 4|paput32 244 or or get pain 14 shl get pain 12 4 shl get pain 13 2
+params|SM_VERSION read from the index word|const PASMOFF ulong 100|const PASMOFF ulong 96
+params|chid 4096 accepted|if gt chid PACHMAX|if gt chid 4096
+params|VA space record 48 bytes|const PASZVAS ulong 56|const PASZVAS ulong 48
+params|vaBase written as 32 bits|paput64 40 vabase|paput32 40 vabase
+params|PRESERVE_PDES at bit 3|paput32 28 or get pain 5 shl get pain 6 2|paput32 28 or get pain 5 shl get pain 6 3
+params|BLACKWELL_CHANNEL_GPFIFO_A off by one|const PACGPF ulong 51567|const PACGPF ulong 51566
+params|short GR reply accepted|if ne n PAGRSZ|if gt n PAGRSZ
+params|eccErrorNotifierMem size treated as NvU32|ret or eq k 38 eq k 39|ret eq k 38
+EOF
+
+killed=0; survived=0; invalid=0; nchan=0; npar=0
+while IFS='|' read -r unit desc o1 n1 o2 n2; do
+  case $unit in
+    gmmu) src=$here/chan/gmmu.om; var=GMMU_OM; diff_sh=$here/tests/chan_diff.sh ;;
+    mem) src=$here/chan/mem.om; var=MEM_OM; diff_sh=$here/tests/chan_diff.sh ;;
+    chan) src=$here/chan/chan.om; var=CHAN_OM; diff_sh=$here/tests/chan_diff.sh ;;
+    params) src=$here/chan/params.om; var=PARAMS_OM; diff_sh=$here/tests/params_diff.sh ;;
+    *) echo "mutant INVALID (unknown unit $unit): $desc"; invalid=$((invalid + 1)); continue ;;
+  esac
+  m=$t/$unit.om
+  awk -v o1="$o1" -v n1="$n1" -v o2="${o2:-}" -v n2="${n2:-}" '
+    $0 == o1 && !d1 { print n1; c1++; d1 = 1; next }
+    o2 != "" && $0 == o2 && !d2 { print n2; c2++; d2 = 1; next }
+    $0 == o1 { c1++ } o2 != "" && $0 == o2 { c2++ }
+    { print }
+    END { if (c1 != 1 || (o2 != "" && c2 != 1)) exit 1 }' "$src" > "$m"
+  if [ $? -ne 0 ] || cmp -s "$src" "$m"; then
+    echo "mutant INVALID (pattern not matched exactly once): $unit: $desc"; invalid=$((invalid + 1)); continue
+  fi
+  env "$var=$m" CHAN_REF="$t/cref.txt" sh "$diff_sh" > "$t/m.log" 2>&1
+  rc=$?
+  case $rc in
+    0) echo "mutant SURVIVED: $unit: $desc"; survived=$((survived + 1)) ;;
+    1) echo "mutant killed: $unit: $desc"; killed=$((killed + 1))
+       if [ "$unit" = params ]; then npar=$((npar + 1)); else nchan=$((nchan + 1)); fi ;;
+    *) echo "mutant INVALID (exit $rc: $(cat "$t/m.log")): $unit: $desc"; invalid=$((invalid + 1)) ;;
+  esac
+done < "$t/list"
+echo "mutants-chan: $killed killed ($nchan channel, $npar params), $survived survived, $invalid invalid"
+[ "$survived" -eq 0 ] && [ "$invalid" -eq 0 ] && [ "$nchan" -ge 12 ] && [ "$npar" -ge 8 ]
diff --git a/tests/mutants-fw.sh b/tests/mutants-fw.sh
new file mode 100755
index 0000000..f8c2b80
--- /dev/null
+++ b/tests/mutants-fw.sh
@@ -0,0 +1,67 @@
+#!/bin/sh
+# mutants-fw.sh: single-line mutants of the firmware units (gsp/fw.om, gsp/inflate.om, gsp/sha2.om,
+# gsp/bindata.om, fwprep.om); each must make tests/fw_diff.sh go red (exit 1). A mutant must change
+# exactly the named line and still compile; otherwise it is INVALID and the run fails.
+set -u
+here=$(cd "$(dirname "$0")/.." && pwd)
+diff_sh=$here/tests/fw_diff.sh
+t=$(mktemp -d /tmp/mutants-fw.XXXXXX) || exit 2
+trap 'rm -rf "$t"' EXIT
+
+if ! sh "$diff_sh" > "$t/base.log" 2>&1; then
+  cat "$t/base.log"; echo "mutants-fw: FAIL baseline is not green"; exit 2
+fi
+
+# unit|desc|old line|new line  (whole-line match, exactly once in the unit)
+cat > "$t/list" <<'EOF'
+fw|ELF magic byte 1 'E' (69) taken as 68|if ne get fwhd 1 69|if ne get fwhd 1 68
+fw|e_machine RISC-V (243) replaced by x86-64 (62)|if ne fwh16 18 243|if ne fwh16 18 62
+fw|EI_VERSION check inverted|if ne get fwhd 6 1|if eq get fwhd 6 1
+fw|e_shentsize 64 replaced by 40|if ne fwh16 58 64|if ne fwh16 58 40
+fw|signature section matched by the build-id note name|if eq fwnmeq o 50 1|if eq fwnmeq o 49 1
+inflate|CRC-32 polynomial low bit set|c = xor shr c 1 and 3988292384 m|c = xor shr c 1 and 3988292385 m
+inflate|CRC-32 check compares the trailer with itself|if ne infle32 sub inlen 8 infcrc outlen|if ne infle32 sub inlen 8 infle32 sub inlen 8
+inflate|ISIZE read from the CRC word|if ne infle32 sub inlen 4 outlen|if ne infle32 sub inlen 8 outlen
+inflate|length base for symbol 257 is 4|put inflb 0 3|put inflb 0 4
+sha2|SHA-256 K[63] off by one|put shk 63 3329325298|put shk 63 3329325299
+sha2|SHA-384 IV word 0 off by one|put sh5h 0 14680500436340154072|put sh5h 0 14680500436340154073
+bindata|lowercase hex digit base 87 ('a'-10) taken as 86|ret sub ulong c 87|ret sub ulong c 86
+bindata|descriptor version 5 taken as 6|if ne bdw32 i 0 5|if ne bdw32 i 0 6
+bindata|UCODE_HASH length 48 taken as 47|if ne get bdpn i 48|if ne get bdpn i 47
+bindata|descriptor region alignment check inverted|if ne rem off 256 0|if eq rem off 256 0
+fwprep|fmc.pubkey takes UCODE_SIG|e = fwpslot 10 4 2|e = fwpslot 11 4 2
+fwprep|descriptor word stride 3 bytes|p = add get fwpdo 0 mul w 4|p = add get fwpdo 0 mul w 3
+fwprep|stale fw.manifest not unlinked|u = unlink fwpp 0 get fwppn 0|u = long 0
+fwprep|function-name check disabled|if eq m 0|if eq m 2
+fwprep|manifest signature offset taken from .fwimage|fwodec get fwsof get fwsx 0|fwodec get fwsof get fwimx 0
+EOF
+
+killed=0; survived=0; invalid=0
+while IFS='|' read -r unit desc o1 n1; do
+  case $unit in
+    fw) var=FW_OM; src=$here/gsp/fw.om ;;
+    inflate) var=INFL_OM; src=$here/gsp/inflate.om ;;
+    sha2) var=SHA2_OM; src=$here/gsp/sha2.om ;;
+    bindata) var=BD_OM; src=$here/gsp/bindata.om ;;
+    fwprep) var=FWPREP_OM; src=$here/fwprep.om ;;
+    *) echo "mutant INVALID (unknown unit $unit): $desc"; invalid=$((invalid + 1)); continue ;;
+  esac
+  m=$t/$unit.om
+  awk -v o1="$o1" -v n1="$n1" '
+    $0 == o1 && !d1 { print n1; c1++; d1 = 1; next }
+    $0 == o1 { c1++ }
+    { print }
+    END { if (c1 != 1) exit 1 }' "$src" > "$m"
+  if [ $? -ne 0 ] || cmp -s "$src" "$m"; then
+    echo "mutant INVALID (pattern not matched exactly once): $unit: $desc"; invalid=$((invalid + 1)); continue
+  fi
+  env "$var=$m" sh "$diff_sh" > "$t/m.log" 2>&1
+  rc=$?
+  case $rc in
+    0) echo "mutant SURVIVED: $unit: $desc"; survived=$((survived + 1)) ;;
+    1) echo "mutant killed: $unit: $desc ($(grep 'FAIL' "$t/m.log" | head -n 1))"; killed=$((killed + 1)) ;;
+    *) echo "mutant INVALID (exit $rc: $(tail -n 1 "$t/m.log")): $unit: $desc"; invalid=$((invalid + 1)) ;;
+  esac
+done < "$t/list"
+echo "mutants-fw: $killed killed, $survived survived, $invalid invalid"
+[ "$survived" -eq 0 ] && [ "$invalid" -eq 0 ] && [ "$killed" -ge 12 ]
diff --git a/tests/mutants-mmio.sh b/tests/mutants-mmio.sh
new file mode 100755
index 0000000..8a99f2c
--- /dev/null
+++ b/tests/mutants-mmio.sh
@@ -0,0 +1,63 @@
+#!/bin/sh
+# mutants-mmio.sh: single-token (one is a two-line order swap) mutants of gsp/mmio.om; each must make
+# tests/mmio_diff.sh go red. The simulator and the test driver are never mutated. A mutant must change
+# exactly the named line(s) and still compile; otherwise it is INVALID and the run fails.
+set -u
+here=$(cd "$(dirname "$0")/.." && pwd)
+src=$here/gsp/mmio.om
+diff_sh=$here/tests/mmio_diff.sh
+t=$(mktemp -d /tmp/mutants-mmio.XXXXXX) || exit 2
+trap 'rm -rf "$t"' EXIT
+
+if ! sh "$diff_sh" > "$t/base.log" 2>&1; then
+  cat "$t/base.log"; echo "mutants-mmio: FAIL baseline is not green"; exit 2
+fi
+
+# desc|old line|new line[|old line 2|new line 2]  (whole-line matches, each exactly once)
+cat > "$t/list" <<'EOF'
+QTAIL written after QHEAD (doorbell before tail)|gspwr S2QT sub mul dw 4 4|gspwr S2QH 0|gspwr S2QH 0|gspwr S2QT sub mul dw 4 4
+EMEMC AINCW bit 23 instead of 24|const AINCW ulong 16777216|const AINCW ulong 8388608
+emem dword formula 32 dwords per block|const DWBLK ulong 64|const DWBLK ulong 32
+poll budget off by one (gt for ge)|if ge n b|if gt n b
+lockdown high-half check shifts 31|if eq m1 shr pa 32|if eq m1 shr pa 31
+CPUCTL active bit 6 instead of 7|const CPUACT ulong 128|const CPUACT ulong 64
+notify writes 1 to QUEUE_HEAD|gspwr GQH 0|gspwr GQH 1
+FALCON_OS gets fmc_args_pa, not app_version|gspwr GOS get gin 2|gspwr GOS get gin 1
+mask timeout reports the lockdown code|ret gspfail EMASK|ret gspfail ELOCK
+tail not zero-padded (one byte past len)|while lt add i k ln bound 4|while le add i k ln bound 4
+target-lock mask covers the low byte|const PRIVMSK ulong 4294967040|const PRIVMSK ulong 4294967295
+lockdown bit 12 instead of 13|const LOCKDN ulong 8192|const LOCKDN ulong 4096
+dword count rounds down|dw = div add ln 3 4|dw = div add ln 0 4
+QUEUE_TAIL = padded size, not size - 4|gspwr S2QT sub mul dw 4 4|gspwr S2QT sub mul dw 4 0
+SEC2 busy value off by one|const CMDBUSY ulong 3221342974|const CMDBUSY ulong 3221342975
+FMC error reported as OK|ret gspfail EFMC|ret gspfail EOK
+step 8 waits for MAILBOX0 zero|ret or eq and h LOCKDN 0 ne m0 0|ret or eq and h LOCKDN 0 eq m0 0
+EMEM pointer check inverted|if ne and sub ememdw ea st M32 dw|if eq and sub ememdw ea st M32 dw
+channel bound refuses exactly 1024 bytes|if or eq ln 0 gt ln CHBYTES|if or eq ln 0 ge ln CHBYTES
+step 1 waits for HEAD != TAIL|ret eq hd gsprd S2QT|ret ne hd gsprd S2QT
+SEC2 timeout reads MAILBOX0 for MAILBOX1|put gout 7 gsprd S2MB1|put gout 7 gsprd S2MB0
+HWCFG2 zero counts as released|if eq h 0|if eq h 1
+EOF
+
+killed=0; survived=0; invalid=0
+while IFS='|' read -r desc o1 n1 o2 n2; do
+  m=$t/mmio.om
+  awk -v o1="$o1" -v n1="$n1" -v o2="${o2:-}" -v n2="${n2:-}" '
+    $0 == o1 && !d1 { print n1; c1++; d1 = 1; next }
+    o2 != "" && $0 == o2 && !d2 { print n2; c2++; d2 = 1; next }
+    $0 == o1 { c1++ } o2 != "" && $0 == o2 { c2++ }
+    { print }
+    END { if (c1 != 1 || (o2 != "" && c2 != 1)) exit 1 }' "$src" > "$m"
+  if [ $? -ne 0 ] || cmp -s "$src" "$m"; then
+    echo "mutant INVALID (pattern not matched exactly once): $desc"; invalid=$((invalid + 1)); continue
+  fi
+  MMIO_OM=$m sh "$diff_sh" > "$t/m.log" 2>&1
+  rc=$?
+  case $rc in
+    0) echo "mutant SURVIVED: $desc"; survived=$((survived + 1)) ;;
+    1) echo "mutant killed: $desc"; killed=$((killed + 1)) ;;
+    *) echo "mutant INVALID (exit $rc: $(cat "$t/m.log")): $desc"; invalid=$((invalid + 1)) ;;
+  esac
+done < "$t/list"
+echo "mutants-mmio: $killed killed, $survived survived, $invalid invalid"
+[ "$survived" -eq 0 ] && [ "$invalid" -eq 0 ] && [ "$killed" -ge 10 ]
diff --git a/tests/mutants-seq.sh b/tests/mutants-seq.sh
new file mode 100755
index 0000000..c5be0c5
--- /dev/null
+++ b/tests/mutants-seq.sh
@@ -0,0 +1,72 @@
+#!/bin/sh
+# mutants-seq.sh: single-line mutants of gsp/seq.om; each must make tests/seq_diff.sh go red.
+# The test driver and the C reference are never mutated. A mutant must change exactly the named line and still
+# compile; otherwise it is INVALID and the run fails.
+set -u
+here=$(cd "$(dirname "$0")/.." && pwd)
+src=$here/gsp/seq.om
+diff_sh=$here/tests/seq_diff.sh
+t=$(mktemp -d /tmp/mutants-seq.XXXXXX) || exit 2
+trap 'rm -rf "$t"' EXIT
+
+if ! sh "$diff_sh" > "$t/base.log" 2>&1; then
+  cat "$t/base.log"; echo "mutants-seq: FAIL baseline is not green"; exit 2
+fi
+
+# desc|old line|new line[|old line 2|new line 2]  (whole-line matches, each exactly once)
+cat > "$t/list" <<'EOF'
+WRITE opcode 0 -> 9|const SQWR ulong 0|const SQWR ulong 9
+MODIFY opcode 1 -> 10|const SQMOD ulong 1|const SQMOD ulong 10
+POLL opcode 2 -> 11|const SQPOLL ulong 2|const SQPOLL ulong 11
+DELAY opcode 3 -> 12|const SQDLY ulong 3|const SQDLY ulong 12
+STORE opcode 4 -> 13|const SQSTO ulong 4|const SQSTO ulong 13
+core opcodes start at 6, not 5|const SQCRST ulong 5|const SQCRST ulong 6
+core opcodes end at 7, not 8|const SQCRES ulong 8|const SQCRES ulong 7
+WRITE/STORE payload 2 -> 3|ret 2|ret 3
+MODIFY payload 3 -> 2|ret 3|ret 2
+POLL payload 5 -> 4|ret 5|ret 4
+DELAY payload 1 -> 2|ret 1|ret 2
+poll ignores the mask|while ne and v a1 a2 bound 999999|while ne v a2 bound 999999
+poll compares with <, not ==|while ne and v a1 a2 bound 999999|while lt and v a1 a2 bound 999999
+poll budget 0 gives 2 extra reads, not 1|left = 1|left = 2
+poll spends 2 per retry|left = sub left 1|left = sub left 2
+poll budget cap 999998 -> 999997|const SQBMAX ulong 999998|const SQBMAX ulong 999997
+delay microseconds not summed|put sqdly 1 add get sqdly 1 us|put sqdly 1 us
+delay calls not counted|put sqdly 0 add get sqdly 0 1|put sqdly 0 1
+overrun check > -> >=|if gt add i n ci|if ge add i n ci
+cmdIndex check >= -> >|if ge ci nw|if gt ci nw
+empty buffer not refused|if eq nw 0|if lt nw 0
+save index 8 accepted|if ge k SQSAVE|if gt k SQSAVE
+save index read from the address dword|k = sqw add i 1|k = sqw i
+MODIFY keeps masked bits (~mask dropped)|gspwr a or and v xor sqw add i 1 M32 sqw add i 2|gspwr a or and v sqw add i 1 sqw add i 2
+MODIFY ignores the value dword|gspwr a or and v xor sqw add i 1 M32 sqw add i 2|gspwr a and v xor sqw add i 1 M32
+WRITE writes the address as value|gspwr sqw i sqw add i 1|gspwr sqw i sqw i
+core opcode runs with no callback|if eq get sqcore 0 0|if eq get sqcore 0 2
+core failure (-1) not refused|if ne c 0|if gt c 0
+walk steps 2, not the payload|i = add i n|i = add i 2
+nwords cap 16384 -> 16383|const SQMAX ulong 16384|const SQMAX ulong 16383
+why text off by one|k = ulong sub 0 add e 1|k = ulong sub 0 e
+EOF
+
+killed=0; survived=0; invalid=0
+while IFS='|' read -r desc o1 n1 o2 n2; do
+  m=$t/seq.om
+  awk -v o1="$o1" -v n1="$n1" -v o2="${o2:-}" -v n2="${n2:-}" '
+    $0 == o1 && !d1 { print n1; c1++; d1 = 1; next }
+    o2 != "" && $0 == o2 && !d2 { print n2; c2++; d2 = 1; next }
+    $0 == o1 { c1++ } o2 != "" && $0 == o2 { c2++ }
+    { print }
+    END { if (c1 != 1 || (o2 != "" && c2 != 1)) exit 1 }' "$src" > "$m"
+  if [ $? -ne 0 ] || cmp -s "$src" "$m"; then
+    echo "mutant INVALID (pattern not matched exactly once): $desc"; invalid=$((invalid + 1)); continue
+  fi
+  SEQ_OM=$m sh "$diff_sh" > "$t/m.log" 2>&1
+  rc=$?
+  case $rc in
+    0) echo "mutant SURVIVED: $desc"; survived=$((survived + 1)) ;;
+    1) echo "mutant killed: $desc"; killed=$((killed + 1)) ;;
+    *) echo "mutant INVALID (exit $rc: $(cat "$t/m.log")): $desc"; invalid=$((invalid + 1)) ;;
+  esac
+done < "$t/list"
+echo "mutants-seq: $killed killed, $survived survived, $invalid invalid"
+[ "$survived" -eq 0 ] && [ "$invalid" -eq 0 ] && [ "$killed" -ge 10 ]
diff --git a/tests/mutants-sysinfo.sh b/tests/mutants-sysinfo.sh
new file mode 100755
index 0000000..7cebee2
--- /dev/null
+++ b/tests/mutants-sysinfo.sh
@@ -0,0 +1,61 @@
+#!/bin/sh
+# mutants-sysinfo.sh: single-line mutants of gsp/sysinfo.om; each must make tests/sysinfo_diff.sh go red.
+# The test driver and the C reference are never mutated. A mutant must change exactly the named line and still
+# compile; otherwise it is INVALID and the run fails.
+set -u
+here=$(cd "$(dirname "$0")/.." && pwd)
+src=$here/gsp/sysinfo.om
+diff_sh=$here/tests/sysinfo_diff.sh
+t=$(mktemp -d /tmp/mutants-sysinfo.XXXXXX) || exit 2
+trap 'rm -rf "$t"' EXIT
+
+if ! sh "$diff_sh" > "$t/base.log" 2>&1; then
+  cat "$t/base.log"; echo "mutants-sysinfo: FAIL baseline is not green"; exit 2
+fi
+
+# desc|old line|new line[|old line 2|new line 2]  (whole-line matches, each exactly once)
+cat > "$t/list" <<'EOF'
+oorArch offset 104 -> 105|put sioff 16 104|put sioff 16 105
+capsMethodData.status offset 828 -> 832|put sioff 44 828|put sioff 44 832
+FHBBusInfo.revisionID size 1 -> 2|put sisz 34 1|put sisz 34 2
+fit check shifts 7 bits per byte|ret eq shr v mul sz 8 0|ret eq shr v mul sz 7 0
+fit check skips 4-byte fields|if lt sz 8|if lt sz 4
+three tokens accepted (k != 2 check dropped)|if ne get sipos 0 b|if gt get sipos 0 b
+0X prefix not taken as hex|if or eq x 120 eq x 88|if eq x 120
+leading 0 read as decimal, not octal|base = 8|base = 10
+bytes not little endian (7-bit shift)|put siout add o b uchar and shr v mul b 8 255|put siout add o b uchar and shr v mul b 7 255
+line limit 512 -> 513|const SILINE ulong 512|const SILINE ulong 513
+comment cut on $ not #|if eq get sitxt h 35|if eq get sitxt h 36
+overflow test ignores the digit|if gt v div sub SIMAX64 d base|if gt v div SIMAX64 base
+text not cut at NUL|if eq get sitxt i 0|if eq get sitxt i 1
+name lookup matches prefixes|if eq sub i s n|if ge sub i s n
+token width 127 -> 128|while and lt p b lt n 127 bound 600|while and lt p b lt n 128 bound 600
+does-not-fit value shown to 41 chars|siwval 40|siwval 41
+lower-case hex digit value off by one|ret sub ulong c 87|ret sub ulong c 86
+leading + not skipped|if eq get sivb 0 43|if eq get sivb 0 44
+CR (13) not whitespace|ret or eq c 32 and ge c 9 le c 13|ret or eq c 32 and ge c 9 le c 12
+text limit refuses exactly 65536 bytes|if gt n SITXMAX|if ge n SITXMAX
+EOF
+
+killed=0; survived=0; invalid=0
+while IFS='|' read -r desc o1 n1 o2 n2; do
+  m=$t/sysinfo.om
+  awk -v o1="$o1" -v n1="$n1" -v o2="${o2:-}" -v n2="${n2:-}" '
+    $0 == o1 && !d1 { print n1; c1++; d1 = 1; next }
+    o2 != "" && $0 == o2 && !d2 { print n2; c2++; d2 = 1; next }
+    $0 == o1 { c1++ } o2 != "" && $0 == o2 { c2++ }
+    { print }
+    END { if (c1 != 1 || (o2 != "" && c2 != 1)) exit 1 }' "$src" > "$m"
+  if [ $? -ne 0 ] || cmp -s "$src" "$m"; then
+    echo "mutant INVALID (pattern not matched exactly once): $desc"; invalid=$((invalid + 1)); continue
+  fi
+  SYSINFO_OM=$m sh "$diff_sh" > "$t/m.log" 2>&1
+  rc=$?
+  case $rc in
+    0) echo "mutant SURVIVED: $desc"; survived=$((survived + 1)) ;;
+    1) echo "mutant killed: $desc"; killed=$((killed + 1)) ;;
+    *) echo "mutant INVALID (exit $rc: $(cat "$t/m.log")): $desc"; invalid=$((invalid + 1)) ;;
+  esac
+done < "$t/list"
+echo "mutants-sysinfo: $killed killed, $survived survived, $invalid invalid"
+[ "$survived" -eq 0 ] && [ "$invalid" -eq 0 ] && [ "$killed" -ge 10 ]
diff --git a/tests/mutants-window.sh b/tests/mutants-window.sh
new file mode 100755
index 0000000..b457dc3
--- /dev/null
+++ b/tests/mutants-window.sh
@@ -0,0 +1,51 @@
+#!/bin/sh
+# tests/mutants-window.sh -- each mutant removes one safety step from a copy of window/*.sh; tests/window_sim.sh
+# must then fail. Test-only shell; evidence label EXERCISED (host simulator).
+set -eu
+R=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
+W=$(mktemp -d /tmp/owndriver-window-mut.XXXXXX)
+killed=0
+total=0
+# file@sed expression@what the mutant removes
+MUTANTS='common.sh@s/^need_approval() {$/need_approval() { return 0/@approval check
+common.sh@s/^privcheck() {$/privcheck() { return 0/@privilege check
+common.sh@/\[ "$s" = active \] || die/d@runtime PM active check
+d2-pre.sh@s/^flock -n 9 || die/true || die/@W1 chip lock
+d2-pre.sh@s/^trap .abort_w1. EXIT$/:/@W1 abort trap
+d2-pre.sh@s/^\tif cmp -s "$SNAP.now" "$SNAP.want"; then$/\tif true; then/@W0 launch record check
+d2-pre.sh@s/^\[ "$STAGE" = D2 \] || \[ -x "$BUILD\/ogd" \] ||/true ||/@D3 needs ogd
+d2-pre.sh@s/^\t(cd "$BUILD\/fw" .* sha256sum -c --quiet .*) ||$/\ttrue ||/@W0 build\/fw hash check
+d2-run.sh@s/^echo restore > "$STATE"$/:/@W2 state=restore before acting
+d2-run.sh@s/^flock -n 9 || die/true || die/@W2 chip lock
+d2-run.sh@/^\[ "$m" = root:root:600 \] || die/d@W2 /dev/vfio mode check
+d2-run.sh@s/^\tpm_auto$/\t:/@W7 power\/control=auto
+d2-restore.sh@s/^fallback() {$/fallback() { die "$*"/@R1 reboot fallback
+d2-restore.sh@s/^\tif \[ -e "$FALLBACK" \]; then$/\tif false; then/@R1 fallback only once
+d2-restore.sh@s/^\tsudo -n sysctl -q -p "$SAVED" || die/\ttrue || die/@R2 sysctl restore
+d2-restore.sh@s/^sudo -n rm -f "$UNIT"$/:/@R4 unit removal
+d2-restore.sh@s/^rm -f "$LIVE_MARKER" "$APPROVAL"/rm -f "$LIVE_MARKER"/@R4 approval removal
+d2-boot.sh@s/^\tsudo -n rm -f "$UNIT"$/\t:/@stale unit removal'
+printf '%s\n' "$MUTANTS" > "$W/list"
+while IFS='@' read -r f expr what; do
+	total=$((total + 1))
+	M=$W/m$total
+	mkdir -p "$M/build"
+	cp -r "$R/window" "$R/tools" "$R/tests" "$M/"
+	ln -s "$R/build/omc" "$M/build/omc"
+	sed -i "$expr" "$M/window/$f"
+	if cmp -s "$R/window/$f" "$M/window/$f"; then
+		echo "BROKEN mutant $total ($what): sed did not change window/$f"
+		rm -rf "$W"
+		exit 2
+	fi
+	if SIMDIR=$W/sim$total sh "$M/tests/window_sim.sh" > "$W/out$total" 2>&1; then
+		echo "SURVIVED $total: $what ($f)"
+	else
+		killed=$((killed + 1))
+		echo "killed   $total: $what ($f): $(tail -1 "$W/out$total" | sed 's/.*in://')"
+	fi
+	for s in "$W"/sim$total/*/st/35b; do [ -s "$s" ] && kill "$(cat "$s")" 2>/dev/null || true; done
+done < "$W/list"
+rm -rf "$W"
+echo "mutants-window: $killed/$total killed"
+[ "$killed" -eq "$total" ]
diff --git a/tests/params_diff.sh b/tests/params_diff.sh
new file mode 100755
index 0000000..38e698a
--- /dev/null
+++ b/tests/params_diff.sh
@@ -0,0 +1,63 @@
+#!/bin/sh
+# params_diff.sh: builds the .om params dump (chan/params.om + tests/params_dump.om) and the C referee
+# tests/params_ref.c (TEST-ONLY, compiled fresh into a temp dir against the NVIDIA open-gpu-kernel-modules
+# 580.173.02 headers) and requires byte-identical stdout: every record's bytes, every record size
+# against NVIDIA's sizeof, the refused cases and the exported constants. Host only.
+# Env: OMC (pinned omc), PARAMS_OM (unit to test; mutants use it), OGKM_SRC (NVIDIA src/ tree),
+# PARAMS_REF (referee output already produced by this script, so a mutant run skips the rebuild).
+# Exit: 0 PASS, 1 outputs differ, 2 setup, 3 omc failure.
+set -u
+here=$(cd "$(dirname "$0")/.." && pwd)
+OMC=${OMC:-$here/build/omc}
+PARAMS_OM=${PARAMS_OM:-$here/chan/params.om}
+OGKM_SRC=${OGKM_SRC:-/home/drakestapleton/workspace/_ext/open-gpu-kernel-modules-580.173.02/src}
+PARAMS_REF=${PARAMS_REF:-}
+OMC_SHA=$(sed -n 's/^OMC_SHA256=//p' "$here/tools/omc.pin")
+run() { nice -n 19 taskset -c "${AIEN_TEST_CPUS:-0-9,15-19}" "$@"; }
+
+got=$(sha256sum "$OMC" | cut -d' ' -f1)
+if [ "$got" != "$OMC_SHA" ]; then
+  echo "params_diff: FAIL omc sha256 $got, pinned $OMC_SHA"; exit 2
+fi
+if grep -n 'vfio\|mapnew\|/dev/\|/sys/' "$PARAMS_OM" "$here/tests/params_dump.om"; then
+  echo "params_diff: FAIL params unit or dump names a device"; exit 2
+fi
+
+t=$(mktemp -d /tmp/params_diff.XXXXXX) || exit 2
+trap 'rm -rf "$t"' EXIT
+if [ -n "$PARAMS_REF" ]; then
+  [ -s "$PARAMS_REF" ] || { echo "params_diff: FAIL PARAMS_REF $PARAMS_REF missing or empty"; exit 2; }
+  cp "$PARAMS_REF" "$t/c.txt" || exit 2
+else
+  S=$OGKM_SRC
+  if ! run cc -std=c11 -O1 -Wall -Werror \
+      -I"$S/common/sdk/nvidia/inc" -I"$S/nvidia/arch/nvalloc/common/inc" -I"$S/common/uproc/os/common/include" \
+      -I"$S/nvidia/inc/kernel" -I"$S/nvidia/inc" -I"$S/nvidia/generated" -I"$S/common/shared/msgq/inc" \
+      -I"$S/nvidia/interface" -I"$S/common/inc" -o "$t/pref" "$here/tests/params_ref.c"; then
+    echo "params_diff: FAIL C referee build"; exit 2
+  fi
+  run "$t/pref" > "$t/c.txt" || { echo "params_diff: FAIL C referee run"; exit 2; }
+fi
+if ! cat "$PARAMS_OM" "$here/tests/params_dump.om" | run "$OMC" > "$t/pd"; then
+  echo "params_diff: FAIL omc build"; exit 3
+fi
+chmod +x "$t/pd"
+run "$t/pd" > "$t/om.txt"
+rc=$?
+if [ "$rc" -ne 0 ]; then
+  echo "params_diff: FAIL om dump exit $rc"; exit 1
+fi
+n=$(wc -l < "$t/c.txt")
+if [ "$n" -eq 0 ]; then
+  echo "params_diff: FAIL empty C output"; exit 2
+fi
+if ! cmp -s "$t/c.txt" "$t/om.txt"; then
+  echo "params_diff: FAIL outputs differ ($(diff "$t/c.txt" "$t/om.txt" | grep -c '^[<>]') differing lines; C $n lines, om $(wc -l < "$t/om.txt"))"
+  exit 1
+fi
+# negative control: the comparison must see a single corrupted byte (first record byte 01 -> 00)
+sed '2s/^01/00/' "$t/om.txt" > "$t/bad.txt"
+if cmp -s "$t/c.txt" "$t/bad.txt"; then
+  echo "params_diff: FAIL negative control: a corrupted byte was not detected"; exit 2
+fi
+echo "params_diff: PASS ($n lines identical, .om vs C referee; corrupted-byte control refused)"
diff --git a/tests/params_dump.om b/tests/params_dump.om
new file mode 100644
index 0000000..071a821
--- /dev/null
+++ b/tests/params_dump.om
@@ -0,0 +1,234 @@
+note tests/params_dump.om: the differential driver for chan/params.om. It encodes the same cases as
+note tests/params_ref.c (the TEST-ONLY C referee built on the NVIDIA 580.173.02 headers) and prints
+note the same text: per case "<label> rc=<rc>[ size=<palen>]" and the record bytes in lowercase hex,
+note 32 per line; then the SM_VERSION decodes and the exported constants. The refused cases are the
+note negative controls (a value too wide for its field, chid 4096, privilege 4, aperture 3, bEnable 2,
+note engine 8, a 3711-byte reply). Build: cat chan/params.om tests/params_dump.om | omc > prog.
+note Prefix pd. Host only: no device, no file but stdout.
+text pdt "NV0000_ALLOC_PARAMETERS root|NV0000_ALLOC_PARAMETERS root hClient>u32|NV0080_ALLOC_PARAMETERS device|NV0080_ALLOC_PARAMETERS device vaMode>u32|NV2080_ALLOC_PARAMETERS subdevice|NV2080_ALLOC_PARAMETERS subdevice id>u32|NV_VASPACE_ALLOCATION_PARAMETERS vaspace|NV_VASPACE_ALLOCATION_PARAMETERS vaspace bigPageSize>u32|NV_CHANNEL_GROUP_ALLOCATION_PARAMETERS tsg|NV_CHANNEL_GROUP_ALLOCATION_PARAMETERS tsg engineType>u32|NV_CTXSHARE_ALLOCATION_PARAMETERS ctxshare|NV_CTXSHARE_ALLOCATION_PARAMETERS ctxshare flags>u32|NV_CHANNEL_ALLOC_PARAMS channel|NV_CHANNEL_ALLOC_PARAMS channel chid=4096|NV_CHANNEL_ALLOC_PARAMS channel gpFifoEntries>u32|NV_CHANNEL_ALLOC_PARAMS channel privilege=4|NV_CHANNEL_ALLOC_PARAMS channel chid=0|NVA06C_CTRL_GPFIFO_SCHEDULE_PARAMS schedule|NVA06C_CTRL_GPFIFO_SCHEDULE_PARAMS schedule bEnable=2|NV2080_CTRL_INTERNAL_STATIC_GR_GET_INFO_PARAMS grinfo|rpc_set_page_directory_v1E_05 setpd|rpc_set_page_directory_v1E_05 setpd aperture=3|rpc_set_page_directory_v1E_05 setpd numEntries>u32|rpc_unset_page_directory_v1E_05 unsetpd|rpc_unset_page_directory_v1E_05 unsetpd hVASpace>u32|smver eng=0|smver eng=7|smver eng=8|smver len=3711| rc=| size=|const |NV01_ROOT |NV01_DEVICE_0 |NV20_SUBDEVICE_0 |FERMI_VASPACE_A |KEPLER_CHANNEL_GROUP_A |FERMI_CONTEXT_SHARE_A |BLACKWELL_CHANNEL_GPFIFO_A |BLACKWELL_COMPUTE_B |NV_VGPU_MSG_FUNCTION_SET_PAGE_DIRECTORY |NV_VGPU_MSG_FUNCTION_GSP_RM_CONTROL |NV_VGPU_MSG_FUNCTION_UNSET_PAGE_DIRECTORY |NV_VGPU_MSG_FUNCTION_GSP_RM_ALLOC |NVA06C_CTRL_CMD_GPFIFO_SCHEDULE |NV2080_CTRL_CMD_INTERNAL_STATIC_KGR_GET_INFO |NV2080_ENGINE_TYPE_GRAPHICS |NV_CTXSHARE_ALLOCATION_FLAGS_SUBCONTEXT_ASYNC "
+note test handles (decimal; the referee uses the same numbers)
+const PDHCLI ulong 3254779905
+const PDHDEV ulong 3254779906
+const PDHVAS ulong 3254779912
+note 2^32: one past the widest NvU32
+const PDBIG ulong 4294967296
+note 2^40 (VA space size), 2^33 (VA base), 0x80040000 (page directory), 2^16 (big page)
+const PDVASZ ulong 1099511627776
+const PDVABA ulong 8589934592
+const PDPDPA ulong 2147745792
+const PDBIGPG ulong 65536
+note channel input pattern: narrow k * 0x01010101 + 1, wide k * 0x0101010101010101 + 2
+const PDN1 ulong 16843009
+const PDW1 ulong 72340172838076673
+global pdob uchar 65536
+global pdpos ulong 1
+global pddig uchar 24
+fn pdflush to void
+n = get pdpos 0
+if gt n 0
+r = write 1 pdob 0 n
+if ne r long n
+exit 1
+end
+end
+put pdpos 0 0
+end
+fn pdch c uchar to void
+p = get pdpos 0
+put pdob p c
+put pdpos 0 add p 1
+if ge add p 1 65000
+pdflush
+end
+end
+fn pdfrag k ulong to void
+w = ulong 0
+for i ulong len pdt
+c = get pdt i
+if eq c 124
+w = add w 1
+else
+if eq w k
+pdch c
+end
+end
+end
+end
+fn pddec v ulong to void
+n = ulong 0
+x = v
+while true bound 24
+put pddig n uchar add rem x 10 48
+n = add n 1
+x = div x 10
+if eq x 0
+break
+end
+end
+for i ulong n
+pdch get pddig sub sub n 1 i
+end
+end
+fn pdsdec v long to void
+if lt v 0
+pdch 45
+pddec ulong neg v
+ret
+end
+pddec ulong v
+end
+fn pdhex2 b uchar to void
+for i ulong 2
+d = uchar and shr b mul sub 1 i 4 15
+if lt d 10
+pdch add d 48
+else
+pdch add d 87
+end
+end
+end
+note "<label k> rc=<rc>", then " size=<palen>" and the hex of pabuf[0..palen) when rc > 0
+fn pdshow k ulong rc long to void
+pdfrag k
+pdfrag 29
+pdsdec rc
+if le rc 0
+pdch 10
+ret
+end
+n = get palen 0
+pdfrag 30
+pddec n
+pdch 10
+for i ulong n
+pdhex2 get pabuf i
+if or eq rem i 32 31 eq add i 1 n
+pdch 10
+end
+end
+end
+fn pdsm k ulong rc long to void
+pdfrag k
+pdfrag 29
+pdsdec rc
+pdch 10
+end
+fn pdconst k ulong v ulong to void
+pdfrag 31
+pdfrag k
+pddec v
+pdch 10
+end
+fn pdwide k ulong to bool
+if or eq k 1 eq k 7
+ret true
+end
+if and ge k 16 le k 35
+ret lt rem sub k 16 4 2
+end
+ret or eq k 38 eq k 39
+end
+fn pdchin to void
+for k ulong 48
+if pdwide k
+put pain k add mul k PDW1 2
+else
+put pain k add mul k PDN1 1
+end
+end
+put pain 3 PAU32
+put pain 8 PAENGGR
+put pain 12 3
+put pain 13 2
+put pain 14 2
+put pain 15 4011
+end
+fn pdspin to void
+for k ulong 48
+put pain k 0
+end
+put pain 0 PDHCLI
+put pain 1 PDHDEV
+put pain 3 PDPDPA
+put pain 4 512
+put pain 5 2
+put pain 6 1
+put pain 7 PDHVAS
+put pain 8 4011
+end
+fn pdallocs to void
+pdshow 0 paroot PDHCLI 4242
+pdshow 1 paroot PDBIG 1
+pdshow 2 padevice 0 PDHCLI 3 2 PDVASZ
+pdshow 3 padevice 0 PDHCLI 3 PDBIG 0
+pdshow 4 pasubdev 0
+pdshow 5 pasubdev PDBIG
+pdshow 6 pavaspace 0 72 PDVASZ PDVABA PDBIGPG
+pdshow 7 pavaspace 0 72 1 0 PDBIG
+pdshow 8 patsg 0 0 PDHVAS PAENGGR
+pdshow 9 patsg 0 0 PDHVAS PDBIG
+pdshow 10 pactxsh PDHVAS PACTXAS 0
+pdshow 11 pactxsh PDHVAS PDBIG 0
+end
+fn pdchans to void
+pdchin
+pdshow 12 pachan
+put pain 15 4096
+pdshow 13 pachan
+put pain 15 4011
+put pain 2 PDBIG
+pdshow 14 pachan
+put pain 2 add mul 2 PDN1 1
+put pain 14 4
+pdshow 15 pachan
+put pain 14 2
+put pain 15 0
+pdshow 16 pachan
+end
+fn pdctrls to void
+pdshow 17 pasched 1 0 0
+pdshow 18 pasched 2 0 0
+pdshow 19 pagrinfo
+pdspin
+pdshow 20 pasetpd
+put pain 5 3
+pdshow 21 pasetpd
+put pain 5 2
+put pain 4 PDBIG
+pdshow 22 pasetpd
+pdshow 23 paunsetpd PDHCLI PDHDEV PDHVAS 0
+pdshow 24 paunsetpd PDHCLI PDHDEV PDBIG 0
+for i ulong 3712
+put pareply i uchar and add mul i 7 3 255
+end
+pdsm 25 pasmver 0 3712
+pdsm 26 pasmver 7 3712
+pdsm 27 pasmver 8 3712
+pdsm 28 pasmver 0 3711
+end
+fn pdconsts to void
+pdconst 32 PACROOT
+pdconst 33 PACDEV
+pdconst 34 PACSUB
+pdconst 35 PACVAS
+pdconst 36 PACTSG
+pdconst 37 PACCTX
+pdconst 38 PACGPF
+pdconst 39 PACCMP
+pdconst 40 PARSETPD
+pdconst 41 PARCTRL
+pdconst 42 PARUNSPD
+pdconst 43 PARALLOC
+pdconst 44 PACMSCH
+pdconst 45 PACMGRI
+pdconst 46 PAENGGR
+pdconst 47 PACTXAS
+end
+fn main to int
+pdallocs
+pdchans
+pdctrls
+pdconsts
+pdflush
+ret 0
+end
diff --git a/tests/params_ref.c b/tests/params_ref.c
new file mode 100644
index 0000000..68030a9
--- /dev/null
+++ b/tests/params_ref.c
@@ -0,0 +1,364 @@
+/* tests/params_ref.c: TEST-ONLY C referee for chan/params.om. Never linked into the product.
+ * Builds against the NVIDIA open-gpu-kernel-modules 580.173.02 headers (MIT) and fills every
+ * record through NVIDIA's own struct types, field names and DRF macros, then prints the same
+ * text tests/params_dump.om prints: per case "<label> rc=<rc>[ size=<sizeof>]" and the record
+ * bytes in lowercase hex, 32 per line; then the class/RPC/control constants from the headers.
+ * The refusal rules (value does not fit -1, outside the legal set -2, wrong reply length -3)
+ * are the port's contract and are mirrored here so the negative controls are compared too.
+ * Build: cc -std=c11 -O1 -Wall -Werror $OGKM_INC -o params_ref tests/params_ref.c */
+#include <stdio.h>
+#include <stddef.h>
+#include <string.h>
+#include "nvtypes.h"
+#include "nvmisc.h"
+#include "class/cl0000.h"
+#include "class/cl0080.h"
+#include "class/cl2080.h"
+#include "class/cl90f1.h"
+#include "class/cla06c.h"
+#include "class/cl9067.h"
+#include "class/clc96f.h"
+#include "class/clcec0.h"
+#include "nvos.h"
+#include "alloc/alloc_channel.h"
+#include "ctrl/ctrl0080/ctrl0080gr.h"
+#include "ctrl/ctrl0080/ctrl0080dma.h"
+#include "ctrl/ctrla06c.h"
+#include "ctrl/ctrla06f/ctrla06fgpfifo.h"
+#include "ctrl/ctrl2080/ctrl2080internal.h"
+#include "ctrl/ctrl2080/ctrl2080fifo.h"
+#include "vgpu/rpc_global_enums.h"
+#define RPC_STRUCTURES
+#include "g_rpc-structures.h"
+
+/* kernel_channel internal flags (nvidia/generated/g_kernel_channel_nvoc.h:181-190) */
+#define NV_KERNELCHANNEL_ALLOC_INTERNALFLAGS_PRIVILEGE               1:0
+#define NV_KERNELCHANNEL_ALLOC_INTERNALFLAGS_ERROR_NOTIFIER_TYPE     3:2
+#define NV_KERNELCHANNEL_ALLOC_INTERNALFLAGS_ECC_ERROR_NOTIFIER_TYPE 5:4
+
+#define U32MAX 0xFFFFFFFFull
+#define EFIT (-1)
+#define ERANGE_ (-2)
+#define ELEN (-3)
+
+static unsigned char rec[4096];
+static size_t reclen;
+static unsigned char reply[4096];
+static NvU64 in[48];
+
+static int fit4(NvU64 a, NvU64 b, NvU64 c, NvU64 d)
+{
+    return a <= U32MAX && b <= U32MAX && c <= U32MAX && d <= U32MAX;
+}
+
+#define TAKE(s) do { memset(rec, 0, sizeof rec); memcpy(rec, &(s), sizeof(s)); reclen = sizeof(s); } while (0)
+
+static int enc_root(NvU64 hcli, NvU64 pid)
+{
+    NV0000_ALLOC_PARAMETERS p;
+    if (!fit4(hcli, pid, 0, 0)) return EFIT;
+    memset(&p, 0, sizeof p);
+    p.hClient = (NvHandle)hcli;
+    p.processID = (NvU32)pid;
+    memcpy(p.processName, "aien-ogd", 8);
+    TAKE(p);
+    return (int)sizeof p;
+}
+
+static int enc_device(NvU64 devid, NvU64 hshare, NvU64 flags, NvU64 vamode, NvU64 vasize)
+{
+    NV0080_ALLOC_PARAMETERS p;
+    if (!fit4(devid, hshare, flags, vamode)) return EFIT;
+    memset(&p, 0, sizeof p);
+    p.deviceId = (NvU32)devid;
+    p.hClientShare = (NvHandle)hshare;
+    p.flags = (NvU32)flags;
+    p.vaSpaceSize = vasize;
+    p.vaMode = (NvV32)vamode;
+    TAKE(p);
+    return (int)sizeof p;
+}
+
+static int enc_subdev(NvU64 subid)
+{
+    NV2080_ALLOC_PARAMETERS p;
+    if (subid > U32MAX) return EFIT;
+    memset(&p, 0, sizeof p);
+    p.subDeviceId = (NvU32)subid;
+    TAKE(p);
+    return (int)sizeof p;
+}
+
+static int enc_vaspace(NvU64 index, NvU64 flags, NvU64 vasize, NvU64 vabase, NvU64 bigpg)
+{
+    NV_VASPACE_ALLOCATION_PARAMETERS p;
+    if (!fit4(index, flags, bigpg, 0)) return EFIT;
+    memset(&p, 0, sizeof p);
+    p.index = (NvU32)index;
+    p.flags = (NvV32)flags;
+    p.vaSize = vasize;
+    p.bigPageSize = (NvU32)bigpg;
+    p.vaBase = vabase;
+    TAKE(p);
+    return (int)sizeof p;
+}
+
+static int enc_tsg(NvU64 herr, NvU64 hecc, NvU64 hvas, NvU64 eng)
+{
+    NV_CHANNEL_GROUP_ALLOCATION_PARAMETERS p;
+    if (!fit4(herr, hecc, hvas, eng)) return EFIT;
+    memset(&p, 0, sizeof p);
+    p.hObjectError = (NvHandle)herr;
+    p.hObjectEccError = (NvHandle)hecc;
+    p.hVASpace = (NvHandle)hvas;
+    p.engineType = (NvU32)eng;
+    p.bIsCallingContextVgpuPlugin = NV_FALSE;
+    TAKE(p);
+    return (int)sizeof p;
+}
+
+static int enc_ctxsh(NvU64 hvas, NvU64 flags, NvU64 subctx)
+{
+    NV_CTXSHARE_ALLOCATION_PARAMETERS p;
+    if (!fit4(hvas, flags, subctx, 0)) return EFIT;
+    memset(&p, 0, sizeof p);
+    p.hVASpace = (NvHandle)hvas;
+    p.flags = (NvU32)flags;
+    p.subctxId = (NvU32)subctx;
+    TAKE(p);
+    return (int)sizeof p;
+}
+
+static int wide(int k)
+{
+    return k == 1 || k == 7 || (k >= 16 && k <= 35 && (k - 16) % 4 < 2) || k == 38 || k == 39;
+}
+
+static void md(NV_MEMORY_DESC_PARAMS *m, int k)
+{
+    m->base = in[k];
+    m->size = in[k + 1];
+    m->addressSpace = (NvU32)in[k + 2];
+    m->cacheAttrib = (NvU32)in[k + 3];
+}
+
+static int enc_chan(void)
+{
+    NV_CHANNEL_ALLOC_PARAMS p;
+    NvU32 chid, flags, numChannelsPerUserd, internal;
+    for (int k = 0; k < 42; k++)
+        if (!wide(k) && in[k] > U32MAX) return EFIT;
+    if (in[12] > 3 || in[13] > 3 || in[14] > 3) return ERANGE_;
+    if (in[15] > 0xFFF) return ERANGE_;
+    chid = (NvU32)in[15];
+    memset(&p, 0, sizeof p);
+    p.hObjectError = (NvHandle)in[0];
+    p.gpFifoOffset = in[1];
+    p.gpFifoEntries = (NvU32)in[2];
+    /* kernel_channel.c:2812-2821, the IS_GSP_CLIENT rewrite */
+    numChannelsPerUserd = NVBIT(DRF_SIZE(NVOS04_FLAGS_CHANNEL_USERD_INDEX_VALUE));
+    flags = (NvU32)in[3];
+    flags = FLD_SET_DRF(OS04, _FLAGS, _CHANNEL_USERD_INDEX_FIXED, _FALSE, flags);
+    flags = FLD_SET_DRF(OS04, _FLAGS, _CHANNEL_USERD_INDEX_PAGE_FIXED, _TRUE, flags);
+    flags = FLD_SET_DRF_NUM(OS04, _FLAGS, _CHANNEL_USERD_INDEX_VALUE, chid % numChannelsPerUserd, flags);
+    flags = FLD_SET_DRF_NUM(OS04, _FLAGS, _CHANNEL_USERD_INDEX_PAGE_VALUE, chid / numChannelsPerUserd, flags);
+    p.flags = flags;
+    p.hContextShare = (NvHandle)in[4];
+    p.hVASpace = (NvHandle)in[5];
+    p.hUserdMemory[0] = (NvHandle)in[6];
+    p.userdOffset[0] = in[7];
+    p.engineType = (NvU32)in[8];
+    p.subDeviceId = (NvU32)in[9];
+    p.hObjectEccError = (NvHandle)in[10];
+    md(&p.instanceMem, 16);
+    md(&p.userdMem, 20);
+    md(&p.ramfcMem, 24);
+    md(&p.mthdbufMem, 28);
+    p.hPhysChannelGroup = (NvHandle)in[11];
+    /* kernel_channel.c:602-609 then :2824-2826 */
+    internal = 0;
+    internal = FLD_SET_DRF_NUM(_KERNELCHANNEL_ALLOC, _INTERNALFLAGS, _ERROR_NOTIFIER_TYPE, (NvU32)in[12], internal);
+    internal = FLD_SET_DRF_NUM(_KERNELCHANNEL_ALLOC, _INTERNALFLAGS, _ECC_ERROR_NOTIFIER_TYPE, (NvU32)in[13], internal);
+    internal = FLD_SET_DRF_NUM(_KERNELCHANNEL_ALLOC, _INTERNALFLAGS, _PRIVILEGE, (NvU32)in[14], internal);
+    p.internalFlags = internal;
+    md(&p.errorNotifierMem, 32);
+    md(&p.eccErrorNotifierMem, 38);
+    p.ProcessID = (NvU32)in[36];
+    p.SubProcessID = (NvU32)in[37];
+    TAKE(p);
+    return (int)sizeof p;
+}
+
+static int enc_sched(NvU64 en, NvU64 skipsub, NvU64 skipen)
+{
+    NVA06C_CTRL_GPFIFO_SCHEDULE_PARAMS p;
+    if (en > 1 || skipsub > 1 || skipen > 1) return ERANGE_;
+    memset(&p, 0, sizeof p);
+    p.bEnable = (NvBool)en;
+    p.bSkipSubmit = (NvBool)skipsub;
+    p.bSkipEnable = (NvBool)skipen;
+    TAKE(p);
+    return (int)sizeof p;
+}
+
+static int enc_grinfo(void)
+{
+    static NV2080_CTRL_INTERNAL_STATIC_GR_GET_INFO_PARAMS p;
+    memset(&p, 0, sizeof p);
+    TAKE(p);
+    return (int)sizeof p;
+}
+
+static long long smver(NvU64 eng, size_t len)
+{
+    static NV2080_CTRL_INTERNAL_STATIC_GR_GET_INFO_PARAMS p;
+    if (len != sizeof p) return ELEN;
+    if (eng >= NV2080_CTRL_INTERNAL_GR_MAX_ENGINES) return ERANGE_;
+    memcpy(&p, reply, sizeof p);
+    return p.engineInfo[eng].infoList[NV0080_CTRL_GR_INFO_INDEX_SM_VERSION].data;
+}
+
+static int enc_setpd(void)
+{
+    rpc_set_page_directory_v1E_05 p;
+    NvU32 flags;
+    for (int k = 0; k < 11; k++)
+        if (k != 3 && in[k] > U32MAX) return EFIT;
+    if (in[5] > NV0080_CTRL_DMA_SET_PAGE_DIRECTORY_FLAGS_APERTURE_SYSMEM_NONCOH || in[6] > 1) return ERANGE_;
+    memset(&p, 0, sizeof p);
+    p.hClient = (NvHandle)in[0];
+    p.hDevice = (NvHandle)in[1];
+    p.pasid = (NvU32)in[2];
+    p.params.physAddress = in[3];
+    p.params.numEntries = (NvU32)in[4];
+    flags = 0;
+    flags = FLD_SET_DRF_NUM(0080, _CTRL_DMA_SET_PAGE_DIRECTORY_FLAGS, _APERTURE, (NvU32)in[5], flags);
+    flags = FLD_SET_DRF_NUM(0080, _CTRL_DMA_SET_PAGE_DIRECTORY_FLAGS, _PRESERVE_PDES, (NvU32)in[6], flags);
+    p.params.flags = flags;
+    p.params.hVASpace = (NvHandle)in[7];
+    p.params.chId = (NvU32)in[8];
+    p.params.subDeviceId = (NvU32)in[9];
+    p.params.pasid = (NvU32)in[10];
+    TAKE(p);
+    return (int)sizeof p;
+}
+
+static int enc_unsetpd(NvU64 hcli, NvU64 hdev, NvU64 hvas, NvU64 subdev)
+{
+    rpc_unset_page_directory_v1E_05 p;
+    if (!fit4(hcli, hdev, hvas, subdev)) return EFIT;
+    memset(&p, 0, sizeof p);
+    p.hClient = (NvHandle)hcli;
+    p.hDevice = (NvHandle)hdev;
+    p.params.hVASpace = (NvHandle)hvas;
+    p.params.subDeviceId = (NvU32)subdev;
+    TAKE(p);
+    return (int)sizeof p;
+}
+
+static void show(const char *label, long long rc)
+{
+    printf("%s rc=%lld", label, rc);
+    if (rc <= 0) {
+        printf("\n");
+        return;
+    }
+    printf(" size=%zu\n", reclen);
+    for (size_t i = 0; i < reclen; i++)
+        printf("%02x%s", rec[i], (i % 32 == 31 || i + 1 == reclen) ? "\n" : "");
+}
+
+static void chan_inputs(void)
+{
+    for (int k = 0; k < 48; k++)
+        in[k] = wide(k) ? (NvU64)k * 0x0101010101010101ull + 2 : (NvU64)k * 0x01010101ull + 1;
+    in[3] = 0xFFFFFFFFull;
+    in[8] = NV2080_ENGINE_TYPE_GRAPHICS;
+    in[12] = 3;
+    in[13] = 2;
+    in[14] = 2;
+    in[15] = 4011;
+}
+
+static void setpd_inputs(void)
+{
+    memset(in, 0, sizeof in);
+    in[0] = 3254779905u;
+    in[1] = 3254779906u;
+    in[2] = 0;
+    in[3] = 2147745792ull;
+    in[4] = 512;
+    in[5] = 2;
+    in[6] = 1;
+    in[7] = 3254779912u;
+    in[8] = 4011;
+    in[9] = 0;
+    in[10] = 0;
+}
+
+int main(void)
+{
+    show("NV0000_ALLOC_PARAMETERS root", enc_root(3254779905u, 4242));
+    show("NV0000_ALLOC_PARAMETERS root hClient>u32", enc_root(4294967296ull, 1));
+    show("NV0080_ALLOC_PARAMETERS device", enc_device(0, 3254779905u, 3, 2, 1099511627776ull));
+    show("NV0080_ALLOC_PARAMETERS device vaMode>u32", enc_device(0, 3254779905u, 3, 4294967296ull, 0));
+    show("NV2080_ALLOC_PARAMETERS subdevice", enc_subdev(0));
+    show("NV2080_ALLOC_PARAMETERS subdevice id>u32", enc_subdev(4294967296ull));
+    show("NV_VASPACE_ALLOCATION_PARAMETERS vaspace",
+         enc_vaspace(0, NV_VASPACE_ALLOCATION_FLAGS_IS_EXTERNALLY_OWNED | NV_VASPACE_ALLOCATION_FLAGS_ENABLE_PAGE_FAULTING,
+                     1099511627776ull, 8589934592ull, 65536));
+    show("NV_VASPACE_ALLOCATION_PARAMETERS vaspace bigPageSize>u32", enc_vaspace(0, 72, 1, 0, 4294967296ull));
+    show("NV_CHANNEL_GROUP_ALLOCATION_PARAMETERS tsg", enc_tsg(0, 0, 3254779912u, NV2080_ENGINE_TYPE_GRAPHICS));
+    show("NV_CHANNEL_GROUP_ALLOCATION_PARAMETERS tsg engineType>u32", enc_tsg(0, 0, 3254779912u, 4294967296ull));
+    show("NV_CTXSHARE_ALLOCATION_PARAMETERS ctxshare",
+         enc_ctxsh(3254779912u, NV_CTXSHARE_ALLOCATION_FLAGS_SUBCONTEXT_ASYNC, 0));
+    show("NV_CTXSHARE_ALLOCATION_PARAMETERS ctxshare flags>u32", enc_ctxsh(3254779912u, 4294967296ull, 0));
+    chan_inputs();
+    show("NV_CHANNEL_ALLOC_PARAMS channel", enc_chan());
+    in[15] = 4096;
+    show("NV_CHANNEL_ALLOC_PARAMS channel chid=4096", enc_chan());
+    in[15] = 4011;
+    in[2] = 4294967296ull;
+    show("NV_CHANNEL_ALLOC_PARAMS channel gpFifoEntries>u32", enc_chan());
+    in[2] = 2 * 0x01010101ull + 1;
+    in[14] = 4;
+    show("NV_CHANNEL_ALLOC_PARAMS channel privilege=4", enc_chan());
+    in[14] = 2;
+    in[15] = 0;
+    show("NV_CHANNEL_ALLOC_PARAMS channel chid=0", enc_chan());
+    show("NVA06C_CTRL_GPFIFO_SCHEDULE_PARAMS schedule", enc_sched(1, 0, 0));
+    show("NVA06C_CTRL_GPFIFO_SCHEDULE_PARAMS schedule bEnable=2", enc_sched(2, 0, 0));
+    show("NV2080_CTRL_INTERNAL_STATIC_GR_GET_INFO_PARAMS grinfo", enc_grinfo());
+    setpd_inputs();
+    show("rpc_set_page_directory_v1E_05 setpd", enc_setpd());
+    in[5] = 3;
+    show("rpc_set_page_directory_v1E_05 setpd aperture=3", enc_setpd());
+    in[5] = 2;
+    in[4] = 4294967296ull;
+    show("rpc_set_page_directory_v1E_05 setpd numEntries>u32", enc_setpd());
+    show("rpc_unset_page_directory_v1E_05 unsetpd", enc_unsetpd(3254779905u, 3254779906u, 3254779912u, 0));
+    show("rpc_unset_page_directory_v1E_05 unsetpd hVASpace>u32", enc_unsetpd(3254779905u, 3254779906u, 4294967296ull, 0));
+    for (int i = 0; i < 3712; i++)
+        reply[i] = (unsigned char)((i * 7 + 3) & 255);
+    printf("smver eng=0 rc=%lld\n", smver(0, 3712));
+    printf("smver eng=7 rc=%lld\n", smver(7, 3712));
+    printf("smver eng=8 rc=%lld\n", smver(8, 3712));
+    printf("smver len=3711 rc=%lld\n", smver(0, 3711));
+    printf("const NV01_ROOT %u\n", (unsigned)NV01_ROOT);
+    printf("const NV01_DEVICE_0 %u\n", (unsigned)NV01_DEVICE_0);
+    printf("const NV20_SUBDEVICE_0 %u\n", (unsigned)NV20_SUBDEVICE_0);
+    printf("const FERMI_VASPACE_A %u\n", (unsigned)FERMI_VASPACE_A);
+    printf("const KEPLER_CHANNEL_GROUP_A %u\n", (unsigned)KEPLER_CHANNEL_GROUP_A);
+    printf("const FERMI_CONTEXT_SHARE_A %u\n", (unsigned)FERMI_CONTEXT_SHARE_A);
+    printf("const BLACKWELL_CHANNEL_GPFIFO_A %u\n", (unsigned)BLACKWELL_CHANNEL_GPFIFO_A);
+    printf("const BLACKWELL_COMPUTE_B %u\n", (unsigned)BLACKWELL_COMPUTE_B);
+    printf("const NV_VGPU_MSG_FUNCTION_SET_PAGE_DIRECTORY %u\n", (unsigned)NV_VGPU_MSG_FUNCTION_SET_PAGE_DIRECTORY);
+    printf("const NV_VGPU_MSG_FUNCTION_GSP_RM_CONTROL %u\n", (unsigned)NV_VGPU_MSG_FUNCTION_GSP_RM_CONTROL);
+    printf("const NV_VGPU_MSG_FUNCTION_UNSET_PAGE_DIRECTORY %u\n", (unsigned)NV_VGPU_MSG_FUNCTION_UNSET_PAGE_DIRECTORY);
+    printf("const NV_VGPU_MSG_FUNCTION_GSP_RM_ALLOC %u\n", (unsigned)NV_VGPU_MSG_FUNCTION_GSP_RM_ALLOC);
+    printf("const NVA06C_CTRL_CMD_GPFIFO_SCHEDULE %u\n", (unsigned)NVA06C_CTRL_CMD_GPFIFO_SCHEDULE);
+    printf("const NV2080_CTRL_CMD_INTERNAL_STATIC_KGR_GET_INFO %u\n", (unsigned)NV2080_CTRL_CMD_INTERNAL_STATIC_KGR_GET_INFO);
+    printf("const NV2080_ENGINE_TYPE_GRAPHICS %u\n", (unsigned)NV2080_ENGINE_TYPE_GRAPHICS);
+    printf("const NV_CTXSHARE_ALLOCATION_FLAGS_SUBCONTEXT_ASYNC %u\n", (unsigned)NV_CTXSHARE_ALLOCATION_FLAGS_SUBCONTEXT_ASYNC);
+    return 0;
+}
diff --git a/tests/pm_gate.om b/tests/pm_gate.om
new file mode 100644
index 0000000..7b331bf
--- /dev/null
+++ b/tests/pm_gate.om
@@ -0,0 +1,82 @@
+note tests/pm_gate.om: the runtime-PM gate of gspboot (gsp/mmio.om). On arm64 a BAR read of a
+note device in D3 is an external abort, so gspboot must refuse with EPM (-9) before its first access.
+note usage: pm_gate SUSPENDED_FILE ACTIVE_FILE NEAR_FILE (host files holding "suspended\n", "active\n"
+note and "activa\n", same length as active but one byte off).
+note exit 0 PASS; 1..7 name the case that failed. Mode 1 is only pointed at host files here: gspbar is
+note never mapped, so a gate that let the start through would trap on its first mapget (exit != 0).
+global pa uchar 128
+global pb uchar 128
+global pc uchar 128
+fn setgin to void
+for i ulong 7
+put gin i 0
+end
+put gin 0 4
+for k ulong 4
+put gpkt k uchar 1
+end
+end
+fn usepath which int n long to void
+for i ulong ulong n
+if eq which 0
+put gpmp i get pa i
+end
+if eq which 1
+put gpmp i get pb i
+end
+if eq which 2
+put gpmp i get pc i
+end
+end
+put gpmn 0 ulong n
+end
+fn main to int
+if ne argcnt 4
+ret 9
+end
+na = argread 1 pa 0 128
+nb = argread 2 pb 0 128
+nc = argread 3 pc 0 128
+if or or le na 0 le nb 0 le nc 0
+ret 9
+end
+note case 1, planted fault: simulated device suspended; refused, zero accesses, zero violations
+put gspmode 0 0
+siminit
+put spm 0 1
+setgin
+if ne gspboot EPM
+ret 1
+end
+if or ne sg SNLOG 0 ne sg SVIOL 0
+ret 2
+end
+note case 2, positive control: the same start with the device active is not refused and touches it
+siminit
+put spm 0 0
+setgin
+if eq gspboot EPM
+ret 3
+end
+if eq sg SNLOG 0
+ret 4
+end
+note case 3: mode 1 reads runtime_status from a file that says suspended; refused before any mapget
+put gspmode 0 1
+usepath 0 na
+if ne gspboot EPM
+ret 5
+end
+note case 4: the same reader accepts exactly "active\n"
+usepath 1 nb
+if not gsppm
+ret 6
+end
+note case 5: one byte off is refused
+usepath 2 nc
+if gsppm
+ret 7
+end
+put gspmode 0 0
+ret 0
+end
diff --git a/tests/pm_gate.sh b/tests/pm_gate.sh
new file mode 100755
index 0000000..d2bbcce
--- /dev/null
+++ b/tests/pm_gate.sh
@@ -0,0 +1,34 @@
+#!/bin/sh
+# pm_gate.sh: runtime-PM planted fault (tests/pm_gate.om) on the real gsp/mmio.om, then two mutants that
+# must go red: the gate removed, and the gate accepting any runtime_status text. Host only: the device
+# file is a temp file, never /sys. Exit 0 PASS, 1 FAIL, 2 setup.
+set -u
+here=$(cd "$(dirname "$0")/.." && pwd)
+OMC=${OMC:-$here/build/omc}
+OMC_SHA=$(sed -n 's/^OMC_SHA256=//p' "$here/tools/omc.pin")
+run() { nice -n 19 taskset -c "${AIEN_TEST_CPUS:-0-9,15-19}" "$@"; }
+[ "$(sha256sum "$OMC" | cut -d' ' -f1)" = "$OMC_SHA" ] || { echo "pm_gate: FAIL omc pin"; exit 2; }
+t=$(mktemp -d /tmp/pm_gate.XXXXXX) || exit 2
+trap 'rm -rf "$t"' EXIT
+printf 'suspended\n' > "$t/sus"
+printf 'active\n' > "$t/act"
+printf 'activa\n' > "$t/near"
+# build SRC -> run -> exit code
+try() {
+  cat "$1" "$here/gsp/sim.om" "$here/tests/pm_gate.om" | run "$OMC" > "$t/p" 2>"$t/err" || return 200
+  chmod +x "$t/p"
+  run "$t/p" "$t/sus" "$t/act" "$t/near" >/dev/null 2>&1
+}
+try "$here/gsp/mmio.om"; rc=$?
+[ "$rc" -eq 0 ] || { echo "pm_gate: FAIL baseline exit $rc"; exit 1; }
+# mutant 1: the gate call removed (3 lines: if not gsppm / ret gspfail EPM / end)
+awk '$0=="if not gsppm"{s=3} s>0{s--; next} {print}' "$here/gsp/mmio.om" > "$t/m1.om"
+cmp -s "$here/gsp/mmio.om" "$t/m1.om" && { echo "pm_gate: FAIL mutant 1 did not apply"; exit 2; }
+try "$t/m1.om"; m1=$?
+# mutant 2: the reader stops comparing bytes
+awk '$0=="if ne get gpmb i get pmact i"{print "if false"; next} {print}' "$here/gsp/mmio.om" > "$t/m2.om"
+cmp -s "$here/gsp/mmio.om" "$t/m2.om" && { echo "pm_gate: FAIL mutant 2 did not apply"; exit 2; }
+try "$t/m2.om"; m2=$?
+[ "$m1" -ne 0 ] && [ "$m1" -ne 200 ] || { echo "pm_gate: FAIL mutant 1 (gate removed) exit $m1"; exit 1; }
+[ "$m2" -ne 0 ] && [ "$m2" -ne 200 ] || { echo "pm_gate: FAIL mutant 2 (any text accepted) exit $m2"; exit 1; }
+echo "pm_gate: PASS (5 cases; mutants red: gate removed exit $m1, any text accepted exit $m2)"
diff --git a/tests/seq_cases.txt b/tests/seq_cases.txt
new file mode 100644
index 0000000..1d10c9e
--- /dev/null
+++ b/tests/seq_cases.txt
@@ -0,0 +1,46 @@
+# tests/seq_cases.txt: cases for tests/seq_diff.sh, read by tests/seq_trace.om (gsp/seq.om) and tests/seq_ref.c (C).
+# name busy budget core corefail nwords end m w0 .. w(m-1)   (decimal; words past m are 0)
+# opcodes: 0 WRITE a v, 1 MODIFY a mask v, 2 POLL a mask v tmo err, 3 DELAY us, 4 STORE a idx, 5..8 core
+# registers: 8653504 SEC2 EMEMC(0) 0x840ac0 (plain), 8653824 SEC2 QUEUE_HEAD(0) 0x840c00 (busy_reads),
+# 1114356 GSP HWCFG2 0x1100f4 (reads 0xBADF41A7, no writes), 1114240 GSP FALCON_OS 0x110080 (write = violation)
+empty 0 4 0 0 0 0 0
+idxeq 0 4 0 0 3 3 3 0 8653504 1
+idxgt 0 4 0 0 3 5 3 0 8653504 1
+one-word 0 4 0 0 1 0 0
+write 0 4 0 0 4 3 3 0 8653504 2748
+modify 0 4 0 0 8 7 7 0 8653504 255 1 8653504 10 5
+modhigh 0 4 0 0 8 7 7 0 8653504 3735928559 1 8653504 4294901760 305397760
+modhwcfg2 0 4 0 0 5 4 4 1 1114356 255 0
+pollnow 0 4 0 0 10 9 9 0 8653504 4615 2 8653504 255 7 0 0
+pollmask 0 4 0 0 10 9 9 0 8653504 4615 2 8653504 65280 4608 0 0
+pollneg 0 4 0 0 10 9 9 0 8653504 4615 2 8653504 65280 18 0 0
+pollzero 0 4 0 0 7 6 6 2 1114356 0 0 0 0
+qhsettle 4 4 0 0 7 6 6 2 8653824 4294967295 16 0 0
+qhtimeout 5 4 0 0 7 6 6 2 8653824 4294967295 16 0 0
+qhbud0ok 1 0 0 0 7 6 6 2 8653824 4294967295 16 0 0
+qhbud0to 2 0 0 0 7 6 6 2 8653824 4294967295 16 0 0
+qhbud1to 2 1 0 0 7 6 6 2 8653824 4294967295 16 0 0
+qhbudmax 999998 999998 0 0 7 6 6 2 8653824 4294967295 16 0 0
+qhlong 900 1000 0 0 7 6 6 2 8653824 4294967295 16 0 0
+delay 0 4 0 0 5 4 4 3 25 3 7
+store 0 4 0 0 10 9 9 0 8653504 3735928559 4 8653504 0 4 8653504 7
+storehw 0 4 0 0 4 3 3 4 1114356 3
+store8 0 4 0 0 10 9 9 0 8653504 1 4 8653504 7 4 8653504 8
+unk9 0 4 1 0 5 4 4 0 8653504 1 9
+unk99 0 4 1 0 2 1 1 99
+unkhigh 0 4 1 0 2 1 1 2147483648
+cut 0 4 0 0 4 2 3 0 1 0
+writeover 0 4 0 0 3 2 3 0 8653504 1
+pollover 0 4 0 0 6 5 5 2 8653504 0 0 0
+delayover 0 4 0 0 2 1 1 3
+storeover 0 4 0 0 3 2 2 4 8653504
+modover 0 4 0 0 4 3 3 1 8653504 0
+pollfit 0 4 0 0 7 6 6 2 8653504 0 0 0 0
+corenone 0 4 0 0 2 1 1 5
+coreall 0 4 1 0 5 4 4 5 6 7 8
+corefail7 0 4 1 7 5 4 4 5 6 7 8
+corefail8 0 4 1 8 5 4 4 0 8653504 1 8
+mixed 0 4 1 0 20 19 19 0 8653504 255 1 8653504 15 160 3 5 4 8653504 2 5 2 8653504 255 240 0 0
+garbage 0 4 0 0 6 3 5 0 8653504 1 99 99
+falconos 0 4 0 0 7 6 6 0 1114240 1 0 0 7
+full 0 4 0 0 16384 16383 0
diff --git a/tests/seq_diff.sh b/tests/seq_diff.sh
new file mode 100755
index 0000000..8757b65
--- /dev/null
+++ b/tests/seq_diff.sh
@@ -0,0 +1,95 @@
+#!/bin/sh
+# seq_diff.sh: builds the .om GSP CPU sequencer (gsp/seq.om, run by tests/seq_trace.om on gsp/sim.om in mode 0) and
+# the C reference (aienux PR #441 native/kernel/gpu/gsp_seq.c + gsp_sim.c, driven by tests/seq_ref.c, compiled fresh
+# into a temp dir as a test-only referee), runs every case of tests/seq_cases.txt through both and requires
+# byte-identical traces (rc, why, delays, core calls, save[8], register log, violations) and the same exit code.
+# Also: malformed case input stops both the same way; a corrupted buffer is refused; the .om-only refusals
+# (nwords cap, poll budget cap) match fixed expected lines. Host only: no device is opened.
+# Env: AIENUX (aienux checkout), OMC (pinned omc), SEQ_OM (library file to test; mutants use this).
+set -u
+here=$(cd "$(dirname "$0")/.." && pwd)
+AIENUX=${AIENUX:-/home/drakestapleton/work/OwnDriver/aienux}
+OMC=${OMC:-$here/build/omc}
+SEQ_OM=${SEQ_OM:-$here/gsp/seq.om}
+OMC_SHA=$(sed -n 's/^OMC_SHA256=//p' "$here/tools/omc.pin")
+run() { nice -n 19 taskset -c "${AIEN_TEST_CPUS:-0-9,15-19}" "$@"; }
+
+got=$(sha256sum "$OMC" | cut -d' ' -f1)
+if [ "$got" != "$OMC_SHA" ]; then
+  echo "seq_diff: FAIL omc sha256 $got, pinned $OMC_SHA"; exit 2
+fi
+if grep -n 'put gspmode [0-9]* [1-9]\|gspbar\|vfio\|mapnew\|/dev/\|/sys/' "$here/tests/seq_trace.om" "$SEQ_OM"; then
+  echo "seq_diff: FAIL sequencer or test driver names a device"; exit 2
+fi
+
+t=$(mktemp -d /tmp/seq_diff.XXXXXX) || exit 2
+trap 'rm -rf "$t"' EXIT
+k=$AIENUX/native/kernel
+if ! run cc -std=c11 -O1 -Wall -Werror -I"$k/gpu" -o "$t/ref" "$here/tests/seq_ref.c" "$k/gpu/gsp_seq.c" "$k/gpu/gsp_sim.c"; then
+  echo "seq_diff: FAIL C reference build"; exit 2
+fi
+if ! cat "$here/gsp/mmio.om" "$here/gsp/sim.om" "$SEQ_OM" "$here/tests/seq_trace.om" | run "$OMC" > "$t/om"; then
+  echo "seq_diff: FAIL omc build"; exit 3
+fi
+chmod +x "$t/om"
+
+fail=0
+# both tools on one input: stdout then the exit code
+both() {  # infile tag
+  run "$t/ref" < "$1" > "$t/c.$2"; echo "exit $?" >> "$t/c.$2"
+  run "$t/om" < "$1" > "$t/o.$2"; echo "exit $?" >> "$t/o.$2"
+  if ! cmp -s "$t/c.$2" "$t/o.$2"; then
+    echo "seq_diff: $2 differs (C left, .om right)"; diff "$t/c.$2" "$t/o.$2" | head -12; fail=1
+  fi
+}
+cases=$here/tests/seq_cases.txt
+both "$cases" cases
+want=$(grep -vc '^#' "$cases")
+n=$(grep -c '^== ' "$t/o.cases")
+if [ "$n" -ne "$want" ] || [ "$(tail -n 1 "$t/o.cases")" != "exit 0" ]; then
+  echo "seq_diff: ran $n of $want cases"; tail -n 1 "$t/o.cases"; fail=1
+fi
+# every refusal the C has must be among the cases
+for w in 'empty buffer' 'cmdIndex not inside the buffer' 'unknown opcode' 'opcode overruns cmdIndex' 'poll timed out' \
+         'save index out of range' 'core opcode with no core callback' 'core opcode failed'; do
+  if ! grep -q " rc=-1 why=$w " "$t/o.cases"; then echo "seq_diff: no case refuses with '$w'"; fail=1; fi
+done
+# malformed case input: both stop with exit 2 after the same output
+printf 'write 0 4 0 0 4 3 3 0 8653504 2748\nbad 0 4 x\n' > "$t/bad1"
+printf 'write 0 4 0 0 4 3 3 0 8653504 2748\nshort 0 4 0 0 4 3 3 0 8653504\n' > "$t/bad2"
+printf 'big 0 4 0 0 4 3 3 0 8653504 4294967296\n' > "$t/bad3"
+for b in bad1 bad2 bad3; do
+  both "$t/$b" "$b"
+  if [ "$(tail -n 1 "$t/o.$b")" != "exit 2" ]; then echo "seq_diff: $b not refused"; fail=1; fi
+done
+# negative control: the modify case with its opcode corrupted (1 -> 9) is refused by both, nothing written after it
+grep '^modify ' "$cases" | sed 's/ 255 1 8653504 / 255 9 8653504 /' > "$t/corrupt"
+both "$t/corrupt" corrupt
+if ! grep -qx '== modify rc=-1 why=unknown opcode delays=0/0 core=0 ops= save=0,0,0,0,0,0,0,0, nlog=1 violations=0' "$t/o.corrupt"; then
+  echo "seq_diff: negative control not refused"; cat "$t/o.corrupt"; fail=1
+fi
+# the comparison itself can go red: a changed modify mask (10 -> 255) on the C side must not match the .om trace
+grep '^modify ' "$cases" > "$t/m.ok"
+sed 's/ 8653504 10 5$/ 8653504 255 5/' "$t/m.ok" > "$t/m.bad"
+run "$t/ref" < "$t/m.bad" > "$t/c.mbad"
+run "$t/om" < "$t/m.ok" > "$t/o.mok"
+if ! grep -q '^modify .* 255 5$' "$t/m.bad" || cmp -s "$t/c.mbad" "$t/o.mok"; then echo "seq_diff: changed mask not detected"; fail=1; fi
+# .om-only refusals (the C has no such limits); cmdIndex is still checked first, as in the C
+cat > "$t/only" <<'EOF'
+cap 0 4 0 0 16385 0 0
+capidx 0 4 0 0 16385 16385 0
+bigbud 0 999999 0 0 2 1 1 3
+EOF
+run "$t/om" < "$t/only" > "$t/only.got"
+cat > "$t/only.want" <<'EOF'
+== cap rc=-1 why=nwords over 16384 delays=0/0 core=0 ops= save=0,0,0,0,0,0,0,0, nlog=0 violations=0
+== capidx rc=-1 why=cmdIndex not inside the buffer delays=0/0 core=0 ops= save=0,0,0,0,0,0,0,0, nlog=0 violations=0
+== bigbud rc=-1 why=poll budget over 999998 delays=0/0 core=0 ops= save=0,0,0,0,0,0,0,0, nlog=0 violations=0
+EOF
+if ! cmp -s "$t/only.want" "$t/only.got"; then
+  echo "seq_diff: .om-only refusals differ"; diff "$t/only.want" "$t/only.got"; fail=1
+fi
+if [ "$fail" -ne 0 ]; then
+  echo "seq_diff: FAIL"; exit 1
+fi
+echo "seq_diff: PASS ($n cases identical trace+exit, 8 C refusals covered, 3 malformed inputs stop alike, negative control refused, changed mask detected, 3 .om-only refusals; .om vs C reference)"
diff --git a/tests/seq_ref.c b/tests/seq_ref.c
new file mode 100644
index 0000000..91e2daf
--- /dev/null
+++ b/tests/seq_ref.c
@@ -0,0 +1,78 @@
+/* tests/seq_ref.c -- TEST-ONLY C referee for tests/seq_diff.sh. Never linked into the product.
+ * Runs aienux PR #441 gpu/gsp_seq.c (gsp_seq_run) against gpu/gsp_sim.c for every case on stdin and prints
+ * the trace tests/seq_trace.om prints for gsp/seq.om. Case line (decimal):
+ *   name busy budget core corefail nwords end m w0 .. w(m-1)
+ * busy = sim busy_reads, budget = poll_budget, core = 1 supplies the core callback (it fails when the
+ * opcode equals corefail), words past m are 0. A line starting with # is a comment. */
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "gsp_seq.h"
+#include "gsp_sim.h"
+
+struct ctx {
+    struct ck_gpu_regs r;
+    uint32_t fail, ncalls, ops[16], ndelay, us;
+};
+
+static uint32_t rd(void *c, uint32_t a) { struct ctx *x = c; return x->r.rd(x->r.ctx, a); }
+static void wr(void *c, uint32_t a, uint32_t v) { struct ctx *x = c; x->r.wr(x->r.ctx, a, v); }
+static int core(void *c, uint32_t op)
+{
+    struct ctx *x = c;
+    if (x->ncalls < 16) x->ops[x->ncalls] = op;
+    x->ncalls++;
+    return op == x->fail ? -1 : 0;
+}
+static void dly(void *c, uint32_t us) { struct ctx *x = c; x->ndelay++; x->us += us; }
+
+int main(void)
+{
+    static struct ck_gspsim sim;
+    char name[64];
+    while (scanf("%63s", name) == 1) {
+        if (name[0] == '#') {
+            int ch;
+            while ((ch = getchar()) != EOF && ch != '\n') {}
+            continue;
+        }
+        unsigned long long busy, bud, con, fail, nw, end, m;
+        if (scanf("%llu %llu %llu %llu %llu %llu %llu", &busy, &bud, &con, &fail, &nw, &end, &m) != 7) return 2;
+        if (nw > (1u << 20) || m > nw || busy > 0xffffffffu || bud > 0xffffffffu || end > 0xffffffffu) return 2;
+        uint32_t *buf = calloc(nw ? nw : 1, 4);
+        if (!buf) return 2;
+        for (unsigned long long i = 0; i < m; i++) {
+            unsigned long long w;
+            if (scanf("%llu", &w) != 1 || w > 0xffffffffu) return 2;
+            buf[i] = (uint32_t)w;
+        }
+        struct ck_gspsim_cfg cfg;
+        memset(&cfg, 0, sizeof cfg);
+        cfg.busy_reads = (uint32_t)busy;
+        ck_gspsim_init(&sim, &cfg);
+        struct ctx x;
+        memset(&x, 0, sizeof x);
+        x.r = ck_gspsim_regs(&sim);
+        x.fail = (uint32_t)fail;
+        gsp_seq_io io;
+        memset(&io, 0, sizeof io);
+        io.rd = rd;
+        io.wr = wr;
+        io.core = con ? core : NULL;
+        io.delay_us = dly;
+        io.ctx = &x;
+        io.poll_budget = (uint32_t)bud;
+        const char *why = 0;
+        int rc = gsp_seq_run(buf, (uint32_t)nw, (uint32_t)end, &io, &why);
+        printf("== %s rc=%d why=%s delays=%u/%u core=%u ops=", name, rc, why ? why : "-", x.ndelay, x.us, x.ncalls);
+        for (uint32_t i = 0; i < x.ncalls && i < 16; i++) printf("%u,", x.ops[i]);
+        printf(" save=");
+        for (int i = 0; i < GSP_SEQ_REG_SAVE; i++) printf("%#x,", io.save[i]);
+        printf(" nlog=%u violations=%u\n", sim.nlog, sim.violations);
+        for (uint32_t i = 0; i < sim.nlog && i < CK_GSPSIM_LOG_MAX; i++)
+            printf("%c %06x %08x\n", sim.log[i].write ? 'W' : 'R', sim.log[i].off, sim.log[i].val);
+        free(buf);
+    }
+    return 0;
+}
diff --git a/tests/seq_trace.om b/tests/seq_trace.om
new file mode 100644
index 0000000..df92c7a
--- /dev/null
+++ b/tests/seq_trace.om
@@ -0,0 +1,301 @@
+note tests/seq_trace.om: host trace of gsp/seq.om (sqrun) on the in-.om simulator (gsp/sim.om, mode 0).
+note Reads the cases on stdin, one per line, decimal: name busy budget core corefail nwords end m w0 .. w(m-1)
+note (busy = scfg busy_reads, budget = sqbud, core = sqcore, corefail = the opcode sqcorefn fails on, words past
+note m are 0; a token starting with # skips the rest of its line). Prints, per case, what tests/seq_ref.c
+note prints for the C gsp_seq_run on the C simulator:
+note   == name rc=0|-1 why=TEXT delays=CALLS/US core=CALLS ops=OP,.. save=%#x,..(8) nlog=N violations=N
+note   then the register log, one "W|R %06x %08x" line per access (the first 1024).
+note Build: cat gsp/mmio.om gsp/sim.om gsp/seq.om tests/seq_trace.om | omc. Host only, mode 0 only.
+text zqtx "== | rc=| why=| delays=| core=| ops=| save=| nlog=| violations=|"
+global zqin uchar 262144
+global zqn ulong 1
+global zqp ulong 1
+global zqt uchar 64
+global zqtl ulong 1
+global zqnm uchar 64
+global zqnml ulong 1
+global zqob uchar 65536
+global zqo ulong 1
+global zqops ulong 16
+global zqnop ulong 1
+global zqfail ulong 1
+note the core callback gsp/seq.om calls: records the opcode, fails on zqfail
+fn sqcorefn op ulong to long
+n = get zqnop 0
+if lt n 16
+put zqops n op
+end
+put zqnop 0 add n 1
+if eq op get zqfail 0
+ret -1
+end
+ret 0
+end
+fn zqflush to void
+n = get zqo 0
+if gt n 0
+r = write 1 zqob 0 n
+if ne r long n
+exit 1
+end
+end
+put zqo 0 0
+end
+note malformed input: print what is done, then exit 2 (the C referee does the same)
+fn zqbad to void
+zqflush
+exit 2
+end
+fn zqch c uchar to void
+p = get zqo 0
+put zqob p c
+put zqo 0 add p 1
+if ge add p 1 65000
+zqflush
+end
+end
+fn zqfr k ulong to void
+w = ulong 0
+for i ulong len zqtx
+c = get zqtx i
+if eq c 124
+w = add w 1
+else
+if eq w k
+zqch c
+end
+end
+end
+end
+fn zqdec v ulong to void
+d = ulong 1
+while le d div v 10 bound 20
+d = mul d 10
+end
+while ne d 0 bound 20
+zqch uchar add rem div v d 10 48
+d = div d 10
+end
+end
+fn zqsdec v long to void
+if lt v 0
+zqch 45
+zqdec ulong sub 0 v
+ret
+end
+zqdec ulong v
+end
+fn zqdig d ulong to void
+if lt d 10
+zqch uchar add d 48
+else
+zqch uchar add d 87
+end
+end
+note %0Nx: at least w digits, zero padded
+fn zqhexw v ulong w ulong to void
+nd = ulong 0
+t = v
+while ne t 0 bound 17
+nd = add nd 1
+t = shr t 4
+end
+if lt nd w
+nd = w
+end
+for i ulong nd
+zqdig and shr v mul sub sub nd i 1 4 15
+end
+end
+note %#x: 0 prints as 0, otherwise 0x and the digits
+fn zqhex v ulong to void
+if eq v 0
+zqch 48
+ret
+end
+zqch 48
+zqch 120
+zqhexw v 1
+end
+fn zqsp c uchar to bool
+ret or eq c 32 and ge c 9 le c 13
+end
+note next whitespace-separated token into zqt[0..zqtl); its length, 0 at the end of input
+fn zqtok to ulong
+p = get zqp 0
+n = get zqn 0
+while and lt p n zqsp get zqin p bound 300000
+p = add p 1
+end
+l = ulong 0
+while and lt p n not zqsp get zqin p bound 300000
+if ge l 63
+zqbad
+end
+put zqt l get zqin p
+l = add l 1
+p = add p 1
+end
+put zqp 0 p
+put zqtl 0 l
+ret l
+end
+fn zqskipl to void
+p = get zqp 0
+n = get zqn 0
+while and lt p n ne get zqin p 10 bound 300000
+p = add p 1
+end
+put zqp 0 p
+end
+note next token as a decimal number; anything else (or more than 4294967295) stops the run with zqbad
+fn zqnum to ulong
+l = zqtok
+if eq l 0
+zqbad
+end
+v = ulong 0
+for i ulong l
+c = get zqt i
+if or lt c 48 gt c 57
+zqbad
+end
+v = add mul v 10 sub ulong c 48
+if gt v 4294967295
+zqbad
+end
+end
+ret v
+end
+fn zqcase busy ulong bud ulong con ulong fail ulong nw ulong ci ulong to void
+for i ulong 10
+put scfg i 0
+end
+put scfg 0 busy
+siminit
+put spm 0 0
+put gspmode 0 0
+for j ulong SQSAVE
+put sqsave j 0
+end
+put sqdly 0 0
+put sqdly 1 0
+put zqnop 0 0
+put sqbud 0 bud
+put sqcore 0 con
+put zqfail 0 fail
+rc = sqrun nw ci
+sqwhy rc
+zqfr 0
+for k ulong get zqnml 0
+zqch get zqnm k
+end
+zqfr 1
+note the C returns -1 for every refusal; the why text below names which one
+if lt rc 0
+zqsdec -1
+else
+zqsdec rc
+end
+zqfr 2
+if eq get sqwl 0 0
+zqch 45
+end
+for k ulong get sqwl 0
+zqch get sqwb k
+end
+zqfr 3
+zqdec get sqdly 0
+zqch 47
+zqdec and get sqdly 1 M32
+zqfr 4
+zqdec get zqnop 0
+zqfr 5
+for k ulong get zqnop 0
+if lt k 16
+zqdec get zqops k
+zqch 44
+end
+end
+zqfr 6
+for k ulong SQSAVE
+zqhex get sqsave k
+zqch 44
+end
+zqfr 7
+zqdec sg SNLOG
+zqfr 8
+zqdec sg SVIOL
+zqch 10
+for k ulong sg SNLOG
+if lt k LOGMAX
+if eq get slogw k 1
+zqch 87
+else
+zqch 82
+end
+zqch 32
+zqhexw get slogo k 6
+zqch 32
+zqhexw get slogv k 8
+zqch 10
+end
+end
+end
+fn main to int
+p = ulong 0
+while lt p 262144 bound 300000
+r = read int 0 zqin p sub 262144 p
+if lt r 0
+zqbad
+end
+if eq r 0
+break
+end
+p = add p ulong r
+end
+put zqn 0 p
+put zqp 0 0
+while true bound 100000
+l = zqtok
+if eq l 0
+break
+end
+if eq get zqt 0 35
+zqskipl
+continue
+end
+for i ulong l
+put zqnm i get zqt i
+end
+put zqnml 0 l
+busy = zqnum
+bud = zqnum
+con = zqnum
+fail = zqnum
+nw = zqnum
+ci = zqnum
+m = zqnum
+if gt m nw
+zqbad
+end
+for i ulong m
+w = zqnum
+if lt i SQMAX
+put sqbuf i uint w
+end
+end
+lim = nw
+if gt lim SQMAX
+lim = SQMAX
+end
+for i ulong lim
+if ge i m
+put sqbuf i 0
+end
+end
+zqcase busy bud con fail nw ci
+end
+zqflush
+ret 0
+end
diff --git a/tests/sysinfo_cli.om b/tests/sysinfo_cli.om
new file mode 100644
index 0000000..6ea6ad1
--- /dev/null
+++ b/tests/sysinfo_cli.om
@@ -0,0 +1,409 @@
+note tests/sysinfo_cli.om: the command line of aien-dev/aienux PR #441 native/kernel/tools/ck_gsp_sysinfo_encode.c
+note over gsp/sysinfo.om, same stdout bytes and exit codes, so tests/sysinfo_diff.sh can cmp the two.
+note   fields            the 72 fields: "%-36s off=%3u size=%u"
+note   encode IN OUT     parse IN, echo "set %-36s off=%3u size=%u value=%#llx" per accepted line, then
+note                     "REFUSED: why" (exit 2) or write the 936 bytes to OUT and "RESULT OK OUT 936 bytes"
+note   byidx OUT         .om only: set all 72 fields through siseti with distinct non-zero bytes, print the
+note                     same values as "name 0x.." text (for the C tool to encode) and write the bytes
+note   api               .om only: the API refusals (siseti/sisetn/sitext), one line each
+note Anything else: usage on stderr, exit 1 (as the C tool). Host only; never touches a device.
+note Build: cat gsp/sysinfo.om tests/sysinfo_cli.om | omc
+text zitx "REFUSED: |cannot read |cannot write |RESULT OK | 936 bytes|set | off=| size=| value=|fields|encode|byidx|api|api | rc=| why=|nit|idx|fit|ok|rep|name|unk|big|bytes|Chipset|chipset|"
+text ziut "usage: ck_gsp_sysinfo_encode encode IN.txt OUT.bin | fields | selftest\n"
+global ziob uchar 65536
+global zipos ulong 1
+global zia uchar 64
+global zip1 uchar 4096
+global zip2 uchar 4096
+global zix uchar 1
+fn ziflush to void
+n = get zipos 0
+if gt n 0
+r = write 1 ziob 0 n
+if ne r long n
+exit 1
+end
+end
+put zipos 0 0
+end
+fn zich c uchar to void
+p = get zipos 0
+put ziob p c
+put zipos 0 add p 1
+if ge add p 1 65000
+ziflush
+end
+end
+note fragment k of zitx (fragments end at | 124)
+fn zifr k ulong to void
+w = ulong 0
+for i ulong len zitx
+c = get zitx i
+if eq c 124
+w = add w 1
+else
+if eq w k
+zich c
+end
+end
+end
+end
+fn zinl to void
+zich 10
+end
+fn zidec v ulong to void
+d = ulong 1
+while le d div v 10 bound 20
+d = mul d 10
+end
+while ne d 0 bound 20
+zich uchar add rem div v d 10 48
+d = div d 10
+end
+end
+fn zisdec v long to void
+if lt v 0
+zich 45
+zidec ulong sub 0 v
+ret
+end
+zidec ulong v
+end
+note %3u
+fn zipad3 v ulong to void
+if lt v 100
+zich 32
+end
+if lt v 10
+zich 32
+end
+zidec v
+end
+note %#llx (0 prints as 0)
+fn zihex v ulong to void
+if eq v 0
+zich 48
+ret
+end
+zich 48
+zich 120
+nd = ulong 0
+t = v
+while ne t 0 bound 17
+nd = add nd 1
+t = shr t 4
+end
+for i ulong nd
+d = and shr v mul sub sub nd i 1 4 15
+if lt d 10
+zich uchar add d 48
+else
+zich uchar add d 87
+end
+end
+end
+note %-36s of sinam
+fn zinam to void
+n = get sinl 0
+for i ulong n
+zich get sinam i
+end
+if lt n 36
+for j ulong sub 36 n
+zich 32
+end
+end
+end
+fn zipath which ulong n ulong to void
+for i ulong n
+if eq which 1
+zich get zip1 i
+else
+zich get zip2 i
+end
+end
+end
+note "name off=%3u size=%u" for field k (name already in sinam)
+fn zifield k ulong to void
+zinam
+zifr 6
+zipad3 get sioff k
+zifr 7
+zidec get sisz k
+end
+note argv[1] equals fragment k of zitx
+fn zimode n long k ulong to bool
+w = ulong 0
+j = ulong 0
+for i ulong len zitx
+c = get zitx i
+if eq c 124
+w = add w 1
+else
+if eq w k
+if ge j ulong n
+ret false
+end
+if ne get zia j c
+ret false
+end
+j = add j 1
+end
+end
+end
+ret eq j ulong n
+end
+fn ziusage to int
+ziflush
+r = write 2 ziut 0 len ziut
+ret 1
+end
+fn zifields to int
+sireset
+for k ulong SINF
+sinmk k
+zifield k
+zinl
+end
+ziflush
+ret 0
+end
+fn ziecho to void
+for i ulong get sinord 0
+k = get siord i
+sinmk k
+zifr 5
+zifield k
+zifr 8
+zihex get sival k
+zinl
+end
+end
+note siwb already holds the refusal text (siwhy is called before the echo, which reuses sinam)
+fn zirefuse to int
+zifr 0
+for i ulong get siwl 0
+zich get siwb i
+end
+zinl
+ziflush
+ret 2
+end
+fn zicant k ulong which ulong n ulong to int
+zifr 0
+zifr k
+zipath which n
+zinl
+ziflush
+ret 2
+end
+note write siout to the path in zip2[0..n); false when any step fails
+fn ziput n ulong to bool
+fd = fopen zip2 0 n 524865 438
+if lt fd 0
+ret false
+end
+w = write int fd siout 0 SISIZE
+c = fclose int fd
+ret and eq w long SISIZE eq c 0
+end
+fn zislurp n ulong to long
+fd = fopen zip1 0 n 524288 0
+if lt fd 0
+ret -1
+end
+t = ulong 0
+bad = false
+while lt t SITXMAX bound 70000
+r = read int fd sitxt t sub SITXMAX t
+if lt r 0
+bad = true
+break
+end
+if eq r 0
+break
+end
+t = add t ulong r
+end
+if and eq t SITXMAX not bad
+r = read int fd zix 0 1
+if lt r 0
+bad = true
+end
+if gt r 0
+t = add t 1
+end
+end
+c = fclose int fd
+if bad
+ret -1
+end
+ret long t
+end
+fn ziencode n1 ulong n2 ulong to int
+t = zislurp n1
+if lt t 0
+r = zicant 1 1 n1
+ret r
+end
+sireset
+e = sitext ulong t
+siwhy e
+ziecho
+if ne e SIEOK
+r = zirefuse
+ret r
+end
+siencode
+if not ziput n2
+r = zicant 2 2 n2
+ret r
+end
+zifr 3
+zipath 2 n2
+zifr 4
+zinl
+ziflush
+ret 0
+end
+fn zipat k ulong to ulong
+v = ulong 0
+for b ulong get sisz k
+x = add rem add mul k 8 b 251 1
+v = or v shl x mul b 8
+end
+ret v
+end
+fn zibyidx n2 ulong to int
+sireset
+for k ulong SINF
+v = zipat k
+e = siseti k v
+if ne e SIEOK
+siwhy e
+r = zirefuse
+ret r
+end
+for i ulong get sinl 0
+zich get sinam i
+end
+zich 32
+zihex v
+zinl
+end
+siencode
+if not ziput n2
+r = zicant 2 2 n2
+ret r
+end
+ziflush
+ret 0
+end
+note one api line: "api TAG rc=N why=TEXT"
+fn ziapi tag ulong e long to void
+zifr 13
+zifr tag
+zifr 14
+zisdec e
+zifr 15
+siwhy e
+for i ulong get siwl 0
+zich get siwb i
+end
+zinl
+end
+note put fragment k of zitx into sinam/sinl (for sisetn)
+fn zisetnm k ulong to void
+w = ulong 0
+o = ulong 0
+for i ulong len zitx
+c = get zitx i
+if eq c 124
+w = add w 1
+else
+if eq w k
+put sinam o c
+o = add o 1
+end
+end
+end
+put sinl 0 o
+end
+fn ziapis to int
+e = siseti 0 1
+ziapi 16 e
+sireset
+e = siseti 72 5
+ziapi 17 e
+e = siseti 16 256
+ziapi 18 e
+e = siseti 16 255
+ziapi 19 e
+e = siseti 16 1
+ziapi 20 e
+zisetnm 25
+e = sisetn 4205
+ziapi 21 e
+zisetnm 26
+e = sisetn 4205
+ziapi 22 e
+e = sitext 65537
+ziapi 23 e
+e = sitext 65536
+ziapi 19 e
+siencode
+zifr 13
+zifr 24
+zich 32
+zidec get sinord 0
+zich 32
+zihex ulong get siout 104
+for i ulong 4
+zich 32
+zihex ulong get siout add 120 i
+end
+zinl
+ziflush
+ret 0
+end
+fn main to int
+na = argcnt
+if lt na 2
+r = ziusage
+ret r
+end
+a = argread 1 zia 0 64
+if lt a 0
+r = ziusage
+ret r
+end
+if and eq na 2 zimode a 9
+r = zifields
+ret r
+end
+if and eq na 2 zimode a 12
+r = ziapis
+ret r
+end
+if and eq na 3 zimode a 11
+n2 = argread 2 zip2 0 4096
+if lt n2 0
+r = ziusage
+ret r
+end
+r = zibyidx ulong n2
+ret r
+end
+if and eq na 4 zimode a 10
+n1 = argread 2 zip1 0 4096
+n2 = argread 3 zip2 0 4096
+if or lt n1 0 lt n2 0
+r = ziusage
+ret r
+end
+r = ziencode ulong n1 ulong n2
+ret r
+end
+r = ziusage
+ret r
+end
diff --git a/tests/sysinfo_diff.sh b/tests/sysinfo_diff.sh
new file mode 100755
index 0000000..7c90e83
--- /dev/null
+++ b/tests/sysinfo_diff.sh
@@ -0,0 +1,168 @@
+#!/bin/sh
+# sysinfo_diff.sh: builds the .om GspSystemInfo encoder (gsp/sysinfo.om + tests/sysinfo_cli.om) and the C reference
+# (aienux PR #441 native/kernel/tools/ck_gsp_sysinfo_encode.c, compiled fresh into a temp dir as a test-only referee)
+# and requires, for every case text, byte-identical stdout, the same exit code and the same 936 output bytes.
+# Also: `fields` output identical; every field set by index (byidx) encodes like the C tool encodes the same values
+# as text; the .om-only API refusals match fixed expected lines. Host only: no device is opened.
+# Env: AIENUX (aienux checkout), OMC (pinned omc), SYSINFO_OM (library file to test; mutants use this).
+set -u
+here=$(cd "$(dirname "$0")/.." && pwd)
+AIENUX=${AIENUX:-/home/drakestapleton/work/OwnDriver/aienux}
+OMC=${OMC:-$here/build/omc}
+SYSINFO_OM=${SYSINFO_OM:-$here/gsp/sysinfo.om}
+OMC_SHA=$(sed -n 's/^OMC_SHA256=//p' "$here/tools/omc.pin")
+run() { nice -n 19 taskset -c "${AIEN_TEST_CPUS:-0-9,15-19}" "$@"; }
+
+got=$(sha256sum "$OMC" | cut -d' ' -f1)
+if [ "$got" != "$OMC_SHA" ]; then
+  echo "sysinfo_diff: FAIL omc sha256 $got, pinned $OMC_SHA"; exit 2
+fi
+if grep -n 'gspmode [0-9]* [1-9]\|gspbar\|vfio\|mapnew\|/dev/\|/sys/' "$here/tests/sysinfo_cli.om" "$SYSINFO_OM"; then
+  echo "sysinfo_diff: FAIL encoder or test driver names a device"; exit 2
+fi
+
+t=$(mktemp -d /tmp/sysinfo_diff.XXXXXX) || exit 2
+trap 'rm -rf "$t"' EXIT
+k=$AIENUX/native/kernel
+if ! run cc -std=c11 -O1 -Wall -Werror -o "$t/ck" "$k/tools/ck_gsp_sysinfo_encode.c"; then
+  echo "sysinfo_diff: FAIL C reference build"; exit 2
+fi
+if ! cat "$SYSINFO_OM" "$here/tests/sysinfo_cli.om" | run "$OMC" > "$t/om"; then
+  echo "sysinfo_diff: FAIL omc build"; exit 3
+fi
+chmod +x "$t/om"
+
+# ---- case texts (the C tool's selftest texts first, then the parser's edge cases) ----
+c=$t/cases
+mkdir "$c"
+rep() { printf "%$2s" '' | tr ' ' "$1"; }
+printf 'gpuPhysAddr 0x24000000\nPCIDeviceID 0x2e1210de # GB10\n\nFHBBusInfo.deviceID 0x22d1\nhostPageSize 4096\nbWindowChannelAlwaysMapped 1\n' > "$c/01valid"
+printf 'gpuPhysAdr 1\n' > "$c/02unknown"
+printf 'Chipset 1\nChipset 2\n' > "$c/03repeat"
+printf 'oorArch 256\n' > "$c/04fit1"
+printf 'FHBBusInfo.deviceID 0x10000\n' > "$c/05fit2"
+printf 'PCIRevisionID 0x100000000\n' > "$c/06fit4"
+printf 'maxUserVa 0x10000000000000000\n' > "$c/07ovf16"
+printf 'bIsPrimary -1\n' > "$c/08minus"
+printf 'bIsPrimary 1x\n' > "$c/09trail"
+printf 'bIsPrimary\n' > "$c/10want1"
+printf 'bIsPrimary 1 2\n' > "$c/11want3"
+printf 'acpiMethodData.dodMethodData 1\n' > "$c/12unkpart"
+printf 'acpiMethodData.dodMethodData.status 0xffff\nacpiMethodData.jtMethodData.status 0x56\nacpiMethodData.capsMethodData.status 0x56\n' > "$c/13acpi"
+printf 'Chipset 0777\nbIsPrimary 00\noorArch 0377\nconsoleMemSize 01777777777777777777777\n' > "$c/14octal"
+printf 'maxUserVa 02000000000000000000000\n' > "$c/15octovf"
+printf 'Chipset 08\n' > "$c/16octbad"
+printf 'Chipset +0x10\nhypervisorType +7\nbIsPassthru +0\n' > "$c/17plus"
+printf 'Chipset +-1\n' > "$c/18plusminus"
+printf 'Chipset +\n' > "$c/19plusonly"
+printf 'Chipset -0\n' > "$c/20minuszero"
+printf '\tChipset\t0x10\r\n  oorArch   3  \r\n\013\014\n \t \n' > "$c/21ws"
+{ printf 'Chipset 1'; rep ' ' 502; printf '\n'; } > "$c/22len511"
+{ printf 'Chipset 1'; rep ' ' 503; printf '\n'; } > "$c/23len512"
+{ printf 'oorArch 1\n#'; rep x 600; printf '\n'; } > "$c/24longcomment"
+{ rep a 200; printf ' 1\n'; } > "$c/25longname3"
+{ rep a 130; printf '\n'; } > "$c/26longname2"
+{ printf 'Chipset '; rep 1 130; printf '\n'; } > "$c/27longval"
+{ printf 'Chipset 0x'; rep 0 124; printf '1\n'; } > "$c/28zeros127"
+{ printf 'Chipset 0x'; rep 0 125; printf '1\n'; } > "$c/29zeros128"
+printf '# full comment\nChipset 5 # trailing\n#\noorArch 2#x\n   # indented\n' > "$c/30comments"
+printf 'Chipset 5\noorArch 3' > "$c/31noeol"
+printf 'Chipset 5\n\000oorArch 999\n' > "$c/32nul"
+: > "$c/33empty"
+printf 'maxUserVa 0xffffffffffffffff\nconsoleMemSize 18446744073709551615\n' > "$c/34max64"
+printf 'maxUserVa 18446744073709551616\n' > "$c/35dec2p64"
+{ printf 'oorArch 0x'; rep 0 50; printf '100\n'; } > "$c/36trunc40"
+printf 'Chipset 0x\n' > "$c/37zerox"
+printf 'Chipset 0xg\n' > "$c/38zeroxg"
+printf 'Chipset 0X1F\nPCIDeviceID 0xABCDEF\nPCISubDeviceID 0xAbCd\n' > "$c/39hexcase"
+printf 'FHBBusInfo.deviceID 0xffff\nPCIRevisionID 0xffffffff\noorArch 255\nvirtualConfigBits 65535\n' > "$c/40fitedge"
+printf 'virtualConfigBits 65536\n' > "$c/41fit2dec"
+printf 'Chipset   \n' > "$c/42nameonly"
+printf 'Chipset 1\noorArch 1\n\n# c\nChipset 2\n' > "$c/43replate"
+printf 'gpuPhysAddrX 1\n' > "$c/44longer"
+printf 'gpuPhysAdd 1\n' > "$c/45prefix"
+printf 'gpuphysaddr 1\n' > "$c/46case"
+{ i=0; while [ $i -lt 3000 ]; do printf '\n'; i=$((i + 1)); done; printf 'bogus 1\n'; } > "$c/47line3001"
+printf 'Chipset 0x1 0x2\n' > "$c/48want3b"
+printf 'gpuPhysAddr 0x24000000\ngpuPhysInstAddr 0x24700000\nnvDomainBusDeviceFunc 0x0000000f00000100\nPCIDeviceID 0x2e1210de\nPCISubDeviceID 0x000010de\nPCIRevisionID 0xa1\nmaxUserVa 0x1000000000000\nhostPageSize 4096\npcieConfigReg.linkCap 0x00457901\noorArch 3\nChipset 0x106d\nFHBBusInfo.deviceID 0x22d1\nFHBBusInfo.vendorID 0x10de\nchipsetIDInfo.deviceID 0x22d1\nchipsetIDInfo.vendorID 0x10de\nclPdbProperties 0x1088020c1\nbFlrSupported 1\nb64bBar0Supported 1\npciConfigMirrorBase 0x92000\npciConfigMirrorSize 0x1000\npcieAtomicsOpMask 0x7\nhypervisorType 4\nacpiMethodData.bValid 1\nacpiMethodData.dodMethodData.status 0xffff\nacpiMethodData.dodMethodData.acpiIdListLen 64\nacpiMethodData.jtMethodData.status 0x56\nacpiMethodData.capsMethodData.status 0x56\nupstreamAddressValid 1\nbWindowChannelAlwaysMapped 1\nbIsUnixHdmiFrlComplianceEnabled 1\n' > "$c/49window1"
+printf 'gspVFInfo.b64bitBar2 1\ngspVFInfo.FirstVFBar2Address 0x0102030405060708\nsysTimerOffsetNs 0x8000000000000000\nbS0ixSupport 0x0\n' > "$c/50tail"
+
+# one run: stdout, then the exit code, then the output bytes (or "no output file")
+one() {  # tool infile outfile -> stdout of the record
+  rm -f "$t/out.bin"
+  run "$1" encode "$2" "$3" > "$t/r.txt" 2> /dev/null
+  echo "rc=$?" >> "$t/r.txt"
+  cat "$t/r.txt"
+  if [ -f "$t/out.bin" ]; then od -An -tx1 -v "$t/out.bin"; else echo "no output file"; fi
+}
+fail=0; n=0
+for f in "$c"/*; do
+  n=$((n + 1))
+  one "$t/ck" "$f" "$t/out.bin" > "$t/c.rec"
+  one "$t/om" "$f" "$t/out.bin" > "$t/o.rec"
+  if ! cmp -s "$t/c.rec" "$t/o.rec"; then
+    echo "sysinfo_diff: case $(basename "$f") differs:"; diff "$t/c.rec" "$t/o.rec" | head -8; fail=1
+  fi
+done
+# missing input, unwritable output (negative controls on the file paths)
+for args in "$t/no-such-file $t/out.bin" "$c/01valid $t/no-dir/out.bin"; do
+  n=$((n + 1))
+  # shellcheck disable=SC2086
+  { run "$t/ck" encode $args; echo "rc=$?"; } > "$t/c.rec" 2>&1
+  # shellcheck disable=SC2086
+  { run "$t/om" encode $args; echo "rc=$?"; } > "$t/o.rec" 2>&1
+  if ! cmp -s "$t/c.rec" "$t/o.rec"; then
+    echo "sysinfo_diff: path case '$args' differs:"; diff "$t/c.rec" "$t/o.rec"; fail=1
+  fi
+done
+# usage: stdout empty, exit 1 on both
+for args in "" "fields x" "encode a" "selftestx" "encode a b c"; do
+  n=$((n + 1))
+  # shellcheck disable=SC2086
+  { run "$t/ck" $args; echo "rc=$?"; } > "$t/c.rec" 2> /dev/null
+  # shellcheck disable=SC2086
+  { run "$t/om" $args; echo "rc=$?"; } > "$t/o.rec" 2> /dev/null
+  if ! cmp -s "$t/c.rec" "$t/o.rec"; then
+    echo "sysinfo_diff: usage case '$args' differs:"; diff "$t/c.rec" "$t/o.rec"; fail=1
+  fi
+done
+# the field table
+run "$t/ck" fields > "$t/c.f"; run "$t/om" fields > "$t/o.f"
+if ! cmp -s "$t/c.f" "$t/o.f" || [ "$(wc -l < "$t/c.f")" -ne 72 ]; then
+  echo "sysinfo_diff: fields differ"; diff "$t/c.f" "$t/o.f" | head -8; fail=1
+fi
+# every field by index: the .om bytes must equal the C tool's bytes for the same values as text
+if ! run "$t/om" byidx "$t/idx.bin" > "$t/idx.txt" || [ "$(wc -l < "$t/idx.txt")" -ne 72 ]; then
+  echo "sysinfo_diff: byidx run failed"; cat "$t/idx.txt"; fail=1
+elif ! run "$t/ck" encode "$t/idx.txt" "$t/idxc.bin" > "$t/idxc.log" || ! cmp -s "$t/idx.bin" "$t/idxc.bin"; then
+  echo "sysinfo_diff: byidx bytes differ from the C encoding of the same values"; cat "$t/idxc.log"; fail=1
+fi
+# negative control: a corrupted copy of the window-1 text is refused with nothing written
+sed 's/^oorArch 3$/oorArch 0x103/' "$c/49window1" > "$t/bad.txt"
+rm -f "$t/out.bin"
+run "$t/om" encode "$t/bad.txt" "$t/out.bin" > "$t/bad.log"
+brc=$?
+if [ "$brc" -ne 2 ] || [ -f "$t/out.bin" ] || ! grep -qx 'REFUSED: line 10: 0x103 does not fit oorArch (1 bytes)' "$t/bad.log"; then
+  echo "sysinfo_diff: negative control not refused (rc $brc)"; cat "$t/bad.log"; fail=1
+fi
+# .om-only API refusals
+run "$t/om" api > "$t/api.txt"
+cat > "$t/api.want" <<'EOF'
+api nit rc=-9 why=sireset not called
+api idx rc=-1 why=field index out of range
+api fit rc=-3 why=0x100 does not fit oorArch (1 bytes)
+api ok rc=0 why=
+api rep rc=-2 why=field oorArch repeated
+api name rc=0 why=
+api unk rc=-4 why=unknown field chipset
+api big rc=-8 why=text over 65536 bytes
+api ok rc=0 why=
+api bytes 2 0xff 0x6d 0x10 0 0
+EOF
+if ! cmp -s "$t/api.want" "$t/api.txt"; then
+  echo "sysinfo_diff: api refusals differ"; diff "$t/api.want" "$t/api.txt"; fail=1
+fi
+if [ "$fail" -ne 0 ]; then
+  echo "sysinfo_diff: FAIL"; exit 1
+fi
+echo "sysinfo_diff: PASS ($n encode/usage cases identical stdout+exit+bytes, 72 fields, 72 by-index sets, negative control refused, 10 API lines; .om vs C reference)"
diff --git a/tests/window_sim.sh b/tests/window_sim.sh
new file mode 100755
index 0000000..33a93d5
--- /dev/null
+++ b/tests/window_sim.sh
@@ -0,0 +1,379 @@
+#!/bin/sh
+# tests/window_sim.sh -- run the real window scripts (window/*.sh, copied unchanged) against a simulated Spark
+# under /tmp: fake sysfs, /etc, /dev/vfio, /proc and shims for sudo, systemctl, modprobe, sysctl, lsmod,
+# nvidia-smi, pgrep, curl, tee (sysfs side effects), stat, fuser, modinfo, lsinitramfs and spark-window. The
+# "35B" is a sleep process the fake start script launches. A reboot is simulated by the harness: /tmp emptied,
+# 35B gone, sysctls reset, nvidia loaded unless the hold-back file says otherwise, then the boot unit if enabled.
+# Test-only shell (no product code); evidence label: EXERCISED (host simulator). Nothing here touches the GPU,
+# the real /sys, /etc, sudo or the live 35B: window/common.sh refuses unless every acting command is a shim.
+#   sh tests/window_sim.sh            all scenarios
+#   SIMDIR=/tmp/x sh tests/window_sim.sh   keep the simulated machines in /tmp/x
+set -eu
+R=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
+BASE=${SIMDIR:-$(mktemp -d /tmp/owndriver-window-sim.XXXXXX)}
+case $BASE in /tmp/*) ;; *) echo "SIMDIR must be under /tmp"; exit 2 ;; esac
+BDF=000f:01:00.0
+pass=0
+fail=0
+
+# --- the simulated machine ------------------------------------------------------------------------------
+mkroot() {
+	S=$BASE/$1
+	rm -rf "$S"
+	mkdir -p "$S/bin" "$S/st/modes" "$S/repo" "$S/tmp" "$S/home/handoffs/OwnDriver/window" "$S/q36/bin-19173f9e" \
+		"$S/etc/sudoers.d" "$S/etc/udev/rules.d" "$S/etc/security/limits.d" "$S/etc/modprobe.d" "$S/etc/systemd/system" \
+		"$S/sys/bus/pci/devices/$BDF/power" "$S/sys/bus/pci/drivers/nvidia" "$S/sys/bus/pci/drivers/vfio-pci" \
+		"$S/sys/kernel/iommu_groups/20/devices" "$S/dev/vfio" "$S/proc" "$S/build"
+	touch "$S/.owndriver-window-sim"
+	cp -r "$R/window" "$R/tools" "$S/repo/"
+	mkdir -p "$S/repo/build"
+	ln -s "$R/build/omc" "$S/repo/build/omc"
+	D=$S/sys/bus/pci/devices/$BDF
+	echo 0x10de > "$D/vendor"; echo 0x2e12 > "$D/device"; echo "flr bus" > "$D/reset_method"
+	: > "$D/driver_override"; echo auto > "$D/power/control"; echo active > "$D/power/runtime_status"
+	ln -s ../../../../kernel/iommu_groups/20 "$D/iommu_group"
+	touch "$S/sys/kernel/iommu_groups/20/devices/$BDF" "$S/sys/bus/pci/drivers_probe" \
+		"$S/sys/bus/pci/drivers/vfio-pci/unbind" "$S/sys/bus/pci/drivers/nvidia/unbind"
+	echo "drakestapleton ALL=(root) NOPASSWD: /usr/local/sbin/aien-run-exec" > "$S/etc/sudoers.d/aien-local-ci"
+	echo "options nvidia NVreg_Example=1" > "$S/etc/modprobe.d/nvidia.conf"
+	echo simkey > "$S/q36/KEY"
+	echo 0 > "$S/st/sysctl.kernel.panic"; echo 0 > "$S/st/sysctl.kernel.panic_on_oops"
+	echo 0 > "$S/st/boots"; : > "$S/st/events"
+	printf 'window: sim\nreset: approved\nreboot: approved\n' > "$S/home/handoffs/OwnDriver/window/APPROVED"
+	shims "$S"
+	cat > "$S/q36/start-35b-batch.sh" <<'EOF'
+#!/bin/sh
+# fake start-35b-batch.sh: a sleep stands in for aien-serve-http; its launch record goes to $ROOT/proc/<pid>.
+S=${OWNDRIVER_WINDOW_ROOT:?}
+[ -e "$S/st/start_fail" ] && { echo "start failed"; exit 1; }
+nohup sleep 100000 >/dev/null 2>&1 &
+p=$!
+mkdir -p "$S/proc/$p"
+printf '%s\0' ./aien-serve-http --engine omega --model-dir /home/drakestapleton/models/qwen3.6-35b-a3b-fp8-95a723d0 --port 18091 \
+	--max-context 49152 --max-tokens-cap 16384 --thinking off --batch-slots 8 > "$S/proc/$p/cmdline"
+printf 'Q36_BATCH_BIN=%s\0AIEN_Q36_STROKE=%s\0AIEN_SERVE_GPU_LOCK=%s\0AIEN_COORD_KEY=%s\0HOME=x\0' \
+	"${Q36_BATCH_BIN:-}" "${AIEN_Q36_STROKE:-}" "${AIEN_SERVE_GPU_LOCK:-}" "${AIEN_COORD_KEY:-}" > "$S/proc/$p/environ"
+ln -s "$S/q36/${Q36_BATCH_BIN:-bin-99230310}" "$S/proc/$p/cwd"
+echo aien-serve-http > "$S/proc/$p/comm"
+echo "$p" > "$S/st/35b"
+echo "start35b $p" >> "$S/st/events"
+echo "pid $p"
+EOF
+	chmod +x "$S/q36/start-35b-batch.sh"
+	cat > "$S/build/w0" <<'EOF'
+#!/bin/sh
+# fake build/w0: refuses unless the device is on vfio-pci, powered on and active, as the real one needs.
+S=${OWNDRIVER_WINDOW_ROOT:?}
+D=$S/sys/bus/pci/devices/000f:01:00.0
+echo "w0 $*" >> "$S/st/events"
+[ "$(basename "$(readlink "$D/driver")")" = vfio-pci ] || { echo "w0: not on vfio-pci"; exit 3; }
+[ "$(cat "$D/power/control")" = on ] && [ "$(cat "$D/power/runtime_status")" = active ] || { echo "w0: device not powered"; exit 4; }
+[ -e "$S/st/w0_leak" ] && echo 'SUBSYSTEM=="vfio", MODE="0666"' > "$S/etc/udev/rules.d/99-vfio.rules"
+if [ -e "$S/st/w0_crash" ]; then
+	echo crash >> "$S/st/events"; touch "$S/st/reboot"
+	pkill -KILL -f "$S/repo/window/d2-run.sh"
+	exit 9
+fi
+echo "BOOT_0 0x1b000000 BOOT_42 0x1b000000 (simulated)"
+exit "$(cat "$S/st/w0_rc" 2>/dev/null || echo 0)"
+EOF
+	chmod +x "$S/build/w0"
+	boot_power_on "$S" 0
+	start35b "$S"
+}
+
+start35b() { OWNDRIVER_WINDOW_ROOT=$1 Q36_BATCH_BIN=bin-19173f9e AIEN_Q36_STROKE=1 AIEN_SERVE_GPU_LOCK=/tmp/aien-serve-18091.lock AIEN_COORD_KEY=simkey "$1/q36/start-35b-batch.sh" >/dev/null; }
+
+bind_nvidia() {
+	S=$1; D=$S/sys/bus/pci/devices/$BDF
+	rm -f "$D/driver"; ln -s ../../drivers/nvidia "$D/driver"
+}
+
+# Power-on state; $2=1 runs the boot unit afterwards.
+boot_power_on() {
+	S=$1
+	n=$(($(cat "$S/st/boots") + 1)); echo $n > "$S/st/boots"
+	echo "boot $n" >> "$S/st/events"
+	if [ -s "$S/st/35b" ]; then kill "$(cat "$S/st/35b")" 2>/dev/null || true; rm -f "$S/st/35b"; fi
+	rm -rf "$S/tmp" && mkdir -p "$S/tmp"
+	if [ -e "$S/st/lock_after_reboot" ] && [ "$2" = 1 ]; then
+		rm -f "$S/st/lock_after_reboot"
+		(flock -x 9; sleep 20) 9>>"$S/tmp/aien-gb10.lock" &
+		echo $! > "$S/st/lockholder"; sleep 0.3
+		echo "boot: another GPU job took the chip lock" >> "$S/st/events"
+	fi
+	D=$S/sys/bus/pci/devices/$BDF
+	rm -f "$D/driver" "$S/st/modules" "$S/st/persistenced" "$S/st/nvidia_broken" "$S/dev/vfio/vfio" "$S/dev/vfio/20"
+	: > "$D/driver_override"; echo auto > "$D/power/control"
+	if [ -e "$S/st/pm_suspended" ]; then echo suspended > "$D/power/runtime_status"; else echo active > "$D/power/runtime_status"; fi
+	echo 0 > "$S/st/sysctl.kernel.panic"; echo 0 > "$S/st/sysctl.kernel.panic_on_oops"
+	bad=$(cat "$S/st/nvidia_bad_boots" 2>/dev/null || echo 0)
+	if grep -q 'install nvidia /bin/false' "$S"/etc/modprobe.d/* 2>/dev/null; then
+		echo "boot: nvidia held back" >> "$S/st/events"
+	elif [ "$bad" -gt 0 ] && [ "$2" = 1 ]; then
+		echo $((bad - 1)) > "$S/st/nvidia_bad_boots"; touch "$S/st/nvidia_broken"
+		echo "boot: nvidia failed to load (this boot)" >> "$S/st/events"
+	else
+		printf 'nvidia_uvm\nnvidia_drm\nnvidia_modeset\nnvidia\n' > "$S/st/modules"
+		bind_nvidia "$S"; touch "$S/st/persistenced"
+	fi
+	if [ "$2" = 1 ] && [ -e "$S/st/unit-enabled" ] && [ -e "$S/etc/systemd/system/aien-owndriver-window.service" ]; then
+		echo "unit runs" >> "$S/st/events"
+		(cd "$S/repo" && OWNDRIVER_WINDOW_ROOT=$S PATH="$S/bin:$PATH" sh "$S/repo/window/d2-boot.sh") > "$S/st/unit-$n.out" 2>&1 ||
+			echo "unit exit $?" >> "$S/st/events"
+	fi
+}
+
+# Run a window command, then follow every reboot it asks for (at most 8 boots).
+run_window() {
+	S=$1; shift
+	(cd "$S/repo" && OWNDRIVER_WINDOW_ROOT=$S PATH="$S/bin:$PATH" "$@") > "$S/st/cmd.out" 2>&1 && echo "cmd exit 0" >> "$S/st/events" ||
+		echo "cmd exit $?" >> "$S/st/events"
+	while [ -e "$S/st/reboot" ]; do
+		rm -f "$S/st/reboot"
+		[ "$(cat "$S/st/boots")" -lt 9 ] || { echo "boot loop" >> "$S/st/events"; return; }
+		boot_power_on "$S" 1
+	done
+}
+
+shims() {
+	S=$1; B=$S/bin
+	w() { printf '#!/bin/sh\nS=%s\nD=$S/sys/bus/pci/devices/%s\n%s\n' "$S" "$BDF" "$2" > "$B/$1"; chmod +x "$B/$1"; }
+	w sudo '[ "$1" = -n ] && shift
+exec "$@"'
+	w systemctl 'echo "systemctl $*" >> $S/st/events
+case $1 in
+daemon-reload) ;;
+enable) [ -e $S/st/fail_enable ] && exit 1; [ -e $S/etc/systemd/system/$2 ] && touch $S/st/unit-enabled ;;
+disable) rm -f $S/st/unit-enabled ;;
+is-active) [ "$2" = --quiet ] && shift; [ -e $S/st/persistenced ] || { [ "$2" = --quiet ] || echo inactive; exit 3; }; echo active ;;
+start) [ -s $S/st/modules ] && touch $S/st/persistenced ;;
+reboot) touch $S/st/reboot ;;
+*) exit 1 ;;
+esac'
+	w modprobe 'echo "modprobe $*" >> $S/st/events
+for m in "$@"; do case $m in
+vfio-pci) grep -qx vfio_pci $S/st/modules 2>/dev/null || echo vfio_pci >> $S/st/modules; : > $S/dev/vfio/vfio; echo root:root:666 > $S/st/modes/vfio ;;
+nvidia*) grep -q "install nvidia /bin/false" $S/etc/modprobe.d/* 2>/dev/null && exit 1
+	[ -e $S/st/nvidia_broken ] && exit 1
+	for n in nvidia nvidia_modeset nvidia_drm nvidia_uvm; do grep -qx $n $S/st/modules 2>/dev/null || echo $n >> $S/st/modules; done
+	[ -e $D/driver ] || [ -n "$(cat $D/driver_override)" ] || { ln -s ../../drivers/nvidia $D/driver; } ;;
+*) exit 1 ;;
+esac; done'
+	w lsmod 'echo "Module Size Used by"
+[ -s $S/st/modules ] && while read -r m; do echo "$m 16384 0"; done < $S/st/modules
+exit 0'
+	w sysctl 'case $1 in
+-n) cat $S/st/sysctl.$2 ;;
+-q) shift; if [ "$1" = -p ]; then while IFS== read -r k v; do echo "$v" > $S/st/sysctl.$k; done < "$2"; else for a; do echo "${a#*=}" > $S/st/sysctl.${a%%=*}; done; fi
+	echo "sysctl $*" >> $S/st/events ;;
+*) exit 1 ;;
+esac'
+	w nvidia-smi 'up() { [ -s $S/st/35b ] && kill -0 "$(cat $S/st/35b)" 2>/dev/null; }
+case $1 in
+-L) grep -qx nvidia $S/st/modules 2>/dev/null && [ "$(basename "$(readlink $D/driver)")" = nvidia ] && echo "GPU 0: NVIDIA GB10 (UUID: GPU-sim)" || { echo "No devices were found"; exit 6; } ;;
+--query-compute-apps=pid) up && cat $S/st/35b; exit 0 ;;
+--query-compute-apps=process_name,used_memory) up && echo "aien-serve-http, 43520 MiB"; exit 0 ;;
+*) exit 1 ;;
+esac'
+	w pgrep '[ -s $S/st/35b ] && kill -0 "$(cat $S/st/35b)" 2>/dev/null && cat $S/st/35b && exit 0
+exit 1'
+	w curl 'up() { [ -s $S/st/35b ] && kill -0 "$(cat $S/st/35b)" 2>/dev/null && [ ! -e $S/st/serve_dead ]; }
+up || exit 7
+case "$*" in
+*/v1/models*) echo "{\"data\":[{\"id\":\"qwen3.6-35b-a3b\"}]}" ;;
+*/v1/chat/completions*) echo "{\"choices\":[{\"message\":{\"content\":\"ready\"}}]}" ;;
+*) exit 22 ;;
+esac'
+	w tee '/usr/bin/tee "$@" || exit $?
+for a; do t=$a; done
+case $t in
+$S/sys/bus/pci/drivers_probe)
+	if [ ! -e $D/driver ]; then
+		o=$(cat $D/driver_override)
+		if [ "$o" = vfio-pci ] && grep -qx vfio_pci $S/st/modules; then ln -s ../../drivers/vfio-pci $D/driver; : > $S/dev/vfio/20; cat $S/st/vfio_mode 2>/dev/null > $S/st/modes/20 || echo root:root:600 > $S/st/modes/20; echo "bind vfio-pci" >> $S/st/events
+		elif [ -z "$o" ] && grep -qx nvidia $S/st/modules 2>/dev/null; then ln -s ../../drivers/nvidia $D/driver; echo "bind nvidia" >> $S/st/events; fi
+	fi ;;
+$S/sys/bus/pci/drivers/vfio-pci/unbind) rm -f $D/driver $S/dev/vfio/20; echo "unbind vfio-pci (FLR)" >> $S/st/events ;;
+$D/power/control) [ "$(cat $D/power/control)" = on ] && [ ! -e $S/st/pm_stuck ] && echo active > $D/power/runtime_status ;;
+esac
+exit 0'
+	w stat 'for a; do f=$a; done
+case $f in $S/dev/vfio/*) cat $S/st/modes/$(basename $f) ;; *) exec /usr/bin/stat "$@" ;; esac'
+	w fuser 'echo " 1755 $(cat $S/st/35b 2>/dev/null)"'
+	w modinfo 'case "$*" in
+"-n vfio-pci") echo /lib/modules/sim/vfio-pci.ko ;;
+nvgrace-gpu-vfio-pci) for a in 31C2 2941 2348 2345 2342; do echo "alias: pci:v000010DEd0000${a}sv*sd*bc*sc*i*"; done ;;
+*) exit 1 ;;
+esac'
+	w lsinitramfs 'echo usr/lib/modules/sim/kernel/drivers/vfio/pci/vfio-pci.ko'
+	w spark-window 'echo free'
+}
+
+# --- assertions ----------------------------------------------------------------------------------------
+ok() { pass=$((pass + 1)); echo "  ok   $1"; }
+bad() { fail=$((fail + 1)); echo "  FAIL $1"; FAILED_IN="$FAILED_IN $CASE"; }
+check() { if eval "$2"; then ok "$1"; else bad "$1"; fi; }
+L() { echo "$S/home/handoffs/OwnDriver/window"; }
+alive35b() { [ -s "$S/st/35b" ] && kill -0 "$(cat "$S/st/35b")" 2>/dev/null; }
+restored() {
+	check "35B running again" alive35b
+	check "35B restarted with the recorded env (key compared)" "tr '\\0' '\\n' < $S/proc/\$(cat $S/st/35b)/environ | grep -qx AIEN_COORD_KEY=simkey && tr '\\0' '\\n' < $S/proc/\$(cat $S/st/35b)/environ | grep -qx Q36_BATCH_BIN=bin-19173f9e"
+	check "nvidia bound, 4 modules" "[ \$(basename \$(readlink $S/sys/bus/pci/devices/$BDF/driver)) = nvidia ] && [ \$(grep -c nvidia $S/st/modules) = 4 ]"
+	check "hold-back file and unit gone" "[ ! -e $S/etc/modprobe.d/zz-aien-owndriver-window.conf ] && [ ! -e $S/etc/systemd/system/aien-owndriver-window.service ] && [ ! -e $S/st/unit-enabled ]"
+	check "sysctl back to 0/0" "[ \$(cat $S/st/sysctl.kernel.panic) = 0 ] && [ \$(cat $S/st/sysctl.kernel.panic_on_oops) = 0 ]"
+	check "state, approval, restore-path cleared" "[ ! -e $(L)/state ] && [ ! -e $(L)/APPROVED ] && [ ! -e $(L)/restore-path ]"
+	check "driver_override empty" "[ -z \"\$(tr -d '\\n' < $S/sys/bus/pci/devices/$BDF/driver_override)\" ]"
+	check "BOARD says WINDOW CLOSED" "grep -q 'WINDOW CLOSED' $S/home/handoffs/BOARD.md"
+	check "power/control back to auto" "[ \$(cat $S/sys/bus/pci/devices/$BDF/power/control) = auto ]"
+}
+untouched() {
+	check "35B never stopped" "alive35b && ! grep -q 'boot 2' $S/st/events"
+	check "no window file written" "[ ! -e $S/etc/modprobe.d/zz-aien-owndriver-window.conf ] && [ ! -e $S/etc/systemd/system/aien-owndriver-window.service ] && [ ! -e $(L)/state ]"
+}
+boots() { check "boots after power-on: $1" "[ \$(cat $S/st/boots) = $(($1 + 1)) ]"; }
+
+FAILED_IN=
+CASE=w0;          echo "case $CASE: W0 read-only"; mkroot $CASE
+run_window "$S" sh window/d2-pre.sh
+check "W0 exit 0" "grep -qx 'cmd exit 0' $S/st/events"; untouched
+check "baseline written" "[ -s $(L)/priv-baseline ]"
+
+# mkfw S: a build/fw in fwprep's manifest format (fw_file names the real firmware sha256).
+mkfw() {
+	mkdir -p "$1/build/fw"
+	{
+		echo "fwmanifest 1"
+		echo "fw_file bytes=75012080 sha256=32cb7cf3e77f97e92f6e92135939ccb3ba382748144569c0dfccf3338d43d963"
+		for o in fmc.img fmc.hash fmc.pubkey fmc.sig bl.img; do
+			echo "sim $o" > "$1/build/fw/$o"
+			echo "out $o bytes=$(wc -c < "$1/build/fw/$o") sha256=$(sha256sum "$1/build/fw/$o" | cut -c1-64)"
+		done
+		echo end
+	} > "$1/build/fw/fw.manifest.tmp"
+	mv "$1/build/fw/fw.manifest.tmp" "$1/build/fw/fw.manifest"
+}
+CASE=fwgood;      echo "case $CASE: W0 with a matching build/fw"; mkroot $CASE
+mkfw "$S"
+run_window "$S" sh window/d2-pre.sh
+check "W0 exit 0" "grep -qx 'cmd exit 0' $S/st/events"; untouched
+check "build/fw checked" "grep -q 'build/fw matches fw.manifest' $(L)/*-pre.log"
+
+CASE=fwbad;       echo "case $CASE: W0 with a build/fw file that differs from fw.manifest"; mkroot $CASE
+mkfw "$S"; echo tampered > "$S/build/fw/bl.img"
+run_window "$S" sh window/d2-pre.sh
+check "W0 refused" "grep -qx 'cmd exit 1' $S/st/events"; untouched
+check "names the mismatch" "grep -q 'build/fw files do not match' $(L)/*-pre.log"
+
+CASE=d2;          echo "case $CASE: full D2 window, reboot restore path"; mkroot $CASE
+run_window "$S" sh window/d2-pre.sh --go D2
+boots 2; restored
+check "W2 bound vfio-pci, then W7 unbound it (FLR)" "grep -q 'bind vfio-pci' $S/st/events && grep -q 'unbind vfio-pci' $S/st/events"
+check "w0 ran on the device" "grep -q '^w0 000f:01:00.0 20' $S/st/events"
+check "W4/W5 logged NOT_RUN (no build/ogd)" "grep -q \"W-boot NOT_RUN\" $(L)/*-run.log && grep -q \"W-hello NOT_RUN\" $(L)/*-run.log"
+check "panic sysctls were 10/1 during W2" "grep -q 'sysctl kernel.panic=10 kernel.panic_on_oops=1' $S/st/events"
+
+CASE=rebind;      echo "case $CASE: D2 window, RESTORE_PATH=rebind"; mkroot $CASE
+run_window "$S" env RESTORE_PATH=rebind sh window/d2-pre.sh --go D2
+boots 1; restored
+
+CASE=noappr;      echo "case $CASE: no approval file"; mkroot $CASE
+rm "$(L)/APPROVED"
+run_window "$S" sh window/d2-pre.sh --go D2
+check "refused" "grep -q 'cmd exit 1' $S/st/events"; untouched
+
+CASE=noreset;     echo "case $CASE: approval without 'reset: approved'"; mkroot $CASE
+printf 'window: sim\nreboot: approved\n' > "$(L)/APPROVED"
+run_window "$S" sh window/d2-pre.sh --go D2
+check "refused" "grep -q 'cmd exit 1' $S/st/events"; untouched
+
+CASE=locked;      echo "case $CASE: chip lock held by another GPU job"; mkroot $CASE
+(flock -x 9; sleep 30) 9>>"$S/tmp/aien-gb10.lock" &
+lockpid=$!; sleep 0.3
+run_window "$S" sh window/d2-pre.sh --go D2
+kill $lockpid 2>/dev/null || true
+check "refused" "grep -q 'cmd exit 1' $S/st/events"; untouched
+
+CASE=snapdiff;    echo "case $CASE: live 35B started differently from the restore recipe"; mkroot $CASE
+printf 'Q36_BATCH_BIN=bin-99230310\0AIEN_COORD_KEY=simkey\0' > "$S/proc/$(cat "$S/st/35b")/environ"
+run_window "$S" sh window/d2-pre.sh --go D2
+check "refused" "grep -q 'cmd exit 1' $S/st/events"; untouched
+
+CASE=w1abort;     echo "case $CASE: W1 fails after stopping the 35B (systemctl enable fails)"; mkroot $CASE
+touch "$S/st/fail_enable"
+run_window "$S" sh window/d2-pre.sh --go D2
+boots 0; restored
+check "W1 exit nonzero" "grep -q 'cmd exit 1' $S/st/events"
+
+CASE=pm;          echo "case $CASE: runtime PM stays suspended after power/control=on"; mkroot $CASE
+touch "$S/st/pm_suspended" "$S/st/pm_stuck"
+run_window "$S" sh window/d2-pre.sh --go D2
+rm -f "$S/st/pm_suspended" "$S/st/pm_stuck"
+check "w0 never ran (no BAR access while suspended)" "! grep -q '^w0 ' $S/st/events"
+check "W3 refused on runtime_status" "grep -q 'runtime_status=suspended, not active' $(L)/*-run.log"
+boots 2; restored
+
+CASE=w0fail;      echo "case $CASE: w0 fails"; mkroot $CASE
+echo 3 > "$S/st/w0_rc"
+run_window "$S" sh window/d2-pre.sh --go D2
+boots 2; restored
+check "release logged rc=1" "grep -q 'W7 release (rc=1)' $(L)/*-run.log"
+
+CASE=crash;       echo "case $CASE: crash during W3 (no trap runs)"; mkroot $CASE
+touch "$S/st/w0_crash"
+run_window "$S" sh window/d2-pre.sh --go D2
+boots 2; restored
+
+CASE=fallback;    echo "case $CASE: nvidia fails to come back once: one reboot fallback"; mkroot $CASE
+echo 1 > "$S/st/nvidia_bad_boots"
+run_window "$S" sh window/d2-pre.sh --go D2
+boots 3; restored
+check "fallback used once" "grep -q 'reboot fallback' $S/home/handoffs/BOARD.md"
+
+CASE=fallback2;   echo "case $CASE: nvidia never comes back: stop after one fallback"; mkroot $CASE
+echo 99 > "$S/st/nvidia_bad_boots"
+run_window "$S" sh window/d2-pre.sh --go D2
+boots 3
+check "BOARD says restore FAILED" "grep -q 'restore FAILED after the reboot fallback' $S/home/handoffs/BOARD.md"
+check "no reboot loop" "! grep -q 'boot loop' $S/st/events"
+check "unit and state kept for the next (manual) boot" "[ -e $S/etc/systemd/system/aien-owndriver-window.service ] && [ \$(cat $(L)/state) = restore ]"
+
+CASE=leak;        echo "case $CASE: a privilege file appears during the window"; mkroot $CASE
+touch "$S/st/w0_leak"
+run_window "$S" sh window/d2-pre.sh --go D2
+check "BOARD says PRIVILEGE PERSISTED" "grep -q 'PRIVILEGE PERSISTED' $S/home/handoffs/BOARD.md"
+check "no WINDOW CLOSED" "! grep -q 'WINDOW CLOSED' $S/home/handoffs/BOARD.md"
+
+CASE=vfiomode;    echo "case $CASE: /dev/vfio/20 comes up world-writable"; mkroot $CASE
+echo root:root:666 > "$S/st/vfio_mode"
+run_window "$S" sh window/d2-pre.sh --go D2
+check "w0 never ran" "! grep -q '^w0 ' $S/st/events"
+check "W2 refused on the mode" "grep -q 'is root:root:666, expected root:root:600' $(L)/*-run.log"
+boots 2; restored
+
+CASE=lockboot;    echo "case $CASE: another GPU job takes the chip lock right after the W1 reboot"; mkroot $CASE
+touch "$S/st/lock_after_reboot"
+run_window "$S" sh window/d2-pre.sh --go D2
+kill "$(cat "$S/st/lockholder")" 2>/dev/null || true
+check "w0 never ran" "! grep -q '^w0 ' $S/st/events"
+check "W2 refused on the lock" "grep -q 'is held: something started a GPU job' $(L)/*-run.log"
+boots 2; restored
+
+CASE=d3noogd;     echo "case $CASE: D3 without build/ogd"; mkroot $CASE
+D3_CMD="make chip-gates" run_window "$S" sh window/d2-pre.sh --go D3
+check "refused" "grep -q 'cmd exit 1' $S/st/events"; untouched
+
+CASE=stale;       echo "case $CASE: boot unit left over with no state"; mkroot $CASE
+cp "$R/window/aien-owndriver-window.service" "$S/etc/systemd/system/"; touch "$S/st/unit-enabled"
+boot_power_on "$S" 1
+check "unit removed itself" "[ ! -e $S/etc/systemd/system/aien-owndriver-window.service ] && [ ! -e $S/st/unit-enabled ]"
+check "no driver change" "! grep -q 'bind vfio-pci' $S/st/events"
+
+for s in "$BASE"/*/st/35b; do [ -s "$s" ] && kill "$(cat "$s")" 2>/dev/null || true; done
+[ -n "${SIMDIR:-}" ] || rm -rf "$BASE"
+if [ "$fail" -eq 0 ]; then
+	echo "window_sim: PASS ($pass checks, $(grep -c '^CASE=' "$0") scenarios)"
+else
+	echo "window_sim: FAIL ($fail of $((pass + fail)) checks; in:$FAILED_IN)"
+	exit 1
+fi
diff --git a/tools/omc.pin b/tools/omc.pin
index 427ef74..b640c16 100644
--- a/tools/omc.pin
+++ b/tools/omc.pin
@@ -1,5 +1,6 @@
 # The Omega compiler omega-gpu-driver is built with. Only these bytes are trusted.
-# Parent: aien-dev/omega-mv branch feat/vfio-device-calls (draft PR), which adds vfioctl/vfiomap.
+# Parent: aien-dev/omega-mv branch feat/vfio-dma-bar (draft PR #890, on #878 feat/vfio-device-calls),
+# which adds vfioctl/vfiomap (#878) and IOMMU_MAP_DMA/UNMAP_DMA plus writable vfiomapw (#890).
 OMEGA_REPO=https://github.com/aien-dev/omega-mv.git
-OMEGA_COMMIT=24b4cd6fc69063ace6fe1d8b02c90400ffd6c93f
-OMC_SHA256=5dac75437a0eaeabe086441ae776317e21e9fd0c059a979bc4db409e833cf04c
+OMEGA_COMMIT=397e67040fb74853c6814097fe02ae4e1ebd6f66
+OMC_SHA256=bcfa582892afca8f65e551fe56867d918d86e84540c7381be8fa9ef18d0cf0f6
diff --git a/window/README.md b/window/README.md
new file mode 100644
index 0000000..9a6eba7
--- /dev/null
+++ b/window/README.md
@@ -0,0 +1,89 @@
+# OwnDriver window procedure (D2, D3)
+
+Status: **NOT_RUN** on the GB10. W0 has run read-only beside the live 35B (EXERCISED, host). Nothing in W1..W7
+or R has touched the GB10. The unchanged scripts have run end to end against a simulated machine under /tmp
+(`tests/window_sim.sh`, EXERCISED host simulator; `tests/mutants-window.sh` removes one safety step at a time and
+the simulator must catch it). Every step below stops the resident 35B on 127.0.0.1:18091, resets the GPU and
+reboots the Spark twice. It runs only in an exclusive window that Drake opens for this job.
+
+## What the window does to the machine
+
+- **Two reboots.** nvidia.ko is held back for one boot so the GPU comes up without a driver. A live unload of
+  nvidia can hang in `nvEvoWaitForCoreNotifier`, and a fresh boot hands the driver an untouched GPU. Each reboot
+  ends **every agent session on the Spark, Main's included.** The window therefore runs unattended through a
+  one-shot systemd unit (`aien-owndriver-window.service`) that W1 installs and R removes.
+- **GPU reset.** `reset_method` is `flr bus`. vfio-pci FLRs the GPU when W2/W3 open it, and on release calls
+  `pci_reset_bus`: a Secondary Bus Reset of root port 000f:00:00.0 (10de:22d1, not quirked NO_BUS_RESET),
+  whose only device is the GPU 000f:01:00.0. Emptying `reset_method` would not stop that SBR (README.md,
+  `qemu/sbr/sbr-on-release.log`, EXERCISED in QEMU only).
+- **No privilege grant.** No udev rule, group, sudoers line, memlock limit or `/dev/vfio` mode change. The driver
+  programs run as root through `sudo -n`. `/dev/vfio/20` must stay `root:root 0600`. W0 records the privilege
+  baseline (`priv-baseline`: every file in `/etc/sudoers.d`, `/etc/udev/rules.d`, `/etc/security/limits.d` and
+  `/etc/modprobe.d` with its sha256, plus the user's groups). R4 fails closed and posts to BOARD if anything differs.
+- **Window files**, present only between W1 and R:
+  - `/etc/modprobe.d/zz-aien-owndriver-window.conf`: nvidia hold-back;
+  - `/etc/systemd/system/aien-owndriver-window.service`;
+  - `~/handoffs/OwnDriver/window/{state,saved-sysctl,d3-cmd,reboot-fallback-used}`.
+
+## Approval
+
+Main writes `/home/drakestapleton/handoffs/OwnDriver/window/APPROVED` when Drake opens the window. The file lives
+there and not in `/tmp`, because `/tmp` is emptied at every boot (`D /tmp` in tmpfiles.d). It must contain:
+
+```
+window: <Drake's words, or the BOARD line that quotes them>
+reset: approved
+reboot: approved
+```
+
+W1 and W2 refuse without all three lines. R deletes the file at the end (one approval, one window).
+
+## Steps
+
+| Step | Script | What it does | Ends with |
+|---|---|---|---|
+| W0 | `sh window/d2-pre.sh` | Read-only. Checks the firmware sha256, logs the sha256 of every script and binary, checks that `build/omc` matches `tools/omc.pin` and that `build/fw` matches `fw.manifest`. Checks the device identity (10de:2e12), that group 20 holds only 000f:01:00.0, that nvgrace-gpu-vfio-pci does not alias 2e12, and that the initramfs has no nvidia modules. Records the privilege baseline and runs privcheck. Checks that the live 35B launch record (argv, cwd, env names, coordinator key) equals the restore recipe. Lists GPU users and the chip lock. | exit 0 |
+| W1 | `sh window/d2-pre.sh --go [D2\|D3]` | Repeats W0, then needs APPROVED and takes `/tmp/aien-gb10.lock` (`flock -n`; refuses if any GPU job holds it). Posts to BOARD, sends TERM to the 35B and waits until `nvidia-smi` shows no compute app. Saves the kernel.panic values, writes the hold-back file, installs and enables the unit, and sets state `run D2`. A failure before the reboot removes the window files and runs R. | reboot |
+| W2 | unit → `d2-run.sh --go D2` | Sets state `restore` and deletes the hold-back file first, so any later boot is a normal one that ends in R. Needs APPROVED and the chip lock, and checks that no nvidia module is loaded. Sets `kernel.panic=10` and `panic_on_oops=1` (an oops reboots into R). Runs `modprobe vfio-pci`, sets `driver_override`, binds through `drivers_probe`, and checks `/dev/vfio/20` is `root:root:600`. | |
+| W3 | | Runtime PM: `power/control=on` and `runtime_status=active` before any BAR access. `build/w0` reads config identity, BOOT_0/BOOT_1/BOOT_42 and the GSP falcon state (read-only), then `build/ogd ident`. | |
+| W4 | | `build/ogd boot`: GSP boot to INIT_DONE, static info, unload. | |
+| W5 | | `build/ogd hello`: objects, channel, one semaphore release, teardown. | |
+| W6 (D3 only) | | `build/ogd exec ... -- $D3_CMD`, where D3_CMD is the CUDApp chip-gate command line. W1 stores it in `d3-cmd`. | |
+| W7 | EXIT trap | Unbinds vfio-pci (GPU reset), clears `driver_override` and sets `power/control=auto`. Then by default reboots, and the unit runs R. With `RESTORE_PATH=rebind` it runs R in place. | reboot |
+| R | unit → `d2-restore.sh --go` | R0: if the hold-back file is still there, removes it and reboots. R1: loads the nvidia modules, binds the device and checks that `nvidia-smi -L` lists the GB10. Any failure takes ONE reboot fallback (`reboot-fallback-used`), then R runs again. R2: starts nvidia-persistenced and restores the saved sysctls. R3: restarts the 35B with `start-35b-batch.sh` and the recorded env, waits for `/v1/models` (up to 900 s), runs one greedy chat, and requires exactly one `aien-serve-http` on the GPU. R4: removes the unit, runs privcheck against the baseline, removes markers, state and APPROVED, and posts BOARD `WINDOW CLOSED`. | |
+
+Each driver step (W3 ident, W4, W5, W6) runs only if `build/ogd modes` lists it. Otherwise it is logged
+`NOT_RUN: build/ogd has no '<mode>' mode` and the window goes straight to W7 and R. All logs go to
+`~/handoffs/OwnDriver/window/d2-<UTC>-{pre,run,restore,boot}.log`.
+
+**Current state (2026-10-27): `build/ogd` does not exist, so W4 and W5 are NOT_RUN and policy-blocked.** On
+2026-10-27 the .om port of aienux `gb10_gsp_boot.c` (boot arena, COT packet, message queue, RM RPC) was stopped by
+a model-policy refusal. Per the lane rule it was not retried. It needs a human-written port; that is Drake's
+item. A D2 window today therefore exercises W2, W3 (`build/w0`), W7 and R. That still settles DESIGN §7
+UNKNOWN 1 (BOOT_42 naming) and proves the vfio-pci bind/release and the nvidia.ko restore after the FLR and SBR.
+`d2-pre.sh --go D3` refuses without `build/ogd`.
+
+## Recovery when R fails twice
+
+R posts `restore FAILED after the reboot fallback` to BOARD and stops. The GPU state is then unknown.
+Recovery is a physical power cycle by Drake. After that boot the hold-back file is already gone (W2 or R0
+deleted it), so nvidia.ko loads normally. The unit is still installed with state `restore`, so it runs R again.
+
+## Simulator
+
+`sh tests/window_sim.sh` runs these scripts, unchanged, against a fake machine in /tmp: sysfs, `/etc`, `/dev/vfio`
+and `/proc` live under `OWNDRIVER_WINDOW_ROOT`, and sudo, systemctl, modprobe, sysctl, lsmod, nvidia-smi, pgrep,
+curl, tee, stat, fuser, modinfo, lsinitramfs and spark-window are shims there. `common.sh` exits 2 unless the root
+is under /tmp, carries `.owndriver-window-sim`, and every one of those commands resolves to the shim, so a
+simulation can never reach the real machine. The harness simulates each reboot (fresh /tmp, 35B gone, nvidia loaded
+unless held back, boot unit run if enabled). Scenarios: W0, W0 with a matching and with a tampered `build/fw`, full
+D2, rebind restore, missing approval, missing reset line, chip lock held, mismatched 35B launch record, W1 failure
+after the 35B stop, runtime PM stuck, w0 failure, crash mid-W3, one restore fallback, restore failing twice,
+privilege leak, world-writable `/dev/vfio/20`, chip lock taken right after the W1 reboot, D3 without ogd, stale
+unit. `tests/mutants-window.sh` deletes one safety step at a time and checks that a scenario fails. What it cannot
+show: real FLR and SBR behaviour, nvidia.ko reload after them, real boot timing.
+
+## Before posting WINDOW-READY
+
+Run `OGKM=<checkout> sh build.sh` and `sh window/d2-pre.sh`. The sha256 values on the W0 log lines are the ones quoted in the
+BOARD `WINDOW-READY` line. Any later edit to a hashed file changes those values, and W0 must be re-run.
diff --git a/window/aien-owndriver-window.service b/window/aien-owndriver-window.service
new file mode 100644
index 0000000..f880337
--- /dev/null
+++ b/window/aien-owndriver-window.service
@@ -0,0 +1,21 @@
+# Installed by window/d2-pre.sh --go (W1) as /etc/systemd/system/aien-owndriver-window.service and removed by
+# window/d2-restore.sh at the end of R. It exists only because a reboot ends every agent session on the Spark:
+# it carries the window across the two reboots without an operator. It runs window/d2-boot.sh once per boot,
+# which does nothing (and removes this unit) unless window/state says a step is pending. Status: NOT_RUN.
+[Unit]
+Description=aien OwnDriver window step after reboot (one-shot, removed at window close)
+After=multi-user.target network-online.target
+Wants=network-online.target
+
+[Service]
+Type=oneshot
+User=drakestapleton
+Environment=HOME=/home/drakestapleton
+WorkingDirectory=/home/drakestapleton/work/OwnDriver/omega-gpu-driver
+ExecStart=/bin/sh /home/drakestapleton/work/OwnDriver/omega-gpu-driver/window/d2-boot.sh
+# R starts the 35B from inside this unit: only the main process is stopped when the unit ends.
+KillMode=process
+TimeoutStartSec=3600
+
+[Install]
+WantedBy=multi-user.target
diff --git a/window/common.sh b/window/common.sh
new file mode 100644
index 0000000..9f1d5ad
--- /dev/null
+++ b/window/common.sh
@@ -0,0 +1,145 @@
+# window/common.sh -- shared settings for the OwnDriver window scripts. Sourced, never run.
+# Status: NOT_RUN on the GB10; window/README.md has the procedure. tests/window_sim.sh runs these exact
+# scripts against a simulated machine under /tmp (OWNDRIVER_WINDOW_ROOT, below).
+BDF=000f:01:00.0
+GRP=20
+FW=/lib/firmware/nvidia/580.173.02/gsp_ga10x.bin
+FW_SHA=32cb7cf3e77f97e92f6e92135939ccb3ba382748144569c0dfccf3338d43d963
+
+# ROOT is empty on the Spark. tests/window_sim.sh sets it to a simulated machine: every system path below
+# moves under it, and the commands that act on the machine must be that simulator's shims (checked here,
+# so a half-set-up simulation can never reach the real sudo, systemctl or the live 35B).
+ROOT=${OWNDRIVER_WINDOW_ROOT:-}
+if [ -n "$ROOT" ]; then
+	case $ROOT in /tmp/*) ;; *) echo "OWNDRIVER_WINDOW_ROOT must be under /tmp" >&2; exit 2 ;; esac
+	[ -e "$ROOT/.owndriver-window-sim" ] || { echo "$ROOT is not a window simulator root" >&2; exit 2; }
+	for c in sudo systemctl modprobe sysctl lsmod nvidia-smi pgrep curl tee stat fuser modinfo lsinitramfs spark-window; do
+		[ "$(command -v "$c")" = "$ROOT/bin/$c" ] || { echo "simulator: $c is not $ROOT/bin/$c" >&2; exit 2; }
+	done
+	HOMEDIR=$ROOT/home
+	Q36=$ROOT/q36
+	Q36_KEY=$ROOT/q36/KEY
+	BUILD=$ROOT/build
+else
+	HOMEDIR=/home/drakestapleton
+	Q36=/home/drakestapleton/.local/state/aien-q36
+	Q36_KEY=/home/drakestapleton/.local/state/aien-coordinator/KEY
+	BUILD=$R/build
+fi
+Q36_BIN=bin-19173f9e
+PCI=$ROOT/sys/bus/pci
+DEV=$PCI/devices/$BDF
+IOMMU=$ROOT/sys/kernel/iommu_groups
+VFIODEV=$ROOT/dev/vfio
+PROC=$ROOT/proc
+ETC=$ROOT/etc
+# Window files. Each exists only between W1 and R; privcheck fails if one persists.
+HOLD=$ETC/modprobe.d/zz-aien-owndriver-window.conf
+UNIT=$ETC/systemd/system/aien-owndriver-window.service
+LIVE_MARKER=$ROOT/tmp/aien-q36-live-down-for-tests
+GB10_LOCK=$ROOT/tmp/aien-gb10.lock
+BOARD=$HOMEDIR/handoffs/BOARD.md
+LOGDIR=$HOMEDIR/handoffs/OwnDriver/window
+# /tmp is emptied at every boot (tmpfiles "D /tmp"), so the approval and the state live with the logs.
+APPROVAL=$LOGDIR/APPROVED
+# STATE holds one line between reboots: "run D2|D3" (W2.. pending), "restore" (R pending). SAVED keeps the
+# sysctl values W2 changes; SNAP is the live 35B launch record W0 checks the restore recipe against;
+# RPATH holds "rebind" if W1 was asked for RESTORE_PATH=rebind; PRIVBASE is the privilege baseline (W0).
+STATE=$LOGDIR/state
+SAVED=$LOGDIR/saved-sysctl
+SNAP=$LOGDIR/live-35b.snapshot
+RPATH=$LOGDIR/restore-path
+PRIVBASE=$LOGDIR/priv-baseline
+mkdir -p "$LOGDIR"
+
+utc() { date -u +%Y-%m-%dT%H:%M:%SZ; }
+log() { echo "$(utc) $*" | tee -a "$LOG"; }
+board() { echo "$(utc) OwnDriver: $*" >> "$BOARD"; }
+die() { log "ABORT: $*"; exit 1; }
+# A character device on the Spark; the simulator cannot create device nodes and uses plain files.
+ischr() { if [ -n "$ROOT" ]; then [ -e "$1" ]; else [ -c "$1" ]; fi; }
+
+# The approval file (Main writes it when Drake opens the window) must carry these lines:
+#   window: <Drake's words / BOARD line ref>
+#   reset: approved      -- vfio-pci FLRs the GPU on open and bus-resets (SBR) root port 000f:00:00.0 on release
+#   reboot: approved     -- W1 and W7 reboot the Spark; every agent session on it ends
+need_approval() {
+	[ -s "$APPROVAL" ] || die "no $APPROVAL (Main writes it when Drake opens the window)"
+	grep -q '^window: ..*' "$APPROVAL" || die "$APPROVAL lacks a 'window: <Drake's words>' line"
+	grep -qx 'reset: approved' "$APPROVAL" || die "$APPROVAL lacks 'reset: approved' (VFIO bind/release resets the GPU)"
+	grep -qx 'reboot: approved' "$APPROVAL" || die "$APPROVAL lacks 'reboot: approved' (the window reboots the Spark twice)"
+	log "approval: $(grep '^window: ' "$APPROVAL" | head -1)"
+}
+
+# Every file that can grant device, root or memlock rights, with its sha256, plus the user's groups.
+privstate() {
+	for d in "$ETC/sudoers.d" "$ETC/udev/rules.d" "$ETC/security/limits.d" "$ETC/modprobe.d"; do
+		for f in "$d"/*; do
+			[ -e "$f" ] && echo "$(sudo -n sha256sum "$f" | cut -c1-64) $(stat -c '%U:%G:%a' "$f") $f"
+		done
+	done
+	echo "groups $(id -nG "$(id -un)" | tr ' ' '\n' | sort | tr '\n' ' ')"
+}
+
+# Privilege state outside the window. No udev rule, group, sudoers line, memlock limit or /dev/vfio
+# permission change is ever made: the window programs run as root through sudo -n instead. Fails closed
+# if the privilege files differ from the W0 baseline, or a window file (HOLD, UNIT) or a driver_override persists.
+privcheck() {
+	bad=0
+	for f in "$VFIODEV"/[0-9]*; do
+		[ -e "$f" ] || continue
+		m=$(stat -c '%U:%G:%a' "$f")
+		[ "$m" = root:root:600 ] || { log "PRIV: $f is $m, expected root:root:600"; bad=1; }
+	done
+	# Pre-existing files (e.g. /etc/sudoers.d/aien-local-ci, 2026-10-19, not this lane's) are compared against the
+	# baseline W0 records before the window opens: anything added, removed or changed since then fails.
+	privstate > "$PRIVBASE.now"
+	if [ -e "$PRIVBASE" ] && ! cmp -s "$PRIVBASE" "$PRIVBASE.now"; then
+		diff "$PRIVBASE" "$PRIVBASE.now" | sed 's/^/PRIV: /' | tee -a "${LOG:-/dev/null}"
+		bad=1
+	fi
+	for f in "$ETC"/udev/rules.d/*vfio* "$ETC"/security/limits.d/*memlock* "$HOLD" "$UNIT"; do
+		[ -e "$f" ] && { log "PRIV: $f exists"; bad=1; }
+	done
+	id -nG | tr ' ' '\n' | grep -qx vfio && { log "PRIV: $(id -un) is in group vfio"; bad=1; }
+	o=$(cat "$DEV/driver_override" 2>/dev/null || true)
+	[ -z "$o" ] || [ "$o" = "(null)" ] || { log "PRIV: driver_override=$o"; bad=1; }
+	return $bad
+}
+
+# The 35B serving process on 18091, if any (empty when down).
+live_pid() { pgrep -f -- '--port 18091' | head -1 || true; }
+
+# The restore recipe (d2-restore.sh R3) must equal how the live server was started. Prints the record:
+# argv, cwd and the env names it needs; the coordinator key is compared, never written.
+snap35b() {
+	p=$1
+	echo "argv $(tr '\0' ' ' < "$PROC/$p/cmdline")"
+	echo "cwd $(readlink "$PROC/$p/cwd")"
+	tr '\0' '\n' < "$PROC/$p/environ" | grep -E '^(Q36_BATCH_BIN|AIEN_Q36_STROKE|AIEN_SERVE_GPU_LOCK)=' | sort | sed 's/^/env /'
+	k=$(tr '\0' '\n' < "$PROC/$p/environ" | sed -n 's/^AIEN_COORD_KEY=//p')
+	if [ -n "$k" ] && [ "$k" = "$(cat "$Q36_KEY")" ]; then echo "env AIEN_COORD_KEY=<equals KEY>"; else echo "env AIEN_COORD_KEY=<MISMATCH>"; fi
+}
+snap_expected() {
+	echo "argv ./aien-serve-http --engine omega --model-dir /home/drakestapleton/models/qwen3.6-35b-a3b-fp8-95a723d0 --port 18091 --max-context 49152 --max-tokens-cap 16384 --thinking off --batch-slots 8 "
+	echo "cwd $Q36/$Q36_BIN"
+	echo "env AIEN_Q36_STROKE=1"
+	echo "env AIEN_SERVE_GPU_LOCK=/tmp/aien-serve-18091.lock"
+	echo "env Q36_BATCH_BIN=$Q36_BIN"
+	echo "env AIEN_COORD_KEY=<equals KEY>"
+}
+
+# Runtime PM on and active before any BAR0 access (arm64: a read of a D3 device is an external abort).
+pm_on() {
+	echo on | sudo -n tee "$DEV/power/control" >/dev/null
+	s=$(cat "$DEV/power/runtime_status")
+	[ "$s" = active ] || die "runtime_status=$s, not active"
+	log "power/control=on runtime_status=active"
+}
+pm_auto() { echo auto | sudo -n tee "$DEV/power/control" >/dev/null || true; }
+
+drv() { basename "$(readlink "$DEV/driver" 2>/dev/null || echo none)"; }
+nv_modules() { lsmod | grep -cE '^nvidia(_uvm|_modeset|_drm)? ' || true; }
+
+# Files whose sha256 W0 records and WINDOW-READY posts.
+HASHED="window/common.sh window/d2-pre.sh window/d2-boot.sh window/d2-run.sh window/d2-restore.sh window/aien-owndriver-window.service tools/omc.pin build/omc build/w0 build/ogd build/fw/fw.manifest"
diff --git a/window/d2-boot.sh b/window/d2-boot.sh
new file mode 100755
index 0000000..350e876
--- /dev/null
+++ b/window/d2-boot.sh
@@ -0,0 +1,21 @@
+#!/bin/sh
+# window/d2-boot.sh -- run once per boot by aien-owndriver-window.service. Status: NOT_RUN.
+#   state "run D2" / "run D3": the reboot from W1 has happened; run window/d2-run.sh --go STAGE.
+#   state "restore":           the reboot from W7 (or a fallback) has happened; run window/d2-restore.sh --go.
+#   no state:                  nothing pending: remove the unit (a leftover unit must never act twice).
+set -eu
+R=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
+. "$R/window/common.sh"
+LOG=$LOGDIR/d2-$(date -u +%Y%m%dT%H%M%SZ)-boot.log
+s=$(cat "$STATE" 2>/dev/null || true)
+log "boot unit: state '$s'"
+case $s in
+"run D2" | "run D3") exec sh "$R/window/d2-run.sh" --go "${s#run }" ;;
+restore) exec sh "$R/window/d2-restore.sh" --go ;;
+*)
+	sudo -n systemctl disable aien-owndriver-window.service >/dev/null 2>&1 || true
+	sudo -n rm -f "$UNIT"
+	sudo -n systemctl daemon-reload
+	log "no pending step: unit removed"
+	;;
+esac
diff --git a/window/d2-pre.sh b/window/d2-pre.sh
new file mode 100755
index 0000000..0516c9a
--- /dev/null
+++ b/window/d2-pre.sh
@@ -0,0 +1,158 @@
+#!/bin/sh
+# window/d2-pre.sh -- W0 and W1 of the OwnDriver window. Status: W0 EXERCISED read-only on the host; W1 NOT_RUN.
+#   no argument:     W0, read-only checks, safe while the 35B runs. Changes nothing except its own log.
+#   --go [D2|D3]:    W1, needs $APPROVAL. Stops the 35B on 18091, writes the one-boot nvidia hold-back file and the
+#                    boot unit, sets state "run D2" (default) or "run D3", reboots. The unit then runs W2.. by itself
+#                    (window/d2-run.sh), and after the second reboot R (window/d2-restore.sh).
+# Abort before the reboot: the window files are removed and window/d2-restore.sh restarts the 35B.
+set -eu
+R=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
+. "$R/window/common.sh"
+LOG=$LOGDIR/d2-$(date -u +%Y%m%dT%H%M%SZ)-pre.log
+GO=${1:-}
+STAGE=${2:-D2}
+
+log "W0 checks (repo $(git -C "$R" rev-parse HEAD 2>/dev/null || echo no-git), dirty files: $(git -C "$R" status --porcelain 2>/dev/null | wc -l))"
+echo "$FW_SHA  $FW" | sha256sum -c --quiet || die "firmware sha256 mismatch"
+log "firmware $FW sha256 ok"
+for f in $HASHED; do
+	if [ -e "$R/$f" ]; then log "sha256 $(sha256sum "$R/$f" | cut -c1-64) $f"; else log "missing $f"; fi
+done
+omc_pin=$(sed -n 's/^OMC_SHA256=//p' "$R/tools/omc.pin")
+[ "$(sha256sum "$R/build/omc" | cut -c1-64)" = "$omc_pin" ] || die "build/omc does not match tools/omc.pin"
+[ -x "$BUILD/w0" ] || die "build/w0 missing: run sh build.sh"
+if [ -e "$BUILD/fw/fw.manifest" ]; then
+	# fwprep writes fw.manifest last, with one 'out NAME bytes=N sha256=H' line per output file.
+	fwsha=$(sha256sum "$FW" | cut -c1-64)
+	grep -q "^fw_file bytes=[0-9]* sha256=$fwsha\$" "$BUILD/fw/fw.manifest" ||
+		die "build/fw/fw.manifest was made from a different firmware file: rerun sh build.sh"
+	sed -n 's/^out \([a-z.]*\) bytes=[0-9]* sha256=\([0-9a-f]\{64\}\)$/\2  \1/p' "$BUILD/fw/fw.manifest" > "$LOGDIR/fw.check"
+	[ "$(wc -l < "$LOGDIR/fw.check")" = 5 ] && grep -qx end "$BUILD/fw/fw.manifest" ||
+		die "build/fw/fw.manifest is incomplete: rerun sh build.sh"
+	(cd "$BUILD/fw" && sha256sum -c --quiet "$LOGDIR/fw.check") ||
+		die "build/fw files do not match build/fw/fw.manifest: rerun sh build.sh"
+	rm -f "$LOGDIR/fw.check"
+	log "build/fw matches fw.manifest"
+fi
+if [ -x "$BUILD/ogd" ]; then
+	log "ogd modes: $("$BUILD/ogd" modes | tr '\n' ' ')"
+fi
+[ "$(cat "$DEV/vendor"):$(cat "$DEV/device")" = 0x10de:0x2e12 ] || die "$BDF is not 10de:2e12"
+[ "$(basename "$(readlink "$DEV/iommu_group")")" = "$GRP" ] || die "iommu group is not $GRP"
+[ "$(ls "$IOMMU/$GRP/devices")" = "$BDF" ] || die "group $GRP is not $BDF alone"
+log "device $(cat "$DEV/vendor"):$(cat "$DEV/device") driver=$(drv) reset_method=$(cat "$DEV/reset_method") power=$(cat "$DEV/power/control")/$(cat "$DEV/power/runtime_status")"
+log "modules: $(lsmod | awk '/^nvidia/{printf "%s(%s) ", $1, $3}')"
+log "cmdline: $(cat /proc/cmdline)"
+log "sysctl: kernel.panic=$(sysctl -n kernel.panic) kernel.panic_on_oops=$(sysctl -n kernel.panic_on_oops)"
+for f in "$HOLD" "$UNIT" "$STATE"; do
+	[ ! -e "$f" ] || die "$f already exists (an earlier window did not finish): run window/d2-restore.sh --go"
+done
+# No window is open (checked above), so the current privilege state is the baseline R4 must return to.
+if [ -e "$PRIVBASE" ]; then
+	privstate | diff "$PRIVBASE" - | sed 's/^/baseline change since last W0: /' | tee -a "$LOG" || true
+fi
+privstate > "$PRIVBASE"
+log "privilege baseline: $(wc -l < "$PRIVBASE") entries in $PRIVBASE (sha256 $(sha256sum "$PRIVBASE" | cut -c1-64))"
+privcheck || die "privilege state not clean before the window (see PRIV lines)"
+log "privilege state clean: /dev/vfio groups root 0600, no vfio udev/memlock file, user not in group vfio, no driver_override, no window files"
+# nvgrace-gpu-vfio-pci (the upstream variant for Grace C2C GPUs) must not claim this device: plain vfio-pci.
+if modinfo nvgrace-gpu-vfio-pci 2>/dev/null | grep -qi 'd00002E12'; then
+	die "nvgrace-gpu-vfio-pci now lists 2E12: re-decide variant vs plain vfio-pci before binding"
+fi
+log "nvgrace-gpu-vfio-pci aliases ($(modinfo nvgrace-gpu-vfio-pci 2>/dev/null | grep -c '^alias')) do not list 10de:2e12: plain vfio-pci"
+if lsinitramfs "/boot/initrd.img-$(uname -r)" | grep -Eq '/nvidia(_uvm|_modeset|_drm)?\.ko'; then
+	die "initramfs carries nvidia.ko: a modprobe.d hold-back would not be enough"
+fi
+log "initramfs has no nvidia/nvidia_uvm/nvidia_modeset/nvidia_drm"
+modinfo -n vfio-pci >/dev/null 2>&1 || die "vfio-pci module not available"
+p=$(live_pid)
+if [ -n "$p" ]; then
+	snap35b "$p" > "$SNAP.now"
+	snap_expected > "$SNAP.want"
+	if cmp -s "$SNAP.now" "$SNAP.want"; then
+		mv "$SNAP.now" "$SNAP"; rm -f "$SNAP.want"
+		log "35B pid $p: launch record equals the restore recipe ($SNAP)"
+	else
+		diff "$SNAP.want" "$SNAP.now" | tee -a "$LOG" || true
+		die "the live 35B was not started the way d2-restore.sh restarts it: update snap_expected and R3 first"
+	fi
+else
+	log "35B not running (restore will start it from the recipe)"
+fi
+log "GPU device users: $(sudo -n fuser "$ROOT"/dev/nvidia* 2>/dev/null | tr -s ' ' | tr ' ' '\n' | sort -u | while read -r q; do [ -n "$q" ] && printf '%s(%s) ' "$q" "$(cat "$PROC/$q/comm" 2>/dev/null)"; done)"
+log "chip lock (read from the kernel lock table, not taken): $(spark-window locks gb10 2>&1 | head -2 | tr '\n' ' ')"
+
+if [ "$GO" != --go ]; then
+	log "W0 PASS (checks only; nothing changed)"
+	exit 0
+fi
+
+# W1 --------------------------------------------------------------------------
+case $STAGE in D2 | D3) ;; *) die "stage must be D2 or D3" ;; esac
+need_approval
+# build/ogd is optional: without it the window runs W2, W3 (build/w0), W7 and R, and logs the driver steps NOT_RUN.
+[ "$STAGE" = D2 ] || [ -x "$BUILD/ogd" ] || die "D3 needs build/ogd with an 'exec' mode"
+case ${RESTORE_PATH:-reboot} in
+reboot) rm -f "$RPATH" ;;
+rebind) echo rebind > "$RPATH" ;;
+*) die "RESTORE_PATH must be reboot or rebind" ;;
+esac
+log "restore path after W7: ${RESTORE_PATH:-reboot}"
+if [ "$STAGE" = D3 ]; then
+	[ -n "${D3_CMD:-}" ] || die "D3 needs D3_CMD: the CUDApp gate command line (window/README.md, D3)"
+	printf '%s\n' "$D3_CMD" > "$LOGDIR/d3-cmd"
+	log "D3 command: $D3_CMD"
+fi
+# The chip lock: no other GPU job may be running; it is held until the reboot ends this process.
+exec 9>>"$GB10_LOCK"
+flock -n 9 || die "$GB10_LOCK is held by another GPU job: wait for it"
+abort_w1() {
+	rc=$?
+	trap - EXIT
+	[ "$rc" -eq 0 ] && return
+	sudo -n systemctl disable aien-owndriver-window.service >/dev/null 2>&1 || true
+	sudo -n rm -f "$HOLD" "$UNIT"
+	sudo -n systemctl daemon-reload || true
+	echo restore > "$STATE"
+	log "W1 aborted before reboot (rc=$rc); window files removed; restoring the 35B"
+	sh "$R/window/d2-restore.sh" --go || true
+}
+trap 'abort_w1' EXIT
+
+touch "$LIVE_MARKER"
+board "WINDOW OPEN $STAGE (own driver): stopping 18091, reboot with nvidia held back; every agent session on the Spark ends at the reboot. Log $LOG"
+p=$(live_pid)
+if [ -n "$p" ]; then
+	log "TERM 35B pid $p"
+	kill -TERM "$p"
+fi
+i=0
+while [ -n "$(live_pid)" ] || [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader)" ]; do
+	i=$((i + 1)); [ "$i" -le 60 ] || die "the 35B or another compute app is still on the GPU after 60 s"
+	sleep 1
+done
+log "no compute apps on the GPU"
+printf 'kernel.panic=%s\nkernel.panic_on_oops=%s\n' "$(sysctl -n kernel.panic)" "$(sysctl -n kernel.panic_on_oops)" > "$SAVED"
+sudo -n tee "$HOLD" >/dev/null <<'EOF'
+# aien OwnDriver window: hold the nvidia modules back for ONE boot.
+# window/d2-run.sh deletes this file first thing after the reboot; if it is still here, delete it and reboot.
+blacklist nvidia
+blacklist nvidia_uvm
+blacklist nvidia_modeset
+blacklist nvidia_drm
+install nvidia /bin/false
+install nvidia_uvm /bin/false
+install nvidia_modeset /bin/false
+install nvidia_drm /bin/false
+EOF
+sudo -n cp "$R/window/aien-owndriver-window.service" "$UNIT"
+sudo -n chmod 0644 "$UNIT"
+sudo -n systemctl daemon-reload
+sudo -n systemctl enable aien-owndriver-window.service
+echo "run $STAGE" > "$STATE"
+log "wrote $HOLD, installed and enabled $UNIT, state 'run $STAGE'"
+trap - EXIT
+board "$STAGE W1: rebooting with nvidia held back; the boot unit runs window/d2-run.sh, then R after the next reboot"
+sync
+log "reboot"
+sudo -n systemctl reboot
diff --git a/window/d2-restore.sh b/window/d2-restore.sh
new file mode 100755
index 0000000..6317834
--- /dev/null
+++ b/window/d2-restore.sh
@@ -0,0 +1,98 @@
+#!/bin/sh
+# window/d2-restore.sh --go -- R: bring the resident 35B back on 18091 under nvidia.ko and remove every window
+# file. Status: NOT_RUN. Runs from the boot unit after the reboot that W7 ends with, directly from W7
+# (RESTORE_PATH=rebind), or from the W1 abort path. Safe to run again: each part checks before it acts.
+#   R0 hold-back file still present: remove it and reboot (the unit runs R again)
+#   R1 nvidia.ko back: unbind vfio-pci, clear driver_override, modprobe, bind, nvidia-smi lists the GB10.
+#      Whether nvidia.ko re-initialises GSP after the FLR/bus reset of the vfio-pci release is NOT_RUN on this
+#      chip, so any failure takes the reboot fallback once (state stays "restore", the unit runs R again).
+#   R2 nvidia-persistenced running; kernel.panic / panic_on_oops back to the values W1 saved
+#   R3 the 35B restarted exactly as it was started (W0 checked window/live-35b.snapshot against this recipe),
+#      /v1/models lists qwen, one greedy chat, exactly one aien-serve-http on the GPU
+#   R4 boot unit removed, privilege state clean, markers removed, BOARD line
+set -eu
+R=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
+. "$R/window/common.sh"
+LOG=$LOGDIR/d2-$(date -u +%Y%m%dT%H%M%SZ)-restore.log
+[ "${1:-}" = --go ] || { echo "usage: $0 --go"; exit 2; }
+echo restore > "$STATE"
+# Any refusal leaves state "restore" and the unit in place (the next boot tries R again) and says so on BOARD.
+trap 'rc=$?; [ "$rc" -eq 0 ] || board "restore STOPPED rc=$rc, 18091 may be down, log $LOG (page Main; next boot retries R)"' EXIT
+
+# R0 -------------------------------------------------------------------------
+if [ -e "$HOLD" ]; then
+	sudo -n rm -f "$HOLD"
+	log "R0 hold-back file was still present: removed; rebooting; the boot unit runs R again"
+	board "restore: hold-back file was still present, removed, rebooting"
+	sync
+	sudo -n systemctl reboot
+	exit 0
+fi
+
+# R1 -------------------------------------------------------------------------
+FALLBACK=$LOGDIR/reboot-fallback-used
+fallback() {
+	if [ -e "$FALLBACK" ]; then
+		board "restore FAILED after the reboot fallback: $* (page Main and Drake; GPU state unknown; log $LOG)"
+		die "$* after the reboot fallback already ran"
+	fi
+	date -u > "$FALLBACK"
+	log "R1 reboot fallback: $*; the boot unit runs R again after the reboot"
+	board "restore: $*; reboot fallback, then R again from the boot unit"
+	sync
+	sudo -n systemctl reboot
+	exit 0
+}
+if [ "$(drv)" = vfio-pci ]; then echo "$BDF" | sudo -n tee "$PCI/drivers/vfio-pci/unbind" >/dev/null || true; fi
+echo | sudo -n tee "$DEV/driver_override" >/dev/null || true
+if [ "$(nv_modules)" -ne 4 ]; then
+	log "R1 nvidia modules loaded: $(nv_modules) of 4; modprobe nvidia_uvm nvidia_drm"
+	timeout 180 sudo -n modprobe nvidia_uvm || fallback "modprobe nvidia_uvm failed"
+	timeout 180 sudo -n modprobe nvidia_drm || fallback "modprobe nvidia_drm failed"
+	[ "$(nv_modules)" -eq 4 ] || fallback "nvidia modules: $(nv_modules) of 4"
+fi
+if [ "$(drv)" != nvidia ]; then
+	echo "$BDF" | sudo -n tee "$PCI/drivers_probe" >/dev/null || true
+fi
+[ "$(drv)" = nvidia ] || fallback "$BDF driver is $(drv), not nvidia"
+timeout 120 nvidia-smi -L | tee -a "$LOG" | grep -q GB10 || fallback "nvidia-smi does not list the GB10"
+log "R1 PASS: nvidia.ko back, 4 modules, driver bound, nvidia-smi lists the GB10"
+
+# R2 -------------------------------------------------------------------------
+systemctl is-active --quiet nvidia-persistenced || sudo -n systemctl start nvidia-persistenced || log "R2 nvidia-persistenced did not start"
+if [ -s "$SAVED" ]; then
+	sudo -n sysctl -q -p "$SAVED" || die "could not restore sysctl from $SAVED"
+fi
+log "R2 persistenced $(systemctl is-active nvidia-persistenced); kernel.panic=$(sysctl -n kernel.panic) panic_on_oops=$(sysctl -n kernel.panic_on_oops)"
+
+# R3 -------------------------------------------------------------------------
+if [ -z "$(live_pid)" ]; then
+	K=$(cat "$Q36_KEY")
+	Q36_BATCH_BIN=$Q36_BIN AIEN_Q36_STROKE=1 AIEN_SERVE_GPU_LOCK=/tmp/aien-serve-18091.lock AIEN_COORD_KEY="$K" \
+		"$Q36/start-35b-batch.sh" | tee -a "$LOG"
+fi
+i=0
+until curl -fsS --max-time 5 http://127.0.0.1:18091/v1/models 2>/dev/null | grep -qi qwen; do
+	i=$((i + 5)); [ "$i" -le 900 ] || { board "restore: 18091 did not come up in 900 s (page Main; $Q36/serve.log)"; die "18091 did not list qwen within 900 s"; }
+	sleep 5
+done
+log "R3 18091 /v1/models lists qwen after ~${i} s"
+out=$(curl -fsS --max-time 120 http://127.0.0.1:18091/v1/chat/completions -H 'Content-Type: application/json' \
+	-d '{"messages":[{"role":"user","content":"Reply with the single word: ready"}],"max_tokens":8,"temperature":0}') ||
+	die "greedy chat failed"
+log "R3 greedy chat: $out"
+p=$(live_pid)
+snap35b "$p" > "$SNAP.restored"
+snap_expected | cmp -s - "$SNAP.restored" || log "R3 WARNING: restarted 35B launch record differs from the recipe (see $SNAP.restored)"
+apps=$(nvidia-smi --query-compute-apps=process_name,used_memory --format=csv,noheader)
+log "R3 compute apps: $apps"
+[ "$(printf '%s\n' "$apps" | grep -c aien-serve-http)" -eq 1 ] || die "expected exactly one aien-serve-http on the GPU"
+
+# R4 -------------------------------------------------------------------------
+sudo -n systemctl disable aien-owndriver-window.service >/dev/null 2>&1 || true
+sudo -n rm -f "$UNIT"
+sudo -n systemctl daemon-reload
+privcheck || { board "PRIVILEGE PERSISTED after the window, see $LOG (page Main)"; die "privilege state not clean"; }
+rm -f "$LIVE_MARKER" "$APPROVAL" "$FALLBACK" "$SAVED" "$RPATH" "$LOGDIR/d3-cmd" "$STATE"
+board "WINDOW CLOSED (own driver), 18091 restored ($(printf '%s' "$apps" | tr '\n' ' ')). Log $LOG"
+log "R PASS"
diff --git a/window/d2-run.sh b/window/d2-run.sh
new file mode 100755
index 0000000..4a38611
--- /dev/null
+++ b/window/d2-run.sh
@@ -0,0 +1,103 @@
+#!/bin/sh
+# window/d2-run.sh --go D2|D3 -- W2..W7, run by the boot unit after the reboot that d2-pre.sh --go started.
+# Status: NOT_RUN.
+#   W2 state "restore" and remove the hold-back file FIRST (any later reboot is a normal one that ends in R),
+#      check no nvidia module, kernel.panic=10 + panic_on_oops=1 (an oops reboots into R), bind vfio-pci
+#   W3 runtime PM on and active, build/w0 (config identity, BOOT_0/BOOT_1/BOOT_42, read-only), build/ogd ident
+#   D2: W4 build/ogd boot   (GSP boot through SEC2 to INIT_DONE, static info, unload)
+#       W5 build/ogd hello  (objects, channel, one semaphore release, teardown)
+#   D3: W6 build/ogd exec -- <CUDApp gate>   (needs ogd 'exec' and CUDApp's aien provider; NOT_RUN without them)
+#   Each driver step runs only if build/ogd lists it under 'modes'; otherwise it is logged NOT_RUN.
+#   W7 unbind vfio-pci (releasing the device SBRs root port 000f:00:00.0, which resets the GPU), clear
+#      driver_override, power/control=auto,
+#      then by default reboot (the boot unit runs R), or, if W1 was given RESTORE_PATH=rebind (window/restore-path),
+#      run window/d2-restore.sh --go now (modprobe nvidia, bind; reboot fallback once).
+# Any failure: the EXIT trap does W7. No privilege is granted: /dev/vfio/$GRP stays root 0600 and the
+# driver programs run as root through sudo -n.
+set -eu
+R=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
+. "$R/window/common.sh"
+LOG=$LOGDIR/d2-$(date -u +%Y%m%dT%H%M%SZ)-run.log
+[ "${1:-}" = --go ] || { echo "usage: $0 --go D2|D3 (window only)"; exit 2; }
+STAGE=${2:-}
+case $STAGE in D2 | D3) ;; *) echo "usage: $0 --go D2|D3"; exit 2 ;; esac
+
+# W2 -------------------------------------------------------------------------
+release() {
+	rc=$?
+	trap - EXIT
+	log "W7 release (rc=$rc)"
+	if [ "$(drv)" = vfio-pci ]; then echo "$BDF" | sudo -n tee "$PCI/drivers/vfio-pci/unbind" >/dev/null || true; fi
+	echo | sudo -n tee "$DEV/driver_override" >/dev/null || true
+	pm_auto
+	log "W7 driver=$(drv) override='$(cat "$DEV/driver_override")' power=$(cat "$DEV/power/control")"
+	if [ "$(cat "$RPATH" 2>/dev/null || true)" = rebind ]; then
+		board "$STAGE run ended rc=$rc, log $LOG; restoring by rebind (reboot fallback inside d2-restore)"
+		exec sh "$R/window/d2-restore.sh" --go
+	fi
+	board "$STAGE run ended rc=$rc, log $LOG; rebooting into the normal nvidia boot; the boot unit runs R"
+	sync
+	sudo -n systemctl reboot
+}
+# From here on every exit, including a refusal below, goes through W7 and ends in R.
+echo restore > "$STATE"
+trap release EXIT
+sudo -n rm -f "$HOLD"
+[ ! -e "$HOLD" ] && log "W2 ($STAGE) state 'restore'; hold-back removed: the next boot loads nvidia again and runs R" ||
+	die "could not remove $HOLD (R0 removes it after the reboot)"
+need_approval
+exec 9>>"$GB10_LOCK"
+flock -n 9 || die "$GB10_LOCK is held: something started a GPU job after the reboot"
+if [ "$(nv_modules)" -ne 0 ]; then die "nvidia is loaded: the hold-back did not take"; fi
+
+
+sudo -n sysctl -q kernel.panic=10 kernel.panic_on_oops=1
+log "kernel.panic=10 panic_on_oops=1 (saved values in $SAVED, R puts them back)"
+# Run one driver program, keep its output in the log, fail the window step on its exit code.
+run_logged() {
+	o=$("$@" 2>&1) && rc=0 || rc=$?
+	printf '%s\n' "$o" | tee -a "$LOG"
+	[ "$rc" -eq 0 ] || die "$* exit $rc"
+}
+has_mode() { [ -x "$BUILD/ogd" ] && "$BUILD/ogd" modes 2>/dev/null | grep -qx "$1"; }
+
+sudo -n modprobe vfio-pci
+ischr "$VFIODEV/vfio" || die "/dev/vfio/vfio missing"
+echo vfio-pci | sudo -n tee "$DEV/driver_override" >/dev/null
+echo "$BDF" | sudo -n tee "$PCI/drivers_probe" >/dev/null
+[ "$(drv)" = vfio-pci ] || die "driver is $(drv), not vfio-pci"
+ischr "$VFIODEV/$GRP" || die "/dev/vfio/$GRP missing"
+m=$(stat -c '%U:%G:%a' "$VFIODEV/$GRP")
+[ "$m" = root:root:600 ] || die "/dev/vfio/$GRP is $m, expected root:root:600"
+log "W2 PASS: $BDF on vfio-pci, /dev/vfio/$GRP root:root:600 (programs run as root via sudo -n)"
+
+# W3 -------------------------------------------------------------------------
+pm_on
+run_logged sudo -n "$BUILD/w0" "$BDF" "$GRP"
+if has_mode ident; then
+	pm_on
+	run_logged sudo -n "$BUILD/ogd" ident "$BDF" "$GRP" "$FW" "$BUILD/fw"
+fi
+log "W3 PASS: identity read (BOOT_42 above settles the chip id)"
+
+# W4..W6 ----------------------------------------------------------------------
+if [ "$STAGE" = D2 ]; then steps="boot hello"; else steps="exec"; fi
+for step in $steps; do
+	if ! has_mode "$step"; then
+		log "W-$step NOT_RUN: build/ogd has no '$step' mode"
+		continue
+	fi
+	pm_on
+	log "W-$step start"
+	if [ "$step" = exec ]; then
+		D3_CMD=$(cat "$LOGDIR/d3-cmd" 2>/dev/null || true)
+		[ -n "$D3_CMD" ] || die "D3 needs $LOGDIR/d3-cmd (the CUDApp gate command line, written by d2-pre.sh --go D3)"
+		# shellcheck disable=SC2086
+		run_logged sudo -n "$BUILD/ogd" exec "$BDF" "$GRP" "$FW" "$BUILD/fw" -- $D3_CMD
+	else
+		run_logged sudo -n "$BUILD/ogd" "$step" "$BDF" "$GRP" "$FW" "$BUILD/fw"
+	fi
+	log "W-$step PASS"
+done
+log "W7 release"
+# the EXIT trap does W7