interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

GitHub aien-dev/aienux#320 (code only)

closed derived 9fd6c888ee0e9d0e #320

Imported from GitHub aien-dev/aienux#320 (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 4448a508c04d8d6fe459884ad2f01379fe8caf31 · Head eab1c167db84287a45dc06bf5646520a5db1c026

Apply it

git checkout -b patch-9fd6c888ee0e9d0e 4448a508c04d8d6fe459884ad2f01379fe8caf31
curl -fsSL https://interplane.io/drakestapleton/aienux/patches/9fd6c888ee0e9d0e.patch | git am

Raw patch (mbox) · 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/aienux
320
eab1c167db84287a45dc06bf5646520a5db1c026
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":320,"url":"https://github.com/aien-dev/aienux/pull/320","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:12Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/.crumb b/.crumb
index 1e13cc87..13b65978 100644
--- a/.crumb
+++ b/.crumb
@@ -27,33 +27,33 @@
           "purpose": "Directory crates. Purpose not yet described by a human."
         },
         {
-          "digest": "67c7dafea9dd11fce8a30e2758fc9c0553d5e75c442bc6c2c22f134a090a5008",
-          "last_commit": "e09825a",
+          "digest": "b1b6101be716c9f1ca0a55e0ce904127f1ddce05d251e97d00399b049249c96b",
+          "last_commit": "0711ee0",
           "name": "docs",
           "purpose": "Directory docs. Purpose not yet described by a human."
         },
         {
-          "digest": "00b3df5ff408cf07d222d4ebd836026a58a12532ff116b765594246a09a901bc",
-          "last_commit": "e09825a",
+          "digest": "91bcbb8a7af535f438701fa1a4a8bd630370f1a7da25ad5ded775a3d0969dad6",
+          "last_commit": "0711ee0",
           "name": "native",
           "purpose": "Directory native. Purpose not yet described by a human."
         },
         {
           "digest": "348804e26984e873db9914d2a3ebfcf6c9ea02619247d78809999011b354e048",
-          "last_commit": "e09825a",
+          "last_commit": "eb70ba8",
           "name": "scripts",
           "purpose": "Directory scripts. Purpose not yet described by a human."
         }
       ],
-      "children_root": "sha256:5e6b18b2f6fa0f85281593d5f46a2a039850a7a3bca50f3f06ad88dc557626f9",
-      "compiled_at": "2026-10-12T12:21:27Z",
+      "children_root": "sha256:2702b75a866f8718154bfee4fdb0dd15f7cd894315f845f96423c1da00d7d9d2",
+      "compiled_at": "2026-10-12T13:00:09Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:815433c9c8cef1effe798105427e5d1f18af2014f0d2265838d91ac870214cf6",
+      "digest": "sha256:a5226d112dfbcf74ab90d1fbb2772b7090bf440c2e852f97a1f356ae7e21b4fa",
       "evidence_files": 155,
       "evidence_root": "sha256:d59c0cef4e7dd5172923754a95b411ca54b01f35baca4587f792f1b259f1eaf7",
-      "files": 3091,
-      "generated_at_commit": "e09825afddde294659ca4a06354990e7ff530b62",
-      "source_tree": "sha256:6ffa7e6c4e272b46b100fa2f8b698c7d25588870c03b2f320d513ae2297e926a"
+      "files": 3093,
+      "generated_at_commit": "0711ee05e49b9837d8c3dc55a5980582a4c37e4e",
+      "source_tree": "sha256:7f985394190d56c2cda0bd80c2757b895ebc04d33f94b074d9e0b83daf65610d"
     },
     "owner_lane": "",
     "provenance": {
diff --git a/docs/.crumb b/docs/.crumb
index 9a9abe12..5e4df806 100644
--- a/docs/.crumb
+++ b/docs/.crumb
@@ -30,14 +30,14 @@
         }
       ],
       "children_root": "sha256:baea130f2c52779b57d90139beb66ac01b21ab499d113471a334be5500f3e369",
-      "compiled_at": "2026-10-12T12:21:27Z",
+      "compiled_at": "2026-10-12T13:00:09Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:67c7dafea9dd11fce8a30e2758fc9c0553d5e75c442bc6c2c22f134a090a5008",
+      "digest": "sha256:b1b6101be716c9f1ca0a55e0ce904127f1ddce05d251e97d00399b049249c96b",
       "evidence_files": 0,
       "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
       "files": 70,
-      "generated_at_commit": "e09825afddde294659ca4a06354990e7ff530b62",
-      "source_tree": "sha256:479955d7d585b02e7323f4dbdbab0ac2ad395207ce4475eb4138b985ba7cb9ad"
+      "generated_at_commit": "0711ee05e49b9837d8c3dc55a5980582a4c37e4e",
+      "source_tree": "sha256:65a766bd092243b4518fe62af668ea51375b08cf80513f0c33e330ececf086ca"
     },
     "owner_lane": "",
     "provenance": {
diff --git a/docs/GB10_FIRMWARE_INVENTORY.md b/docs/GB10_FIRMWARE_INVENTORY.md
index 370d15fe..fc9dcd55 100644
--- a/docs/GB10_FIRMWARE_INVENTORY.md
+++ b/docs/GB10_FIRMWARE_INVENTORY.md
@@ -40,10 +40,19 @@ the driver on the box; fetched read-only into a scratch directory, not vendored)
   SEC2 (section 10), and `ck_gsp_bindata_extract` reads the eight GB10B
   firmware arrays out of the public driver source with our own inflater and
   hash code, cross-checks every size, record and digest, and writes them as
-  files (section 11). `make -C native/kernel test` runs all three self-tests.
+  files (section 11). A fourth, `ck_gsp_boot_args_encode`, builds and checks
+  the five memory blocks the driver hands to the GSP-RM boot (the 256-byte
+  WPR description, the libos argument page, the log-buffer tables, the
+  message-queue arguments and the three-level page table for the 75 MB
+  firmware), with the GB10B values traced line by line from the driver
+  (section 12). A fifth, `ck_gsp_rpc_encode`, builds and checks the message
+  queue itself: the two ring-buffer headers, one queue message with its
+  checksum and sequence numbers, the split of oversize messages, and the
+  packed settings table the driver sends first (section 13). `make -C
+  native/kernel test` runs all five self-tests.
 - The largest remaining unknowns for a native bring-up (section 8) are the
   SEC2 command protocol details beyond what the driver source shows, the
-  exact GspFwWprMeta/boot-argument layout expected by this GSP-FMC build, and
+  message-queue (RPC) protocol after the FMC starts GSP-RM, and
   the state the SoC firmware (UEFI) leaves SEC2 and the GPU in at AIENOS entry.
   Do not attach a calendar to cut C/D until those are measured on the machine.
 
@@ -296,8 +305,16 @@ code into AIENOS would require carrying the MIT notice (none was copied here).
   SHA-384, `make -C native/kernel gsp-bindata-test`; (b) DONE 2026-10-12: the encoder, decoder
   and refusal tests for `NVDM_PAYLOAD_COT`, the MCTP/NVDM headers, the EMEM
   packet and `GSP_FMC_BOOT_PARAMS` are `ck_gsp_cot_encode` (section 10);
-  (c) remaining: an encoder for `GspFwWprMeta` (256 bytes, layout known, the
-  GH100 populate values not yet traced) and the libos init-argument block.
+  (c) DONE 2026-10-12: `ck_gsp_boot_args_encode` (section 12) encodes,
+  decodes and refuses `GspFwWprMeta`, the libos init-argument page, the
+  log-buffer PTE prefix, `GSP_ARGUMENTS_CACHED`, the RPC shared-buffer page
+  table and the radix-3 ELF table with the GB10B populate values traced;
+  (d) DONE on the host side 2026-10-12: `ck_gsp_rpc_encode` encodes, decodes
+  and refuses the queue headers, queue elements, RPC headers, continuation
+  records and the packed registry table (section 13). What remains for item
+  4 of section 8 is the content of `GspSystemInfo` and the list of RPCs a
+  native kernel must issue after `GSP_INIT_DONE`, both of which need the real
+  device.
 - The machine-side part of cut C (first SEC2 command, FMC boot, GSP-RM init
   done) is an attended-window item under the P08 rules: documented cold power
   state, no prior Linux GPU initialization, camera, abort rule, and the
@@ -308,22 +325,33 @@ code into AIENOS would require carrying the MIT notice (none was copied here).
 1. RESOLVED 2026-10-12 [SOURCE]: the `NVDM_PAYLOAD_COT` layout is 860 packed
    bytes, GB10B uses version 1, signature and key sizes 384, hash 48; the
    whole wire format is in section 10 and checked by `ck_gsp_cot_encode`.
-2. [PARTLY RESOLVED 2026-10-12] `GSP_FMC_BOOT_PARAMS` (88 bytes, section 10)
-   and the `GspFwWprMeta` struct (256 bytes, `gsp/gsp_fw_wpr_meta.h`, magic
-   `0xdc3aae21371a60b3`, revision 1; GB10B zeroes `vgaWorkspaceSize`,
-   `pmuReservedSize` and `nonWprHeapSize`, kernel_gsp_gb10b.c:32-55) are
-   known. [UNKNOWN] the values `kgspPopulateWprMeta_GH100` computes (radix3
-   ELF placement, heap sizes, WPR carveout) and the libos init-argument block
-   (`gsp_init_args.h` gives `GSP_ARGUMENTS_CACHED`; the libos block itself not
-   traced).
+2. RESOLVED on the host side 2026-10-12 [SOURCE]: `GSP_FMC_BOOT_PARAMS`
+   (section 10), `GspFwWprMeta` with every value `kgspPopulateWprMeta_GH100`
+   and `_GB10B` fill (heap 133 MiB, bootloader 196,608 bytes at descriptor
+   offsets 0xb000/0xa00/0x0, frts 0, nonWprHeap 0, FB layout left to the
+   FMC), the libos init-argument page (seven logs then RMARGS), the
+   log-buffer PTE prefix, `GSP_ARGUMENTS_CACHED` (message-queue offsets,
+   512 MiB sysmem heap on ZERO_FB) and the radix-3 ELF table are in section
+   12 and checked by `ck_gsp_boot_args_encode`. [INFERRED (medium)] that the
+   GSP-FMC accepts these exact values without Linux present: only the chip
+   can confirm that.
 3. [UNKNOWN] What SEC2 requires to be already true when the first command
    arrives (its own firmware loaded by the SoC boot chain? clocks? power
    state?), and whether UEFI leaves the GPU in that state at AIENOS entry.
    On Linux the driver finds "GFW_BOOT" complete before it starts
    (`kgspWaitForGfwBootOk_HAL`); who completes it without Linux is not shown.
-4. [UNKNOWN] The message-queue (RPC) format and the init sequence after
-   `RmInitDone`; the native kernel needs only a subset (device init, memory
-   mapping, channel, submit) but which RPCs are mandatory is not established.
+4. RESOLVED on the host side 2026-10-12 [SOURCE] for the transport: the queue
+   headers, element format, checksum, sequence rules, continuation records,
+   the init handshake (`GSP_INIT_DONE` 0x1001 with sequence 0 and result
+   NV_OK) and the two RPCs queued before boot (`GSP_SET_SYSTEM_INFO` 72,
+   `SET_REGISTRY` 73) are byte-exact in section 13 and `ck_gsp_rpc_encode`.
+   `GspSystemInfo` is 936 bytes (RPC length 968) under the natural layout
+   [INFERRED (high): struct text copied from the pinned headers and compiled;
+   no pack pragma]. Still [UNKNOWN]: the exact `GspSystemInfo` contents a
+   native kernel must send (they come from the real PCI/BAR/ACPI state), and
+   which RPCs after init are mandatory for device init, memory mapping,
+   channel and submit; the native kernel needs only a subset but it is not
+   established.
 5. [UNKNOWN] Whether the confidential-computing (`_cc_`) sections or the SPDM
    session are ever required on this platform. Assumed not [INFERRED (high)].
 6. [RESOLVED on the host side 2026-10-12, SOURCE; consumer side INFERRED
@@ -363,8 +391,31 @@ nouveau/extract-firmware-nouveau.py (lines 82-114 only), kernel_gsp_gh100.c
 (`kgspBootstrap_GH100`, `_kgspLockdownReleasedOrFmcError`,
 `kgspPopulateWprMeta_GH100`, `_kgspBootstrapGspFmc_GH100`), g_kern_fsp_nvoc.c
 (the `PDB_PROP_KFSP_IS_MISSING` chip list), and the full bindata record
-tables of both GB10B files. Not read: the GSP RPC layer, the libos
-init-argument block, ACR or GSP internals (not available). No Context7 or web manual covers this layer; the
+tables of both GB10B files; for section 12 also gsp_fw_wpr_meta.h,
+libos_init_args.h, gsp_fw_heap.h, gsp_init_args.h, nvrm_registry.h (heap
+and stack keys), nv-firmware-registry.h, nvtypes.h (`NvLength`), g_gpu_nvoc.c
+(the ZERO_FB chip list), g_kernel_gsp_nvoc.c/.h (frts, heap, log-count,
+libos-version and kernel-logging HAL tables), kernel_gsp.c (`kgspSetupLibos
+InitArgs_IMPL`, `_kgspGenerateInitArgId`, `kgspPopulateGspRmInitArgs_IMPL`,
+`kgspCreateRadix3`, `_kgspCalculateFwHeapSize`, `kgspGetFwHeapSize_IMPL`,
+`kgspInitLogging`, log registration), kernel_gsp_tu102.c (the boot-argument
+allocations), kernel_gsp_gh100.c (`kgspPopulateWprMeta_GH100`), kernel_gsp_
+gb10b.c (`kgspPopulateWprMeta_GB10B`), message_queue_cpu.c, message_queue.h,
+message_queue_priv.h (sizes and page table only); for section 13 also
+msgq.c, msgq_priv.h (the shared ring library), message_queue_cpu.c
+(`GspMsgQueueSendCommand`, `GspMsgQueueReceiveStatus`, `GspStatusQueueInit`),
+message_queue_priv.h (`GSP_MSG_QUEUE_ELEMENT`, `_checkSum32`),
+g_rpc-message-header.h, rpc_headers.h, rpc_global_enums.h, rpc_common.c
+(`rpcWriteCommonHeader`), rpc.c (`_issueRpcLarge`, `rpcSetRegistry_v17_00`,
+`rpcGspSetSystemInfo_v17_00`), kernel_gsp.c (`_kgspRpcSendMessage`,
+`kgspInitRm`, `kgspWaitForRmInitDone`), kernel_gsp_tu102.c
+(`kgspSetCmdQueueHead`), dev_gsp.h (Turing, `NV_PGSP_QUEUE_HEAD`), os.c and
+arch/nvalloc/unix/src/registry.c (`RmPackageRegistry`), g_os_nvoc.h
+(`PACKED_REGISTRY_TABLE`), gsp_static_config.h (`GspSystemInfo`),
+g_chipset_nvoc.h (`BUSINFO`), gpu_acpi_data.h (`ACPI_METHOD_DATA`),
+ctrl0073system.h (`NV0073_CTRL_SYSTEM_ACPI_ID_MAP_MAX_DISPLAYS`),
+nvacpitypes.h and acpigenfuncs.h (DSM enums; not part of `GspSystemInfo`).
+Not read: the RPC set after init, ACR or GSP internals (not available). No Context7 or web manual covers this layer; the
 DGX Spark user guide is silent on GSP firmware loading (DOCS SILENT on native
 GSP bring-up).
 
@@ -514,3 +565,166 @@ ready" (the RPC init handshake, section 8 item 4). Each of these is a
 measurable checkpoint for the attended window, with its own timeout and its
 own refusal line. Nothing in this section has been run on the chip.
 
+
+## 12. The boot-argument blocks, byte for byte [SOURCE]
+
+Tool: `native/kernel/tools/ck_gsp_boot_args_encode.c` (hosted C, no
+dependencies). `make -C native/kernel gsp-bootargs-test` runs the self-test
+(142 checks: compiler layouts, golden constants, round trips, every single-
+field mutation refused); it is part of `make test`. Modes `wprmeta`, `libos`,
+`logbuf`, `rmargs`, `mqtable`, `radix3` write a block; `check-wprmeta`,
+`check-libos`, `check-rmargs` refuse any block that is not the fresh-boot
+GB10B shape; `layout` prints the offsets. Nothing is sent anywhere.
+
+What the driver puts in system memory before it sends the SEC2 message of
+section 10, every line from tag 580.173.02 (file:line in the tool header):
+
+1. **GspFwWprMeta**, 256 bytes in one 4 KiB cached page. Host-filled fields
+   on GB10B: magic `0xdc3aae21371a60b3`, revision 1; bootloader = the
+   GspRmBoot PROD image (196,608 bytes, 4 KiB-aligned copy) with the
+   descriptor offsets code 0xb000, data 0xa00, manifest 0x0; the GSP-RM ELF
+   size and the physical address of the radix-3 root page; the signature
+   buffer (256-aligned, size rounded up to 256); `gspFwHeapSize` 133 MiB;
+   `nonWprHeapSize`, `frtsSize`, `vgaWorkspaceSize`, `pmuReservedSize`, VF
+   partition count all 0 on GB10B; optional crash-report queue; flags 0
+   (`SCAN_RECOVERY_MARGIN` only on a retry with ECC disabled). Every FB
+   layout field (`gspFwRsvdStart` … `vgaWorkspaceOffset`), `bootCount` and
+   `verified` stay 0: the FMC/ACR fill them and set `verified` to
+   `0xa0a0a0a0a0a0a0a0`, which the host later checks.
+   Heap arithmetic: GB10B is ZERO_FB (memory size counted as 1 GB), so the
+   heap is OS carveout 22 MiB + base 14 MiB + 1 MiB + 96 MiB = 133 MiB,
+   clamped to at least 88 MiB; a registry override would be clamped to
+   [88, 280] MiB. The tool refuses anything outside that range.
+2. **Libos init arguments**, one 4 KiB **uncached** page of 32-byte entries
+   (id8, pa, size, kind, loc). GB10B (libos 3, release build, kernel logging
+   on) has exactly eight: LOGINIT, LOGINTR, LOGRM, LOGMNOC, LOGDBG (64 KiB
+   each), LOGROOT (4 KiB), LOGKRNL (64 KiB), then RMARGS (4 KiB, the
+   `GSP_ARGUMENTS_CACHED` page); all CONTIGUOUS/SYSMEM; id8 is the name
+   packed big-endian (RMARGS = `0x524d41524753`). Order and sizes are
+   refused if they differ.
+3. **Each log buffer** (cached, contiguous, 4 KiB aligned, zeroed) starts
+   with an 8-byte put pointer followed by its own page table: one physical
+   address per 4 KiB page. The init-argument `pa` is that first PTE.
+4. **GSP_ARGUMENTS_CACHED**, 88 bytes in one 4 KiB cached page: shared
+   message-queue buffer address, 129 page-table entries, command queue at
+   offset 4096, status queue at 266,240 (page table 4 KiB + command queue
+   256 KiB); suspend/resume fields 0; `bDmemStack` 1; profiler 0; sysmem
+   heap address and size (512 MiB default on ZERO_FB, contiguous uncached).
+   The RPC shared buffer is 129 pages: page 0 holds the addresses of all 129
+   pages (itself first), then 64 pages of command queue and 64 of status
+   queue. The element format inside those queues is item 4 of section 8.
+5. **Radix-3 page table** for the ELF: 4 KiB pages, 512 entries each, three
+   table levels then the data; level 0 must be one page (so up to 512 GiB).
+   For the pinned 75,012,080-byte container: 18,314 data pages, 36 level-2
+   pages, 1 level-1, 1 level-0, tables 155,648 bytes, data at offset
+   0x26000, allocation 75,169,792 bytes. The WPR meta carries the ELF size
+   and the level-0 page address.
+
+Where these sit in the SEC2 flow: the `GSP_FMC_BOOT_PARAMS` page (section
+10) carries both addresses: the WprMeta at offset 16 (`bootGspRmParams.
+gspRmDescOffset`, size 256 at offset 12) and the libos init-argument page at
+offset 48 (`gspRmParams.bootArgsOffset`, DMA target at 40;
+kernel_gsp_gh100.c:457-461). The FMC hands the first to ACR/the bootloader
+and the second to GSP-RM as its libos boot arguments; GSP-RM then finds the
+RMARGS entry, reads `GSP_ARGUMENTS_CACHED` and maps the message queues.
+Everything above
+is what Linux prepares; whether the GSP-FMC on this board accepts exactly
+this shape without Linux ever having run is INFERRED (medium) until the
+attended window measures it. Caching note (section 4 of the hardware manual
+skill): the libos page and the sysmem heap are the only **uncached** blocks;
+the WprMeta, RMARGS, log buffers, radix-3 tables and queue buffer are cached
+sysmem in the driver, so a native port must keep the same attributes or
+flush explicitly.
+
+## 13. The message queue, byte for byte [SOURCE]
+
+Backed by `native/kernel/tools/ck_gsp_rpc_encode.c` (`make -C native/kernel
+gsp-rpc-test`; modes `selftest | layout | txheader | check-txheader | ring |
+element | check-element | contplan | registry | check-registry`). Every value
+is DOCUMENTED from open-gpu-kernel-modules 580.173.02; that the GSP-RM on
+GB10B accepts the same bytes without Linux present is INFERRED (medium) until
+the first attended run. Nothing here touches a device.
+
+1. **Two rings in one 512 KiB buffer** (section 12 item 4: the RPC shared
+   buffer is one 4 KiB page table followed by the command queue then the
+   status queue, each 0x40000 bytes). Both use the shared ring library
+   (`msgq.c`). Each ring starts with a 32-byte producer header
+   `msgqTxHeader` {version 0, size, msgSize, msgCount, writePtr, flags,
+   rxHdrOff, entryOff} and holds the consumer's 4-byte `msgqRxHeader`
+   {readPtr} at `rxHdrOff`. The driver creates its command queue with size
+   0x40000, msgSize 4096, header alignment 16, entry alignment 4096 and
+   `MSGQ_FLAGS_SWAP_RX`, so rxHdrOff = 32, entryOff = 4096, msgCount =
+   (0x40000 - 4096) / 4096 = 63, with 62 usable slots (one slot always stays
+   free). Golden header bytes: `00000000 00000400 00100000 3f000000
+   00000000 01000000 20000000 00100000`. Because both sides set SWAP_RX,
+   each side keeps the read pointer for the messages it consumes in its
+   **own** buffer: the CPU's readPtr for the status queue lives at offset 32
+   of the command queue, and GSP's readPtr for the command queue lives at
+   offset 32 of the status queue.
+2. **Linking to GSP's status queue** (`msgqRxLink`, retried for up to 4 s by
+   `GspStatusQueueInit` with a health check): the CPU reads GSP's 32-byte
+   header from the status queue and refuses it with the library codes -2
+   (msgSize < 16), -3 (msgSize > size), -6 (size < entryOff + msgSize), -7
+   (size mismatch), -8 (msgSize mismatch), -9 (version != 0), -10 (rxHdrOff
+   < 32, entryOff < 36, or msgCount != (size - entryOff) / msgSize). The tool
+   applies the same checks (`check-txheader`) and also refuses writePtr >=
+   msgCount.
+3. **Ring arithmetic**: free = (readPtr + msgCount - writePtr - 1) mod
+   msgCount; available = (writePtr + msgCount - readPtr) mod msgCount; a
+   pointer at or beyond msgCount is corrupt and reads as 0 (`ring` mode).
+4. **One message** (`GSP_MSG_QUEUE_ELEMENT`, 80-byte header-plus-RPC-header
+   struct; `element` mode): bytes 0-31 authentication tag and AAD (zero
+   without confidential computing), u32 checkSum at 32, u32 seqNum at 36,
+   u32 elemCount at 40, then the 32-byte RPC header at 48: header_version
+   0x03000000 (major 3, minor 0), signature 0x43505256, length = 32 +
+   payload, function, rpc_result = rpc_result_private = 0xFFFFFFFF
+   (pending), sequence, cpuRmGfid 0. The message length is 48 + rpc.length
+   and must be within [80, 65536]; it is zero-padded to a multiple of 8;
+   elemCount = ceil(length / 4096); seqNum is the queue's running transmit
+   count (0 for the first message ever sent, then +1 per accepted message);
+   checkSum is computed with the field zeroed as the XOR of every 64-bit
+   word, folded to (high 32) XOR (low 32), so a correct element XOR-sums to
+   zero. The driver copies it 4096 bytes at a time into successive ring
+   slots, publishes the new writePtr, then writes 0 to the doorbell
+   `NV_PGSP_QUEUE_HEAD(0)` = 0x110c00. RPC sequence: synchronous calls take
+   the driver's running RPC counter, asynchronous ones (including the two
+   pre-boot RPCs) carry 0.
+5. **Receiving** (`check-element` mode): the CPU reads slot 0 of the status
+   ring, takes elemCount from it, copies all slots, and refuses the message
+   if the XOR checksum over the padded length is not zero or the seqNum is
+   not the expected receive count (an older seqNum is consumed and the read
+   retried up to 3 times). Init is done when a message with function
+   `GSP_INIT_DONE` 0x1001, sequence 0 and rpc_result NV_OK arrives.
+6. **Oversize RPCs** (`contplan` mode): the largest single RPC is 65488
+   bytes (65536 - 48). A larger buffer is sent as the real function with
+   length 65488 followed by messages whose function is
+   `CONTINUATION_RECORD` 71, each carrying up to 65456 payload bytes.
+7. **Before boot** the driver queues two asynchronous RPCs into the command
+   ring so they are the first things GSP-RM reads: `GSP_SET_SYSTEM_INFO` 72
+   (payload `GspSystemInfo`: PCI/BAR physical addresses, PCI ids, chipset,
+   ACPI method data, hypervisor and VF state, host page size; 936 bytes, so
+   RPC length 968 in one slot; field offsets in the tool's `layout` output;
+   contents come from the real device, so this is attended-window work) and
+   `SET_REGISTRY`
+   73 (payload `PACKED_REGISTRY_TABLE`, `registry` mode): u32 size, u32
+   numEntries, then 16-byte entries {u32 nameOffset; u8 type; u32 data; u32
+   length} followed by the packed NUL-terminated names and values in entry
+   order; a DWORD (type 1) keeps its value in `data` with length 4, STRING
+   (3) and BINARY (2) put their bytes after the name with `data` = their
+   offset. An empty registry is not sent at all; a zero-length string or
+   binary entry is dropped by the driver and refused by the tool.
+8. **Function and event numbers a native kernel must match**: NOP 0,
+   CONTINUATION_RECORD 71, GSP_SET_SYSTEM_INFO 72, SET_REGISTRY 73,
+   GSP_RM_CONTROL 76, GSP_RM_ALLOC 103; events GSP_INIT_DONE 0x1001,
+   GSP_RUN_CPU_SEQUENCER 0x1002, RC_TRIGGERED 0x1004, GSP_LOCKDOWN_NOTICE
+   0x101c, GSP_POST_NOCAT_RECORD 0x1020; results RPC_UNKNOWN_FUNCTION
+   0xFF100001 and RPC_INVALID_MESSAGE_FORMAT 0xFF100002 are what GSP-RM
+   returns for a wrong function number or a malformed header.
+
+Limits: the tool does not know which RPCs after init a native kernel must
+send for device init, memory mapping, channel creation and submission
+(section 8 item 4 remains open there), knows the size but not the contents
+of `GspSystemInfo`, and does not cover the confidential-computing encryption path (assumed off,
+as on this machine today). Caching note: the queue buffer is cached sysmem
+in the driver with explicit store fences before each writePtr publish and
+doorbell write; a native port must keep the fence or use uncached mappings.
diff --git a/native/.crumb b/native/.crumb
index 4ca9b66d..8889fd35 100644
--- a/native/.crumb
+++ b/native/.crumb
@@ -79,8 +79,8 @@
           "purpose": "Directory native/disk. Purpose not yet described by a human."
         },
         {
-          "digest": "5b7f4a413bc71bbd06f2fa0b4dce7beca1671e4d4ae8a27734937820cb85d3b2",
-          "last_commit": "e09825a",
+          "digest": "6845f46fb7d05df8d980e8290908700361869cb5a11eae224f299bf9bf5ddae0",
+          "last_commit": "0711ee0",
           "name": "kernel",
           "purpose": "Directory native/kernel. Purpose not yet described by a human."
         },
@@ -109,15 +109,15 @@
           "purpose": "Directory native/store. Purpose not yet described by a human."
         }
       ],
-      "children_root": "sha256:00ef727fd94a39dffbb0833b33f9a3256b05bc0f01deea8b860ddf0ad08515dd",
-      "compiled_at": "2026-10-12T12:21:27Z",
+      "children_root": "sha256:cb1dc6e50f50ec3a95b7e336c04afa1c67fdb52c3f2eae9a882304b03451f6f5",
+      "compiled_at": "2026-10-12T13:00:09Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:00b3df5ff408cf07d222d4ebd836026a58a12532ff116b765594246a09a901bc",
+      "digest": "sha256:91bcbb8a7af535f438701fa1a4a8bd630370f1a7da25ad5ded775a3d0969dad6",
       "evidence_files": 4,
       "evidence_root": "sha256:e410b845507e00568e15b51a5797af32a97e0e4b8ab4e8487bb7c98e7e0cf335",
-      "files": 472,
-      "generated_at_commit": "e09825afddde294659ca4a06354990e7ff530b62",
-      "source_tree": "sha256:8807b5a7fe5e78aadc6acd37daa24c037b5018f7ae617985ca6677616a8fe59d"
+      "files": 474,
+      "generated_at_commit": "0711ee05e49b9837d8c3dc55a5980582a4c37e4e",
+      "source_tree": "sha256:3c108d93554900341eb25a72ac24448a11be14c341d71a32e329d40500b5eb31"
     },
     "owner_lane": "",
     "provenance": {
diff --git a/native/kernel/.crumb b/native/kernel/.crumb
index e71cde8b..3244adc6 100644
--- a/native/kernel/.crumb
+++ b/native/kernel/.crumb
@@ -93,21 +93,21 @@
           "purpose": "Directory native/kernel/tests. Purpose not yet described by a human."
         },
         {
-          "digest": "62f6ec248db3b6415da5d71b60b24fcb0cb8f4c8ec8478b36874e291c4f1ba24",
-          "last_commit": "e09825a",
+          "digest": "0a07e8dbd80ec6009af73dc47cf5e943493e6bcab3b11669b0ababc940cce53d",
+          "last_commit": "0711ee0",
           "name": "tools",
           "purpose": "Hosted (Linux-built) checkers for the native kernel, run by `make -C native/kernel test`; nothin"
         }
       ],
-      "children_root": "sha256:81e2222e47ea38f16bb90bb7334df06f66d821b956acfdaa1f5df9a43def57d9",
-      "compiled_at": "2026-10-12T12:21:27Z",
+      "children_root": "sha256:8d6d93738edf94b81b3b3c7b17d56058e1771b21bbcd578c32526ec8c1cdbed2",
+      "compiled_at": "2026-10-12T13:00:09Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:5b7f4a413bc71bbd06f2fa0b4dce7beca1671e4d4ae8a27734937820cb85d3b2",
+      "digest": "sha256:6845f46fb7d05df8d980e8290908700361869cb5a11eae224f299bf9bf5ddae0",
       "evidence_files": 0,
       "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
-      "files": 308,
-      "generated_at_commit": "e09825afddde294659ca4a06354990e7ff530b62",
-      "source_tree": "sha256:d83504ba35f0cda9f929b0271c9bf52573f8b0543e64e7f2d04925db5e8ccc4a"
+      "files": 310,
+      "generated_at_commit": "0711ee05e49b9837d8c3dc55a5980582a4c37e4e",
+      "source_tree": "sha256:2e3ab6c0196e93f501e1f5e4747e4dadee7a2a6737c2d9e3c9243c1ae5ff6cbb"
     },
     "owner_lane": "",
     "provenance": {
diff --git a/native/kernel/Makefile b/native/kernel/Makefile
index 8e975ff7..2becf73f 100644
--- a/native/kernel/Makefile
+++ b/native/kernel/Makefile
@@ -1066,8 +1066,8 @@ smmu-l2-mutants: $(OUT)/host/test_smmu
 	else echo "mutant flag refused under CK_HARDWARE_STAGING"; fi; \
 	if [ $$fail = 0 ]; then echo "CK_SMMU_L2_MUTANTS: PASS"; else echo "CK_SMMU_L2_MUTANTS: FAIL"; exit 1; fi
 
-test: $(addprefix $(OUT)/host/,$(TESTS)) handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants osh-op-mutant test-continuity-subject-restart gsp-fw-inspect-test gsp-cot-test gsp-bindata-test
-	@fail=0; for t in $(filter-out handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants osh-op-mutant test-continuity-subject-restart gsp-fw-inspect-test gsp-cot-test gsp-bindata-test,$^); do $$t || fail=1; done; \
+test: $(addprefix $(OUT)/host/,$(TESTS)) handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants osh-op-mutant test-continuity-subject-restart gsp-fw-inspect-test gsp-cot-test gsp-bindata-test gsp-bootargs-test gsp-rpc-test
+	@fail=0; for t in $(filter-out handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants osh-op-mutant test-continuity-subject-restart gsp-fw-inspect-test gsp-cot-test gsp-bindata-test gsp-bootargs-test gsp-rpc-test,$^); do $$t || fail=1; done; \
 	if [ $$fail = 0 ]; then echo "CK_CORE_HOST: PASS"; else echo "CK_CORE_HOST: FAIL"; exit 1; fi
 
 sanitize: $(addprefix $(OUT)/host-san/,$(TESTS))
@@ -1511,6 +1511,35 @@ gsp-bindata-test: $(GSP_BINDATA_TOOL)
 	  echo "CK_GSP_BINDATA_PIN: PASS"; \
 	else echo "CK_GSP_BINDATA_PIN: NOT_RUN ($(GSP_BINDATA_DIR) lacks the two GB10B bindata files)"; fi
 
+# ---- host encoder/decoder for the GSP-RM boot-argument blocks (aienos#286 cut C host work) ----
+# Byte-exact GspFwWprMeta (256), libos init-argument page, log-buffer PTE prefix,
+# GSP_ARGUMENTS_CACHED page, RPC shared-buffer page table and radix-3 ELF table, with
+# the GB10B values traced from the pinned driver (heap 133 MiB, 7 logs + RMARGS, 129 PTEs).
+# Self-test = compiler layouts, golden constants, round trips, every mutation refused.
+# Never loads anything. docs/GB10_FIRMWARE_INVENTORY.md section 12.
+GSP_BOOTARGS_TOOL := $(OUT)/host/ck_gsp_boot_args_encode
+$(GSP_BOOTARGS_TOOL): $(KDIR)/tools/ck_gsp_boot_args_encode.c
+	@mkdir -p $(dir $@)
+	$(HOSTCC) -std=gnu11 -O2 -Wall -Wextra -Werror -o $@ $(KDIR)/tools/ck_gsp_boot_args_encode.c
+gsp-bootargs-encode: $(GSP_BOOTARGS_TOOL)
+gsp-bootargs-test: $(GSP_BOOTARGS_TOOL)
+	$(GSP_BOOTARGS_TOOL) selftest | grep -E '^CK_GSP_BOOT_ARGS_ENCODE_SELFTEST: (PASS|FAIL)' | grep -q PASS || { $(GSP_BOOTARGS_TOOL) selftest | grep -E 'FAIL|SELFTEST'; exit 1; }
+	@$(GSP_BOOTARGS_TOOL) selftest | tail -1
+
+# ---- host encoder/decoder for the GSP-RM message queue (aienos#286 cut C host part 5) ----
+# Byte-exact msgqTxHeader/msgqRxHeader, GSP_MSG_QUEUE_ELEMENT with checksum and sequence
+# rules, rpc_message_header_v03_00, continuation-record plan and PACKED_REGISTRY_TABLE,
+# all from the pinned driver. Self-test = compiler layouts, golden bytes, round trips,
+# every mutation refused. Never touches a device. docs/GB10_FIRMWARE_INVENTORY.md section 13.
+GSP_RPC_TOOL := $(OUT)/host/ck_gsp_rpc_encode
+$(GSP_RPC_TOOL): $(KDIR)/tools/ck_gsp_rpc_encode.c
+	@mkdir -p $(dir $@)
+	$(HOSTCC) -std=gnu11 -O2 -Wall -Wextra -Werror -o $@ $(KDIR)/tools/ck_gsp_rpc_encode.c
+gsp-rpc-encode: $(GSP_RPC_TOOL)
+gsp-rpc-test: $(GSP_RPC_TOOL)
+	$(GSP_RPC_TOOL) selftest | grep -E '^CK_GSP_RPC_ENCODE_SELFTEST: (PASS|FAIL)' | grep -q PASS || { $(GSP_RPC_TOOL) selftest | grep -E 'FAIL|SELFTEST'; exit 1; }
+	@$(GSP_RPC_TOOL) selftest | tail -1
+
 # ---- host checker for the AIENOS_CK_SCREEN gate (scripts/qemu_ck_screen_test.sh) ----
 FB_CHECK_TOOL := $(OUT)/host/ck_fb_check
 $(FB_CHECK_TOOL): $(KDIR)/tools/ck_fb_check.c $(KDIR)/core/fbcon.c $(KDIR)/core/fbcon.h $(KDIR)/core/font8x8.h
diff --git a/native/kernel/tools/.crumb b/native/kernel/tools/.crumb
index 80c40ec6..e8cb8369 100644
--- a/native/kernel/tools/.crumb
+++ b/native/kernel/tools/.crumb
@@ -7,14 +7,14 @@
     "generated": {
       "children": [],
       "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
-      "compiled_at": "2026-10-12T12:21:27Z",
+      "compiled_at": "2026-10-12T13:00:09Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:62f6ec248db3b6415da5d71b60b24fcb0cb8f4c8ec8478b36874e291c4f1ba24",
+      "digest": "sha256:0a07e8dbd80ec6009af73dc47cf5e943493e6bcab3b11669b0ababc940cce53d",
       "evidence_files": 0,
       "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
-      "files": 15,
-      "generated_at_commit": "e09825afddde294659ca4a06354990e7ff530b62",
-      "source_tree": "sha256:34d0d607f3d5f92784e0433c1755ddc6feeafb2beb0892402a20482dd6a356f8"
+      "files": 17,
+      "generated_at_commit": "0711ee05e49b9837d8c3dc55a5980582a4c37e4e",
+      "source_tree": "sha256:d344102b5aaa3ec59cfcc87be7e73a1d4455552b06a57a31bb905cb52a99c485"
     },
     "owner_lane": "",
     "provenance": {
diff --git a/native/kernel/tools/ck_gsp_boot_args_encode.c b/native/kernel/tools/ck_gsp_boot_args_encode.c
new file mode 100644
index 00000000..08fd5587
--- /dev/null
+++ b/native/kernel/tools/ck_gsp_boot_args_encode.c
@@ -0,0 +1,810 @@
+/* ck_gsp_boot_args_encode -- host tool: byte-exact encoder, decoder and
+ * refusal tests for the system-memory argument blocks the pinned Linux
+ * driver (nvidia-open 580.173.02) prepares before it boots GSP-RM on the
+ * GB10B (aienos#286 cut C host work: "parsers and refusal tests for firmware
+ * metadata. No loading"). docs/GB10_FIRMWARE_INVENTORY.md section 12 is the
+ * report this tool backs. Nothing here touches a device.
+ *
+ * Five blocks, every line from open-gpu-kernel-modules tag 580.173.02:
+ *
+ *  1. GspFwWprMeta, 256 bytes, natural layout (gsp_fw_wpr_meta.h:60-208,
+ *     ct_assert(sizeof == 256) in kernel_gsp_gh100.c:305). Allocated as one
+ *     4 KiB page, 4 KiB aligned, cached, unprotected sysmem, zeroed
+ *     (kernel_gsp_tu102.c:120-142). Filled by kgspPopulateWprMeta_GH100
+ *     (kernel_gsp_gh100.c:295-388) then overridden by
+ *     kgspPopulateWprMeta_GB10B (kernel_gsp_gb10b.c:62-86):
+ *       magic 0xdc3aae21371a60b3, revision 1                [gh100.c:375-376]
+ *       sizeOfBootloader = GspRmBoot image size (196,608)    [:321]
+ *       sysmemAddrOfBootloader = its 4 KiB-aligned PA        [:322-323]
+ *       sizeOfRadix3Elf = GSP-RM .fwimage size               [:326]
+ *       sysmemAddrOfRadix3Elf = PA of the radix-3 root page  [:327-328]
+ *       bootloaderCodeOffset/DataOffset/ManifestOffset =
+ *         desc monitorCodeOffset/monitorDataOffset/manifestOffset
+ *         (GB10B: 0xb000 / 0xa00 / 0x0)                      [:331-333]
+ *       sysmemAddrOfSignature (256-aligned PA), sizeOfSignature =
+ *         NV_ALIGN_UP(signatureSize, 256)      [:335-339; kernel_gsp.c:4697-4701]
+ *       nonWprHeapSize = 0 (GB10B override)                  [gb10b.c:82]
+ *       gspFwHeapSize = kgspGetFwHeapSize(.., 0, 0)          [:355]
+ *       frtsSize = 0 (kgspGetFrtsSize_4a4dee for GB10B)      [:358; g_kernel_gsp_nvoc.c:1254-1256, .h:1781-1783]
+ *       gspFwHeapVfPartitionCount = 0 (no vGPU offload)      [:361-362]
+ *       sysmemAddrOfCrashReportQueue/size: crash-cat queue if allocated [:364-372]
+ *       vgaWorkspaceSize = 0, pmuReservedSize = 0 (GB10B)    [gb10b.c:78-79]
+ *       flags: PPCIE cleared; SCAN_RECOVERY_MARGIN only on a retry with
+ *         ECC disabled                                       [:378-385; kernel_gsp.c:3935-3943]
+ *       everything else 0: the FMC/ACR patch the FB layout   [gb10b.c:33-35]
+ *     Heap size on GB10B (kernel_gsp.c:5538-5593, 5617-5668): ZERO_FB is
+ *     true for "GB10B | GB20B | GB20C" (g_gpu_nvoc.c) so memSizeGB = 1;
+ *     heap = OS carveout 22 MiB (kgspGetFwHeapParamOsCarveoutSize_4b5307,
+ *     non-vGPU) + base 14 MiB (fwHeapParamBaseSize, Hopper+ list) +
+ *     align1M(96 KiB * 1) + align1M(48 KiB * 2048) = 22+14+1+96 = 133 MiB,
+ *     clamped to [88 MiB, U32_MAX] (min kgspGetMinWprHeapSizeMB_647ce6 = 88
+ *     non-vGPU; the override path is off by default,
+ *     NV_REG_STR_GSP_FIRMWARE_HEAP_SIZE_MB_DEFAULT = 0). Registry overrides
+ *     would be clamped to [88, 280] MiB (gsp_fw_heap.h:109-110).
+ *
+ *  2. Libos init arguments: an array of LibosMemoryRegionInitArgument
+ *     (libos_init_args.h: id8 u64, pa u64, size u64, kind u8, loc u8;
+ *     natural size 32) in one 4 KiB uncached, 4 KiB-aligned, zeroed page
+ *     (LIBOS_MEMORY_REGION_INIT_ARGUMENTS_MAX = 4096; kernel_gsp_tu102.c:
+ *     147-171). kgspSetupLibosInitArgs_IMPL (kernel_gsp.c:5179-5222): one
+ *     CONTIGUOUS/SYSMEM entry per log buffer in registration order, id8 =
+ *     the memory id packed big-endian (_kgspGenerateInitArgId, :2657-2675),
+ *     pa = the buffer's first page PA, size = buffer size; then "RMARGS" ->
+ *     the GSP_ARGUMENTS_CACHED page (size 4096). Remaining entries stay
+ *     zero (kind NONE). GB10B log set (libos 3: kgspGetLibosVersion_61db9f;
+ *     release build; kernel logging true for GB10B, .fwlogging_kernel_gb10y
+ *     exists) in order (kernel_gsp.c:3150-3240, nv-firmware-chip-family-
+ *     select.h:105-115,151-152): LOGINIT 64 KiB, LOGINTR 64 KiB, LOGRM
+ *     64 KiB, LOGMNOC 64 KiB, LOGDBG 64 KiB, LOGROOT 4 KiB, LOGKRNL 64 KiB
+ *     (= kgspGetLogCount LOG_IDX_LIBOS3_SIZE = 7), then RMARGS: 8 entries.
+ *
+ *  3. Each log buffer: contiguous cached sysmem, 4 KiB aligned, zeroed; the
+ *     host writes its own PTE table into it after an 8-byte put pointer
+ *     (kernel_gsp.c:3070-3104 "Pass the PTE table for the log buffer in the
+ *     log buffer, after the put pointer"): u64 put = 0, then one u64 PA per
+ *     4 KiB page of the buffer. The init-argument pa is PTE[0] = the base.
+ *
+ *  4. GSP_ARGUMENTS_CACHED (gsp_init_args.h), natural layout 88 bytes, in
+ *     one 4 KiB cached, 4 KiB-aligned, zeroed page (kernel_gsp_tu102.c:
+ *     174-198). kgspPopulateGspRmInitArgs_IMPL (kernel_gsp.c:4505-4573):
+ *     messageQueue: sharedMemPhysAddr = PA of page 0 of the RPC shared
+ *     buffer (the page-table page), pageTableEntryCount, cmdQueueOffset =
+ *     pageTableSize, statQueueOffset = cmdQueueOffset + commandQueueSize;
+ *     sr: all 0 on a normal boot; gpuInstance; bDmemStack = true (stack
+ *     placement default 0); profilerArgs 0; sysmemHeapArgs = PA/size of the
+ *     ZERO_FB sysmem heap (512 MiB default, contiguous uncached;
+ *     kernel_gsp_tu102.c:200-223, nvrm_registry.h:2355-2356).
+ *     RPC shared buffer (message_queue_cpu.c:60-125, 220-310): command
+ *     queue 256 KiB on silicon, status queue 256 KiB; numPtes = 128 +
+ *     ceil(128*8/4096) = 129; pageTableSize = align4K(129*8) = 4096; the
+ *     table page holds the PAs of all 129 pages (itself first); command
+ *     queue at 4096, status queue at 266240; sharedMemPA = PTE[0].
+ *
+ *  5. Radix-3 page table for the GSP-RM ELF (kgspCreateRadix3, kernel_gsp.c:
+ *     4915-5050): 4 KiB pages, 512 entries per page; level 3 = data pages,
+ *     level i-1 pages = ceil(level i pages / 512); level 0 must be 1 page;
+ *     levels 0..2 are laid out back to back, then the data; each level
+ *     page holds the PAs of the next level's pages. sizeOfRadix3Elf is the
+ *     ELF size and sysmemAddrOfRadix3Elf the PA of the level-0 page.
+ *
+ * Refusals this tool enforces (reason strings are the test oracle): bad
+ * magic/revision, bootloader size/offsets not the GB10B pair, unaligned or
+ * zero addresses (4 KiB for pages, 256 for the signature), signature size
+ * not a 256 multiple, zero ELF size, heap size outside [88 MiB, 280 MiB],
+ * GB10B-must-be-zero fields non-zero (nonWprHeapSize, frtsSize,
+ * vgaWorkspaceSize, pmuReservedSize, VF count), FMC-owned fields non-zero
+ * on the host side (FB layout, bootCount, verified), unknown flag bits,
+ * libos entries out of order or of the wrong kind/loc/size, RMARGS not last,
+ * message-queue arguments inconsistent, log buffer size not a page multiple.
+ *
+ * INFERRED (medium), not a driver check: the GSP-FMC accepts the 133 MiB
+ * heap request on GB10B exactly as the driver computes it; a different value
+ * within the clamp is a change of behaviour that only the chip can judge.
+ *
+ * No device access, no firmware, no loading. Hosted build only.
+ */
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stddef.h>
+
+/* ---------- the driver's structures, natural layout (LP64, little endian) ---------- */
+
+#define GSP_FW_WPR_META_MAGIC     0xdc3aae21371a60b3ULL
+#define GSP_FW_WPR_META_REVISION  1ULL
+#define GSP_FW_WPR_META_VERIFIED  0xa0a0a0a0a0a0a0a0ULL
+#define GSP_FW_FLAGS_CLOCK_BOOST              (1u << 0)
+#define GSP_FW_FLAGS_RECOVERY_MARGIN_PRESENT  (1u << 1)
+#define GSP_FW_FLAGS_PPCIE_ENABLED            (1u << 2)
+#define GSP_FW_FLAGS_MULTI_GPU_NVLE_ENABLED   (1u << 3)
+#define GSP_FW_FLAGS_SCAN_RECOVERY_MARGIN     (1u << 4)
+
+typedef struct {
+    uint64_t magic;
+    uint64_t revision;
+    uint64_t sysmemAddrOfRadix3Elf;
+    uint64_t sizeOfRadix3Elf;
+    uint64_t sysmemAddrOfBootloader;
+    uint64_t sizeOfBootloader;
+    uint64_t bootloaderCodeOffset;
+    uint64_t bootloaderDataOffset;
+    uint64_t bootloaderManifestOffset;
+    union {
+        struct { uint64_t sysmemAddrOfSignature; uint64_t sizeOfSignature; };
+        struct { uint32_t gspFwHeapFreeListWprOffset; uint32_t unused0; uint64_t unused1; };
+    };
+    uint64_t gspFwRsvdStart;
+    uint64_t nonWprHeapOffset;
+    uint64_t nonWprHeapSize;
+    uint64_t gspFwWprStart;
+    uint64_t gspFwHeapOffset;
+    uint64_t gspFwHeapSize;
+    uint64_t gspFwOffset;
+    uint64_t bootBinOffset;
+    uint64_t frtsOffset;
+    uint64_t frtsSize;
+    uint64_t gspFwWprEnd;
+    uint64_t fbSize;
+    uint64_t vgaWorkspaceOffset;
+    uint64_t vgaWorkspaceSize;
+    uint64_t bootCount;
+    union {
+        struct {
+            uint64_t partitionRpcAddr;
+            uint16_t partitionRpcRequestOffset;
+            uint16_t partitionRpcReplyOffset;
+            uint32_t elfCodeOffset;
+            uint32_t elfDataOffset;
+            uint32_t elfCodeSize;
+            uint32_t elfDataSize;
+            uint32_t lsUcodeVersion;
+        };
+        struct {
+            uint32_t partitionRpcPadding[4];
+            uint64_t sysmemAddrOfCrashReportQueue;
+            uint32_t sizeOfCrashReportQueue;
+            uint32_t lsUcodeVersionPadding[1];
+        };
+    };
+    uint8_t  gspFwHeapVfPartitionCount;
+    uint8_t  flags;
+    uint8_t  padding[2];
+    uint32_t pmuReservedSize;
+    uint64_t verified;
+} GspFwWprMeta;
+
+#define LIBOS_MEMORY_REGION_INIT_ARGUMENTS_MAX 4096
+enum { LIBOS_MEMORY_REGION_NONE = 0, LIBOS_MEMORY_REGION_CONTIGUOUS = 1, LIBOS_MEMORY_REGION_RADIX3 = 2 };
+enum { LIBOS_MEMORY_REGION_LOC_NONE = 0, LIBOS_MEMORY_REGION_LOC_SYSMEM = 1, LIBOS_MEMORY_REGION_LOC_FB = 2 };
+typedef struct {
+    uint64_t id8;
+    uint64_t pa;
+    uint64_t size;
+    uint8_t  kind;
+    uint8_t  loc;
+} LibosMemoryRegionInitArgument;
+
+typedef struct {
+    uint64_t sharedMemPhysAddr;
+    uint32_t pageTableEntryCount;
+    uint64_t cmdQueueOffset;   /* NvLength = NvU64 on LP64 (nvtypes.h:309) */
+    uint64_t statQueueOffset;
+} MESSAGE_QUEUE_INIT_ARGUMENTS;
+typedef struct {
+    uint32_t oldLevel;
+    uint32_t flags;
+    uint8_t  bInPMTransition;  /* NvBool */
+} GSP_SR_INIT_ARGUMENTS;
+typedef struct {
+    MESSAGE_QUEUE_INIT_ARGUMENTS messageQueueInitArguments;
+    GSP_SR_INIT_ARGUMENTS        srInitArguments;
+    uint32_t                     gpuInstance;
+    uint8_t                      bDmemStack;
+    struct { uint64_t pa; uint64_t size; } profilerArgs;
+    struct { uint64_t pa; uint64_t size; } sysmemHeapArgs;
+} GSP_ARGUMENTS_CACHED;
+
+/* ---------- GB10B constants traced from the driver ---------- */
+
+#define PAGE_SZ               4096ULL
+#define GB10B_BOOTLOADER_SIZE 196608ULL   /* GspRmBoot_GB10B UCODE_IMAGE_PROD */
+#define GB10B_BL_CODE_OFF     0xb000ULL   /* desc monitorCodeOffset */
+#define GB10B_BL_DATA_OFF     0xa00ULL    /* desc monitorDataOffset */
+#define GB10B_BL_MANIFEST_OFF 0x0ULL      /* desc manifestOffset */
+#define GB10B_FW_HEAP_SIZE    (133ULL << 20)
+#define GB10B_FW_HEAP_MIN     (88ULL << 20)
+#define GB10B_FW_HEAP_MAX     (280ULL << 20)
+#define GB10B_SYSMEM_HEAP     (512ULL << 20)
+#define MQ_CMD_QUEUE_SIZE     0x40000ULL
+#define MQ_STAT_QUEUE_SIZE    0x40000ULL
+#define MQ_NUM_PTES           129u
+#define MQ_PAGE_TABLE_SIZE    4096ULL
+#define GSP_FW_FLAGS_KNOWN    (GSP_FW_FLAGS_CLOCK_BOOST | GSP_FW_FLAGS_RECOVERY_MARGIN_PRESENT | \
+                               GSP_FW_FLAGS_PPCIE_ENABLED | GSP_FW_FLAGS_MULTI_GPU_NVLE_ENABLED | \
+                               GSP_FW_FLAGS_SCAN_RECOVERY_MARGIN)
+
+static const struct { const char *id; uint64_t size; } gb10b_logs[] = {
+    {"LOGINIT", 0x10000}, {"LOGINTR", 0x10000}, {"LOGRM", 0x10000}, {"LOGMNOC", 0x10000},
+    {"LOGDBG",  0x10000}, {"LOGROOT", 0x1000},  {"LOGKRNL", 0x10000},
+};
+#define GB10B_LOG_COUNT 7u
+#define GB10B_LIBOS_ENTRIES (GB10B_LOG_COUNT + 1u)
+
+/* _kgspGenerateInitArgId: at most 8 ASCII bytes, first byte most significant. */
+static uint64_t init_arg_id(const char *name) {
+    uint64_t id = 0;
+    for (int i = 0; i < 8; i++) {
+        unsigned char c = (unsigned char)*name++;
+        if (c == '\0') break;
+        id = (id << 8) | c;
+    }
+    return id;
+}
+
+/* ---------- little-endian helpers over raw bytes ---------- */
+static uint64_t rd64(const uint8_t *p) { uint64_t v = 0; for (int i = 7; i >= 0; i--) v = (v << 8) | p[i]; return v; }
+static uint32_t rd32(const uint8_t *p) { return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); }
+static void wr64(uint8_t *p, uint64_t v) { for (int i = 0; i < 8; i++) { p[i] = (uint8_t)v; v >>= 8; } }
+static void wr32(uint8_t *p, uint32_t v) { for (int i = 0; i < 4; i++) { p[i] = (uint8_t)v; v >>= 8; } }
+
+/* ---------- 1. GspFwWprMeta ---------- */
+
+typedef struct {
+    uint64_t bootloader_pa, radix3_root_pa, elf_size, signature_pa, signature_size;
+    uint64_t heap_size;            /* 0 = GB10B default 133 MiB */
+    uint64_t crash_queue_pa; uint32_t crash_queue_size;
+    int scan_recovery_margin;      /* retry with ECC disabled only */
+} wpr_in;
+
+static const char *wpr_encode(const wpr_in *in, uint8_t out[256]) {
+    GspFwWprMeta m;
+    memset(&m, 0, sizeof m);
+    if (in->bootloader_pa == 0 || (in->bootloader_pa & (PAGE_SZ - 1))) return "bootloader address zero or not 4 KiB aligned";
+    if (in->radix3_root_pa == 0 || (in->radix3_root_pa & (PAGE_SZ - 1))) return "radix3 root address zero or not 4 KiB aligned";
+    if (in->elf_size == 0) return "ELF size zero";
+    if (in->signature_pa == 0 || (in->signature_pa & 255)) return "signature address zero or not 256 aligned";
+    if (in->signature_size == 0 || (in->signature_size & 255)) return "signature size zero or not a 256 multiple";
+    uint64_t heap = in->heap_size ? in->heap_size : GB10B_FW_HEAP_SIZE;
+    if (heap < GB10B_FW_HEAP_MIN || heap > GB10B_FW_HEAP_MAX || (heap & ((1ULL << 20) - 1))) return "heap size outside [88 MiB, 280 MiB] or not a MiB multiple";
+    if ((in->crash_queue_pa == 0) != (in->crash_queue_size == 0)) return "crash report queue address and size must both be zero or both set";
+    if (in->crash_queue_pa & (PAGE_SZ - 1)) return "crash report queue address not 4 KiB aligned";
+    m.magic = GSP_FW_WPR_META_MAGIC;
+    m.revision = GSP_FW_WPR_META_REVISION;
+    m.sizeOfBootloader = GB10B_BOOTLOADER_SIZE;
+    m.sysmemAddrOfBootloader = in->bootloader_pa;
+    m.sizeOfRadix3Elf = in->elf_size;
+    m.sysmemAddrOfRadix3Elf = in->radix3_root_pa;
+    m.bootloaderCodeOffset = GB10B_BL_CODE_OFF;
+    m.bootloaderDataOffset = GB10B_BL_DATA_OFF;
+    m.bootloaderManifestOffset = GB10B_BL_MANIFEST_OFF;
+    m.sysmemAddrOfSignature = in->signature_pa;
+    m.sizeOfSignature = in->signature_size;
+    m.nonWprHeapSize = 0;
+    m.gspFwHeapSize = heap;
+    m.frtsSize = 0;
+    m.gspFwHeapVfPartitionCount = 0;
+    m.sysmemAddrOfCrashReportQueue = in->crash_queue_pa;
+    m.sizeOfCrashReportQueue = in->crash_queue_size;
+    m.vgaWorkspaceSize = 0;
+    m.pmuReservedSize = 0;
+    m.flags = in->scan_recovery_margin ? GSP_FW_FLAGS_SCAN_RECOVERY_MARGIN : 0;
+    memcpy(out, &m, 256);
+    return NULL;
+}
+
+/* Decode + refuse: the host-side shape of a fresh-boot GB10B WprMeta. */
+static const char *wpr_check(const uint8_t *b, size_t n, wpr_in *out) {
+    if (n != 256) return "WprMeta size not 256";
+    if (rd64(b + 0) != GSP_FW_WPR_META_MAGIC) return "magic wrong";
+    if (rd64(b + 8) != GSP_FW_WPR_META_REVISION) return "revision not 1";
+    uint64_t r3 = rd64(b + 16), elf = rd64(b + 24), bl = rd64(b + 32), bls = rd64(b + 40);
+    if (r3 == 0 || (r3 & (PAGE_SZ - 1))) return "radix3 root address zero or not 4 KiB aligned";
+    if (elf == 0) return "ELF size zero";
+    if (bl == 0 || (bl & (PAGE_SZ - 1))) return "bootloader address zero or not 4 KiB aligned";
+    if (bls != GB10B_BOOTLOADER_SIZE) return "bootloader size not the GB10B GspRmBoot image size";
+    if (rd64(b + 48) != GB10B_BL_CODE_OFF || rd64(b + 56) != GB10B_BL_DATA_OFF || rd64(b + 64) != GB10B_BL_MANIFEST_OFF) return "bootloader offsets not the GB10B descriptor values";
+    uint64_t sig = rd64(b + 72), sigs = rd64(b + 80);
+    if (sig == 0 || (sig & 255)) return "signature address zero or not 256 aligned";
+    if (sigs == 0 || (sigs & 255)) return "signature size zero or not a 256 multiple";
+    /* FB layout fields are the FMC's: gspFwRsvdStart 88, nonWprHeapOffset 96, gspFwWprStart 112,
+       gspFwHeapOffset 120, gspFwOffset 136, bootBinOffset 144, frtsOffset 152, gspFwWprEnd 168,
+       fbSize 176, vgaWorkspaceOffset 184 */
+    static const int fmc_owned[] = {88, 96, 112, 120, 136, 144, 152, 168, 176, 184};
+    for (size_t i = 0; i < sizeof fmc_owned / sizeof fmc_owned[0]; i++)
+        if (rd64(b + fmc_owned[i]) != 0) return "FMC-owned FB layout field non-zero on the host side";
+    if (rd64(b + 104) != 0) return "nonWprHeapSize must be 0 on GB10B";
+    uint64_t heap = rd64(b + 128);
+    if (heap < GB10B_FW_HEAP_MIN || heap > GB10B_FW_HEAP_MAX || (heap & ((1ULL << 20) - 1))) return "heap size outside [88 MiB, 280 MiB] or not a MiB multiple";
+    if (rd64(b + 160) != 0) return "frtsSize must be 0 on GB10B";
+    if (rd64(b + 192) != 0) return "vgaWorkspaceSize must be 0 on GB10B";
+    if (rd64(b + 200) != 0) return "bootCount must be 0 on the host side";
+    /* union at 208: partitionRpc* zero (bootstrapper-owned) = padding[0..3] zero */
+    for (int i = 0; i < 16; i++) if (b[208 + i] != 0) return "partition RPC fields must be 0";
+    uint64_t cq = rd64(b + 224); uint32_t cqs = rd32(b + 232);
+    if ((cq == 0) != (cqs == 0)) return "crash report queue address and size must both be zero or both set";
+    if (cq & (PAGE_SZ - 1)) return "crash report queue address not 4 KiB aligned";
+    if (rd32(b + 236) != 0) return "lsUcodeVersion padding must be 0";
+    if (b[240] != 0) return "gspFwHeapVfPartitionCount must be 0";
+    if (b[241] & ~GSP_FW_FLAGS_KNOWN) return "unknown flag bits";
+    if (b[241] & (GSP_FW_FLAGS_PPCIE_ENABLED | GSP_FW_FLAGS_MULTI_GPU_NVLE_ENABLED | GSP_FW_FLAGS_CLOCK_BOOST | GSP_FW_FLAGS_RECOVERY_MARGIN_PRESENT)) return "flag bit the host never sets on GB10B";
+    if (b[242] != 0 || b[243] != 0) return "padding must be 0";
+    if (rd32(b + 244) != 0) return "pmuReservedSize must be 0 on GB10B";
+    if (rd64(b + 248) != 0) return "verified must be 0 on the host side";
+    if (out) {
+        memset(out, 0, sizeof *out);
+        out->bootloader_pa = bl; out->radix3_root_pa = r3; out->elf_size = elf;
+        out->signature_pa = sig; out->signature_size = sigs; out->heap_size = heap;
+        out->crash_queue_pa = cq; out->crash_queue_size = cqs;
+        out->scan_recovery_margin = (b[241] & GSP_FW_FLAGS_SCAN_RECOVERY_MARGIN) != 0;
+    }
+    return NULL;
+}
+
+/* ---------- 2. libos init arguments ---------- */
+
+typedef struct { uint64_t log_pa[GB10B_LOG_COUNT]; uint64_t rmargs_pa; } libos_in;
+
+static const char *libos_encode(const libos_in *in, uint8_t out[LIBOS_MEMORY_REGION_INIT_ARGUMENTS_MAX]) {
+    memset(out, 0, LIBOS_MEMORY_REGION_INIT_ARGUMENTS_MAX);
+    for (unsigned i = 0; i < GB10B_LOG_COUNT; i++)
+        if (in->log_pa[i] == 0 || (in->log_pa[i] & (PAGE_SZ - 1))) return "log buffer address zero or not 4 KiB aligned";
+    if (in->rmargs_pa == 0 || (in->rmargs_pa & (PAGE_SZ - 1))) return "RMARGS address zero or not 4 KiB aligned";
+    LibosMemoryRegionInitArgument e;
+    for (unsigned i = 0; i < GB10B_LIBOS_ENTRIES; i++) {
+        memset(&e, 0, sizeof e);
+        e.kind = LIBOS_MEMORY_REGION_CONTIGUOUS;
+        e.loc = LIBOS_MEMORY_REGION_LOC_SYSMEM;
+        if (i < GB10B_LOG_COUNT) { e.id8 = init_arg_id(gb10b_logs[i].id); e.pa = in->log_pa[i]; e.size = gb10b_logs[i].size; }
+        else { e.id8 = init_arg_id("RMARGS"); e.pa = in->rmargs_pa; e.size = PAGE_SZ; }
+        memcpy(out + i * sizeof e, &e, sizeof e);
+    }
+    return NULL;
+}
+
+static const char *libos_check(const uint8_t *b, size_t n, libos_in *out) {
+    if (n != LIBOS_MEMORY_REGION_INIT_ARGUMENTS_MAX) return "libos init arguments size not 4096";
+    const size_t es = sizeof(LibosMemoryRegionInitArgument);
+    for (unsigned i = 0; i < GB10B_LIBOS_ENTRIES; i++) {
+        const uint8_t *p = b + i * es;
+        uint64_t id = rd64(p), pa = rd64(p + 8), sz = rd64(p + 16);
+        uint8_t kind = p[24], loc = p[25];
+        for (int k = 26; k < 32; k++) if (p[k] != 0) return "entry padding must be 0";
+        if (kind != LIBOS_MEMORY_REGION_CONTIGUOUS) return "entry kind not CONTIGUOUS";
+        if (loc != LIBOS_MEMORY_REGION_LOC_SYSMEM) return "entry loc not SYSMEM";
+        if (pa == 0 || (pa & (PAGE_SZ - 1))) return "entry address zero or not 4 KiB aligned";
+        if (i < GB10B_LOG_COUNT) {
+            if (id != init_arg_id(gb10b_logs[i].id)) return "log entry id or order wrong for GB10B";
+            if (sz != gb10b_logs[i].size) return "log entry size wrong for GB10B";
+        } else {
+            if (id != init_arg_id("RMARGS")) return "entry after the logs is not RMARGS";
+            if (sz != PAGE_SZ) return "RMARGS size not 4096";
+        }
+    }
+    for (size_t k = GB10B_LIBOS_ENTRIES * es; k < n; k++) if (b[k] != 0) return "bytes after the last entry must be 0";
+    if (out) { for (unsigned i = 0; i < GB10B_LOG_COUNT; i++) out->log_pa[i] = rd64(b + i * es + 8); out->rmargs_pa = rd64(b + GB10B_LOG_COUNT * es + 8); }
+    return NULL;
+}
+
+/* ---------- 3. log buffer prefix: put pointer + own PTE table ---------- */
+
+static const char *logbuf_prefix(uint64_t base_pa, uint64_t size, uint8_t *out, size_t cap, size_t *len) {
+    if (base_pa == 0 || (base_pa & (PAGE_SZ - 1))) return "log buffer address zero or not 4 KiB aligned";
+    if (size == 0 || (size & (PAGE_SZ - 1))) return "log buffer size zero or not a page multiple";
+    uint64_t pages = size / PAGE_SZ;
+    size_t need = 8 + (size_t)pages * 8;
+    if (need > size) return "PTE table does not fit in the buffer";
+    if (need > cap) return "output buffer too small";
+    wr64(out, 0);
+    for (uint64_t i = 0; i < pages; i++) wr64(out + 8 + i * 8, base_pa + i * PAGE_SZ);
+    *len = need;
+    return NULL;
+}
+
+/* ---------- 4. GSP_ARGUMENTS_CACHED + RPC shared-buffer page table ---------- */
+
+typedef struct { uint64_t mq_base_pa; uint32_t gpu_instance; uint64_t sysmem_heap_pa, sysmem_heap_size; } rmargs_in;
+
+static const char *rmargs_encode(const rmargs_in *in, uint8_t out[PAGE_SZ]) {
+    GSP_ARGUMENTS_CACHED a;
+    memset(&a, 0, sizeof a);
+    memset(out, 0, PAGE_SZ);
+    if (in->mq_base_pa == 0 || (in->mq_base_pa & (PAGE_SZ - 1))) return "message queue address zero or not 4 KiB aligned";
+    if (in->sysmem_heap_pa == 0 || (in->sysmem_heap_pa & (PAGE_SZ - 1))) return "sysmem heap address zero or not 4 KiB aligned";
+    if (in->sysmem_heap_size == 0 || (in->sysmem_heap_size & ((1ULL << 20) - 1))) return "sysmem heap size zero or not a MiB multiple";
+    a.messageQueueInitArguments.sharedMemPhysAddr = in->mq_base_pa;
+    a.messageQueueInitArguments.pageTableEntryCount = MQ_NUM_PTES;
+    a.messageQueueInitArguments.cmdQueueOffset = MQ_PAGE_TABLE_SIZE;
+    a.messageQueueInitArguments.statQueueOffset = MQ_PAGE_TABLE_SIZE + MQ_CMD_QUEUE_SIZE;
+    a.gpuInstance = in->gpu_instance;
+    a.bDmemStack = 1;
+    a.sysmemHeapArgs.pa = in->sysmem_heap_pa;
+    a.sysmemHeapArgs.size = in->sysmem_heap_size;
+    memcpy(out, &a, sizeof a);
+    return NULL;
+}
+
+static const char *rmargs_check(const uint8_t *b, size_t n, rmargs_in *out) {
+    if (n != PAGE_SZ) return "RMARGS page size not 4096";
+    uint64_t mq = rd64(b + 0); uint32_t ptes = rd32(b + 8);
+    if (rd32(b + 12) != 0) return "padding after pageTableEntryCount must be 0";
+    uint64_t cmd = rd64(b + 16), stat = rd64(b + 24);
+    if (mq == 0 || (mq & (PAGE_SZ - 1))) return "message queue address zero or not 4 KiB aligned";
+    if (ptes != MQ_NUM_PTES) return "pageTableEntryCount not 129";
+    if (cmd != MQ_PAGE_TABLE_SIZE) return "cmdQueueOffset not 4096";
+    if (stat != MQ_PAGE_TABLE_SIZE + MQ_CMD_QUEUE_SIZE) return "statQueueOffset not 266240";
+    if (rd32(b + 32) != 0 || rd32(b + 36) != 0 || b[40] != 0) return "suspend/resume arguments must be 0 on a normal boot";
+    for (int i = 41; i < 44; i++) if (b[i] != 0) return "padding after srInitArguments must be 0";
+    uint32_t gi = rd32(b + 44);
+    if (b[48] != 1) return "bDmemStack not 1";
+    for (int i = 49; i < 56; i++) if (b[i] != 0) return "padding after bDmemStack must be 0";
+    if (rd64(b + 56) != 0 || rd64(b + 64) != 0) return "profilerArgs must be 0";
+    uint64_t hp = rd64(b + 72), hs = rd64(b + 80);
+    if (hp == 0 || (hp & (PAGE_SZ - 1))) return "sysmem heap address zero or not 4 KiB aligned";
+    if (hs == 0 || (hs & ((1ULL << 20) - 1))) return "sysmem heap size zero or not a MiB multiple";
+    for (size_t k = 88; k < n; k++) if (b[k] != 0) return "bytes after GSP_ARGUMENTS_CACHED must be 0";
+    if (out) { out->mq_base_pa = mq; out->gpu_instance = gi; out->sysmem_heap_pa = hp; out->sysmem_heap_size = hs; }
+    return NULL;
+}
+
+/* The RPC shared buffer's page-table page: PAs of all 129 pages, itself first (contiguous case). */
+static const char *mqtable_encode(uint64_t base_pa, uint8_t out[PAGE_SZ]) {
+    memset(out, 0, PAGE_SZ);
+    if (base_pa == 0 || (base_pa & (PAGE_SZ - 1))) return "message queue address zero or not 4 KiB aligned";
+    for (unsigned i = 0; i < MQ_NUM_PTES; i++) wr64(out + i * 8, base_pa + (uint64_t)i * PAGE_SZ);
+    return NULL;
+}
+
+/* ---------- 5. radix-3 layout ---------- */
+
+typedef struct { uint64_t npages[4]; uint64_t offset[4]; uint64_t pt_size, alloc_size; } radix3_layout;
+
+static const char *radix3_plan(uint64_t size, radix3_layout *l) {
+    if (size == 0) return "ELF size zero";
+    memset(l, 0, sizeof *l);
+    l->npages[3] = (size + PAGE_SZ - 1) / PAGE_SZ;
+    for (int i = 3; i > 0; i--) l->npages[i - 1] = ((l->npages[i] - 1) >> 9) + 1;
+    uint64_t n = 0;
+    for (int i = 1; i < 4; i++) { n += l->npages[i - 1]; l->offset[i] = n * PAGE_SZ; }
+    if (l->npages[0] != 1) return "ELF too large for a 3-level radix table";
+    l->pt_size = n * PAGE_SZ;
+    l->alloc_size = l->pt_size + l->npages[3] * PAGE_SZ;
+    return NULL;
+}
+
+/* Fill the three table levels for a contiguous allocation at base_pa (data follows the tables). */
+static const char *radix3_tables(uint64_t size, uint64_t base_pa, uint8_t *out, size_t cap, size_t *len) {
+    radix3_layout l; const char *e = radix3_plan(size, &l);
+    if (e) return e;
+    if (base_pa == 0 || (base_pa & (PAGE_SZ - 1))) return "radix3 base address zero or not 4 KiB aligned";
+    if (l.pt_size > cap) return "output buffer too small";
+    memset(out, 0, l.pt_size);
+    for (int i = 0; i < 3; i++)
+        for (uint64_t k = 0; k < l.npages[i + 1]; k++)
+            wr64(out + l.offset[i] + k * 8, base_pa + l.offset[i + 1] + k * PAGE_SZ);
+    *len = l.pt_size;
+    return NULL;
+}
+
+/* ---------- self-test ---------- */
+
+static int checks, failures;
+static void check(int ok, const char *what) { checks++; if (!ok) { failures++; printf("FAIL: %s\n", what); } }
+static void expect_refusal(const char *got, const char *want, const char *what) {
+    char buf[256]; snprintf(buf, sizeof buf, "%s: expected \"%s\", got \"%s\"", what, want, got ? got : "(accepted)");
+    check(got != NULL && strcmp(got, want) == 0, buf);
+}
+
+static void sample_wpr(wpr_in *w) {
+    memset(w, 0, sizeof *w);
+    w->bootloader_pa = 0x100000000ULL; w->radix3_root_pa = 0x100100000ULL; w->elf_size = 0x4000000ULL;
+    w->signature_pa = 0x100200100ULL; w->signature_size = 0x400;
+}
+
+static int selftest(void) {
+    /* layouts against the compiler */
+    check(sizeof(GspFwWprMeta) == 256, "sizeof GspFwWprMeta == 256");
+    check(offsetof(GspFwWprMeta, sysmemAddrOfSignature) == 72, "sysmemAddrOfSignature at 72");
+    check(offsetof(GspFwWprMeta, gspFwHeapSize) == 128, "gspFwHeapSize at 128");
+    check(offsetof(GspFwWprMeta, bootCount) == 200, "bootCount at 200");
+    check(offsetof(GspFwWprMeta, sysmemAddrOfCrashReportQueue) == 224, "sysmemAddrOfCrashReportQueue at 224");
+    check(offsetof(GspFwWprMeta, gspFwHeapVfPartitionCount) == 240, "gspFwHeapVfPartitionCount at 240");
+    check(offsetof(GspFwWprMeta, flags) == 241, "flags at 241");
+    check(offsetof(GspFwWprMeta, pmuReservedSize) == 244, "pmuReservedSize at 244");
+    check(offsetof(GspFwWprMeta, verified) == 248, "verified at 248");
+    check(sizeof(LibosMemoryRegionInitArgument) == 32, "sizeof LibosMemoryRegionInitArgument == 32");
+    check(offsetof(LibosMemoryRegionInitArgument, kind) == 24 && offsetof(LibosMemoryRegionInitArgument, loc) == 25, "kind/loc at 24/25");
+    check(sizeof(GSP_ARGUMENTS_CACHED) == 88, "sizeof GSP_ARGUMENTS_CACHED == 88");
+    check(offsetof(GSP_ARGUMENTS_CACHED, srInitArguments) == 32, "srInitArguments at 32");
+    check(offsetof(GSP_ARGUMENTS_CACHED, gpuInstance) == 44, "gpuInstance at 44");
+    check(offsetof(GSP_ARGUMENTS_CACHED, bDmemStack) == 48, "bDmemStack at 48");
+    check(offsetof(GSP_ARGUMENTS_CACHED, profilerArgs) == 56, "profilerArgs at 56");
+    check(offsetof(GSP_ARGUMENTS_CACHED, sysmemHeapArgs) == 72, "sysmemHeapArgs at 72");
+    check(sizeof(MESSAGE_QUEUE_INIT_ARGUMENTS) == 32, "sizeof MESSAGE_QUEUE_INIT_ARGUMENTS == 32");
+    check(sizeof(GSP_SR_INIT_ARGUMENTS) == 12, "sizeof GSP_SR_INIT_ARGUMENTS == 12");
+
+    /* golden constants */
+    check(init_arg_id("RMARGS") == 0x524D41524753ULL, "RMARGS id8");
+    check(init_arg_id("LOGINIT") == 0x4C4F47494E4954ULL, "LOGINIT id8");
+    check(init_arg_id("LOGKRNL") == 0x4C4F474B524E4CULL, "LOGKRNL id8");
+    check(init_arg_id("ABCDEFGHIJ") == 0x4142434445464748ULL, "id8 truncates to 8 bytes");
+    check(GB10B_FW_HEAP_SIZE == 0x8500000ULL, "GB10B heap 133 MiB");
+    {   /* recompute the heap exactly as _kgspCalculateFwHeapSize does with ZERO_FB */
+        uint64_t memSizeGB = 1, a1m = (1ULL << 20) - 1;
+        uint64_t heap = (22ULL << 20) + (14ULL << 20) + (((96ULL << 10) * memSizeGB + a1m) & ~a1m) + (((48ULL << 10) * 2048 + a1m) & ~a1m);
+        if (heap < (88ULL << 20)) heap = 88ULL << 20;
+        check(heap == GB10B_FW_HEAP_SIZE, "heap formula reproduces 133 MiB");
+    }
+    check(MQ_NUM_PTES == (MQ_CMD_QUEUE_SIZE + MQ_STAT_QUEUE_SIZE) / PAGE_SZ + ((MQ_CMD_QUEUE_SIZE + MQ_STAT_QUEUE_SIZE) / PAGE_SZ * 8 + PAGE_SZ - 1) / PAGE_SZ, "numPtes formula gives 129");
+    check(((MQ_NUM_PTES * 8 + PAGE_SZ - 1) & ~(PAGE_SZ - 1)) == MQ_PAGE_TABLE_SIZE, "pageTableSize 4096");
+
+    /* 1. WprMeta round trip + golden bytes */
+    wpr_in w, w2; uint8_t m[256];
+    sample_wpr(&w);
+    check(wpr_encode(&w, m) == NULL, "WprMeta encode accepted");
+    check(rd64(m) == GSP_FW_WPR_META_MAGIC && rd64(m + 8) == 1, "magic + revision bytes");
+    check(rd64(m + 40) == GB10B_BOOTLOADER_SIZE && rd64(m + 48) == 0xb000 && rd64(m + 56) == 0xa00 && rd64(m + 64) == 0, "bootloader size/offsets bytes");
+    check(rd64(m + 128) == GB10B_FW_HEAP_SIZE && rd64(m + 104) == 0 && rd64(m + 160) == 0 && rd64(m + 192) == 0 && rd32(m + 244) == 0, "GB10B zeroed fields + heap");
+    check(wpr_check(m, 256, &w2) == NULL, "WprMeta decode accepted");
+    check(memcmp(&w, &w2, sizeof w) == 0 || (w2.heap_size == GB10B_FW_HEAP_SIZE && w2.bootloader_pa == w.bootloader_pa && w2.radix3_root_pa == w.radix3_root_pa && w2.elf_size == w.elf_size && w2.signature_pa == w.signature_pa && w2.signature_size == w.signature_size), "WprMeta round trip");
+    w.heap_size = 200ULL << 20; w.scan_recovery_margin = 1; w.crash_queue_pa = 0x100300000ULL; w.crash_queue_size = 0x2000;
+    check(wpr_encode(&w, m) == NULL && wpr_check(m, 256, &w2) == NULL && w2.heap_size == (200ULL << 20) && w2.scan_recovery_margin == 1 && w2.crash_queue_pa == w.crash_queue_pa && w2.crash_queue_size == 0x2000, "WprMeta optional fields round trip");
+    check(m[241] == GSP_FW_FLAGS_SCAN_RECOVERY_MARGIN, "flags byte");
+    /* encode refusals */
+    { wpr_in b = w; b.bootloader_pa = 0x100000800ULL; expect_refusal(wpr_encode(&b, m), "bootloader address zero or not 4 KiB aligned", "unaligned bootloader"); }
+    { wpr_in b = w; b.bootloader_pa = 0; expect_refusal(wpr_encode(&b, m), "bootloader address zero or not 4 KiB aligned", "zero bootloader"); }
+    { wpr_in b = w; b.radix3_root_pa = 0x1000ULL + 8; expect_refusal(wpr_encode(&b, m), "radix3 root address zero or not 4 KiB aligned", "unaligned radix3"); }
+    { wpr_in b = w; b.elf_size = 0; expect_refusal(wpr_encode(&b, m), "ELF size zero", "zero elf"); }
+    { wpr_in b = w; b.signature_pa = 0x100200080ULL; expect_refusal(wpr_encode(&b, m), "signature address zero or not 256 aligned", "unaligned signature"); }
+    { wpr_in b = w; b.signature_size = 0x3f0; expect_refusal(wpr_encode(&b, m), "signature size zero or not a 256 multiple", "odd signature size"); }
+    { wpr_in b = w; b.heap_size = 87ULL << 20; expect_refusal(wpr_encode(&b, m), "heap size outside [88 MiB, 280 MiB] or not a MiB multiple", "heap too small"); }
+    { wpr_in b = w; b.heap_size = 281ULL << 20; expect_refusal(wpr_encode(&b, m), "heap size outside [88 MiB, 280 MiB] or not a MiB multiple", "heap too large"); }
+    { wpr_in b = w; b.heap_size = (133ULL << 20) + 1; expect_refusal(wpr_encode(&b, m), "heap size outside [88 MiB, 280 MiB] or not a MiB multiple", "heap not MiB"); }
+    { wpr_in b = w; b.crash_queue_size = 0; expect_refusal(wpr_encode(&b, m), "crash report queue address and size must both be zero or both set", "crash queue half set"); }
+    { wpr_in b = w; b.crash_queue_pa = 0x100300010ULL; expect_refusal(wpr_encode(&b, m), "crash report queue address not 4 KiB aligned", "crash queue unaligned"); }
+    /* decode refusals, one field at a time from a good block */
+    sample_wpr(&w); check(wpr_encode(&w, m) == NULL, "good block");
+    expect_refusal(wpr_check(m, 255, NULL), "WprMeta size not 256", "short block");
+    {
+        struct { int off; int width; uint64_t val; const char *want; } muts[] = {
+            {0, 8, 0xdc3aae21371a60b2ULL, "magic wrong"},
+            {8, 8, 2, "revision not 1"},
+            {16, 8, 0x100100800ULL, "radix3 root address zero or not 4 KiB aligned"},
+            {24, 8, 0, "ELF size zero"},
+            {32, 8, 0, "bootloader address zero or not 4 KiB aligned"},
+            {40, 8, 196607, "bootloader size not the GB10B GspRmBoot image size"},
+            {48, 8, 0xb100, "bootloader offsets not the GB10B descriptor values"},
+            {56, 8, 0xa00 + 0x100, "bootloader offsets not the GB10B descriptor values"},
+            {64, 8, 0x100, "bootloader offsets not the GB10B descriptor values"},
+            {72, 8, 0x100200180ULL, "signature address zero or not 256 aligned"},
+            {80, 8, 0x3ff, "signature size zero or not a 256 multiple"},
+            {88, 8, 1, "FMC-owned FB layout field non-zero on the host side"},
+            {96, 8, 1, "FMC-owned FB layout field non-zero on the host side"},
+            {104, 8, 1, "nonWprHeapSize must be 0 on GB10B"},
+            {112, 8, 1, "FMC-owned FB layout field non-zero on the host side"},
+            {120, 8, 1, "FMC-owned FB layout field non-zero on the host side"},
+            {128, 8, 1ULL << 20, "heap size outside [88 MiB, 280 MiB] or not a MiB multiple"},
+            {136, 8, 1, "FMC-owned FB layout field non-zero on the host side"},
+            {144, 8, 1, "FMC-owned FB layout field non-zero on the host side"},
+            {152, 8, 1, "FMC-owned FB layout field non-zero on the host side"},
+            {160, 8, 1, "frtsSize must be 0 on GB10B"},
+            {168, 8, 1, "FMC-owned FB layout field non-zero on the host side"},
+            {176, 8, 1, "FMC-owned FB layout field non-zero on the host side"},
+            {184, 8, 1, "FMC-owned FB layout field non-zero on the host side"},
+            {192, 8, 1, "vgaWorkspaceSize must be 0 on GB10B"},
+            {200, 8, 1, "bootCount must be 0 on the host side"},
+            {208, 8, 1, "partition RPC fields must be 0"},
+            {220, 4, 1, "partition RPC fields must be 0"},
+            {224, 8, 0x100300000ULL, "crash report queue address and size must both be zero or both set"},
+            {232, 4, 0x2000, "crash report queue address and size must both be zero or both set"},
+            {236, 4, 1, "lsUcodeVersion padding must be 0"},
+            {240, 1, 1, "gspFwHeapVfPartitionCount must be 0"},
+            {241, 1, 0x20, "unknown flag bits"},
+            {241, 1, GSP_FW_FLAGS_PPCIE_ENABLED, "flag bit the host never sets on GB10B"},
+            {241, 1, GSP_FW_FLAGS_CLOCK_BOOST, "flag bit the host never sets on GB10B"},
+            {242, 1, 1, "padding must be 0"},
+            {244, 4, 1, "pmuReservedSize must be 0 on GB10B"},
+            {248, 8, GSP_FW_WPR_META_VERIFIED, "verified must be 0 on the host side"},
+        };
+        for (size_t i = 0; i < sizeof muts / sizeof muts[0]; i++) {
+            uint8_t t[256]; memcpy(t, m, 256);
+            if (muts[i].width == 8) wr64(t + muts[i].off, muts[i].val);
+            else if (muts[i].width == 4) wr32(t + muts[i].off, (uint32_t)muts[i].val);
+            else t[muts[i].off] = (uint8_t)muts[i].val;
+            char what[64]; snprintf(what, sizeof what, "WprMeta mutation at %d", muts[i].off);
+            expect_refusal(wpr_check(t, 256, NULL), muts[i].want, what);
+        }
+        { uint8_t t[256]; memcpy(t, m, 256); wr64(t + 224, 0x100300010ULL); wr32(t + 232, 0x1000);
+          expect_refusal(wpr_check(t, 256, NULL), "crash report queue address not 4 KiB aligned", "crash queue unaligned (decode)"); }
+    }
+
+    /* 2. libos init arguments */
+    libos_in li, li2; uint8_t la[LIBOS_MEMORY_REGION_INIT_ARGUMENTS_MAX];
+    for (unsigned i = 0; i < GB10B_LOG_COUNT; i++) li.log_pa[i] = 0x200000000ULL + (uint64_t)i * 0x10000;
+    li.rmargs_pa = 0x200100000ULL;
+    check(libos_encode(&li, la) == NULL, "libos encode accepted");
+    check(rd64(la) == init_arg_id("LOGINIT") && rd64(la + 16) == 0x10000 && la[24] == 1 && la[25] == 1, "entry 0 bytes");
+    check(rd64(la + 5 * 32) == init_arg_id("LOGROOT") && rd64(la + 5 * 32 + 16) == 0x1000, "LOGROOT entry 4 KiB");
+    check(rd64(la + 6 * 32) == init_arg_id("LOGKRNL"), "LOGKRNL entry seventh");
+    check(rd64(la + 7 * 32) == init_arg_id("RMARGS") && rd64(la + 7 * 32 + 16) == 4096 && rd64(la + 7 * 32 + 8) == li.rmargs_pa, "RMARGS entry eighth");
+    check(la[8 * 32] == 0 && la[8 * 32 + 24] == LIBOS_MEMORY_REGION_NONE, "ninth entry is NONE");
+    check(libos_check(la, sizeof la, &li2) == NULL && memcmp(&li, &li2, sizeof li) == 0, "libos round trip");
+    { libos_in b = li; b.log_pa[2] = 0x200020800ULL; expect_refusal(libos_encode(&b, la), "log buffer address zero or not 4 KiB aligned", "libos unaligned log"); }
+    { libos_in b = li; b.rmargs_pa = 0; expect_refusal(libos_encode(&b, la), "RMARGS address zero or not 4 KiB aligned", "libos zero rmargs"); }
+    check(libos_encode(&li, la) == NULL, "libos good block");
+    expect_refusal(libos_check(la, 4095, NULL), "libos init arguments size not 4096", "libos short");
+    { uint8_t t[4096]; memcpy(t, la, 4096); t[24] = LIBOS_MEMORY_REGION_RADIX3; expect_refusal(libos_check(t, 4096, NULL), "entry kind not CONTIGUOUS", "libos kind"); }
+    { uint8_t t[4096]; memcpy(t, la, 4096); t[25] = LIBOS_MEMORY_REGION_LOC_FB; expect_refusal(libos_check(t, 4096, NULL), "entry loc not SYSMEM", "libos loc"); }
+    { uint8_t t[4096]; memcpy(t, la, 4096); t[30] = 1; expect_refusal(libos_check(t, 4096, NULL), "entry padding must be 0", "libos pad"); }
+    { uint8_t t[4096]; memcpy(t, la, 4096); wr64(t + 32, init_arg_id("LOGRM")); expect_refusal(libos_check(t, 4096, NULL), "log entry id or order wrong for GB10B", "libos order"); }
+    { uint8_t t[4096]; memcpy(t, la, 4096); wr64(t + 5 * 32 + 16, 0x10000); expect_refusal(libos_check(t, 4096, NULL), "log entry size wrong for GB10B", "libos size"); }
+    { uint8_t t[4096]; memcpy(t, la, 4096); wr64(t + 7 * 32, init_arg_id("RMCOV")); expect_refusal(libos_check(t, 4096, NULL), "entry after the logs is not RMARGS", "libos rmargs id"); }
+    { uint8_t t[4096]; memcpy(t, la, 4096); wr64(t + 7 * 32 + 16, 88); expect_refusal(libos_check(t, 4096, NULL), "RMARGS size not 4096", "libos rmargs size"); }
+    { uint8_t t[4096]; memcpy(t, la, 4096); wr64(t + 3 * 32 + 8, 0); expect_refusal(libos_check(t, 4096, NULL), "entry address zero or not 4 KiB aligned", "libos zero pa"); }
+    { uint8_t t[4096]; memcpy(t, la, 4096); t[9 * 32 + 24] = 1; expect_refusal(libos_check(t, 4096, NULL), "bytes after the last entry must be 0", "libos trailing"); }
+
+    /* 3. log buffer prefix */
+    uint8_t lb[8 + 16 * 8]; size_t ln = 0;
+    check(logbuf_prefix(0x200000000ULL, 0x10000, lb, sizeof lb, &ln) == NULL && ln == 8 + 16 * 8, "logbuf 64 KiB prefix length");
+    check(rd64(lb) == 0 && rd64(lb + 8) == 0x200000000ULL && rd64(lb + 8 + 15 * 8) == 0x20000F000ULL, "logbuf put + PTEs");
+    check(logbuf_prefix(0x200000000ULL, 0x1000, lb, sizeof lb, &ln) == NULL && ln == 16, "logbuf 4 KiB prefix");
+    expect_refusal(logbuf_prefix(0x200000000ULL, 0x1800, lb, sizeof lb, &ln), "log buffer size zero or not a page multiple", "logbuf odd size");
+    expect_refusal(logbuf_prefix(0x200000100ULL, 0x1000, lb, sizeof lb, &ln), "log buffer address zero or not 4 KiB aligned", "logbuf unaligned");
+    expect_refusal(logbuf_prefix(0x200000000ULL, 0x10000, lb, 16, &ln), "output buffer too small", "logbuf small out");
+
+    /* 4. RMARGS + message queue table */
+    rmargs_in ri = { 0x300000000ULL, 0, 0x400000000ULL, GB10B_SYSMEM_HEAP }, ri2; uint8_t ra[PAGE_SZ];
+    check(rmargs_encode(&ri, ra) == NULL, "rmargs encode accepted");
+    check(rd64(ra) == 0x300000000ULL && rd32(ra + 8) == 129 && rd64(ra + 16) == 4096 && rd64(ra + 24) == 266240 && ra[48] == 1 && rd64(ra + 72) == 0x400000000ULL && rd64(ra + 80) == (512ULL << 20), "rmargs bytes");
+    check(rmargs_check(ra, PAGE_SZ, &ri2) == NULL && memcmp(&ri, &ri2, sizeof ri) == 0, "rmargs round trip");
+    { rmargs_in b = ri; b.mq_base_pa = 0x300000010ULL; expect_refusal(rmargs_encode(&b, ra), "message queue address zero or not 4 KiB aligned", "rmargs mq unaligned"); }
+    { rmargs_in b = ri; b.sysmem_heap_size = 0x80000; expect_refusal(rmargs_encode(&b, ra), "sysmem heap size zero or not a MiB multiple", "rmargs heap size"); }
+    { rmargs_in b = ri; b.sysmem_heap_pa = 0; expect_refusal(rmargs_encode(&b, ra), "sysmem heap address zero or not 4 KiB aligned", "rmargs heap pa"); }
+    check(rmargs_encode(&ri, ra) == NULL, "rmargs good block");
+    expect_refusal(rmargs_check(ra, 88, NULL), "RMARGS page size not 4096", "rmargs short");
+    { uint8_t t[PAGE_SZ]; memcpy(t, ra, PAGE_SZ); wr32(t + 8, 128); expect_refusal(rmargs_check(t, PAGE_SZ, NULL), "pageTableEntryCount not 129", "rmargs ptes"); }
+    { uint8_t t[PAGE_SZ]; memcpy(t, ra, PAGE_SZ); wr32(t + 12, 1); expect_refusal(rmargs_check(t, PAGE_SZ, NULL), "padding after pageTableEntryCount must be 0", "rmargs pad"); }
+    { uint8_t t[PAGE_SZ]; memcpy(t, ra, PAGE_SZ); wr64(t + 16, 8192); expect_refusal(rmargs_check(t, PAGE_SZ, NULL), "cmdQueueOffset not 4096", "rmargs cmd"); }
+    { uint8_t t[PAGE_SZ]; memcpy(t, ra, PAGE_SZ); wr64(t + 24, 4096); expect_refusal(rmargs_check(t, PAGE_SZ, NULL), "statQueueOffset not 266240", "rmargs stat"); }
+    { uint8_t t[PAGE_SZ]; memcpy(t, ra, PAGE_SZ); t[40] = 1; expect_refusal(rmargs_check(t, PAGE_SZ, NULL), "suspend/resume arguments must be 0 on a normal boot", "rmargs sr"); }
+    { uint8_t t[PAGE_SZ]; memcpy(t, ra, PAGE_SZ); t[48] = 0; expect_refusal(rmargs_check(t, PAGE_SZ, NULL), "bDmemStack not 1", "rmargs dmem"); }
+    { uint8_t t[PAGE_SZ]; memcpy(t, ra, PAGE_SZ); wr64(t + 56, 1); expect_refusal(rmargs_check(t, PAGE_SZ, NULL), "profilerArgs must be 0", "rmargs profiler"); }
+    { uint8_t t[PAGE_SZ]; memcpy(t, ra, PAGE_SZ); t[100] = 1; expect_refusal(rmargs_check(t, PAGE_SZ, NULL), "bytes after GSP_ARGUMENTS_CACHED must be 0", "rmargs trailing"); }
+    uint8_t mt[PAGE_SZ];
+    check(mqtable_encode(0x300000000ULL, mt) == NULL && rd64(mt) == 0x300000000ULL && rd64(mt + 128 * 8) == 0x300080000ULL && rd64(mt + 129 * 8) == 0, "mq table 129 PTEs, itself first");
+    expect_refusal(mqtable_encode(0x300000008ULL, mt), "message queue address zero or not 4 KiB aligned", "mq table unaligned");
+
+    /* 5. radix3 */
+    radix3_layout rl;
+    check(radix3_plan(1, &rl) == NULL && rl.npages[3] == 1 && rl.npages[2] == 1 && rl.npages[1] == 1 && rl.npages[0] == 1 && rl.pt_size == 3 * PAGE_SZ && rl.alloc_size == 4 * PAGE_SZ, "radix3 one byte");
+    check(radix3_plan(512 * PAGE_SZ, &rl) == NULL && rl.npages[3] == 512 && rl.npages[2] == 1 && rl.pt_size == 3 * PAGE_SZ, "radix3 exactly 512 pages");
+    check(radix3_plan(512 * PAGE_SZ + 1, &rl) == NULL && rl.npages[3] == 513 && rl.npages[2] == 2 && rl.npages[1] == 1 && rl.pt_size == 4 * PAGE_SZ && rl.offset[1] == PAGE_SZ && rl.offset[2] == 2 * PAGE_SZ && rl.offset[3] == 4 * PAGE_SZ, "radix3 513 pages");
+    check(radix3_plan(75012080ULL, &rl) == NULL && rl.npages[3] == 18314 && rl.npages[2] == 36 && rl.npages[1] == 1 && rl.pt_size == 38 * PAGE_SZ, "radix3 for the pinned gsp_ga10x.bin size");
+    expect_refusal(radix3_plan(0, &rl), "ELF size zero", "radix3 zero");
+    expect_refusal(radix3_plan(((uint64_t)512 * 512 * 512 + 1) * PAGE_SZ, &rl), "ELF too large for a 3-level radix table", "radix3 too large");
+    static uint8_t rt[4 * 4096]; size_t rn = 0;
+    check(radix3_tables(512 * PAGE_SZ + 1, 0x500000000ULL, rt, sizeof rt, &rn) == NULL && rn == 4 * PAGE_SZ, "radix3 tables length");
+    check(rd64(rt) == 0x500001000ULL && rd64(rt + 8) == 0, "level 0 -> level 1 page");
+    check(rd64(rt + PAGE_SZ) == 0x500002000ULL && rd64(rt + PAGE_SZ + 8) == 0x500003000ULL && rd64(rt + PAGE_SZ + 16) == 0, "level 1 -> two level 2 pages");
+    check(rd64(rt + 2 * PAGE_SZ) == 0x500004000ULL && rd64(rt + 2 * PAGE_SZ + 511 * 8) == 0x500004000ULL + 511 * PAGE_SZ && rd64(rt + 3 * PAGE_SZ) == 0x500004000ULL + 512 * PAGE_SZ && rd64(rt + 3 * PAGE_SZ + 8) == 0, "level 2 -> 513 data pages");
+    expect_refusal(radix3_tables(PAGE_SZ, 0x500000100ULL, rt, sizeof rt, &rn), "radix3 base address zero or not 4 KiB aligned", "radix3 base unaligned");
+
+    printf("CK_GSP_BOOT_ARGS_ENCODE_SELFTEST: %s (%d checks, %d failures)\n", failures ? "FAIL" : "PASS", checks, failures);
+    return failures ? 1 : 0;
+}
+
+/* ---------- CLI ---------- */
+
+static uint64_t parse_u64(const char *s, int *ok) { char *e; unsigned long long v = strtoull(s, &e, 0); if (*s == 0 || *e != 0) { *ok = 0; return 0; } return v; }
+static int write_file(const char *path, const uint8_t *b, size_t n) { FILE *f = fopen(path, "wb"); if (!f) return -1; size_t w = fwrite(b, 1, n, f); fclose(f); return w == n ? 0 : -1; }
+static int read_file(const char *path, uint8_t **b, size_t *n) {
+    FILE *f = fopen(path, "rb"); if (!f) return -1;
+    fseek(f, 0, SEEK_END); long len = ftell(f); fseek(f, 0, SEEK_SET);
+    if (len < 0 || len > (1 << 20)) { fclose(f); return -1; }
+    *b = malloc((size_t)len + 1); if (!*b) { fclose(f); return -1; }
+    *n = fread(*b, 1, (size_t)len, f); fclose(f); return *n == (size_t)len ? 0 : -1;
+}
+static int usage(void) {
+    fprintf(stderr, "usage: ck_gsp_boot_args_encode selftest | layout\n"
+        "  wprmeta --bootloader HEX --radix3 HEX --elf-size N --sig HEX --sig-size N [--heap N] [--crashq HEX --crashq-size N] [--scan-margin] [--out F]\n"
+        "  check-wprmeta F | check-libos F | check-rmargs F\n"
+        "  libos --log HEX x7 (LOGINIT LOGINTR LOGRM LOGMNOC LOGDBG LOGROOT LOGKRNL) --rmargs HEX [--out F]\n"
+        "  logbuf --pa HEX --size N [--out F]\n"
+        "  rmargs --mq HEX [--gpu N] --heap HEX --heap-size N [--out F]\n"
+        "  mqtable --mq HEX [--out F]\n"
+        "  radix3 --elf-size N [--base HEX --out F]\n");
+    return 2;
+}
+static int refused(const char *why) { printf("REFUSED: %s\n", why); return 2; }
+/* Write the block to --out when given; 0 on success, 2 (refused) on a write failure. */
+static int emit(const char *out, const uint8_t *b, size_t n) {
+    if (!out) return 0;
+    if (write_file(out, b, n)) return refused("cannot write output");
+    printf("wrote %s (%zu bytes)\n", out, n);
+    return 0;
+}
+static void dump(const uint8_t *b, size_t n) { for (size_t i = 0; i < n; i++) printf("%02x%s", b[i], (i % 32 == 31 || i + 1 == n) ? "\n" : ""); }
+
+int main(int argc, char **argv) {
+    if (argc < 2) return usage();
+    const char *mode = argv[1];
+    if (!strcmp(mode, "selftest")) return selftest();
+    if (!strcmp(mode, "layout")) {
+        printf("GspFwWprMeta 256 bytes: magic 0 revision 8 sysmemAddrOfRadix3Elf 16 sizeOfRadix3Elf 24 sysmemAddrOfBootloader 32 sizeOfBootloader 40 bootloaderCodeOffset 48 bootloaderDataOffset 56 bootloaderManifestOffset 64 sysmemAddrOfSignature 72 sizeOfSignature 80 gspFwRsvdStart 88 nonWprHeapOffset 96 nonWprHeapSize 104 gspFwWprStart 112 gspFwHeapOffset 120 gspFwHeapSize 128 gspFwOffset 136 bootBinOffset 144 frtsOffset 152 frtsSize 160 gspFwWprEnd 168 fbSize 176 vgaWorkspaceOffset 184 vgaWorkspaceSize 192 bootCount 200 partitionRpc/crashQueue 208..239 gspFwHeapVfPartitionCount 240 flags 241 padding 242 pmuReservedSize 244 verified 248\n");
+        printf("LibosMemoryRegionInitArgument 32 bytes: id8 0 pa 8 size 16 kind 24 loc 25; page holds 128 entries, GB10B uses 8\n");
+        printf("GSP_ARGUMENTS_CACHED 88 bytes: sharedMemPhysAddr 0 pageTableEntryCount 8 cmdQueueOffset 16 statQueueOffset 24 sr.oldLevel 32 sr.flags 36 sr.bInPMTransition 40 gpuInstance 44 bDmemStack 48 profilerArgs 56 sysmemHeapArgs 72\n");
+        printf("GB10B constants: bootloader 196608 code 0xb000 data 0xa00 manifest 0x0; heap 0x%llx (133 MiB) in [88,280] MiB; frts 0; nonWprHeap 0; sysmem heap default 512 MiB; mq cmd 0x40000 stat 0x40000 ptes 129 table 4096; logs LOGINIT LOGINTR LOGRM LOGMNOC LOGDBG(64K each) LOGROOT(4K) LOGKRNL(64K) then RMARGS(4K)\n", (unsigned long long)GB10B_FW_HEAP_SIZE);
+        return 0;
+    }
+    const char *out = NULL; int ok = 1;
+    uint64_t v[16] = {0}; int nlog = 0; uint64_t logs[GB10B_LOG_COUNT] = {0}; int scan = 0; unsigned gpu = 0;
+    enum { A_BL, A_R3, A_ELF, A_SIG, A_SIGS, A_HEAP, A_CQ, A_CQS, A_RM, A_PA, A_SZ, A_MQ, A_HEAPPA, A_HEAPSZ, A_BASE };
+    static const char *names[] = {"--bootloader", "--radix3", "--elf-size", "--sig", "--sig-size", "--heap", "--crashq", "--crashq-size", "--rmargs", "--pa", "--size", "--mq", "--heap", "--heap-size", "--base"};
+    int is_rmargs = !strcmp(mode, "rmargs");
+    for (int i = 2; i < argc; i++) {
+        if (!strcmp(argv[i], "--out") && i + 1 < argc) { out = argv[++i]; continue; }
+        if (!strcmp(argv[i], "--scan-margin")) { scan = 1; continue; }
+        if (!strcmp(argv[i], "--gpu") && i + 1 < argc) { gpu = (unsigned)parse_u64(argv[++i], &ok); continue; }
+        if (!strcmp(argv[i], "--log") && i + 1 < argc) { if (nlog < (int)GB10B_LOG_COUNT) logs[nlog++] = parse_u64(argv[++i], &ok); else return refused("more than 7 --log values"); continue; }
+        int hit = 0;
+        for (int k = 0; k < 15 && i + 1 < argc; k++) {
+            if (!strcmp(argv[i], names[k])) {
+                if (k == A_HEAP && is_rmargs) k = A_HEAPPA;   /* rmargs: --heap is the sysmem heap address */
+                v[k] = parse_u64(argv[++i], &ok); hit = 1; break;
+            }
+        }
+        if (!hit) { if (argv[i][0] == '-') return usage(); }
+        if (!ok) return refused("bad number");
+    }
+    if (!strcmp(mode, "wprmeta")) {
+        wpr_in w = { v[A_BL], v[A_R3], v[A_ELF], v[A_SIG], v[A_SIGS], v[A_HEAP], v[A_CQ], (uint32_t)v[A_CQS], scan };
+        uint8_t m[256]; const char *e = wpr_encode(&w, m); if (e) return refused(e);
+        printf("wprmeta ok heap=0x%llx\n", (unsigned long long)rd64(m + 128)); dump(m, 256);
+        return emit(out, m, 256);
+    }
+    if (!strcmp(mode, "libos")) {
+        if (nlog != (int)GB10B_LOG_COUNT) return refused("need exactly 7 --log values");
+        libos_in li; memcpy(li.log_pa, logs, sizeof logs); li.rmargs_pa = v[A_RM];
+        uint8_t la[4096]; const char *e = libos_encode(&li, la); if (e) return refused(e);
+        printf("libos ok entries=%u\n", GB10B_LIBOS_ENTRIES); dump(la, GB10B_LIBOS_ENTRIES * 32);
+        return emit(out, la, 4096);
+    }
+    if (!strcmp(mode, "logbuf")) {
+        static uint8_t lb[8 + 4096]; size_t ln = 0; const char *e = logbuf_prefix(v[A_PA], v[A_SZ], lb, sizeof lb, &ln); if (e) return refused(e);
+        printf("logbuf ok prefix=%zu bytes pages=%llu\n", ln, (unsigned long long)(v[A_SZ] / PAGE_SZ)); dump(lb, ln > 64 ? 64 : ln);
+        return emit(out, lb, ln);
+    }
+    if (is_rmargs) {
+        rmargs_in ri = { v[A_MQ], gpu, v[A_HEAPPA], v[A_HEAPSZ] ? v[A_HEAPSZ] : GB10B_SYSMEM_HEAP };
+        uint8_t ra[PAGE_SZ]; const char *e = rmargs_encode(&ri, ra); if (e) return refused(e);
+        printf("rmargs ok\n"); dump(ra, 88);
+        return emit(out, ra, PAGE_SZ);
+    }
+    if (!strcmp(mode, "mqtable")) {
+        uint8_t mt[PAGE_SZ]; const char *e = mqtable_encode(v[A_MQ], mt); if (e) return refused(e);
+        printf("mqtable ok ptes=%u cmd=0x%llx stat=0x%llx\n", MQ_NUM_PTES, (unsigned long long)(v[A_MQ] + MQ_PAGE_TABLE_SIZE), (unsigned long long)(v[A_MQ] + MQ_PAGE_TABLE_SIZE + MQ_CMD_QUEUE_SIZE)); dump(mt, 64);
+        return emit(out, mt, PAGE_SZ);
+    }
+    if (!strcmp(mode, "radix3")) {
+        radix3_layout l; const char *e = radix3_plan(v[A_ELF], &l); if (e) return refused(e);
+        printf("radix3 ok data_pages=%llu l2_pages=%llu l1_pages=%llu l0_pages=1 table_bytes=%llu alloc_bytes=%llu data_offset=0x%llx\n",
+               (unsigned long long)l.npages[3], (unsigned long long)l.npages[2], (unsigned long long)l.npages[1], (unsigned long long)l.pt_size, (unsigned long long)l.alloc_size, (unsigned long long)l.offset[3]);
+        if (v[A_BASE]) {
+            uint8_t *rt = malloc(l.pt_size); size_t rn = 0; if (!rt) return refused("out of memory");
+            e = radix3_tables(v[A_ELF], v[A_BASE], rt, l.pt_size, &rn); if (e) { free(rt); return refused(e); }
+            int rc = emit(out, rt, rn);
+            free(rt);
+            if (rc) return rc;
+        }
+        return 0;
+    }
+    if (!strncmp(mode, "check-", 6)) {
+        if (argc < 3) return usage();
+        uint8_t *b; size_t n; if (read_file(argv[2], &b, &n)) return refused("cannot read file");
+        const char *e = !strcmp(mode, "check-wprmeta") ? wpr_check(b, n, NULL) : !strcmp(mode, "check-libos") ? libos_check(b, n, NULL) : !strcmp(mode, "check-rmargs") ? rmargs_check(b, n, NULL) : "unknown check";
+        free(b);
+        if (e) return refused(e);
+        printf("%s: OK\n", mode); return 0;
+    }
+    return usage();
+}
diff --git a/native/kernel/tools/ck_gsp_rpc_encode.c b/native/kernel/tools/ck_gsp_rpc_encode.c
new file mode 100644
index 00000000..d1778733
--- /dev/null
+++ b/native/kernel/tools/ck_gsp_rpc_encode.c
@@ -0,0 +1,594 @@
+/* ck_gsp_rpc_encode -- host tool: byte-exact encoder, decoder and refusal
+ * tests for the GSP-RM message queue (command queue, status queue, queue
+ * element, RPC header, continuation records and the packed registry table)
+ * exactly as the pinned Linux driver (nvidia-open 580.173.02) builds them
+ * (aienos#286 cut C host work: "parsers and refusal tests for firmware
+ * metadata. No loading"). docs/GB10_FIRMWARE_INVENTORY.md section 13 is the
+ * report this tool backs. Nothing here touches a device.
+ *
+ * Every line below is from open-gpu-kernel-modules tag 580.173.02:
+ *
+ *  1. Shared queue library (src/nvidia/src/libraries/.../msgq.c, msgq_priv.h):
+ *     msgqTxHeader 32 bytes {version, size, msgSize, msgCount, writePtr,
+ *     flags, rxHdrOff, entryOff} written by the producer; msgqRxHeader
+ *     4 bytes {readPtr} written by the consumer. MSGQ_VERSION 0.
+ *     msgqTxCreate(size, msgSize, hdrAlign, entryAlign, flags):
+ *       rxHdrOff = ALIGN_UP(32, 1<<hdrAlign)
+ *       entryOff = ALIGN_UP(rxHdrOff + 4, 1<<entryAlign)
+ *       refuse: msgSize < 16, msgSize > size, size < entryOff + msgSize
+ *       msgCount = (size - entryOff) / msgSize, writePtr 0, txFree = msgCount-1
+ *     msgqRxLink(size, msgSize) on the peer's header refuses (return codes):
+ *       -2 msgSize < 16; -3 msgSize > size; -6 size < entryOff + msgSize;
+ *       -7 size mismatch; -8 msgSize mismatch; -9 version != 0;
+ *       -10 rxHdrOff < 32 or entryOff < our rxHdrOff + 4 or
+ *           msgCount != (size - entryOff) / msgSize.
+ *     SWAP_RX (flag 1) on both sides: each side's readPtr for incoming
+ *     messages lives in its OWN backing store at its rxHdrOff.
+ *     Ring arithmetic (msgqTxGetFreeSpace / msgqRxGetReadAvailable):
+ *       free  = (readPtr + msgCount - writePtr - 1) mod msgCount
+ *       avail = (writePtr + msgCount - readPtr) mod msgCount
+ *     a pointer >= msgCount is corrupt: 0 free / 0 available.
+ *
+ *  2. The driver's queues (message_queue_cpu.c GspMsgQueuesInit, kernel_gsp
+ *     tu102 queue setup): command queue 0x40000 bytes, status queue 0x40000
+ *     bytes, both msgSize 4096 (GSP_MSG_QUEUE_ELEMENT_SIZE_MIN), hdrAlign 4
+ *     (16 bytes), entryAlign 12 (4096), flags MSGQ_FLAGS_SWAP_RX. Hence
+ *     rxHdrOff 32, entryOff 4096, msgCount 63, 62 usable slots.
+ *
+ *  3. GSP_MSG_QUEUE_ELEMENT (message_queue_priv.h:36-51): authTagBuffer[16],
+ *     aadBuffer[16], u32 checkSum, u32 seqNum, u32 elemCount, then the RPC
+ *     header aligned 8 at offset 48 (GSP_MSG_QUEUE_ELEMENT_HDR_SIZE 48);
+ *     sizeof = 80. ELEMENT_SIZE_MIN 4096, MAX 16*4096 = 65536,
+ *     BYTES_TO_ELEMENTS = ceil(bytes / 4096). RPC_SIZE_MAX = 65536-48 =
+ *     65488 (pRpc->maxRpcSize, kernel_gsp.c).
+ *
+ *  4. rpc_message_header_v03_00 (g_rpc-message-header.h), 32 bytes:
+ *     u32 header_version, signature, length, function, rpc_result,
+ *     rpc_result_private, sequence, cpuRmGfid. rpcWriteCommonHeader
+ *     (rpc_common.c): zero the buffer, header_version = MAJOR 3 << 24 |
+ *     MINOR 0 << 16 (rpc_headers.h:56-59), signature 0x43505256
+ *     ("VRPC" little-endian, rpc_headers.h:61), rpc_result and
+ *     rpc_result_private = RPC_PENDING 0xFFFFFFFF, function, length = 32 +
+ *     payload. sequence: synchronous RPCs get pRpc->sequence++, asynchronous
+ *     (_issueRpcAsync, pSequence NULL) get 0 (kernel_gsp.c:395-406).
+ *
+ *  5. GspMsgQueueSendCommand (message_queue_cpu.c:440-600), no CC:
+ *     msgLen = 48 + rpc.length; refuse msgLen < 80 or > 65536
+ *     (NV_ERR_INVALID_PARAM_STRUCT); zero-pad to a multiple of 8;
+ *     seqNum = txSeqNum (0 at init, ++ per accepted message); elemCount =
+ *     ceil(msgLen/4096); checkSum = 0 then checkSum = _checkSum32(msgLen):
+ *     XOR of every u64 word, then HI32 ^ LO32, so the finished element
+ *     checksums to zero (message_queue_priv.h:112-124). Elements are copied
+ *     4096 bytes at a time into successive ring slots, then submitted
+ *     (msgqTxSubmitBuffers) and the doorbell NV_PGSP_QUEUE_HEAD(0) =
+ *     0x110c00 is written 0 (dev_gsp_tu102.h:38, kernel_gsp_tu102.c
+ *     kgspSetCmdQueueHead).
+ *
+ *  6. GspMsgQueueReceiveStatus (:600-720): read element 0 of the status
+ *     ring, nElements = elemCount, copy all; checksum over 48 + rpc.length
+ *     must be 0 (NV_ERR_INVALID_DATA); seqNum must equal rxSeqNum ("Bad
+ *     sequence number": an older seqNum is consumed and the read retried,
+ *     up to 3 times), then rxSeqNum++. kgspWaitForRmInitDone polls for
+ *     NV_VGPU_MSG_EVENT_GSP_INIT_DONE (0x1001) with sequence 0 and requires
+ *     rpc_result == NV_OK.
+ *
+ *  7. Large RPCs (_issueRpcLarge, rpc.c:2038-2130): first message carries
+ *     the real function with length = min(total, 65488); each further chunk
+ *     is a fresh header with function CONTINUATION_RECORD (71), length =
+ *     32 + chunk, chunk <= 65488 - 32 = 65456 payload bytes.
+ *
+ *  8. SET_REGISTRY (function 73, rpcSetRegistry_v17_00, rpc.c ~10700 and
+ *     RmPackageRegistry, arch/nvalloc/unix/src/registry.c:628-711) payload
+ *     PACKED_REGISTRY_TABLE (g_os_nvoc.h:226-248): u32 size, u32
+ *     numEntries, entries[] of {u32 nameOffset; u8 type; u32 data; u32
+ *     length} (natural layout 16 bytes, entries at offset 8), then the
+ *     string area: for each entry the NUL-terminated name, then for STRING
+ *     (3) / BINARY (2) the value bytes with data = their offset; DWORD (1)
+ *     keeps the value in data with length 4 and no bytes in the area. size =
+ *     8 + 16*n + sum(namelen+1) + sum(value bytes); numEntries == n;
+ *     a zero-length string/binary is skipped by the driver with a warning
+ *     and this encoder refuses it. An empty registry is NV_WARN_NOTHING_TO_DO
+ *     and the RPC is not sent.
+ *
+ *  9. GSP_SET_SYSTEM_INFO (function 72, rpcGspSetSystemInfo_v17_00,
+ *     rpc.c:10493) payload GspSystemInfo (gsp_static_config.h:172-229):
+ *     PCI/BAR physical addresses, PCI ids, chipset, ACPI method data,
+ *     hypervisor/VF state, host page size. Its contents come from the real
+ *     device and the native kernel's bus layer; this tool records the
+ *     function number, the header rule and the size: 936 bytes under the
+ *     natural LP64 layout (no pack pragma in gsp_static_config.h; nested
+ *     BUSINFO 10 bytes (g_chipset_nvoc.h:220-227), ACPI_METHOD_DATA 676
+ *     bytes = bValid + DOD 72 + JT 12 + MUX 580 + CAPS 8 with
+ *     NV0073_CTRL_SYSTEM_ACPI_ID_MAP_MAX_DISPLAYS 16 (gpu_acpi_data.h:72-115,
+ *     ctrl0073system.h:747), GSP_VF_INFO 40, GSP_PCIE_CONFIG_REG 4), so the
+ *     RPC length is 32 + 936 = 968 and it fits one 4 KiB slot. The size was
+ *     reproduced by compiling the struct text copied from those headers.
+ *
+ * Claim tags: every number above is DOCUMENTED (source lines). That the
+ * GSP-RM firmware on GB10B accepts exactly these bytes without Linux present
+ * is INFERRED (medium) until the first attended run.
+ */
+#include <stddef.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define MSGQ_VERSION            0u
+#define MSGQ_FLAGS_SWAP_RX      1u
+#define MSGQ_MSG_SIZE_MIN       16u
+#define MSGQ_TX_HDR_SIZE        32u
+#define MSGQ_RX_HDR_SIZE        4u
+#define GSP_MQ_SIZE             0x40000u
+#define GSP_MQ_MSG_SIZE         4096u
+#define GSP_MQ_HDR_ALIGN        4u      /* 2^4 */
+#define GSP_MQ_ENTRY_ALIGN      12u     /* 2^12 */
+#define GSP_MQ_RXHDR_OFF        32u
+#define GSP_MQ_ENTRY_OFF        4096u
+#define GSP_MQ_MSG_COUNT        63u
+#define ELEM_HDR_SIZE           48u
+#define ELEM_STRUCT_SIZE        80u
+#define ELEM_SIZE_MIN           4096u
+#define ELEM_SIZE_MAX           65536u
+#define RPC_HDR_SIZE            32u
+#define RPC_SIZE_MAX            (ELEM_SIZE_MAX - ELEM_HDR_SIZE)      /* 65488 */
+#define RPC_CONT_PAYLOAD_MAX    (RPC_SIZE_MAX - RPC_HDR_SIZE)        /* 65456 */
+#define RPC_HEADER_VERSION      0x03000000u
+#define RPC_SIGNATURE_VALID     0x43505256u
+#define RPC_PENDING             0xFFFFFFFFu
+#define RPC_RESULT_UNKNOWN_FN   0xFF100001u
+#define RPC_RESULT_BAD_FORMAT   0xFF100002u
+#define FN_NOP                  0u
+#define FN_CONTINUATION_RECORD  71u
+#define FN_GSP_SET_SYSTEM_INFO  72u
+#define FN_SET_REGISTRY         73u
+#define EV_GSP_INIT_DONE        0x1001u
+#define EV_GSP_RUN_CPU_SEQUENCER 0x1002u
+#define EV_RC_TRIGGERED         0x1004u
+#define EV_GSP_LOCKDOWN_NOTICE  0x101cu
+#define EV_GSP_POST_NOCAT_RECORD 0x1020u
+#define NV_PGSP_QUEUE_HEAD_0    0x110c00u
+#define GSP_SYSTEM_INFO_SIZE    936u
+#define GSP_SYSTEM_INFO_RPC_LEN (RPC_HDR_SIZE + GSP_SYSTEM_INFO_SIZE)   /* 968 */
+#define REG_TYPE_UNKNOWN 0u
+#define REG_TYPE_DWORD   1u
+#define REG_TYPE_BINARY  2u
+#define REG_TYPE_STRING  3u
+#define REG_TABLE_HDR    8u
+#define REG_ENTRY_SIZE   16u
+
+/* Compiler-checked layouts (natural alignment, LP64; same on aarch64 and the
+ * x86-64 CI host). */
+typedef struct { uint32_t version, size, msgSize, msgCount, writePtr, flags, rxHdrOff, entryOff; } msgq_tx_header;
+typedef struct { uint32_t readPtr; } msgq_rx_header;
+typedef struct { uint32_t header_version, signature, length, function, rpc_result, rpc_result_private, sequence, cpuRmGfid; } rpc_header;
+typedef struct { uint8_t authTag[16], aad[16]; uint32_t checkSum, seqNum, elemCount; _Alignas(8) rpc_header rpc; } mq_element;
+typedef struct { uint32_t nameOffset; uint8_t type; uint32_t data; uint32_t length; } packed_reg_entry;
+typedef struct { uint32_t size, numEntries; } packed_reg_table_hdr;
+_Static_assert(sizeof(msgq_tx_header) == MSGQ_TX_HDR_SIZE, "msgqTxHeader is 32 bytes");
+_Static_assert(sizeof(msgq_rx_header) == MSGQ_RX_HDR_SIZE, "msgqRxHeader is 4 bytes");
+_Static_assert(sizeof(rpc_header) == RPC_HDR_SIZE, "rpc_message_header_v is 32 bytes");
+_Static_assert(offsetof(mq_element, rpc) == ELEM_HDR_SIZE, "rpc header at 48");
+_Static_assert(sizeof(mq_element) == ELEM_STRUCT_SIZE, "GSP_MSG_QUEUE_ELEMENT is 80 bytes");
+_Static_assert(sizeof(packed_reg_entry) == REG_ENTRY_SIZE, "PACKED_REGISTRY_ENTRY is 16 bytes");
+_Static_assert(offsetof(packed_reg_entry, type) == 4 && offsetof(packed_reg_entry, data) == 8 && offsetof(packed_reg_entry, length) == 12, "entry field offsets");
+_Static_assert(sizeof(packed_reg_table_hdr) == REG_TABLE_HDR, "PACKED_REGISTRY_TABLE entries at 8");
+
+static uint64_t rd64(const uint8_t *p) { uint64_t v = 0; for (int i = 7; i >= 0; i--) v = (v << 8) | p[i]; return v; }
+static uint32_t rd32(const uint8_t *p) { return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); }
+static void wr32(uint8_t *p, uint32_t v) { for (int i = 0; i < 4; i++) { p[i] = (uint8_t)v; v >>= 8; } }
+static uint32_t align_up(uint32_t v, uint32_t a) { return (v + a - 1) & ~(a - 1); }
+
+/* ---- 1. queue headers ---- */
+typedef struct { uint32_t size, msgSize, hdrAlign, entryAlign, flags; } mq_create_in;
+
+/* msgqTxCreate rules; writes the 32-byte producer header. */
+static const char *mq_tx_create(const mq_create_in *in, uint8_t out[MSGQ_TX_HDR_SIZE]) {
+    if (in->msgSize < MSGQ_MSG_SIZE_MIN || in->msgSize > in->size) return "msgSize out of range";
+    if (in->hdrAlign < 2 || in->hdrAlign > 31 || in->entryAlign < 2 || in->entryAlign > 31) return "alignment out of range";
+    uint32_t rxHdrOff = align_up(MSGQ_TX_HDR_SIZE, 1u << in->hdrAlign);
+    uint32_t entryOff = align_up(rxHdrOff + MSGQ_RX_HDR_SIZE, 1u << in->entryAlign);
+    if (in->size < entryOff + in->msgSize) return "size too small for one entry";
+    msgq_tx_header h = { MSGQ_VERSION, in->size, in->msgSize, (in->size - entryOff) / in->msgSize, 0, in->flags, rxHdrOff, entryOff };
+    memcpy(out, &h, sizeof h);
+    return NULL;
+}
+
+/* msgqRxLink checks on a peer header we read from shared memory. Returns the
+ * driver's negative code as text so a log line can be matched. our_rxHdrOff
+ * is our own header's rxHdrOff (the -10 rule compares against it). */
+static const char *mq_rx_link_check(const uint8_t *b, size_t n, uint32_t size, uint32_t msgSize, uint32_t our_rxHdrOff, msgq_tx_header *out) {
+    if (n < MSGQ_TX_HDR_SIZE) return "short header";
+    if (msgSize < MSGQ_MSG_SIZE_MIN) return "-2 msgSize below 16";
+    if (msgSize > size) return "-3 msgSize above size";
+    msgq_tx_header h; memcpy(&h, b, sizeof h);
+    if (size < h.entryOff + msgSize) return "-6 size below entryOff + msgSize";
+    if (h.size != size) return "-7 size mismatch";
+    if (h.msgSize != msgSize) return "-8 msgSize mismatch";
+    if (h.version != MSGQ_VERSION) return "-9 version not 0";
+    if (h.rxHdrOff < MSGQ_TX_HDR_SIZE || h.entryOff < our_rxHdrOff + MSGQ_RX_HDR_SIZE || h.msgCount != (size - h.entryOff) / msgSize) return "-10 offsets or msgCount inconsistent";
+    if (h.writePtr >= h.msgCount) return "writePtr beyond msgCount";
+    if (out) *out = h;
+    return NULL;
+}
+
+static uint32_t ring_free(uint32_t readPtr, uint32_t writePtr, uint32_t msgCount) {
+    if (readPtr >= msgCount || writePtr >= msgCount || msgCount == 0) return 0;
+    return (readPtr + msgCount - writePtr - 1) % msgCount;
+}
+static uint32_t ring_avail(uint32_t readPtr, uint32_t writePtr, uint32_t msgCount) {
+    if (readPtr >= msgCount || writePtr >= msgCount || msgCount == 0) return 0;
+    return (writePtr + msgCount - readPtr) % msgCount;
+}
+
+/* ---- 2. RPC header + queue element ---- */
+static uint32_t checksum32(const uint8_t *p, size_t len) {
+    uint64_t x = 0;
+    for (size_t i = 0; i < len; i += 8) x ^= rd64(p + i);
+    return (uint32_t)(x >> 32) ^ (uint32_t)x;
+}
+
+typedef struct { uint32_t function, sequence, payload_len; const uint8_t *payload; uint32_t seqNum; } elem_in;
+
+/* Build one message as the driver would place it in the ring: element header +
+ * RPC header + payload, zero padded to elemCount*4096. out must hold 65536.
+ * *msg_len gets the padded-to-8 message length used for the checksum. */
+static const char *elem_encode(const elem_in *in, uint8_t *out, size_t cap, uint32_t *msg_len, uint32_t *elem_count) {
+    if (in->payload_len > RPC_SIZE_MAX - RPC_HDR_SIZE) return "payload exceeds RPC_SIZE_MAX";
+    uint32_t rpc_len = RPC_HDR_SIZE + in->payload_len;
+    uint32_t msgLen = ELEM_HDR_SIZE + rpc_len;
+    if (msgLen < ELEM_STRUCT_SIZE || msgLen > ELEM_SIZE_MAX) return "message length outside [80, 65536]";
+    uint32_t nelem = (msgLen + ELEM_SIZE_MIN - 1) / ELEM_SIZE_MIN;
+    if (cap < (size_t)nelem * ELEM_SIZE_MIN) return "output too small";
+    memset(out, 0, (size_t)nelem * ELEM_SIZE_MIN);
+    rpc_header h = { RPC_HEADER_VERSION, RPC_SIGNATURE_VALID, rpc_len, in->function, RPC_PENDING, RPC_PENDING, in->sequence, 0 };
+    memcpy(out + ELEM_HDR_SIZE, &h, sizeof h);
+    if (in->payload_len) memcpy(out + ELEM_HDR_SIZE + RPC_HDR_SIZE, in->payload, in->payload_len);
+    wr32(out + 36, in->seqNum);
+    wr32(out + 40, nelem);
+    wr32(out + 32, 0);
+    uint32_t padded = align_up(msgLen, 8);
+    wr32(out + 32, checksum32(out, padded));
+    if (msg_len) *msg_len = padded;
+    if (elem_count) *elem_count = nelem;
+    return NULL;
+}
+
+typedef struct { uint32_t checkSum, seqNum, elemCount; rpc_header rpc; uint32_t msgLen; } elem_view;
+
+/* Receive-side validation (GspMsgQueueReceiveStatus + rpcRecvPoll checks). */
+static const char *elem_check(const uint8_t *b, size_t n, uint32_t expect_seq, elem_view *out) {
+    if (n < ELEM_STRUCT_SIZE) return "short element";
+    elem_view v; v.checkSum = rd32(b + 32); v.seqNum = rd32(b + 36); v.elemCount = rd32(b + 40);
+    memcpy(&v.rpc, b + ELEM_HDR_SIZE, sizeof v.rpc);
+    if (v.rpc.signature != RPC_SIGNATURE_VALID) return "bad RPC signature";
+    if (v.rpc.header_version != RPC_HEADER_VERSION) return "bad RPC header version";
+    if (v.rpc.length < RPC_HDR_SIZE || v.rpc.length > RPC_SIZE_MAX) return "RPC length outside [32, 65488]";
+    v.msgLen = ELEM_HDR_SIZE + v.rpc.length;
+    if (v.elemCount == 0 || v.elemCount > ELEM_SIZE_MAX / ELEM_SIZE_MIN) return "elemCount outside [1, 16]";
+    if (v.elemCount != (v.msgLen + ELEM_SIZE_MIN - 1) / ELEM_SIZE_MIN) return "elemCount does not match length";
+    if (n < (size_t)align_up(v.msgLen, 8)) return "element shorter than its RPC length";
+    if (checksum32(b, align_up(v.msgLen, 8)) != 0) return "checksum not zero";
+    if (v.seqNum != expect_seq) return v.seqNum < expect_seq ? "old seqNum (driver consumes and retries)" : "seqNum ahead of expected";
+    if (out) *out = v;
+    return NULL;
+}
+
+/* ---- 3. continuation plan for a large RPC ---- */
+typedef struct { uint32_t chunks; uint32_t first_len; uint32_t last_payload; } cont_plan;
+static const char *cont_plan_for(uint32_t total_rpc_len, cont_plan *p) {
+    if (total_rpc_len < RPC_HDR_SIZE) return "total below header";
+    p->first_len = total_rpc_len < RPC_SIZE_MAX ? total_rpc_len : RPC_SIZE_MAX;
+    uint32_t rem = total_rpc_len - p->first_len; p->chunks = 1; p->last_payload = 0;
+    while (rem) { uint32_t c = rem < RPC_CONT_PAYLOAD_MAX ? rem : RPC_CONT_PAYLOAD_MAX; rem -= c; p->chunks++; p->last_payload = c; }
+    return NULL;
+}
+
+/* ---- 4. packed registry table ---- */
+typedef struct { const char *name; uint8_t type; uint32_t dword; const uint8_t *bytes; uint32_t len; } reg_in;
+
+static const char *reg_encode(const reg_in *e, uint32_t n, uint8_t *out, size_t cap, uint32_t *size_out) {
+    if (n == 0) return "empty registry (driver: NV_WARN_NOTHING_TO_DO, RPC not sent)";
+    uint32_t size = REG_TABLE_HDR + REG_ENTRY_SIZE * n;
+    for (uint32_t i = 0; i < n; i++) {
+        if (!e[i].name || !e[i].name[0]) return "entry without a name";
+        if (e[i].type == REG_TYPE_DWORD) { if (e[i].len) return "DWORD entry carries bytes"; }
+        else if (e[i].type == REG_TYPE_STRING || e[i].type == REG_TYPE_BINARY) { if (e[i].len == 0) return "zero-length string/binary (driver would drop it)"; }
+        else return "unknown entry type";
+        size += (uint32_t)strlen(e[i].name) + 1 + e[i].len;
+    }
+    if (size > RPC_SIZE_MAX - RPC_HDR_SIZE) return "registry exceeds one RPC (driver would use continuation records)";
+    if (cap < size) return "output too small";
+    memset(out, 0, size);
+    wr32(out, size); wr32(out + 4, n);
+    uint32_t off = REG_TABLE_HDR + REG_ENTRY_SIZE * n;
+    for (uint32_t i = 0; i < n; i++) {
+        uint8_t *ent = out + REG_TABLE_HDR + REG_ENTRY_SIZE * i;
+        uint32_t slen = (uint32_t)strlen(e[i].name) + 1;
+        wr32(ent, off); memcpy(out + off, e[i].name, slen); off += slen;
+        ent[4] = e[i].type;
+        if (e[i].type == REG_TYPE_DWORD) { wr32(ent + 8, e[i].dword); wr32(ent + 12, 4); }
+        else { wr32(ent + 8, off); wr32(ent + 12, e[i].len); memcpy(out + off, e[i].bytes, e[i].len); off += e[i].len; }
+    }
+    if (off != size) return "first/second pass mismatch";
+    if (size_out) *size_out = size;
+    return NULL;
+}
+
+static const char *reg_check(const uint8_t *b, size_t n, uint32_t *entries_out) {
+    if (n < REG_TABLE_HDR) return "short table";
+    uint32_t size = rd32(b), cnt = rd32(b + 4);
+    if (size != n) return "size field does not match buffer";
+    if (cnt == 0) return "no entries";
+    if ((uint64_t)REG_TABLE_HDR + (uint64_t)REG_ENTRY_SIZE * cnt > size) return "entry table overruns size";
+    uint32_t expect_off = REG_TABLE_HDR + REG_ENTRY_SIZE * cnt;
+    for (uint32_t i = 0; i < cnt; i++) {
+        const uint8_t *ent = b + REG_TABLE_HDR + REG_ENTRY_SIZE * i;
+        uint32_t nameOff = rd32(ent), type = ent[4], data = rd32(ent + 8), len = rd32(ent + 12);
+        if (ent[5] || ent[6] || ent[7]) return "entry padding not zero";
+        if (nameOff != expect_off) return "name not packed in order";
+        uint32_t k = nameOff; while (k < size && b[k]) k++;
+        if (k >= size || k == nameOff) return "name not terminated or empty";
+        expect_off = k + 1;
+        if (type == REG_TYPE_DWORD) { if (len != 4) return "DWORD length not 4"; }
+        else if (type == REG_TYPE_STRING || type == REG_TYPE_BINARY) {
+            if (len == 0 || data != expect_off) return "string/binary data offset or length wrong";
+            if ((uint64_t)data + len > size) return "value overruns size";
+            expect_off += len;
+        } else return "unknown entry type";
+    }
+    if (expect_off != size) return "trailing bytes or size short";
+    if (entries_out) *entries_out = cnt;
+    return NULL;
+}
+
+/* ---- self-test ---- */
+static int checks, failures;
+static void check(int ok, const char *what) { checks++; if (!ok) { failures++; printf("FAIL: %s\n", what); } }
+static void expect_refusal(const char *got, const char *want, const char *what) {
+    checks++; if (!got || strncmp(got, want, strlen(want))) { failures++; printf("FAIL: %s: got '%s' want '%s'\n", what, got ? got : "(accepted)", want); }
+}
+
+static int selftest(void) {
+    /* 1. the driver's own queue geometry */
+    mq_create_in q = { GSP_MQ_SIZE, GSP_MQ_MSG_SIZE, GSP_MQ_HDR_ALIGN, GSP_MQ_ENTRY_ALIGN, MSGQ_FLAGS_SWAP_RX };
+    uint8_t th[MSGQ_TX_HDR_SIZE];
+    check(mq_tx_create(&q, th) == NULL, "command queue header encodes");
+    static const uint8_t golden_tx[32] = { 0,0,0,0, 0,0,4,0, 0,16,0,0, 63,0,0,0, 0,0,0,0, 1,0,0,0, 32,0,0,0, 0,16,0,0 };
+    check(memcmp(th, golden_tx, 32) == 0, "golden msgqTxHeader for 256 KiB / 4096 / swap-rx");
+    check(rd32(th + 12) == GSP_MQ_MSG_COUNT && rd32(th + 24) == GSP_MQ_RXHDR_OFF && rd32(th + 28) == GSP_MQ_ENTRY_OFF, "msgCount 63, rxHdrOff 32, entryOff 4096");
+    mq_create_in bad = q; bad.msgSize = 8; expect_refusal(mq_tx_create(&bad, th), "msgSize out of range", "msgSize below 16 refused");
+    bad = q; bad.msgSize = GSP_MQ_SIZE + 1; expect_refusal(mq_tx_create(&bad, th), "msgSize out of range", "msgSize above size refused");
+    bad = q; bad.size = 4096; expect_refusal(mq_tx_create(&bad, th), "size too small", "size without room for an entry refused");
+    bad = q; bad.hdrAlign = 1; expect_refusal(mq_tx_create(&bad, th), "alignment out of range", "hdrAlign below 2 refused");
+    /* peer link checks against the same header (GSP builds its status queue identically) */
+    msgq_tx_header peer;
+    check(mq_rx_link_check(golden_tx, 32, GSP_MQ_SIZE, GSP_MQ_MSG_SIZE, GSP_MQ_RXHDR_OFF, &peer) == NULL && peer.msgCount == 63, "rxLink accepts the driver's header");
+    expect_refusal(mq_rx_link_check(golden_tx, 32, GSP_MQ_SIZE, 8, 32, NULL), "-2", "rxLink msgSize < 16");
+    expect_refusal(mq_rx_link_check(golden_tx, 32, 4096, 8192, 32, NULL), "-3", "rxLink msgSize > size");
+    expect_refusal(mq_rx_link_check(golden_tx, 32, 4096, 4096, 32, NULL), "-6", "rxLink size < entryOff + msgSize");
+    expect_refusal(mq_rx_link_check(golden_tx, 32, 0x80000, 4096, 32, NULL), "-7", "rxLink size mismatch");
+    expect_refusal(mq_rx_link_check(golden_tx, 32, GSP_MQ_SIZE, 8192, 32, NULL), "-8", "rxLink msgSize mismatch");
+    uint8_t mut[32]; memcpy(mut, golden_tx, 32); wr32(mut, 1); expect_refusal(mq_rx_link_check(mut, 32, GSP_MQ_SIZE, 4096, 32, NULL), "-9", "rxLink version != 0");
+    memcpy(mut, golden_tx, 32); wr32(mut + 24, 16); expect_refusal(mq_rx_link_check(mut, 32, GSP_MQ_SIZE, 4096, 32, NULL), "-10", "rxLink rxHdrOff < 32");
+    memcpy(mut, golden_tx, 32); wr32(mut + 12, 62); expect_refusal(mq_rx_link_check(mut, 32, GSP_MQ_SIZE, 4096, 32, NULL), "-10", "rxLink msgCount wrong");
+    memcpy(mut, golden_tx, 32); wr32(mut + 16, 63); expect_refusal(mq_rx_link_check(mut, 32, GSP_MQ_SIZE, 4096, 32, NULL), "writePtr beyond", "writePtr >= msgCount refused");
+    expect_refusal(mq_rx_link_check(golden_tx, 16, GSP_MQ_SIZE, 4096, 32, NULL), "short header", "short header refused");
+    /* ring arithmetic */
+    check(ring_free(0, 0, 63) == 62 && ring_avail(0, 0, 63) == 0, "empty ring: 62 free, 0 available");
+    check(ring_free(0, 62, 63) == 0 && ring_avail(0, 62, 63) == 62, "full ring: 0 free, 62 available");
+    check(ring_free(5, 3, 63) == 1 && ring_avail(5, 3, 63) == 61, "wrapped write behind read");
+    check(ring_free(10, 20, 63) == 52 && ring_avail(10, 20, 63) == 10, "read behind write");
+    check(ring_free(63, 0, 63) == 0 && ring_avail(0, 63, 63) == 0, "pointer at msgCount reads as corrupt: 0");
+    check(ring_free(0, 0, 0) == 0, "msgCount 0 never divides");
+    /* 2. one small RPC (NOP, sync sequence 7, queue seqNum 3) */
+    static uint8_t el[ELEM_SIZE_MAX]; uint32_t ml = 0, ec = 0;
+    elem_in e = { FN_NOP, 7, 0, NULL, 3 };
+    check(elem_encode(&e, el, sizeof el, &ml, &ec) == NULL && ml == 80 && ec == 1, "NOP element: 80 bytes, 1 slot");
+    check(rd32(el + 48) == RPC_HEADER_VERSION && rd32(el + 52) == RPC_SIGNATURE_VALID && rd32(el + 56) == 32 && rd32(el + 60) == FN_NOP, "RPC header words");
+    check(rd32(el + 64) == RPC_PENDING && rd32(el + 68) == RPC_PENDING && rd32(el + 72) == 7 && rd32(el + 76) == 0, "pending results, sequence, gfid 0");
+    check(rd32(el + 36) == 3 && rd32(el + 40) == 1, "element seqNum and elemCount");
+    check(checksum32(el, 80) == 0, "finished element checksums to zero");
+    for (int i = 0; i < 32; i++) check(el[i] == 0, "auth/aad bytes zero without CC");
+    elem_view v;
+    check(elem_check(el, 4096, 3, &v) == NULL && v.rpc.function == FN_NOP && v.msgLen == 80, "receive-side validation accepts it");
+    expect_refusal(elem_check(el, 4096, 4, NULL), "old seqNum", "older seqNum flagged for consume-and-retry");
+    expect_refusal(elem_check(el, 4096, 2, NULL), "seqNum ahead", "future seqNum refused");
+    memcpy(mut, el, 32); uint8_t tmp[4096]; memcpy(tmp, el, 4096);
+    tmp[70] ^= 1; expect_refusal(elem_check(tmp, 4096, 3, NULL), "checksum not zero", "flipped header bit breaks the checksum");
+    memcpy(tmp, el, 4096); wr32(tmp + 52, 0x43505257); expect_refusal(elem_check(tmp, 4096, 3, NULL), "bad RPC signature", "signature mutation refused");
+    memcpy(tmp, el, 4096); wr32(tmp + 48, 0x02000000); expect_refusal(elem_check(tmp, 4096, 3, NULL), "bad RPC header version", "version 2 refused");
+    memcpy(tmp, el, 4096); wr32(tmp + 40, 2); expect_refusal(elem_check(tmp, 4096, 3, NULL), "elemCount does not match", "elemCount 2 for an 80-byte message refused");
+    memcpy(tmp, el, 4096); wr32(tmp + 56, 16); expect_refusal(elem_check(tmp, 4096, 3, NULL), "RPC length outside", "length below header refused");
+    expect_refusal(elem_check(el, 64, 3, NULL), "short element", "short buffer refused");
+    /* 3. a payload that needs several ring slots, odd length to exercise the pad */
+    static uint8_t pay[9000]; for (size_t i = 0; i < sizeof pay; i++) pay[i] = (uint8_t)(i * 7 + 1);
+    e.function = FN_SET_REGISTRY; e.sequence = 0; e.payload_len = 9001 - 32; e.payload = pay; e.seqNum = 0;
+    check(elem_encode(&e, el, sizeof el, &ml, &ec) == NULL && ec == 3 && ml == align_up(48 + 9001, 8), "9001-byte RPC: 3 slots, padded to 8");
+    check(checksum32(el, ml) == 0 && el[48 + 9001] == 0 && el[48 + 9001 + 6] == 0, "zero padding after the message");
+    check(elem_check(el, 3 * 4096, 0, &v) == NULL && v.elemCount == 3 && v.rpc.length == 9001, "multi-slot element validates");
+    check(elem_check(el, 9056, 0, NULL) == NULL, "exactly the padded length suffices");
+    expect_refusal(elem_check(el, 9048, 0, NULL), "element shorter", "buffer one word short refused");
+    /* bounds */
+    static uint8_t big[70000];
+    e.payload = big; e.payload_len = RPC_SIZE_MAX - RPC_HDR_SIZE; check(elem_encode(&e, el, sizeof el, &ml, &ec) == NULL && ec == 16 && ml == ELEM_SIZE_MAX, "largest RPC: 65488 bytes in 16 slots");
+    e.payload_len = RPC_SIZE_MAX - RPC_HDR_SIZE + 1; expect_refusal(elem_encode(&e, el, sizeof el, &ml, &ec), "payload exceeds", "65489 refused");
+    e.payload_len = 0; expect_refusal(elem_encode(&e, el, 64, &ml, &ec), "output too small", "small output refused");
+    /* 4. continuation plan */
+    cont_plan cp;
+    check(cont_plan_for(32, &cp) == NULL && cp.chunks == 1 && cp.first_len == 32, "header-only RPC: one message");
+    check(cont_plan_for(RPC_SIZE_MAX, &cp) == NULL && cp.chunks == 1, "65488 fits in one message");
+    check(cont_plan_for(RPC_SIZE_MAX + 1, &cp) == NULL && cp.chunks == 2 && cp.last_payload == 1, "65489: one continuation record of 1 byte");
+    check(cont_plan_for(RPC_SIZE_MAX + RPC_CONT_PAYLOAD_MAX, &cp) == NULL && cp.chunks == 2 && cp.last_payload == RPC_CONT_PAYLOAD_MAX, "exactly one full continuation");
+    check(cont_plan_for(RPC_SIZE_MAX + RPC_CONT_PAYLOAD_MAX + 1, &cp) == NULL && cp.chunks == 3 && cp.last_payload == 1, "third chunk starts at 65489+65456+1");
+    expect_refusal(cont_plan_for(8, &cp), "total below header", "sub-header total refused");
+    /* 5. registry table */
+    static const uint8_t bin[3] = { 0xaa, 0xbb, 0xcc };
+    reg_in regs[3] = { { "RmMsg", REG_TYPE_STRING, 0, (const uint8_t *)"abc", 3 }, { "EnableGpuFirmwareLogs", REG_TYPE_DWORD, 1, NULL, 0 }, { "Blob", REG_TYPE_BINARY, 0, bin, 3 } };
+    static uint8_t rt[4096]; uint32_t rs = 0;
+    check(reg_encode(regs, 3, rt, sizeof rt, &rs) == NULL, "three-entry registry encodes");
+    /* 8 + 48 + ("RmMsg"6 + 3) + ("EnableGpuFirmwareLogs"22) + ("Blob"5 + 3) = 95 */
+    check(rs == 95 && rd32(rt) == 95 && rd32(rt + 4) == 3, "size 95, numEntries 3");
+    check(rd32(rt + 8) == 56 && rt[12] == REG_TYPE_STRING && rd32(rt + 16) == 62 && rd32(rt + 20) == 3 && memcmp(rt + 56, "RmMsg", 6) == 0 && memcmp(rt + 62, "abc", 3) == 0, "string entry: name at 56, value at 62");
+    check(rd32(rt + 24) == 65 && rt[28] == REG_TYPE_DWORD && rd32(rt + 32) == 1 && rd32(rt + 36) == 4, "dword entry: name at 65, data 1, length 4");
+    check(rd32(rt + 40) == 87 && rt[44] == REG_TYPE_BINARY && rd32(rt + 48) == 92 && rd32(rt + 52) == 3 && memcmp(rt + 92, bin, 3) == 0, "binary entry: name at 87, value at 92");
+    check(rt[13] == 0 && rt[14] == 0 && rt[15] == 0, "entry padding bytes zero");
+    uint32_t cnt = 0; check(reg_check(rt, rs, &cnt) == NULL && cnt == 3, "registry check accepts its own output");
+    uint8_t rm[4096]; memcpy(rm, rt, rs); wr32(rm, 96); expect_refusal(reg_check(rm, rs, NULL), "size field", "size field mismatch refused");
+    memcpy(rm, rt, rs); wr32(rm + 4, 0); expect_refusal(reg_check(rm, rs, NULL), "no entries", "zero entries refused");
+    memcpy(rm, rt, rs); wr32(rm + 4, 7); expect_refusal(reg_check(rm, rs, NULL), "entry table overruns", "numEntries beyond size refused");
+    memcpy(rm, rt, rs); rm[13] = 1; expect_refusal(reg_check(rm, rs, NULL), "entry padding", "dirty padding refused");
+    memcpy(rm, rt, rs); wr32(rm + 8, 57); expect_refusal(reg_check(rm, rs, NULL), "name not packed", "out-of-order name refused");
+    memcpy(rm, rt, rs); rm[61] = 'x'; expect_refusal(reg_check(rm, rs, NULL), "string/binary data offset", "unterminated name is caught by the value offset");
+    memcpy(rm, rt, rs); wr32(rm + 36, 8); expect_refusal(reg_check(rm, rs, NULL), "DWORD length", "dword with length 8 refused");
+    memcpy(rm, rt, rs); wr32(rm + 52, 4); expect_refusal(reg_check(rm, rs, NULL), "value overruns", "binary length past the end refused");
+    memcpy(rm, rt, rs); rm[44] = 9; expect_refusal(reg_check(rm, rs, NULL), "unknown entry type", "type 9 refused");
+    memcpy(rm, rt, rs); rm[rs] = 0; expect_refusal(reg_check(rm, rs + 1, NULL), "size field", "trailing byte refused");
+    expect_refusal(reg_encode(regs, 0, rt, sizeof rt, &rs), "empty registry", "empty registry refused");
+    reg_in z = { "Zero", REG_TYPE_STRING, 0, (const uint8_t *)"", 0 }; expect_refusal(reg_encode(&z, 1, rt, sizeof rt, &rs), "zero-length", "zero-length string refused");
+    reg_in d = { "D", REG_TYPE_DWORD, 5, bin, 3 }; expect_refusal(reg_encode(&d, 1, rt, sizeof rt, &rs), "DWORD entry carries", "dword with bytes refused");
+    reg_in u = { "U", 7, 0, NULL, 0 }; expect_refusal(reg_encode(&u, 1, rt, sizeof rt, &rs), "unknown entry type", "unknown type refused");
+    reg_in nn = { "", REG_TYPE_DWORD, 1, NULL, 0 }; expect_refusal(reg_encode(&nn, 1, rt, sizeof rt, &rs), "entry without a name", "empty name refused");
+    reg_in bg = { "Big", REG_TYPE_BINARY, 0, big, 66000 }; expect_refusal(reg_encode(&bg, 1, rt, sizeof rt, &rs), "registry exceeds one RPC", "oversize registry refused");
+    expect_refusal(reg_encode(regs, 3, rt, 16, &rs), "output too small", "small registry output refused");
+    /* 6. a complete SET_REGISTRY message, as the driver would ring it */
+    e.function = FN_SET_REGISTRY; e.sequence = 0; e.payload_len = rs; e.payload = rt; e.seqNum = 1;
+    check(elem_encode(&e, el, sizeof el, &ml, &ec) == NULL && ec == 1 && rd32(el + 56) == 32 + 95 && rd32(el + 60) == FN_SET_REGISTRY, "SET_REGISTRY element: length 127, function 73");
+    check(elem_check(el, 4096, 1, &v) == NULL && reg_check(el + 80, v.rpc.length - 32, &cnt) == NULL && cnt == 3, "registry survives the element round trip");
+    /* 7. constants a native kernel must match */
+    check(FN_CONTINUATION_RECORD == 71 && FN_GSP_SET_SYSTEM_INFO == 72 && FN_SET_REGISTRY == 73, "function numbers 71/72/73");
+    check(EV_GSP_INIT_DONE == 0x1001 && EV_GSP_RUN_CPU_SEQUENCER == 0x1002 && EV_RC_TRIGGERED == 0x1004 && EV_GSP_LOCKDOWN_NOTICE == 0x101c && EV_GSP_POST_NOCAT_RECORD == 0x1020, "event numbers");
+    check(RPC_RESULT_UNKNOWN_FN == 0xFF100001 && RPC_RESULT_BAD_FORMAT == 0xFF100002 && NV_PGSP_QUEUE_HEAD_0 == 0x110c00, "result codes and doorbell register");
+    check(RPC_SIZE_MAX == 65488 && RPC_CONT_PAYLOAD_MAX == 65456, "RPC_SIZE_MAX 65488, continuation payload 65456");
+    /* 8. the system-info message: 936-byte payload, one slot */
+    e.function = FN_GSP_SET_SYSTEM_INFO; e.sequence = 0; e.payload_len = GSP_SYSTEM_INFO_SIZE; e.payload = big; e.seqNum = 0;
+    check(elem_encode(&e, el, sizeof el, &ml, &ec) == NULL && ec == 1 && rd32(el + 56) == GSP_SYSTEM_INFO_RPC_LEN && ml == 1016, "GSP_SET_SYSTEM_INFO: length 968, 1 slot, padded 1016");
+    check(elem_check(el, 4096, 0, &v) == NULL && v.rpc.function == FN_GSP_SET_SYSTEM_INFO, "system-info element validates with seqNum 0");
+    printf("CK_GSP_RPC_ENCODE_SELFTEST: %s (%d checks, %d failures)\n", failures ? "FAIL" : "PASS", checks, failures);
+    return failures ? 1 : 0;
+}
+
+/* ---- CLI ---- */
+static uint64_t parse_u64(const char *s, int *ok) { char *e; unsigned long long v = strtoull(s, &e, 0); if (*s == 0 || *e != 0) { *ok = 0; return 0; } return v; }
+static int write_file(const char *path, const uint8_t *b, size_t n) { FILE *f = fopen(path, "wb"); if (!f) return -1; size_t w = fwrite(b, 1, n, f); fclose(f); return w == n ? 0 : -1; }
+static int read_file(const char *path, uint8_t **b, size_t *n) {
+    FILE *f = fopen(path, "rb"); if (!f) return -1;
+    fseek(f, 0, SEEK_END); long len = ftell(f); fseek(f, 0, SEEK_SET);
+    if (len < 0 || len > (1 << 20)) { fclose(f); return -1; }
+    *b = malloc((size_t)len + 1); if (!*b) { fclose(f); return -1; }
+    *n = fread(*b, 1, (size_t)len, f); fclose(f); return *n == (size_t)len ? 0 : -1;
+}
+static int usage(void) {
+    fprintf(stderr, "usage: ck_gsp_rpc_encode selftest | layout\n"
+        "  txheader [--size N --msg-size N --hdr-align N --entry-align N --flags N] [--out F]   (defaults: the driver's command queue)\n"
+        "  check-txheader F [--size N --msg-size N --our-rxhdr N]                               (msgqRxLink rules on a peer header)\n"
+        "  ring --read N --write N [--count N]                                                  (free / available slots)\n"
+        "  element --function N [--sequence N] [--seqnum N] [--payload F] [--out F]            (one ring message, padded to whole slots)\n"
+        "  check-element F [--seqnum N]                                                         (receive-side validation)\n"
+        "  contplan --rpc-len N                                                                 (continuation records needed)\n"
+        "  registry --dword NAME=N | --string NAME=TEXT ... [--out F]                           (PACKED_REGISTRY_TABLE)\n"
+        "  check-registry F\n");
+    return 2;
+}
+static int refused(const char *why) { printf("REFUSED: %s\n", why); return 2; }
+static int emit(const char *out, const uint8_t *b, size_t n) {
+    if (!out) return 0;
+    if (write_file(out, b, n)) return refused("cannot write output");
+    printf("wrote %s (%zu bytes)\n", out, n);
+    return 0;
+}
+static void dump(const uint8_t *b, size_t n) { for (size_t i = 0; i < n; i++) printf("%02x%s", b[i], (i % 32 == 31 || i + 1 == n) ? "\n" : ""); }
+
+int main(int argc, char **argv) {
+    if (argc < 2) return usage();
+    const char *mode = argv[1];
+    if (!strcmp(mode, "selftest")) return selftest();
+    if (!strcmp(mode, "layout")) {
+        printf("msgqTxHeader 32 bytes: version 0 size 4 msgSize 8 msgCount 12 writePtr 16 flags 20 rxHdrOff 24 entryOff 28; msgqRxHeader: readPtr 0\n");
+        printf("driver queues: size 0x40000 msgSize 4096 hdrAlign 16 entryAlign 4096 flags SWAP_RX -> rxHdrOff 32 entryOff 4096 msgCount 63 (62 usable)\n");
+        printf("GSP_MSG_QUEUE_ELEMENT: authTag 0 aad 16 checkSum 32 seqNum 36 elemCount 40 rpc 48 (sizeof 80); slot 4096, max 16 slots, RPC_SIZE_MAX 65488\n");
+        printf("rpc_message_header_v03_00 32 bytes: header_version 0 (0x03000000) signature 4 (0x43505256) length 8 function 12 rpc_result 16 rpc_result_private 20 sequence 24 cpuRmGfid 28\n");
+        printf("functions: NOP 0 CONTINUATION_RECORD 71 GSP_SET_SYSTEM_INFO 72 SET_REGISTRY 73; events: GSP_INIT_DONE 0x1001 RUN_CPU_SEQUENCER 0x1002 RC_TRIGGERED 0x1004 LOCKDOWN_NOTICE 0x101c POST_NOCAT_RECORD 0x1020\n");
+        printf("results: RPC_PENDING 0xffffffff UNKNOWN_FUNCTION 0xff100001 INVALID_MESSAGE_FORMAT 0xff100002; doorbell NV_PGSP_QUEUE_HEAD(0) 0x110c00 <- 0\n");
+        printf("GspSystemInfo payload 936 bytes (gpuPhysAddr 0 ... FHBBusInfo 138 chipsetIDInfo 148 acpiMethodData 160 hypervisorType 836 gspVFInfo 856 hostPageSize 920 bWindowChannelAlwaysMapped 931); GSP_SET_SYSTEM_INFO RPC length 968\n");
+        printf("PACKED_REGISTRY_TABLE: size 0 numEntries 4 entries 8 x {nameOffset 0 type 4 data 8 length 12} (16 each), then names and values; types DWORD 1 BINARY 2 STRING 3\n");
+        return 0;
+    }
+    const char *out = NULL, *payload_path = NULL; int ok = 1;
+    uint64_t size = GSP_MQ_SIZE, msg_size = GSP_MQ_MSG_SIZE, hdr_align = GSP_MQ_HDR_ALIGN, entry_align = GSP_MQ_ENTRY_ALIGN, flags = MSGQ_FLAGS_SWAP_RX;
+    uint64_t our_rxhdr = GSP_MQ_RXHDR_OFF, rptr = 0, wptr = 0, count = GSP_MQ_MSG_COUNT, function = 0, sequence = 0, seqnum = 0, rpc_len = 0;
+    int have_function = 0;
+    reg_in regs[64]; uint32_t nregs = 0; static char regbuf[64][512];
+    for (int i = 2; i < argc; i++) {
+        const char *a = argv[i];
+        if (!strcmp(a, "--out") && i + 1 < argc) { out = argv[++i]; continue; }
+        if (!strcmp(a, "--payload") && i + 1 < argc) { payload_path = argv[++i]; continue; }
+        if ((!strcmp(a, "--dword") || !strcmp(a, "--string")) && i + 1 < argc) {
+            if (nregs >= 64) return refused("more than 64 registry entries");
+            const char *kv = argv[++i]; const char *eq = strchr(kv, '=');
+            if (!eq || eq == kv || strlen(kv) >= sizeof regbuf[0]) return refused("registry entry must be NAME=VALUE");
+            strcpy(regbuf[nregs], kv); regbuf[nregs][eq - kv] = 0;
+            reg_in *r = &regs[nregs]; r->name = regbuf[nregs]; r->bytes = NULL; r->len = 0; r->dword = 0;
+            if (!strcmp(a, "--dword")) { r->type = REG_TYPE_DWORD; r->dword = (uint32_t)parse_u64(eq + 1, &ok); if (!ok) return refused("bad dword value"); }
+            else { r->type = REG_TYPE_STRING; r->bytes = (const uint8_t *)regbuf[nregs] + (eq - kv) + 1; r->len = (uint32_t)strlen(eq + 1); }
+            nregs++; continue;
+        }
+        struct { const char *n; uint64_t *v; } opts[] = { {"--size", &size}, {"--msg-size", &msg_size}, {"--hdr-align", &hdr_align}, {"--entry-align", &entry_align}, {"--flags", &flags},
+            {"--our-rxhdr", &our_rxhdr}, {"--read", &rptr}, {"--write", &wptr}, {"--count", &count}, {"--function", &function}, {"--sequence", &sequence}, {"--seqnum", &seqnum}, {"--rpc-len", &rpc_len} };
+        int hit = 0;
+        for (size_t k = 0; k < sizeof opts / sizeof opts[0] && i + 1 < argc; k++)
+            if (!strcmp(a, opts[k].n)) { *opts[k].v = parse_u64(argv[++i], &ok); if (opts[k].v == &function) have_function = 1; hit = 1; break; }
+        if (!hit && a[0] == '-') return usage();
+        if (!ok) return refused("bad number");
+    }
+    if (size > 0xffffffffu || msg_size > 0xffffffffu || hdr_align > 31 || entry_align > 31 || flags > 0xffffffffu) return refused("value out of 32-bit range");
+    if (!strcmp(mode, "txheader")) {
+        mq_create_in q = { (uint32_t)size, (uint32_t)msg_size, (uint32_t)hdr_align, (uint32_t)entry_align, (uint32_t)flags };
+        uint8_t h[MSGQ_TX_HDR_SIZE]; const char *e = mq_tx_create(&q, h); if (e) return refused(e);
+        printf("txheader ok msgCount=%u rxHdrOff=%u entryOff=%u\n", rd32(h + 12), rd32(h + 24), rd32(h + 28)); dump(h, 32);
+        return emit(out, h, 32);
+    }
+    if (!strcmp(mode, "ring")) {
+        if (rptr > 0xffffffffu || wptr > 0xffffffffu || count > 0xffffffffu) return refused("value out of 32-bit range");
+        printf("ring count=%llu read=%llu write=%llu free=%u available=%u\n", (unsigned long long)count, (unsigned long long)rptr, (unsigned long long)wptr,
+               ring_free((uint32_t)rptr, (uint32_t)wptr, (uint32_t)count), ring_avail((uint32_t)rptr, (uint32_t)wptr, (uint32_t)count));
+        return 0;
+    }
+    if (!strcmp(mode, "element")) {
+        if (!have_function) return refused("need --function");
+        if (function > 0xffffffffu || sequence > 0xffffffffu || seqnum > 0xffffffffu) return refused("value out of 32-bit range");
+        uint8_t *p = NULL; size_t pn = 0;
+        if (payload_path && read_file(payload_path, &p, &pn)) return refused("cannot read payload");
+        static uint8_t el[ELEM_SIZE_MAX]; uint32_t ml = 0, ec = 0;
+        elem_in in = { (uint32_t)function, (uint32_t)sequence, (uint32_t)pn, p, (uint32_t)seqnum };
+        const char *e = elem_encode(&in, el, sizeof el, &ml, &ec); free(p); if (e) return refused(e);
+        printf("element ok function=%u sequence=%u seqNum=%u rpc_length=%u msg_len=%u slots=%u checksum=0x%08x\n", in.function, in.sequence, in.seqNum, rd32(el + 56), ml, ec, rd32(el + 32));
+        dump(el, 80);
+        return emit(out, el, (size_t)ec * ELEM_SIZE_MIN);
+    }
+    if (!strcmp(mode, "contplan")) {
+        if (rpc_len > 0xffffffffu) return refused("value out of 32-bit range");
+        cont_plan cp; const char *e = cont_plan_for((uint32_t)rpc_len, &cp); if (e) return refused(e);
+        printf("contplan rpc_len=%u messages=%u first_len=%u last_continuation_payload=%u\n", (uint32_t)rpc_len, cp.chunks, cp.first_len, cp.last_payload);
+        return 0;
+    }
+    if (!strcmp(mode, "registry")) {
+        static uint8_t rt[RPC_SIZE_MAX]; uint32_t rs = 0;
+        const char *e = reg_encode(regs, nregs, rt, sizeof rt, &rs); if (e) return refused(e);
+        printf("registry ok size=%u entries=%u\n", rs, nregs); dump(rt, rs > 96 ? 96 : rs);
+        return emit(out, rt, rs);
+    }
+    if (!strncmp(mode, "check-", 6)) {
+        if (argc < 3 || argv[2][0] == '-') return usage();
+        uint8_t *b; size_t n; if (read_file(argv[2], &b, &n)) return refused("cannot read file");
+        const char *e; char extra[96] = "";
+        if (!strcmp(mode, "check-txheader")) { msgq_tx_header h; e = mq_rx_link_check(b, n, (uint32_t)size, (uint32_t)msg_size, (uint32_t)our_rxhdr, &h); if (!e) snprintf(extra, sizeof extra, " msgCount=%u writePtr=%u", h.msgCount, h.writePtr); }
+        else if (!strcmp(mode, "check-element")) { elem_view v; e = elem_check(b, n, (uint32_t)seqnum, &v); if (!e) snprintf(extra, sizeof extra, " function=0x%x sequence=%u result=0x%08x length=%u slots=%u", v.rpc.function, v.rpc.sequence, v.rpc.rpc_result, v.rpc.length, v.elemCount); }
+        else if (!strcmp(mode, "check-registry")) { uint32_t c = 0; e = reg_check(b, n, &c); if (!e) snprintf(extra, sizeof extra, " entries=%u", c); }
+        else e = "unknown check";
+        free(b);
+        if (e) return refused(e);
+        printf("%s: OK%s\n", mode, extra); return 0;
+    }
+    return usage();
+}