Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/patches/5672a3f42d369db8 # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aienux#463 (code only) closed derived `5672a3f42d369db8` #463 Imported from GitHub aien-dev/aienux#463 (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 `659ddd2d7e3e140cb9bf942c3171cbd9cf3d092e` · Head `5c6db90b55047874452e3d6cc96974ea9c80f371` ### Fetch it A git bundle of the pull request's head, 249149 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aienux/patches/5672a3f42d369db8.bundle -o 5672a3f42d369db8.bundle git fetch 5672a3f42d369db8.bundle refs/pull/463/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aienux 463 5c6db90b55047874452e3d6cc96974ea9c80f371 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aienux","number":463,"url":"https://github.com/aien-dev/aienux/pull/463","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:28Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index e10cbfb7..8a466216 100644 --- a/.crumb +++ b/.crumb @@ -22,38 +22,38 @@ "children": [ { "digest": "41ab40c2d3b6bf2c002f46e749504ef1b072e6ddb67283f7857cfc5cb6da57a9", - "last_commit": "d701275", + "last_commit": "d7012755", "name": "crates", "purpose": "Directory crates. Purpose not yet described by a human." }, { - "digest": "9264bacd541007f662024e3ff5d64419cb5b884c7d819aadecab4b8c4ffc536f", - "last_commit": "d701275", + "digest": "baa0127f2f9ce162757bd2e48f9c815a3577f7108354a210889bde71f4f1e876", + "last_commit": "93fe68cf", "name": "docs", "purpose": "Directory docs. Purpose not yet described by a human." }, { - "digest": "220236525b9d03bf1f6c7bd065edcf54abfdb8125989c5cc3c26a5d0981cfac1", - "last_commit": "d701275", + "digest": "fa20ea43bdf23a6f9340106e859687ee83a41ac11b1628b5be2574aa4d395123", + "last_commit": "93fe68cf", "name": "native", "purpose": "Directory native. Purpose not yet described by a human." }, { "digest": "57c32a0629f9c7717240a2faf06cb6efaa374e386d5756dd184cf8fa208f45c7", - "last_commit": "d701275", + "last_commit": "d7012755", "name": "scripts", "purpose": "Directory scripts. Purpose not yet described by a human." } ], - "children_root": "sha256:465c1d98cb60fa29e5bef246b20e3b2447c1e681e8ac0fd2b23e183e3793693b", - "compiled_at": "2026-10-26T15:58:42Z", + "children_root": "sha256:9d275bc9e873ce91316cc349322e23737a1c6ec5e42b14b21606222ea3c35a9e", + "compiled_at": "2026-10-30T03:02:40Z", "compiler": "crumb-compile/1", - "digest": "sha256:79bf80014956d708e86767a9345d58db15c76ffc850fac69a45749de92bfb644", - "evidence_files": 216, - "evidence_root": "sha256:88ba864f439c06750b936b281f5958c12cbfb47f3c0cc8024c2f58e442dfeb24", - "files": 3497, - "generated_at_commit": "aa54ee57f1d4a042ad123c16d5e7717070300ef9", - "source_tree": "sha256:88f70b1791fc06ff9edbde41245efe457cf9a250edb3b2d4b2d2f4422df5e36f" + "digest": "sha256:af743480b972265381a2c6f1daa093939fdd759fd55234b51c537409a100d3fe", + "evidence_files": 248, + "evidence_root": "sha256:98faec047e4b414f36fe866e22887a0d8318e34905c89cb264d6cd60a70b7194", + "files": 3568, + "generated_at_commit": "93fe68cfd18e0d3768be442776a3c4ebaf7f0667", + "source_tree": "sha256:6d1ef26a373e5bb90cc85db1538a774956e29f85d2d2e154ea3160abaf06ba0c" }, "owner_lane": "", "provenance": { diff --git a/docs/.crumb b/docs/.crumb index 822579bf..35e9c559 100644 --- a/docs/.crumb +++ b/docs/.crumb @@ -30,14 +30,14 @@ } ], "children_root": "sha256:efb4a0449db172a441d8663f55ab48d6d81405e011961fd54213541c119b6852", - "compiled_at": "2026-10-26T15:49:35Z", + "compiled_at": "2026-10-30T03:02:40Z", "compiler": "crumb-compile/1", - "digest": "sha256:9264bacd541007f662024e3ff5d64419cb5b884c7d819aadecab4b8c4ffc536f", + "digest": "sha256:baa0127f2f9ce162757bd2e48f9c815a3577f7108354a210889bde71f4f1e876", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 216, - "generated_at_commit": "d70127557fd45192a9f24fc092963f72f15e9e29", - "source_tree": "sha256:21fa8ff1b2de46cb43b1e7eef8c4bfd56fa5642edffc5b995a98c2a7feb158ae" + "files": 217, + "generated_at_commit": "93fe68cfd18e0d3768be442776a3c4ebaf7f0667", + "source_tree": "sha256:8e6c3482298b07c27236dd8ee44d6bf4b8283dd9d0548b6725b60f31a6300888" }, "owner_lane": "", "provenance": { diff --git a/docs/GB10_FIRMWARE_INVENTORY.md b/docs/GB10_FIRMWARE_INVENTORY.md index c63ae691..8523a23f 100644 --- a/docs/GB10_FIRMWARE_INVENTORY.md +++ b/docs/GB10_FIRMWARE_INVENTORY.md @@ -15,8 +15,13 @@ the driver on the box; fetched read-only into a scratch directory, not vendored) ## 1. Plain-English summary -- The GPU in the Spark is NVIDIA's "GB10B" chip (the integrated variant of the - GB10 family). To run it, three pieces of NVIDIA code have to be put in place +- This inventory assumes the GPU in the Spark is NVIDIA's "GB10B" chip. Correction 2026-10-26 (NoNvDriver + review): that was never measured (PMC_BOOT_42 is unread), and the evidence points at GB20B instead. In + 580.173.02, GB10B is Thor ("T264/GB10B", uvm_va_space.c:817; Thor is sm_110, the Spark is sm_121), and + GB10B's class list has BLACKWELL_COMPUTE_A only (g_gpu_class_list.c:2418-2487) while CUDA++ refuses to run + without BLACKWELL_COMPUTE_B and has passing chip receipts on this Spark (CUDApp + evidence/FB1-CUT5-HD128-7dd92dc). COMPUTE_B appears only for GB202-GB207, GB20B and GB20C. window1-pre.sh + now refuses unless window 0 reads CHIP_ID 0x1AB. To run it, three pieces of NVIDIA code have to be put in place in a fixed order: a small signed "first stage" (GSP-FMC) that the SEC2 security engine on the chip verifies and starts, which then unpacks and starts the big GSP-RM firmware (the GPU's own resource manager, 75 MB on disk), after @@ -340,6 +345,9 @@ code into AIENOS would require carrying the MIT notice (none was copied here). 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. + NARROWED 2026-10-20 (section 14.2 items 1-2): on GB10B that wait is a no-op + and the SEC2 send checks only a software property and EMEM HEAD == TAIL; what + stays UNKNOWN is whether SEC2 is running with an empty queue at AIENOS entry. 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 @@ -353,7 +361,8 @@ code into AIENOS would require carrying the MIT notice (none was copied here). 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)]. + session are ever required on this platform. Assumed not [INFERRED (high)]; + default `PDB_PROP_CONFCOMPUTE_ENABLED` is NV_FALSE (section 14.2 item 3). 6. [RESOLVED on the host side 2026-10-12, SOURCE; consumer side INFERRED (medium)] `GspRmFmcGfwProdSigned_GB10B` (image, hash, signature, public key) is what SEC2 receives in the chain-of-trust payload (section 10). @@ -433,7 +442,7 @@ Transport. NVDM (NVIDIA Data Model) over MCTP over SEC2 EMEM channel 0, | dword | field | value for the boot message | source | |---|---|---|---| -| 0 | MCTP transport header: SOM bit 31, EOM bit 30, SEQ 29:28, TO 27, TAG 26:24, SEID 23:16, DEID 15:8, RSVD 7:4, VERSION 3:0 | `0xC0000000` (SOM=1, EOM=1, SEQ=0, SEID=0; the driver sets only those four) | `fsp_mctp_format.h:8-16`; `kernel_sec2.c:319-321`; SEID 0 for GB10B `g_kernel_sec2_nvoc.c:879-888`, `g_kernel_sec2_nvoc.h:907-909` | +| 0 | MCTP transport header. Layout (GB20B form): SOM bit 31, EOM bit 30, SEQ 29:28, TO 27, TAG 26:24, SEID 23:16, DEID 15:8, RSVD 7:4, VERSION 3:0 | **GB10B: `0x00000001`**, the HAL constant; the driver does not build SOM/EOM on GB10B. (GB20B/GB20C: `0xC0000000` = SOM=1, EOM=1, SEQ=0, SEID=0.) Corrected 2026-10-26; this row said `0xC0000000` for GB10B | `kernel_sec2.c:320` calls `ksec2CreateMctpHeader_HAL`; GB10B binds `ksec2CreateMctpHeader_539ab4` = `return 1;` (`g_kernel_sec2_nvoc.c:786-788`, `g_kernel_sec2_nvoc.h:853-855`); GB20B/GB20C bind `ksec2CreateMctpHeader_GB20B` (`kernel_sec2_gb20b.c:206-219`) | | 1 | NVDM header: TYPE 6:0 = 0x7e (vendor PCI), IC 7 = 0, VENDOR_ID 23:8 = 0x10de, NVDM_TYPE 31:24 | `0x1410DE7E` (NVDM_TYPE_COT = 0x14) | `fsp_mctp_format.h:17-22`; `fsp_nvdm_format.h:14`; `kernel_sec2_gb10b.c:391-402` | A message longer than 1016 bytes would continue in packets that carry only @@ -728,3 +737,128 @@ of `GspSystemInfo`, and does not cover the confidential-computing encryption pat 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. + +## 14. The composed boot builder and the post-init RPCs (L192, 2026-10-20) [SOURCE / OBSERVED] + +Plain English: sections 10 to 13 described each piece the driver hands the chip, one at a +time, in standalone tools. `native/kernel/dev/gb10_gsp_boot.c` now builds all of them +together, in kernel-style C (no C library, no device access), into one block of memory with +real cross-links: the boot parameters point at the WprMeta page, the WprMeta page points at +the radix-3 table and the bootloader, the libos page points at the logs and the RPC +arguments, and so on. It also builds the single message SEC2 receives and the messages a +native kernel sends to GSP-RM after it is up. Nothing is loaded and no register is written: +the output is bytes and addresses, ready for an attended run that is not authorized here. + +### 14.1 What the builder produces + +`gsp_boot_build(arena, inputs, plan)` lays out, every block 4 KiB aligned, in this order: +WprMeta page, libos init-argument page, the seven GB10B log buffers with their PTE prefix, +`GSP_ARGUMENTS_CACHED`, the 129-page RPC shared buffer (page table, command queue with its +`msgqTxHeader`, status queue left zero for GSP to create), the radix-3 table plus a copy of the +GSP-RM ELF, the GspRmBoot bootloader, the signature (size rounded up to 256), the GSP-FMC +image and `GSP_FMC_BOOT_PARAMS`. It queues the two pre-boot RPCs (`GSP_SET_SYSTEM_INFO` with the +caller's 936 bytes, then `SET_REGISTRY` when entries are given; both async, sequence 0, +element seqNum 0 and 1) and returns the SEC2 EMEM packet (MCTP dword `0x00000001` on GB10B, NVDM dword +`0x1410de7e`, 860-byte `NVDM_PAYLOAD_COT`, 868 bytes, QUEUE_TAIL 864). The firmware bytes, +the 512 MiB sysmem heap address, `GspSystemInfo` and the registry are inputs; the builder never +reads a file or a device. + +Post-init encoders over the same ring: `gsp_rpc_rm_alloc` (103), `gsp_rpc_rm_control` (76), +`gsp_rpc_rm_free` (10), `gsp_rpc_get_static_info` (65), and `gsp_mq_recv` for the status queue +(checksum, sequence and element-count checks; the CPU's readPtr lives in the command queue at +rxHdrOff 32, SWAP_RX). Messages stream into the ring slot by slot, including across the ring +end, with no large stack buffer. A full fence precedes every writePtr publish +(message_queue_cpu.c:574-576 uses `portAtomicMemoryFenceStore`); the doorbell write +(`NV_PGSP_QUEUE_HEAD(0)`) is the caller's and is not in this file. + +### 14.2 New source findings + +1. **No GFW-boot wait on GB10B** [SOURCE]: `kgspWaitForGfwBootOk` is bound to + `kgspWaitForGfwBootOk_ac1694` for "GB10B | GB20B | GB20C" (g_kernel_gsp_nvoc.c:1499-1513), + which is `return NV_OK;` (g_kernel_gsp_nvoc.h:1889-1891). The Linux driver does not wait for + a GPU firmware boot stage on this chip before talking to SEC2. Narrows section 8 item 3. +2. **SEC2 send preconditions are software-only** [SOURCE]: `ksec2SafeToSendBootCommands_GB10B` + checks only `PDB_PROP_KSEC2_BOOT_GSPFMC` (kernel_sec2_gb10b.c:415-425), which is NV_TRUE for + GB10B (g_kernel_sec2_nvoc.c:446-455); `ksec2CanSendPacket_GB10B` requires EMEM queue + HEAD == TAIL (kernel_sec2_gb10b.c:344-353). After the packet: `_ksec2WaitForCmdHandling` + (MAILBOX0), then `kgspBootstrap_GH100` waits for the GSP target mask release, read as + `NV_PGSP + NV_PFALCON_FALCON_HWCFG2` being non-zero and not `0xBADF41xx` + (kernel_sec2_gb10b.c:265-283, kernel_gsp_gh100.c:897-910). Still [UNKNOWN]: whether SEC2 is + running and its EMEM queue empty when AIENOS starts without Linux; nothing in the driver + starts SEC2 itself. +3. **Confidential computing is off by default** [SOURCE]: `PDB_PROP_CONFCOMPUTE_ENABLED` is set + NV_FALSE at construction (g_conf_compute_nvoc.c:235); the encrypted-queue branch of + `GspMsgQueueSendCommand` (message_queue_cpu.c:485-505) is only taken when it is enabled. + Strengthens section 8 item 5 [INFERRED (high)]. `GSP_FMC_BOOT_PARAMS.initParams.regkeys` is + `pCC->gspProxyRegkeys` (kernel_gsp_gh100.c:426); its value without CC is [UNKNOWN] and is a + builder input (default 0). +4. **DMA targets in GSP_FMC_BOOT_PARAMS** [SOURCE]: `_kgspMemdescToDmaTarget` + (kernel_gsp_gh100.c:390-404) maps cached sysmem to `GSP_DMA_TARGET_COHERENT_SYSTEM` (1) and + uncached sysmem to `NONCOHERENT_SYSTEM` (2). The WprMeta page is cached and the libos page + uncached (kernel_gsp_tu102.c:120-171), so the boot descriptor target is 1 and the boot-args + target is 2. +5. **`GSP_RM_ALLOC` length leaves the params out** [SOURCE]: `rpcRmApiAlloc_GSP` calls + `rpcWriteCommonHeader(.., sizeof(rpc_gsp_rm_alloc_v03_00))` (rpc.c:11195) and copies the + params after the fixed part without growing the length; `rpcWriteCommonHeader` sets + `length = 32 + paramLength` (rpc_common.c:183). The queue sizes, checksums and element + count from that length (message_queue_cpu.c:465-505) but copies whole 4 KiB slots, so the + params travel in the first slot outside the checksum. The builder reproduces this exactly + and refuses params that would spill past the first slot (more than 3,984 bytes). + `GSP_RM_CONTROL` does count its params (rpc.c:10978-10984: `sizeof(*rpc_params) + + paramsSize`). [UNKNOWN] whether GSP-RM would also accept a length that includes the alloc + params; we keep the driver's form. +6. **`GET_GSP_STATIC_INFO` request** [SOURCE]: zero-filled, `length = 32 + + sizeof(GspStaticConfigInfo)`, refused by the driver above `maxRpcSize` + (rpc.c `rpcGetGspStaticInfo_v14_00`). `sizeof(GspStaticConfigInfo)` could not be computed: + gsp_static_config.h pulls nvassert.h, which requires an RM port header (`NV_PORT_HEADER`). + [UNKNOWN]; the builder takes the size as a parameter. + +### 14.3 The object chain to a usable channel [OBSERVED on Linux, INFERRED for native] + +What our working Linux path asks the driver for, in order (physics `nvrm/nvrm.c` at e95e3ed, +the layer every chip result on this box went through): `NV01_ROOT_CLIENT`; +`NV0000_CTRL_CMD_GPU_GET_ID_INFO_V2`; `NV01_DEVICE_0`; `NV20_SUBDEVICE_0`; +`NV01_MEMORY_VIRTUAL`; `NV0080_CTRL_CMD_GPU_GET_CLASSLIST` (twice: count, then list); +`NV2080_CTRL_CMD_GR_GET_INFO`; `FERMI_VASPACE_A`; `NV2080_CTRL_CMD_GPU_GET_GID_INFO`; +`NV01_MEMORY_SYSTEM` per buffer; `KEPLER_CHANNEL_GROUP_A`; `FERMI_CONTEXT_SHARE_A`; +`BLACKWELL_CHANNEL_GPFIFO_A`; `BLACKWELL_COMPUTE_B`; +`NVC36F_CTRL_CMD_GPFIFO_GET_WORK_SUBMIT_TOKEN`; `NVA06C_CTRL_CMD_GPFIFO_SCHEDULE`. + +On Linux these reach CPU-RM first, and CPU-RM forwards to GSP-RM with `GSP_RM_ALLOC` / +`GSP_RM_CONTROL` the objects GSP owns, while doing memory descriptors, page tables and BAR +mappings itself. [INFERRED (medium)] a native kernel sends the same chain through +`gsp_rpc_rm_alloc` / `gsp_rpc_rm_control` with its own handles, after `GSP_INIT_DONE` and +`GET_GSP_STATIC_INFO`. [UNKNOWN] which objects GSP-RM accepts without the CPU-RM-side state +(VA space page directory via `SET_PAGE_DIRECTORY` 54, memory registration) and in what form: +that is the boundary with cut D (L193, GPU page tables and channel model) and is only +settled by reading CPU-RM's per-class forwarding and then by the chip. + +### 14.4 How it is tested (host only) + +- `make -C native/kernel test-gb10-gsp-boot` (also part of `make test` and `make sanitize`): + every block decoded at hand-written byte offsets, cross-links, determinism, the ring + (full ring, wrap across the ring end, corrupt pointers), the status reader (empty, good, + bad checksum, bad sequence, bad element count) and every input refusal. +- `make -C native/kernel gb10-gsp-nvhdr-test`: the builder's mirror structs compared field by + field (offset and size) with the NVIDIA headers themselves, and a built plan decoded through + NVIDIA's own types (`GspFwWprMeta`, `LibosMemoryRegionInitArgument`, `GSP_ARGUMENTS_CACHED`, + `msgqTxHeader`, `rpc_message_header_v03_00`, `rpc_gsp_rm_alloc_v03_00`, + `rpc_gsp_rm_control_v03_00`, `NVOS00_PARAMETERS_v03_00`, `GSP_FMC_BOOT_PARAMS`, + `NVDM_PAYLOAD_COT`, function and event numbers). Needs the 580.173.02 source tree at + `OGKM_DIR` and fails without it; `make test` runs it through `gb10-gsp-nvhdr-check`, which + prints NOT_RUN instead when the tree is absent. +- `make -C native/kernel gb10-gsp-free`: compiled with the kernel's freestanding flags plus + `-Wstack-usage=4096`; no undefined symbols (no hidden memcpy/memset). +- `make -C native/kernel gb10-gsp-mutants`: four test-only mutants (readPtr read from the wrong + queue, checksum not stored, radix pointers shifted one page, alloc length counting the params) + must each make the test fail. + +Results with commands and exit codes are in the L192 handoff +(`~/handoffs/2026-10-20-gb10-gsp-host.md`). + +### 14.5 Still needs the chip (unchanged authority: attended window only) + +Whether SEC2 accepts the packet with Linux absent; whether GSP-FMC accepts this WprMeta and +the 133 MiB heap; the real `GspSystemInfo` bytes; `sizeof(GspStaticConfigInfo)`; the per-class +CPU-RM work behind each forwarded alloc; reset and re-open after a failed boot (section 8 +item 7). The builder is not linked into any kernel image. diff --git a/docs/GPU_DRIVER.md b/docs/GPU_DRIVER.md new file mode 100644 index 00000000..a627c530 --- /dev/null +++ b/docs/GPU_DRIVER.md @@ -0,0 +1,110 @@ +# Our own GPU driver for the Spark (GB10) + +Written for Drake. Ledger L332. Status at the bottom; every number has its source next to it. + +## What a GPU driver does here + +The GB10 graphics chip is a separate computer inside the Spark. It has its own small processor (NVIDIA calls it GSP) +that runs NVIDIA's own program, and it has job queues our code fills with work. A driver is the software on the main +processor that: + +1. wakes the chip up and starts the chip's small processor with NVIDIA's program, +2. sets up memory so the chip and the main processor see the same model weights, +3. opens a job queue (a "channel") and tells the chip where it is, +4. after that, stays out of the way while our code puts work in the queue and rings a doorbell. + +Today NVIDIA's open-source Linux driver (two main pieces, `nvidia.ko` and `nvidia-uvm.ko`, plus two display pieces, +`nvidia_modeset` and `nvidia_drm`) does steps 1 to 3. Omega and physics already do step 4 themselves: they write the +work into the queue and ring the doorbell straight from our own program, with no call into the driver at all +(physics nvrm/nvrm.c: the doorbell is a single memory write to a page the driver handed us once). + +## What NVIDIA's driver costs us today + +Rung 0 measures it. Results go in evidence/own-gpu-driver/rung0/ with the table below filled from them. + +| What | Today with NVIDIA | Source | +|---|---|---| +| Driver calls per generated word | expected zero (work submit never calls the driver) | rung 0 cell (a), pending the window | +| Processor time the driver burns while idle | the display piece spins one core forever on this headless box | L158; rung 0 idle cells | +| Start-up calls before the first job | pending | rung 0 strace cell | +| Time to load the driver and wake the chip | not measured (never reloaded since boot) | rung 2 window 0, step 6 | + +## What ours does instead + +The driver core is written as device contracts: short, checked descriptions of the chip (registers, job queues, the +order things must happen in) that our compiler (`crates/aienos-devc`, ADR 0021) turns into C code. The first one is the +job queue: `native/kernel/gpu/contract/gb10_chan.devc`. Every number in it is tied to a quoted line of NVIDIA's own +source. The compiler refuses a contract that would be unsafe on the chip, for example one that rings the doorbell before +the work is published, forgets the memory barrier between the two, lets the queue overflow, or keeps memory in the +chip's cache that the main processor writes while the chip reads it (the mistake that cost two days in October). + +The generated code has to behave exactly like the hand-written version from L193: same 225 checks, and a side-by-side +trace of every register write and the whole simulated memory after each of about 330 operations must match byte for byte. + +The second contract is the chip start-up: `native/kernel/gpu/contract/gb10_gsp.devc`. It describes the eleven register +steps that hand NVIDIA's signed start-up package to the chip's security processor (SEC2), wait for it to check and start +the chip's own operating program, and confirm that program is running. The compiler refuses a start-up that writes the +package while an older message is still there, rings the bell before the message is complete, touches the chip's main +processor before the security processor releases it, or waits on anything without a time limit. A hand-written version +(`native/kernel/gpu/gsp_mmio.c`) runs against a simulated security processor; the generated one must pass the same 67 +checks and make the very same register accesses in 16 scenarios, including every way the start-up can fail. Twenty +deliberate small errors in each version are all caught. None of this has run on the chip yet. + +On Linux, a small add-on module `aien-gpu` (native/linux/aien-gpu) will host that core in place of NVIDIA's driver. +Its first version only reads the chip's identity, loads NVIDIA's firmware file and sets up one big shared memory area; +it binds to the chip only when told to, after NVIDIA's driver is gone. + +## What stays on loan from NVIDIA, and why + +The chip's small processor only runs a program signed by NVIDIA. A security block on the chip checks the signature before +it lets that program start (on the GB10 that is the SEC2 processor; this chip has no FSP), and we do not have NVIDIA's +signing key. So these files stay NVIDIA's, loaded the way +we load model weights, named here: + +1. `gsp_ga10x.bin` (75,012,080 bytes, /lib/firmware/nvidia/580.173.02/), the chip's operating program. +2. The GSP boot loader and the signed first-stage loader (FMC) for GB10B, which ship inside nvidia.ko as embedded data + (g_bindata_kgspGetBinArchiveGspRmBoot_GB10B.c, GspRmFmcGfwProdSigned_GB10B.c in the open driver source), together with + the hash, signature and public key the driver hands to the security processor in one 868-byte message. + +Everything on the main processor side becomes ours. If evidence ever shows the signature check can be satisfied another +way, it goes in as an open question with an experiment, and nothing is tried that could damage the chip. + +## The rungs + +0. Measure what NVIDIA's driver costs (above). +1. The driver core in our contract language, proven on the simulator (job queue and chip start-up done; next the + shared memory area the chip program needs and the first message exchange with it). +2. Run it on the real chip under Linux, in a window the coordinator schedules, because it takes the GPU away from + everything else for a while. Window 0 only reads the chip and gives it back (evidence/own-gpu-driver/rung2/RUNBOOK.md). + Window 1, after window 0 passes, starts NVIDIA's signed chip program with our own code: our small Linux module lets + our start-up tool touch only the 12 start-up registers (6 of them writable) and ring the security processor once; + the tool builds the start-up package, hands it over and waits for the chip program to say it is ready. Every + register access is recorded with its time. The one real risk: if the restart afterwards does not fully reset the + GPU, it needs a power cycle at the wall before NVIDIA's driver works again. Status 2026-10-22: window 1 is built + and passes its 56 simulator checks, with the real firmware package checked against its pinned fingerprints; it waits + for window 0. Still open until it runs: whether the chip program asks our side to run a short list of chores before + it says it is ready (if so, window 1 records the request and stops there). +3. The same core inside our own operating system on the Spark, once that boots natively (L318). + +## Known unknowns (tested on the chip, never assumed) + +- How the GB10 makes a channel runnable without NVIDIA's chip program: today the chip program does it on request. +- The doorbell's address on the chip when NVIDIA's driver is not there to hand us the page. +- Whether the main processor may write the address-translation flush register directly. +- GB10B keeps some cache lines "sticky" until flushed (uvm_gpu.h:1135, NVIDIA bug 4577236, fixed only in later chips): + memory the main processor polls must be set up uncached; the contract compiler enforces that rule. + +## The CPU sequencer + +NVIDIA's driver runs a short program the chip sends back (`kgspExecuteSequencerBuffer` in +kernel_gsp.c of open-gpu-kernel-modules 580.173.02): register write, modify, poll, a delay, a +save, and four core operations. That program is now ours (`native/kernel/gpu/gsp_seq.c`). It +refuses an unknown opcode, a short payload, a save index of 8 or more, and any core operation +unless the caller supplies the callback, because those restart the chip. A copy with the save-index +check removed fails the test. The window-1 simulator runs a register-write sequencer and then +reaches INIT-DONE; an empty sequencer request still stops, as before. This has not run on the chip. +The live `nvidia.ko` is not replaced by this commit. + +## Status + +See the handoff ~/handoffs/2026-10-21-own-gpu-driver.md and the ledger line L332 for the live state. diff --git a/evidence/own-gpu-driver/rung0/a-20261021T011957Z/bin.sha256 b/evidence/own-gpu-driver/rung0/a-20261021T011957Z/bin.sha256 new file mode 100644 index 00000000..ee33d9bc --- /dev/null +++ b/evidence/own-gpu-driver/rung0/a-20261021T011957Z/bin.sha256 @@ -0,0 +1 @@ +0689fd2cd6a0c1bd8148e7d93afc506c7110102cbdc532a50d9c22f5034fdbf6 /home/drakestapleton/workspace/targets/l332-omega/gpu_launch_cost_test diff --git a/evidence/own-gpu-driver/rung0/a-20261021T011957Z/window.open b/evidence/own-gpu-driver/rung0/a-20261021T011957Z/window.open new file mode 100644 index 00000000..2dcc3e2a --- /dev/null +++ b/evidence/own-gpu-driver/rung0/a-20261021T011957Z/window.open @@ -0,0 +1,14 @@ +spark-window: in line 60 s, place 6; open now: 20261021T011111Z-0adf8e +spark-window: in line 121 s, place 6; open now: 20261021T011111Z-0adf8e +spark-window: in line 181 s, place 6; open now: 20261021T011111Z-0adf8e +spark-window: in line 241 s, place 6; open now: 20261021T011111Z-0adf8e +spark-window: in line 302 s, place 6; open now: 20261021T011111Z-0adf8e +spark-window: in line 362 s, place 6; open now: 20261021T011111Z-0adf8e +spark-window: in line 422 s, place 6; open now: 20261021T011111Z-0adf8e +spark-window: in line 483 s, place 6; open now: 20261021T011111Z-0adf8e +spark-window: in line 543 s, place 6; open now: 20261021T011111Z-0adf8e +spark-window: in line 603 s, place 6; open now: 20261021T011111Z-0adf8e +spark-window: in line 664 s, place 6; open now: 20261021T011111Z-0adf8e +spark-window: in line 724 s, place 6; open now: 20261021T011111Z-0adf8e +Terminated +window open failed diff --git a/evidence/own-gpu-driver/rung0/a-20261021T215416Z/bin.sha256 b/evidence/own-gpu-driver/rung0/a-20261021T215416Z/bin.sha256 new file mode 100644 index 00000000..ee33d9bc --- /dev/null +++ b/evidence/own-gpu-driver/rung0/a-20261021T215416Z/bin.sha256 @@ -0,0 +1 @@ +0689fd2cd6a0c1bd8148e7d93afc506c7110102cbdc532a50d9c22f5034fdbf6 /home/drakestapleton/workspace/targets/l332-omega/gpu_launch_cost_test diff --git a/evidence/own-gpu-driver/rung0/a-20261021T215416Z/window.open b/evidence/own-gpu-driver/rung0/a-20261021T215416Z/window.open new file mode 100644 index 00000000..f3471cca --- /dev/null +++ b/evidence/own-gpu-driver/rung0/a-20261021T215416Z/window.open @@ -0,0 +1,2 @@ +spark-window: refused, the chip is reserved: L312 L354 L355 L356 L314 L313 L352 L369 L371 L375 L376 (Drake 2026-10-21 ~02:10Z: many conversations per beat first, every lever to the ceiling; the PR judge shares). Do non-chip work; the coordinator lifts it. +window open failed diff --git a/evidence/own-gpu-driver/rung0/rung0.sh b/evidence/own-gpu-driver/rung0/rung0.sh new file mode 100755 index 00000000..8f4394ad --- /dev/null +++ b/evidence/own-gpu-driver/rung0/rung0.sh @@ -0,0 +1,73 @@ +#!/usr/bin/env bash +# rung0.sh: what NVIDIA's kernel driver costs, measured (L332 rung 0). Run INSIDE a spark-window. +# rung0.sh OUTDIR idle LABEL SECONDS baseline: nothing of ours runs (negative control) +# rung0.sh OUTDIR run LABEL -- CMD... one workload, unprobed (time -v only) +# rung0.sh OUTDIR probe LABEL -- CMD... same workload with perf (kernel CPU per module) + bpftrace (ioctl counts/time) +# rung0.sh OUTDIR strace LABEL -- CMD... same workload under strace (call list and session-start timeline only) +# rung0.sh OUTDIR attach LABEL PID SECONDS live process (35B server): perf + bpftrace for SECONDS, no ptrace +# Read-only: sudo is used for perf/bpftrace and to read schedstat/interrupts; nothing is loaded, set or killed. +set -u +out=$1; mode=$2; shift 2 +mkdir -p "$out" +snap() { # $1 = file: nvidia interrupt counts, nvidia/uvm kthread schedstat (ns on cpu), clock + { + echo "t_ns $(date +%s%N)" + grep -iE "nvidia|nvgpu|000f:01:00" /proc/interrupts | awk '{s=0; for(i=2;i<=NF;i++) if($i ~ /^[0-9]+$/) s+=$i; else break; print "irq", $1, s, $NF}' + for d in /proc/[0-9]*; do + c=$(cat "$d/comm" 2>/dev/null) || continue + case "$c" in nv_*|nvidia*|UVM*|uvm*) echo "kthread ${d#/proc/} $c $(awk '{print $1}' "$d/schedstat" 2>/dev/null)";; esac + done + } > "$1" +} +perf_start() { sudo perf record -a -e cpu-clock -F 99 -o "$out/$1.perf.data" -- sleep "$2" > "$out/$1.perf.log" 2>&1 & PERF_PID=$!; } +perf_report() { # kernel CPU per NVIDIA module (symbols from /proc/kallsyms), per thread name; samples at 99 Hz cpu-clock => seconds = samples/99 + sudo awk '$4 ~ /^\[nvidia/ {gsub(/[\[\]]/, "", $4); print $3, $4}' /proc/kallsyms > "$out/$1.modsyms.txt" + sudo perf report --no-inline -g none -i "$out/$1.perf.data" --sort comm,sym --stdio --no-children -n -F sample,comm,sym 2>/dev/null \ + | grep -E "^ +[0-9]" > "$out/$1.commsym.txt" + awk 'NR==FNR {mod[$1]=$2; next} + { n=$1; sym=$NF; comm=$2; for (i=3; i= 3) printf "sym %s %d\n", k, bys[k] }' \ + "$out/$1.modsyms.txt" "$out/$1.commsym.txt" | sort -k1,1 -k3,3nr > "$out/$1.modules.txt" +} +bpf_start() { # $1 label, $2 = pid filter expression target (comm name or pid) + sudo bpftrace -q -e " +tracepoint:syscalls:sys_enter_ioctl /$2/ { @start[tid] = nsecs; @cmd[tid] = args->cmd; } +tracepoint:syscalls:sys_exit_ioctl /@start[tid]/ { @n[@cmd[tid]] = count(); @ns[@cmd[tid]] = sum(nsecs - @start[tid]); delete(@start[tid]); delete(@cmd[tid]); } +tracepoint:syscalls:sys_enter_mmap /$2/ { @mmap = count(); } +tracepoint:syscalls:sys_enter_munmap /$2/ { @munmap = count(); } +" > "$out/$1.bpf.txt" 2>&1 & BPF_PID=$! +} +case "$mode" in + idle) + label=$1 secs=$2; snap "$out/$label.before"; perf_start "$label" "$secs"; wait "$PERF_PID"; snap "$out/$label.after"; perf_report "$label" ;; + run|probe|strace) + label=$1; shift; [ "$1" = "--" ] && shift + snap "$out/$label.before" + if [ "$mode" = probe ]; then + bpf_start "$label" "comm == \"$(basename "$1" | cut -c1-15)\""; sleep 2 + perf_start "$label" 600 + fi + t0=$(date +%s%N) + if [ "$mode" = strace ]; then + strace -f -r -T -e trace=openat,ioctl,mmap,munmap -o "$out/$label.strace" /usr/bin/time -v -o "$out/$label.time" "$@" > "$out/$label.stdout" 2>&1 + else + /usr/bin/time -v -o "$out/$label.time" "$@" > "$out/$label.stdout" 2>&1 + fi + rc=$?; t1=$(date +%s%N) + snap "$out/$label.after" + echo "exit $rc wall_ns $((t1 - t0))" > "$out/$label.result" + if [ "$mode" = probe ]; then + sudo pkill -INT -f "perf record -a -e cpu-clock -F 99 -o $out/$label.perf.data" ; sleep 1 + sudo kill -INT "$BPF_PID" 2>/dev/null; sleep 1; perf_report "$label" + fi ;; + attach) + label=$1 pid=$2 secs=$3 + snap "$out/$label.before" + bpf_start "$label" "pid == $pid"; sleep 2 + perf_start "$label" "$secs"; wait "$PERF_PID" + sudo kill -INT "$BPF_PID" 2>/dev/null; sleep 1 + snap "$out/$label.after"; perf_report "$label" ;; + *) echo "usage: see header" >&2; exit 2 ;; +esac diff --git a/evidence/own-gpu-driver/rung0/wait-then-window.sh b/evidence/own-gpu-driver/rung0/wait-then-window.sh new file mode 100755 index 00000000..161d8fdc --- /dev/null +++ b/evidence/own-gpu-driver/rung0/wait-then-window.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# L332 rung 0: wait (5 min polls of a file, no locks held) until the coordinator's chip reservation is gone or names L332, then run window.sh. +here=$(cd "$(dirname "$0")" && pwd) +RES=$HOME/.local/state/aien-coordinator/CHIP-RESERVED +while [ -f "$RES" ] && ! head -1 "$RES" | cut -d"(" -f1 | tr " " "\n" | grep -qx L332; do sleep 300; done +exec bash "$here/window.sh" diff --git a/evidence/own-gpu-driver/rung0/window.sh b/evidence/own-gpu-driver/rung0/window.sh new file mode 100755 index 00000000..4d22a7e0 --- /dev/null +++ b/evidence/own-gpu-driver/rung0/window.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# L332 rung 0, one spark-window: +# cell (a) idle control, Omega launch-cost test unprobed/probed/strace at two rep counts, idle again; +# cell (b) the live 35B server on 18091: attach perf+bpftrace (no ptrace) while one fixed greedy request decodes, and an +# attached idle control of the same length. The server is never restarted or signalled. +set -u +here=$(cd "$(dirname "$0")" && pwd) +BIN=${BIN:-$HOME/workspace/targets/l332-omega/gpu_launch_cost_test} +OUT=${OUT:-$here/a-$(date -u +%Y%m%dT%H%M%SZ)} +PORT=${PORT:-18091} +mkdir -p "$OUT" +while [ ! -x "$BIN" ]; do sleep 30; done +sha256sum "$BIN" > "$OUT/bin.sha256" +ledger note L332 "measure: in line for spark-window l332-rung0 ($OUT)" >/dev/null 2>&1 +spark-window open l332-rung0 --ledger L332 --gb10 exclusive --lease 20 --wait > "$OUT/window.open" 2>&1 || { echo "window open failed" >> "$OUT/window.open"; exit 1; } +R="spark-window run $here/rung0.sh $OUT" +$R idle idle1 30 +$R run run-r3 -- "$BIN" --reps 3 +$R run run-r30 -- "$BIN" --reps 30 +$R probe probe-r3 -- "$BIN" --reps 3 +$R probe probe-r30 -- "$BIN" --reps 30 +$R strace strace-r3 -- "$BIN" --reps 3 +$R idle idle2 30 +spark-window close > "$OUT/window.close" 2>&1 +# cell (b): own window without the chip lock (the server takes /tmp/aien-gb10.lock per request itself), quiet lock for timing +spark-window open l332-rung0b --ledger L332 --gb10 none --lease 20 --wait > "$OUT/window-b.open" 2>&1 || { echo "window b open failed" >> "$OUT/window-b.open"; exit 1; } +# cell (b): 35B decode on the live server +SPID=$(ss -ltnpH "sport = :$PORT" | grep -o "pid=[0-9]*" | head -1 | cut -d= -f2) +if [ -n "$SPID" ]; then + tr "\0" " " < /proc/$SPID/cmdline > "$OUT/server.cmdline" + curl -s -m 5 127.0.0.1:$PORT/v1/models > "$OUT/server.models.json" + MODEL=$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["data"][0]["id"])' "$OUT/server.models.json") + LOG=$(readlink /proc/$SPID/fd/1); wc -l < "$LOG" > "$OUT/server.log.line0" + SECS=45 + $R attach srv-idle "$SPID" "$SECS" + BODY='{"model":"'"$MODEL"'","temperature":0,"max_tokens":4096,"messages":[{"role":"user","content":"Write a long, detailed history of the bicycle, chapter by chapter."}]}' + ( sleep 4; date +%s%N > "$OUT/srv-decode.req_start_ns" + curl -s -m $((SECS-6)) 127.0.0.1:$PORT/v1/chat/completions -H "content-type: application/json" -d "$BODY" \ + > "$OUT/srv-decode.response.json"; echo "curl_exit $?" > "$OUT/srv-decode.curl"; date +%s%N > "$OUT/srv-decode.req_done_ns" ) & + $R attach srv-decode "$SPID" "$SECS" + wait + tail -n +$(( $(cat "$OUT/server.log.line0") + 1 )) "$LOG" > "$OUT/server.log.window" +else + echo "no listener on $PORT" > "$OUT/server.absent" +fi +spark-window close > "$OUT/window-b.close" 2>&1 +sudo find "$OUT" -maxdepth 1 -name '*.perf.data*' -delete; sudo chown -R "$(id -un)" "$OUT" +ledger note L332 "measure: rung0 window done, results $OUT" >/dev/null 2>&1 +echo DONE > "$OUT/DONE" diff --git a/evidence/own-gpu-driver/rung1/contract_mutants.sh b/evidence/own-gpu-driver/rung1/contract_mutants.sh new file mode 100755 index 00000000..5ea9a731 --- /dev/null +++ b/evidence/own-gpu-driver/rung1/contract_mutants.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# contract_mutants.sh DEVC_BIN KERNEL_DIR OUT: wrong-but-well-formed edits of gb10_chan.devc. The checker accepts each +# (they break no ordering rule); the generated twin must then FAIL test_gpu_sim or differ in the differential trace. +# A mutant that passes both = a hole in the tests. Exit 0 only if every mutant is killed. +set -u +DEVC=$1 K=$2 OUT=$3 +src=$K/gpu/contract/gb10_chan.devc +work=$(mktemp -d); trap 'rm -rf "$work"' EXIT +mkdir -p "$work/gpu/contract/gen" +cp "$src" "$work/orig.devc" +muts=( + "TARGET=TARGET_SYS_COH|TARGET=1" + "BIG_PAGE_64K=1|BIG_PAGE_64K=0" + "LENGTH=nwords LEVEL=1|LENGTH=nwords LEVEL=0" + "const USERD_GPPUT 0x8C|const USERD_GPPUT 0x88" + "const RAMIN_PDB_WORD 128|const RAMIN_PDB_WORD 130" + "format TOKEN 32 RUNLIST_ID 22:16|format TOKEN 32 RUNLIST_ID 23:17" + "reg vf DOORBELL 0x30090 4 wo|reg vf DOORBELL 0x30094 4 wo" + "LENGTH 62:42|LENGTH 63:43" + "PTR_HI 51:32 place|PTR_HI 51:32" + " fence\n bind| bind\n fence\n bind" +) +killed=0 total=0 +for m in "${muts[@]}"; do + from=${m%%|*} to=${m#*|}; total=$((total + 1)) + if ! grep -qF "$(printf '%b' "$from" | head -1)" "$work/orig.devc"; then echo "MUTANT TEXT MISSING: $from"; exit 2; fi + awk -v f="$(printf '%b' "$from")" -v t="$(printf '%b' "$to")" 'BEGIN{RS="\0"} {i=index($0,f); if(i) $0=substr($0,1,i-1) t substr($0,i+length(f)); printf "%s", $0}' "$work/orig.devc" > "$work/gb10_chan.devc" + if ! "$DEVC" gen "$work/gb10_chan.devc" "$work/gen" > "$work/gen.log" 2>&1; then + echo "mutant killed (checker): $from -> $to"; killed=$((killed + 1)); continue + fi + make -s -C "$K" OUT="$OUT" GPU_CONTRACT_C="$work/gen/gch_contract.c" \ + "$OUT/host/test_gpu_sim_contract" "$OUT/host/gpu_chan_trace_hand" "$OUT/host/gpu_chan_trace_contract" -B > "$work/mk.log" 2>&1 \ + || { echo "mutant killed (does not compile): $from -> $to"; killed=$((killed + 1)); continue; } + if ! "$OUT/host/test_gpu_sim_contract" > /dev/null 2>&1; then echo "mutant killed (test_gpu_sim): $from -> $to"; killed=$((killed + 1)); continue; fi + "$OUT/host/gpu_chan_trace_hand" > "$work/h.txt"; "$OUT/host/gpu_chan_trace_contract" > "$work/c.txt" + if ! cmp -s "$work/h.txt" "$work/c.txt"; then echo "mutant killed (trace differs): $from -> $to"; killed=$((killed + 1)); continue; fi + echo "MUTANT SURVIVED: $from -> $to" +done +echo "contract mutants: $killed of $total killed" +test "$killed" -eq "$total" diff --git a/evidence/own-gpu-driver/rung1/gates-20261021T2158Z.txt b/evidence/own-gpu-driver/rung1/gates-20261021T2158Z.txt new file mode 100644 index 00000000..9b1a35ac --- /dev/null +++ b/evidence/own-gpu-driver/rung1/gates-20261021T2158Z.txt @@ -0,0 +1,23 @@ +# L332 rung 1 host gates, 2026-10-21T22:01:54Z, aienos feat/own-gpu-driver d5891389, feat/devc-gpu 0af8a6fe, via quiet-build bash gates.sh +....... +test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s + +drift: gb10_gpu_channel.md identical +drift: gch_contract.c identical +test_gpu_sim: PASS (225 checks) +test_gpu_sim: PASS (225 checks) +gpu-contract-trace: PASS (391 lines identical, hand vs contract) +gpu-contract-freestanding: PASS (gch_contract.c with KCC/KCFLAGS, needs only the ck_gmem allocator) +test_gpu_sim: PASS (225 checks) +mutant killed (test_gpu_sim): TARGET=TARGET_SYS_COH -> TARGET=1 +mutant killed (test_gpu_sim): BIG_PAGE_64K=1 -> BIG_PAGE_64K=0 +mutant killed (test_gpu_sim): LENGTH=nwords LEVEL=1 -> LENGTH=nwords LEVEL=0 +mutant killed (test_gpu_sim): const USERD_GPPUT 0x8C -> const USERD_GPPUT 0x88 +mutant killed (test_gpu_sim): const RAMIN_PDB_WORD 128 -> const RAMIN_PDB_WORD 130 +mutant killed (test_gpu_sim): format TOKEN 32 RUNLIST_ID 22:16 -> format TOKEN 32 RUNLIST_ID 23:17 +mutant killed (test_gpu_sim): reg vf DOORBELL 0x30090 4 wo -> reg vf DOORBELL 0x30094 4 wo +mutant killed (test_gpu_sim): LENGTH 62:42 -> LENGTH 63:43 +mutant killed (checker): PTR_HI 51:32 place -> PTR_HI 51:32 +mutant killed (checker): fence\n bind -> bind\n fence\n bind +contract mutants: 10 of 10 killed +gates exit done diff --git a/evidence/own-gpu-driver/rung1/gates-20261021T2300Z.txt b/evidence/own-gpu-driver/rung1/gates-20261021T2300Z.txt new file mode 100644 index 00000000..80ad92f1 --- /dev/null +++ b/evidence/own-gpu-driver/rung1/gates-20261021T2300Z.txt @@ -0,0 +1,39 @@ +# gates.sh direct at nice 19 ionice -c3 (correctness only; quiet lock held exclusive by spark-window 20261021T215856Z-b73c7d L371). head 884596e2dd50f2080d0d85e13e2b15fa14e4b037 devc 19992f84ef24729cdae394f0d81a2438d85b6b81 start 2026-10-21T23:00:24Z load 9.70 10.34 10.76 +......... +test result: ok. 9 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s + +drift: gb10_gpu_channel.md identical +drift: gch_contract.c identical +test_gpu_sim: PASS (225 checks) +test_gpu_sim: PASS (225 checks) +gpu-contract-trace: PASS (391 lines identical, hand vs contract) +gpu-contract-freestanding: PASS (gch_contract.c with KCC/KCFLAGS, needs only the ck_gmem allocator) +test_gpu_sim: PASS (225 checks) +mutant killed (test_gpu_sim): TARGET=TARGET_SYS_COH -> TARGET=1 +mutant killed (test_gpu_sim): BIG_PAGE_64K=1 -> BIG_PAGE_64K=0 +mutant killed (test_gpu_sim): LENGTH=nwords LEVEL=1 -> LENGTH=nwords LEVEL=0 +mutant killed (test_gpu_sim): const USERD_GPPUT 0x8C -> const USERD_GPPUT 0x88 +mutant killed (test_gpu_sim): const RAMIN_PDB_WORD 128 -> const RAMIN_PDB_WORD 130 +mutant killed (test_gpu_sim): format TOKEN 32 RUNLIST_ID 22:16 -> format TOKEN 32 RUNLIST_ID 23:17 +mutant killed (test_gpu_sim): reg vf DOORBELL 0x30090 4 wo -> reg vf DOORBELL 0x30094 4 wo +mutant killed (test_gpu_sim): LENGTH 62:42 -> LENGTH 63:43 +mutant killed (checker): PTR_HI 51:32 place -> PTR_HI 51:32 +mutant killed (checker): fence\n bind -> bind\n fence\n bind +contract mutants: 10 of 10 killed +test_gsp_mmio: PASS (67 checks) +test_gsp_mmio: PASS (67 checks) +gsp-mmio-freestanding: PASS (gsp_mmio.c with KCC/KCFLAGS, no undefined symbol) +mutant killed (test_gsp_mmio): in->len > CK_GSP_EMEM_CHANNEL_BYTES -> in->len >= CK_GSP_EMEM_CHANNEL_BYTES +mutant killed (test_gsp_mmio): wr(r, CK_GSP_QHEAD0, 0); -> wr(r, CK_GSP_QHEAD0, 1); +gsp_mmio mutants: 20 of 20 killed +drift: gb10_gsp_boot.md identical +drift: gsb_contract.c identical +test_gsp_mmio: PASS (67 checks) +test_gsp_mmio: PASS (67 checks) +gsp-contract-trace: PASS (3228 lines identical, hand vs contract) +gsp-contract-freestanding: PASS (gsb_contract.c with KCC/KCFLAGS, no undefined symbol) +mutant killed (checker): write GSP_QHEAD0 0 -> write GSP_QHEAD0 1 +mutant killed (trace differs): into sec2_mb0 timeout-read SEC2_MAILBOX1 sec2_mb1 -> into sec2_mb0 +gsp contract mutants: 20 of 20 killed +gates exit done +rc=0 end 2026-10-21T23:00:57Z load 8.69 10.04 10.65 diff --git a/evidence/own-gpu-driver/rung1/gates.sh b/evidence/own-gpu-driver/rung1/gates.sh new file mode 100644 index 00000000..89e5796f --- /dev/null +++ b/evidence/own-gpu-driver/rung1/gates.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# L332 rung 1 host gates: devc tests, generated-code drift, simulator twin, differential trace, freestanding, contract mutants, GSP start-up sim + mutants. +set -u +A=$HOME/workspace/aienos-own-gpu-driver D=$HOME/workspace/aienos-devc-gpu O=/tmp/l332-k +cd "$D" && cargo test -q -p aienos-devc 2>&1 | tail -3 && cargo build -q --release -p aienos-devc || { echo "GATE devc build FAIL"; exit 1; } +DEVC=$D/target/release/aienos-devc +t=$(mktemp -d); "$DEVC" gen "$A/native/kernel/gpu/contract/gb10_chan.devc" "$t" >/dev/null || { echo "GATE gen FAIL"; exit 1; } +for f in "$t"/*; do cmp -s "$f" "$A/native/kernel/gpu/contract/gen/$(basename "$f")" && echo "drift: $(basename "$f") identical" || echo "GATE drift FAIL: $(basename "$f")"; done +cd "$A" +make -s -C native/kernel OUT=$O test-gpu-contract 2>&1 | tail -4 +make -s -C native/kernel OUT=$O gpu-contract-trace 2>&1 | tail -2 +make -s -C native/kernel OUT=$O gpu-contract-freestanding 2>&1 | tail -2 +make -s -C native/kernel OUT=$O test-gpu-sim 2>&1 | tail -2 +bash evidence/own-gpu-driver/rung1/contract_mutants.sh "$DEVC" "$A/native/kernel" /tmp/l332-km 2>&1 | tail -14 +make -s -C native/kernel OUT=$O test-gsp-mmio 2>&1 | tail -3 +make -s -C native/kernel OUT=$O gsp-mmio-freestanding 2>&1 | tail -2 +bash evidence/own-gpu-driver/rung1/gsp_mmio_mutants.sh "$A/native/kernel" 2>&1 | tail -3 +t2=$(mktemp -d); "$DEVC" gen "$A/native/kernel/gpu/contract/gb10_gsp.devc" "$t2" >/dev/null || { echo "GATE gsp gen FAIL"; exit 1; } +for f in "$t2"/*; do cmp -s "$f" "$A/native/kernel/gpu/contract/gen/$(basename "$f")" && echo "drift: $(basename "$f") identical" || echo "GATE drift FAIL: $(basename "$f")"; done +make -s -C native/kernel OUT=$O test-gsp-contract 2>&1 | tail -3 +make -s -C native/kernel OUT=$O gsp-contract-trace 2>&1 | tail -2 +make -s -C native/kernel OUT=$O gsp-contract-freestanding 2>&1 | tail -2 +bash evidence/own-gpu-driver/rung1/gsp_contract_mutants.sh "$DEVC" "$A/native/kernel" 2>&1 | tail -3 +echo "gates exit done" diff --git a/evidence/own-gpu-driver/rung1/gsp-seq-20261022.txt b/evidence/own-gpu-driver/rung1/gsp-seq-20261022.txt new file mode 100644 index 00000000..3e482981 --- /dev/null +++ b/evidence/own-gpu-driver/rung1/gsp-seq-20261022.txt @@ -0,0 +1,3 @@ +GSP_SEQ_PASS checks=13 +mut_rc=1 +mutant (index check removed) failed the save-index case, as required diff --git a/evidence/own-gpu-driver/rung1/gsp_contract_mutants.sh b/evidence/own-gpu-driver/rung1/gsp_contract_mutants.sh new file mode 100755 index 00000000..3bc97374 --- /dev/null +++ b/evidence/own-gpu-driver/rung1/gsp_contract_mutants.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +# gsp_contract_mutants.sh DEVC KERNEL_DIR: wrong-but-well-formed edits of gpu/contract/gb10_gsp.devc (offsets, bits, +# constants). The checker may accept them (they break no ordering rule); the generated twin must then FAIL +# test_gsp_mmio or differ from the hand twin in gsp_boot_trace. A mutant that survives = a hole. Exit 0 only if all die. +set -u +DEVC=$1 K=$2 +CC=${CC:-cc} +src=$K/gpu/contract/gb10_gsp.devc +work=$(mktemp -d); trap 'rm -rf "$work"' EXIT +cc_() { $CC -std=c11 -O1 -I"$K/gpu" -I"$K/tests" -o "$1" "${@:2}" "$K/gpu/gsp_sim.c" > "$work/cc.log" 2>&1; } +cc_ "$work/trace_hand" "$K/tests/gsp_boot_trace.c" "$K/gpu/gsp_mmio.c" && "$work/trace_hand" > "$work/h.txt" || { echo "BASELINE FAILS"; exit 2; } +"$DEVC" gen "$src" "$work/gen" > /dev/null && cc_ "$work/t" "$K/tests/test_gsp_mmio.c" "$work/gen/gsb_contract.c" && "$work/t" > /dev/null && + cc_ "$work/tr" "$K/tests/gsp_boot_trace.c" "$work/gen/gsb_contract.c" && "$work/tr" | cmp -s - "$work/h.txt" || { echo "BASELINE CONTRACT FAILS"; exit 2; } +muts=( + "reg sec2 QTAIL0 0xc04|reg sec2 QTAIL0 0xc0c" + "reg sec2 EMEMD0 0xac4|reg sec2 EMEMD0 0xacc" + "reg sec2 SEC2_MAILBOX0 0x040|reg sec2 SEC2_MAILBOX0 0x048" + "reg gsp GSP_MAILBOX1 0x044|reg gsp GSP_MAILBOX1 0x04c" + "reg gsp FALCON_OS 0x080|reg gsp FALCON_OS 0x084" + "reg gsp HWCFG2 0x0f4|reg gsp HWCFG2 0x0f8" + "reg gsp CPUCTL 0x1388|reg gsp CPUCTL 0x1384" + "reg gsp GSP_QHEAD0 0xc00|reg gsp GSP_QHEAD0 0xc08" + "window sec2 bar 0 base 0x840000|window sec2 bar 0 base 0x841000" + "window gsp bar 0 base 0x110000|window gsp bar 0 base 0x114000" + "bit LOCKDOWN HWCFG2 13|bit LOCKDOWN HWCFG2 12" + "bit ACTIVE CPUCTL 7|bit ACTIVE CPUCTL 6" + "bit AINCW EMEMC0 24|bit AINCW EMEMC0 25" + "const SEC2_CMD_BUSY 0xc001cafe|const SEC2_CMD_BUSY 0xc001caff" + "const PRIV_LOCKED_MASK 0xFFFFFF00|const PRIV_LOCKED_MASK 0xFFFFFFF0" + "const EMEM_CHANNEL_BYTES 1024|const EMEM_CHANNEL_BYTES 1020" + "budget polls_can_send else E_BUSY|budget polls_can_send else E_EMEM" + "write FALCON_OS app_version|write FALCON_OS 0" + "write GSP_QHEAD0 0|write GSP_QHEAD0 1" + "into sec2_mb0 timeout-read SEC2_MAILBOX1 sec2_mb1|into sec2_mb0" +) +killed=0 total=0 +for m in "${muts[@]}"; do + from=${m%%|*} to=${m#*|}; total=$((total + 1)) + F=$from T=$to perl -0777 -ne '$i = index($_, $ENV{F}); exit 3 if $i < 0; substr($_, $i, length $ENV{F}) = $ENV{T}; print' \ + "$src" > "$work/gb10_gsp.devc" || { echo "MUTANT TEXT MISSING: $from"; exit 2; } + rm -rf "$work/gen" + if ! "$DEVC" gen "$work/gb10_gsp.devc" "$work/gen" > "$work/gen.log" 2>&1; then + echo "mutant killed (checker): $from -> $to"; killed=$((killed + 1)); continue + fi + if ! cc_ "$work/t" "$K/tests/test_gsp_mmio.c" "$work/gen/gsb_contract.c" || ! cc_ "$work/tr" "$K/tests/gsp_boot_trace.c" "$work/gen/gsb_contract.c"; then + echo "mutant killed (does not compile): $from -> $to"; killed=$((killed + 1)); continue + fi + if ! "$work/t" > /dev/null 2>&1; then echo "mutant killed (test_gsp_mmio): $from -> $to"; killed=$((killed + 1)); continue; fi + "$work/tr" > "$work/c.txt" + if ! cmp -s "$work/h.txt" "$work/c.txt"; then echo "mutant killed (trace differs): $from -> $to"; killed=$((killed + 1)); continue; fi + echo "MUTANT SURVIVED: $from -> $to" +done +echo "gsp contract mutants: $killed of $total killed" +test "$killed" -eq "$total" diff --git a/evidence/own-gpu-driver/rung1/gsp_mmio_mutants.sh b/evidence/own-gpu-driver/rung1/gsp_mmio_mutants.sh new file mode 100755 index 00000000..7f7e8ffc --- /dev/null +++ b/evidence/own-gpu-driver/rung1/gsp_mmio_mutants.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# gsp_mmio_mutants.sh KERNEL_DIR: wrong-but-compilable edits of gpu/gsp_mmio.c (the GB10B GSP start-up). Each must +# make test_gsp_mmio FAIL against the simulated SEC2 + GSP. A mutant that passes = a hole in the tests. +# Register offsets and bit positions live in gsp_mmio.h, which the simulator shares, so they cannot be mutated here; +# the gpu-boot device contract checks those against the driver source independently. Exit 0 only if all are killed. +set -u +K=$1 +CC=${CC:-cc} +work=$(mktemp -d); trap 'rm -rf "$work"' EXIT +mkdir -p "$work/gpu" +cp "$K/gpu/gsp_mmio.h" "$K/gpu/gsp_sim.h" "$K/gpu/gsp_sim.c" "$K/gpu/gmmu.h" "$work/gpu/" +build() { $CC -std=c11 -O1 -I"$work/gpu" -I"$K/tests" -o "$work/t" "$K/tests/test_gsp_mmio.c" "$1" "$work/gpu/gsp_sim.c" > "$work/cc.log" 2>&1; } +build "$K/gpu/gsp_mmio.c" && "$work/t" > /dev/null 2>&1 || { echo "BASELINE FAILS"; exit 2; } +muts=( + "if (head == rd(r, CK_GSP_SEC2_QTAIL0))|if (head != rd(r, CK_GSP_SEC2_QTAIL0))" + "if (n >= in->polls_can_send) {|if (n > in->polls_can_send) {" + "wr(r, CK_GSP_SEC2_EMEMC0, CK_GSP_EMEMC_AINCW);|wr(r, CK_GSP_SEC2_EMEMC0, 0);" + "(uint32_t)in->packet[i + 3] << 24|(uint32_t)in->packet[i + 3] << 16" + "v |= (uint32_t)in->packet[i + k] << (8 * k);|v |= (uint32_t)in->packet[i + k] << (8 * (3 - k));" + "if (emem_dwords(o->ememc_after) - start != o->dwords)|if (0)" + "wr(r, CK_GSP_SEC2_QTAIL0, o->dwords * 4 - 4);\n wr(r, CK_GSP_SEC2_QHEAD0, 0);|wr(r, CK_GSP_SEC2_QHEAD0, 0);\n wr(r, CK_GSP_SEC2_QTAIL0, o->dwords * 4 - 4);" + "o->dwords * 4 - 4|o->dwords * 4" + "if (o->sec2_mb0 != CK_GSP_SEC2_CMD_BUSY)|if (1)" + "return hwcfg2 != 0 && (hwcfg2|return (hwcfg2" + "return hwcfg2 != 0 && (hwcfg2 & CK_GSP_PRIV_LOCKED_MASK) != CK_GSP_PRIV_LOCKED;|return hwcfg2 != 0;" + " return 0; /* boot arguments| return 1; /* boot arguments" + "if (o->gsp_mb1 == (uint32_t)(in->fmc_args_pa >> 32))|if (1)" + "|| o->gsp_mb0 != 0;|;" + "return !(o->hwcfg2 & CK_GSP_HWCFG2_LOCKDOWN)|return (o->hwcfg2 & CK_GSP_HWCFG2_LOCKDOWN)" + " o->gsp_mb0 = rd(r, CK_GSP_FLCN_MAILBOX0);\n if (o->gsp_mb0 != 0)\n return o->stage = CK_GSP_E_FMC;|" + "wr(r, CK_GSP_FLCN_OS, in->app_version);|wr(r, CK_GSP_FLCN_OS, 0);" + "if (!(o->cpuctl & CK_GSP_CPUCTL_ACTIVE))|if (0)" + "in->len > CK_GSP_EMEM_CHANNEL_BYTES|in->len >= CK_GSP_EMEM_CHANNEL_BYTES" + "wr(r, CK_GSP_QHEAD0, 0);|wr(r, CK_GSP_QHEAD0, 1);" +) +killed=0 total=0 +for m in "${muts[@]}"; do + from=${m%%|*} to=${m#*|}; total=$((total + 1)) + f=$(printf '%b' "$from") t=$(printf '%b' "$to") + F=$f T=$t perl -0777 -ne '$i = index($_, $ENV{F}); exit 3 if $i < 0; substr($_, $i, length $ENV{F}) = $ENV{T}; print' \ + "$K/gpu/gsp_mmio.c" > "$work/gpu/gsp_mmio.c" || { echo "MUTANT TEXT MISSING: $from"; exit 2; } + if ! build "$work/gpu/gsp_mmio.c"; then echo "mutant killed (does not compile): $from -> $to"; killed=$((killed + 1)); continue; fi + if ! "$work/t" > /dev/null 2>&1; then echo "mutant killed (test_gsp_mmio): $from -> $to"; killed=$((killed + 1)); continue; fi + echo "MUTANT SURVIVED: $from -> $to" +done +echo "gsp_mmio mutants: $killed of $total killed" +test "$killed" -eq "$total" diff --git a/evidence/own-gpu-driver/rung2/.gitignore b/evidence/own-gpu-driver/rung2/.gitignore new file mode 100644 index 00000000..a57a5eba --- /dev/null +++ b/evidence/own-gpu-driver/rung2/.gitignore @@ -0,0 +1,2 @@ +window0-current.log +aien_gpu_check diff --git a/evidence/own-gpu-driver/rung2/RUNBOOK.md b/evidence/own-gpu-driver/rung2/RUNBOOK.md new file mode 100644 index 00000000..d908671c --- /dev/null +++ b/evidence/own-gpu-driver/rung2/RUNBOOK.md @@ -0,0 +1,120 @@ +# L332 rung 2, window 0: give the GPU to our driver for a few minutes, read it, give it back + +Purpose: the smallest real step. Prove we can take the GB10 away from NVIDIA's driver and give it back, measure how long +that takes (nvidia.ko has never been reloaded on this box since boot, so nobody knows), and let our module `aien-gpu` +read the chip's identity and set up its memory area. Our module writes nothing to the GPU in window 0. + +Scheduled by: the coordinator (ledger line "L332 window 0"). Run only inside that window. Hands-off: nothing needs a +person at the machine unless the box fails to come back from a reboot (see Recovery). + +## What goes down, and for how long +Everything that uses the GPU, from part 1 until the restore reboot at the end of part 2. The four NVIDIA modules are +nvidia_drm, nvidia_modeset, nvidia_uvm, nvidia (lsmod). Holders of /dev/nvidia* on 2026-10-21 22:0xZ (`sudo fuser -v`): +- aien-serve-http pid 2587647 (the 35B on 18091, owner L306/L387 server lane), +- qwen36_stroke_g pid 2613825 (motor stroke work, L312 lane), +- nvidia-persistenced pid 1816 (root service, enabled; fails harmlessly while the modules are held back). +Plus anything the judge or a window starts meanwhile. Stop order: the coordinator stops the chip jobs and the 35B server +(owners restart them after the restore reboot); persistenced is left alone (the reboot handles it). +Expected time down: two reboots plus about 2 minutes of steps. Reboot-to-ssh time on this box is not measured (journal +gaps are not clean reboots); part 2 logs boot time and uptime, so this window measures it. + +## Why a reboot and not "unload the driver" +NVIDIA's display part has a worker that spins forever on this headless box (L158: nvEvoWaitForCoreNotifier). Unloading +`nvidia_modeset` waits for that worker, so the unload would most likely hang with the GPU half torn down (INFERRED from +~/handoffs/fixer-modeset-kthread.md item 2; not tested). So the GPU is freed by booting once with NVIDIA's modules held +back. Revised 2026-10-26 (NoNvDriver review): the hold-back is self-reverting (`window-boot.sh`). GRUB_DEFAULT=0 stays; +a one-shot custom.cfg entry `aien-gpu-window` (today's command line plus `aien.gpuwindow=1 systemd.watchdog_sec=30 +panic=10 oops=panic`) is chosen for exactly one boot by `grub-reboot`. In that boot only, aien-gpu-window-hold.service +writes the hold-back file to /run/modprobe.d (tmpfs) before udev and modules-load, and aien-gpu-window-lease.service +reboots after 25 minutes. Any later boot, planned or not, is today's boot with NVIDIA; no file to delete by hand. The +old /etc/modprobe.d file survived a crash and pinned every later boot to "no NVIDIA". The NVIDIA modules are not in the +initramfs (checked, fail-closed, by part 1 and by `window-boot.sh check`). Alternative not chosen: kexec with +`modprobe.blacklist=` on the command line (no file, faster) because the GPU state after a kexec without a firmware reset +is UNKNOWN on GB10. + +## Facts checked on 2026-10-21 (read-only) +- Secure Boot disabled, lockdown none, module signatures not enforced: the unsigned aien_gpu.ko loads (taints). +- aien_gpu.ko vermagic 7.0.0-1019-nvidia = running kernel. +- kernel.panic = 0: a kernel panic would freeze the box until power-cycled. Part 2 sets kernel.panic=10 and + panic_on_oops=1 (runtime only, gone at the next boot) before our module touches the chip, so a bad register read + reboots the box on its own. +- GB10 = 000f:01:00.0, 10de:2e12, BAR0 64 MiB at 0x24000000. + +## Steps +Scripts in this directory, each line timed into window0-.log (window0-current.log points at it). +Prep (changes the boot config, needs Drake's go): `./window-boot.sh check` (read-only, any time), then +`./window-boot.sh install --yes` (adds the inert GRUB entry and the two units; normal boots are unchanged). +0. Any time before the window: `./window0-pre.sh` (no --go) checks the module, Secure Boot, initramfs and lists holders. +1. Window opens; coordinator stops the GPU users; `./window0-pre.sh --go`: records lsmod, nvidia-smi, cmdline, module + hash, refuses if anything but persistenced still holds the GPU, runs `window-boot.sh check` and `arm --yes` and + reboots into the one-shot window entry. +2. After ssh is back: `./window0-post.sh`: refuses unless this is the window boot; logs boot time; checks no nvidia + module and no driver on the GPU; sets panic auto-reboot; insmod aien_gpu allow_bind=1; aien_gpu_check (identity, + firmware size, arena mmap pattern); rmmod; optional FLR recovery test (`AIEN_W0_FLR=1`, Drake decides); removes the + /run hold-back file; timed `modprobe nvidia nvidia_uvm` + first nvidia-smi answer (NVIDIA's load-to-ready baseline); + Omega gpu_launch_cost_test --reps 3 (first open after load, timed); prints WINDOW0 PASS or FAIL; normal reboot. +3. After the restore reboot: `lsmod | grep -c ^nvidia` = 4, `nvidia-smi -L` lists the GPU, no aien.gpuwindow=1 on the + command line, `./window-boot.sh status` shows no next_entry; owners restart their servers; commit the log; window + closes. `./window-boot.sh uninstall --yes` when no more windows are planned. + +## Recovery +- Anything odd during part 2: `sudo rmmod aien_gpu` if loaded, then `sudo reboot` (the next boot is the default entry). +- Box does not come back within 10 minutes after part 1's reboot: the 30 s hardware watchdog (SBSA, armed by systemd + from the command line) resets a hung boot, and the default entry with NVIDIA comes up. Whether an SBSA reset also + resets GSP/SEC2 is NOT_RUN; if ssh never answers, a power cycle at the wall is the only step left (Drake, physical). +- Window overruns: the lease reboots the box 25 minutes into the window boot. +- Kernel panic or oops while our module reads the chip: auto-reboot after 10 s (command line, so it holds from the first + instruction, not only after part 2 sets it), back to today's boot. + +## Gate (window 0 PASS when all hold) +- aien-gpu: PMC_BOOT_0 read (not 0, not all-ones), firmware 75,012,080 bytes, arena mmap pattern PASS, rmmod clean. +- PMC_BOOT_42 logged. window1-pre.sh refuses unless CHIP_ID = (BOOT_42 >> 20) & 0x3ff is 0x1AB (GB10B), because the + window-1 package carries GB10B images only; the Spark reports sm_121, which in 580.173.02 points at GB20B (0x1BB) + rather than GB10B (Thor, T264). Until window 0 reads it, the chip identity is unmeasured. +- After the reload: nvidia-smi lists the GPU; Omega launch-cost test exit 0. +- After the restore reboot: four modules back, not the window boot, no next_entry. +- Log committed under evidence/own-gpu-driver/rung2/, pass or fail. + +## Window 1: start NVIDIA's GSP firmware with our own code +Only after window 0 PASS (part 1 refuses otherwise). Same take-away and give-back as window 0 (reboot with NVIDIA held +back, restore reboot), so the same people stop the same GPU users. + +What our code does to the chip, all of it from the source lines quoted in native/kernel/gpu/gsp_mmio.h and +gpu/contract/gb10_gsp.devc: builds the start-up package in memory the GPU can read (L192 builder), writes one 868-byte +signed packet into SEC2's mailbox memory, rings SEC2 once, waits for SEC2 to hand control to GSP, writes the GSP-RM +version into one register, then only reads: GSP's status messages until "INIT_DONE" or 30 s. + +Why this cannot harm the chip: the GPU checks NVIDIA's signature on the firmware itself (the chain of trust lives in +SEC2 and the boot ROM; we hand over NVIDIA's signed images byte for byte, pinned by SHA-256). Our module lets user space +reach only the 12 start-up registers (6 of them writable), only with allow_boot=1, and rings the SEC2 doorbell once per +load. What can go wrong is that GSP is left stopped or half started until the GPU is reset. + +UNKNOWN until this window (said out loud): +- whether the restore reboot resets the GB10's GSP and SEC2 fully. If it does not, NVIDIA's driver fails after the + restore reboot (part 3 shows it) and the fix is a full power cycle at the wall: Drake, physical. That would also keep + the 35B server down until then. This is the one real cost; the coordinator weighs it when scheduling. +- whether SEC2 accepts the packet with Linux's driver absent (inventory 14.5), whether GSP-FMC accepts our WprMeta and + heap, whether our GspSystemInfo values (rung2/system_info.txt, each tagged with its source) are what GSP-RM needs, + whether GSP-RM asks for a CPU sequencer run before INIT_DONE (window 1 records it and stops; handling it is window 2). + +Steps (each line timed into window1-.log, window1-current.log points at it): +0. Before the window: `make -C native/linux/aien-gpu all tools sim-test` (sim test PASS), the package + `./window1-package.sh ` (WINDOW1_PACKAGE: PASS), then `./window1-pre.sh ` (checks only). +1. Window opens, GPU users stopped: `./window1-pre.sh --go` (blacklist file, reboot). +2. After ssh is back: `./window1-post.sh`: deletes the file, aborts if any NVIDIA module is loaded, sets panic + auto-reboot, insmod aien_gpu allow_bind=1 allow_boot=1 arena_mib= heap_mib=512, runs + aien_gsp_boot (register trace with times, plan, every status message, GSP log buffers, verdict) into + window1--run/, prints WINDOW1 PASS or STOPPED, reboots WITHOUT rmmod. +3. After the restore reboot: `./window1-check.sh` (four NVIDIA modules, nvidia-smi answers, file gone, aien_gpu not + loaded): WINDOW1 RESTORE PASS. Owners restart their servers. Commit the log and the run directory, pass or fail. + +Recovery: as window 0. If part 3 fails (nvidia-smi does not list the GPU after the restore reboot), reboot once more; +if it still fails, the GPU needs a power cycle (Drake, physical), and nothing else is tried on the chip until then. + +Gate (window 1 PASS): aien_gsp_boot verdict INIT-DONE, register trace inside the allowlist, WINDOW1 RESTORE PASS. +Any other verdict is still a result: it names the step that stopped (SEC2, mask, lockdown, FMC code, core, queue). + +## Later windows (each needs its own prepared step and its own request) +1. (window 1 above.) +2. The RPC subset from docs/numeric/DRIVER_FLOOR.md and one channel (gpu/contract/gb10_chan.devc). +3. Omega on aien-gpu through L202's typed handles: golden tokens identical to nvidia.ko, per-word timing and start time side by side. diff --git a/evidence/own-gpu-driver/rung2/build-receipts-20261022T0108Z.txt b/evidence/own-gpu-driver/rung2/build-receipts-20261022T0108Z.txt new file mode 100644 index 00000000..1924de8d --- /dev/null +++ b/evidence/own-gpu-driver/rung2/build-receipts-20261022T0108Z.txt @@ -0,0 +1,33 @@ +# L332 window 1 build receipts, run under quiet-build 2026-10-22T00:58:42Z to 2026-10-22T01:08:48Z +# source: aienux feat/own-gpu-driver 89360c06 + the two build fixes committed with this file + +## kernel module (make all) +kmod-rc=0 +aee06949cb1fd40dd7efc68c0be7f4e4df4ab0b36ce2c7bd01afd99e41c9df0a native/linux/aien-gpu/aien_gpu.ko +vermagic 7.0.0-1019-nvidia; params: allow_bind arena_mib heap_mib allow_boot + +## GspSystemInfo encoder selftest + layout vs NVIDIA's own header text +PASS no other GspSystemInfo byte changed +PASS no other GspSystemInfo byte changed +CK_GSP_SYSINFO_ENCODE_SELFTEST: PASS (15 checks, 72 fields) +GSP_SYSINFO_NVHDR: PASS (70 comparisons, sizeof GspSystemInfo 936) + +## window-1 package (real firmware, pinned hashes) +WINDOW1_PACKAGE: PASS (/tmp/l332-pkg) +pkg-rc=0 +# window-1 boot package, built 2026-10-22T01:08:48Z on spark-b87b from repo 89360c060102e4242187cda6156d696452e38181 +# firmware /lib/firmware/nvidia/580.173.02/gsp_ga10x.bin sha256 32cb7cf3e77f97e92f6e92135939ccb3ba382748144569c0dfccf3338d43d963; bindata from /home/drakestapleton/workspace/_ext/open-gpu-kernel-modules-580.173.02/src/nvidia/generated; system info from /home/drakestapleton/workspace/aienos-own-gpu-driver/evidence/own-gpu-driver/rung2/system_info.txt sha256 fd384ca727b74c6c29feda3b7a8c20491099b1a2dac6966707d4264e5ae7086f +app_version 0 (RM_RISCV_UCODE_DESC.appVersion of UCODE_DESC_PROD, GspRmBoot_GB10B) +rm_elf.bin 74969088 931add19204a5f0240442272f58fb2bc5db6cec4dd6f6341c1d888754146aa07 +rm_sig.bin 4096 08541c3a909f8fd21c3eaf55fbe6c6c30ff2b7729e885417f3fcb06a4d108f2d +bootloader.bin 196608 427a691d8453f02548d395f40ac900eb0d5b8ea864e8f14f958eef890ba400a2 +fmc.bin 195912 b13ead4b9a6b8a0d268f3094cc4f4521d6be8a9a525edbc9a8f3f397c86f1f2e +fmc_hash.bin 48 f0389f3a9ce3bb6093e80bfc924bbe2a4ece0199b080a37f64bc1fef63f7500c +fmc_pkey.bin 384 e9bbc669c27ad8827b5bbc2b2f52fdb47718659a651088869a5f3b11d2df7816 +fmc_sig.bin 384 9db429257a18e7c5c1a3df185001c671e21bec4e94c719a574d2ce72e2e07272 +system_info.bin 936 bd4b23c08ecf78e074132b58a6968ee52262d801e8092ed4e63cc12d8c82ee5d + +## sim test (plain build) from this run +WINDOW1_SIM_TEST: PASS +(sanitized build FAILED in this run: LeakSanitizer flagged the host arena and loaded package files never freed by the one-shot tool. Fixed by keeping them reachable; both builds PASS in sim-test-20261022T0120Z.txt.) +app_version 0 checked: the decoded descriptor fields match the known bootloader offsets (manifest 0xa00, monitor code 0xb000), so appVersion 0 is what NVIDIA itself writes to FALCON_OS (kernel_gsp_gh100.c:954-956). diff --git a/evidence/own-gpu-driver/rung2/reproduce-pipefail.sh b/evidence/own-gpu-driver/rung2/reproduce-pipefail.sh new file mode 100755 index 00000000..91172b98 --- /dev/null +++ b/evidence/own-gpu-driver/rung2/reproduce-pipefail.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +# reproduce-pipefail.sh: deterministic reproduction of the SIGPIPE (exit 141) +# race in window1-package.sh when using `tail | head` under `set -eo pipefail`, +# and verification that `dd if=... of=... bs=64k iflag=skip_bytes,count_bytes` +# exits 0 and produces byte-identical slices without pipes. +set -eu +FW=${FW:-/lib/firmware/nvidia/580.173.02/gsp_ga10x.bin} +T=$(mktemp -d /tmp/repro-pipefail.XXXXXX) +trap 'rm -rf "$T"' EXIT + +if [[ -r "$FW" ]]; then + SRC="$FW" + off=64 + size=74969088 + echo "Using real GSP firmware: $FW (size $(stat -c %s "$FW") bytes)" +else + SRC="$T/synthetic.bin" + dd if=/dev/urandom of="$SRC" bs=1M count=16 status=none + off=64 + size=8388608 + echo "Using synthetic binary payload: $SRC (size $(stat -c %s "$SRC") bytes)" +fi + +echo "--- 1. Demonstrating SIGPIPE (exit 141) with tail | head under pipefail ---" +old_141_count=0 +trials=20 +for i in $(seq 1 "$trials"); do + rc=0 + ( + set -euo pipefail + tail -c +$((off + 1)) "$SRC" | head -c "$size" > /dev/null + ) || rc=$? + if [[ $rc -eq 141 ]]; then + old_141_count=$((old_141_count + 1)) + fi +done +echo "tail | head under pipefail: $old_141_count / $trials runs exited with 141 (SIGPIPE)" + +echo "--- 2. Demonstrating exit 0 with dd (no pipe, direct seek and slice) ---" +new_fail_count=0 +for i in $(seq 1 "$trials"); do + rc=0 + ( + set -euo pipefail + dd if="$SRC" of=/dev/null bs=64k iflag=skip_bytes,count_bytes skip="$off" count="$size" status=none + ) || rc=$? + if [[ $rc -ne 0 ]]; then + new_fail_count=$((new_fail_count + 1)) + fi +done +echo "dd with skip_bytes,count_bytes: $new_fail_count / $trials failures (all passed with rc 0)" + +echo "--- 3. Verifying byte-for-byte identity against reference ---" +python3 -c " +with open('$SRC', 'rb') as f: + f.seek($off) + chunk = f.read($size) +with open('$T/reference.bin', 'wb') as f: + f.write(chunk) +" +dd if="$SRC" of="$T/dd.bin" bs=64k iflag=skip_bytes,count_bytes skip="$off" count="$size" status=none + +cmp "$T/reference.bin" "$T/dd.bin" +echo "BYTE-IDENTICAL: Reference and dd outputs match exactly ($size bytes)" + +if [[ $old_141_count -gt 0 && $new_fail_count -eq 0 ]]; then + echo "REPRODUCTION SUCCESS: tail|head exited 141; dd exited 0 with byte-identical output" + exit 0 +else + echo "REPRODUCTION FAILED unexpected counts: old_141=$old_141_count new_fail=$new_fail_count" + exit 1 +fi diff --git a/evidence/own-gpu-driver/rung2/sim-test-20261022T0120Z.txt b/evidence/own-gpu-driver/rung2/sim-test-20261022T0120Z.txt new file mode 100644 index 00000000..2468a4d2 --- /dev/null +++ b/evidence/own-gpu-driver/rung2/sim-test-20261022T0120Z.txt @@ -0,0 +1,60 @@ +# window1_sim_test.sh, plain and ASan/UBSan builds of aien_gsp_boot (sim), run under quiet-build 2026-10-22T01:2xZ +PASS init: INIT-DONE (exit 0) +PASS seq: SEQUENCER-REQUESTED (exit 1) +PASS silent: NO-INIT-DONE (exit 1) +PASS junk: STATUS-QUEUE-ERROR (exit 1) +PASS busy: STOPPED-AT E_BUSY (exit 1) +PASS fmcerr: STOPPED-AT E_FMC (exit 1) +PASS dead: STOPPED-AT E_RISCV (exit 1) +PASS planonly: PLAN-ONLY (exit 0) +PASS small: BUILD-REFUSED (exit 2) +PASS arena too small: no register touched +PASS init wrote plan.txt +PASS init wrote result.txt +PASS init wrote messages.txt +PASS init wrote regs.txt +PASS init wrote cot_packet.bin +PASS init wrote log-LOGINIT.bin +PASS init wrote rpc-shared.bin +PASS INIT_DONE recorded in messages.txt +PASS COT packet 868 bytes +PASS result.txt carries the verdict +PASS package notify address sent unchanged +PASS zero notify field filled with the zeroed first arena page +PASS no other GspSystemInfo byte changed +PASS 935-byte GspSystemInfo refused, no register touched +PASS every read the tool made is on the module read list (8 registers) +PASS every write the tool made is on the module write list (5 registers) +PASS write list has one register the start-up does not use: GSP QHEAD0 (notify, after INIT_DONE) +PASS one SEC2 doorbell per start-up +WINDOW1_SIM_TEST: PASS +PASS init: INIT-DONE (exit 0) +PASS seq: SEQUENCER-REQUESTED (exit 1) +PASS silent: NO-INIT-DONE (exit 1) +PASS junk: STATUS-QUEUE-ERROR (exit 1) +PASS busy: STOPPED-AT E_BUSY (exit 1) +PASS fmcerr: STOPPED-AT E_FMC (exit 1) +PASS dead: STOPPED-AT E_RISCV (exit 1) +PASS planonly: PLAN-ONLY (exit 0) +PASS small: BUILD-REFUSED (exit 2) +PASS arena too small: no register touched +PASS init wrote plan.txt +PASS init wrote result.txt +PASS init wrote messages.txt +PASS init wrote regs.txt +PASS init wrote cot_packet.bin +PASS init wrote log-LOGINIT.bin +PASS init wrote rpc-shared.bin +PASS INIT_DONE recorded in messages.txt +PASS COT packet 868 bytes +PASS result.txt carries the verdict +PASS package notify address sent unchanged +PASS zero notify field filled with the zeroed first arena page +PASS no other GspSystemInfo byte changed +PASS 935-byte GspSystemInfo refused, no register touched +PASS every read the tool made is on the module read list (8 registers) +PASS every write the tool made is on the module write list (5 registers) +PASS write list has one register the start-up does not use: GSP QHEAD0 (notify, after INIT_DONE) +PASS one SEC2 doorbell per start-up +WINDOW1_SIM_TEST: PASS +sim-rc=0 diff --git a/evidence/own-gpu-driver/rung2/system_info.txt b/evidence/own-gpu-driver/rung2/system_info.txt new file mode 100644 index 00000000..1a85b9e1 --- /dev/null +++ b/evidence/own-gpu-driver/rung2/system_info.txt @@ -0,0 +1,111 @@ +# GspSystemInfo for window 1 (L332 rung 2): what NVIDIA's driver 580.173.02 would send in GSP_SET_SYSTEM_INFO on this +# Spark (GB10 at PCI 000f:01:00.0). Encoded by native/kernel/tools/ck_gsp_sysinfo_encode; every field not listed is 0. +# Driver source: rpcGspSetSystemInfo_v17_00 (src/nvidia/src/kernel/vgpu/rpc.c:10493-) and clSyncWithGsp_IMPL +# (src/nvidia/src/kernel/platform/chipset/chipset.c:760-815). Tags: DOCUMENTED = driver line, OBSERVED = read on this box +# 2026-10-21, ASSUMED = not settled, reason given. $O = ~/workspace/_ext/open-gpu-kernel-modules-580.173.02. + +# Bus addresses. The GB10 has one memory BAR: BAR0 0x24000000, 64 MiB (sysfs resource, lspci; OBSERVED). nv-pci.c:1495-1508 +# fills nv->bars[] with valid memory BARs in order, so nv->fb (bars[1]) and bars[2] (IMEM) stay zero (DOCUMENTED). +# osinit.c:737-742 -> gpu_mgr.c (non-SOC branch): gpuPhysAddr = BAR0, gpuPhysFbAddr = 0, gpuPhysIoAddr = 0, and with no +# IMEM BAR gpuPhysInstAddr = BAR0 + 0x700000 (NV_PRAMIN, gpu_mgr.c ~1994). +gpuPhysAddr 0x24000000 +gpuPhysInstAddr 0x24700000 +# gpuEncodeDomainBusDevice (g_gpu_nvoc.h:502-507, fields 63:32 domain, 15:8 bus, 7:0 device; function not encoded), +# via nv_encode_pci_info (osinit.c:144-147): domain 0xf, bus 1, device 0. +nvDomainBusDeviceFunc 0x0000000f00000100 + +# PCI identity, as the GB100-family HAL reads config space (kern_gpu_gb100.c:940-967): DEVICE_VENDOR_ID dword, +# SUBSYSTEM_ID_AND_VENDOR_ID dword, revision byte of dword 8. OBSERVED: 10de:2e12, subsystem 10de:0000, revision 0xa1. +PCIDeviceID 0x2e1210de +PCISubDeviceID 0x000010de +PCIRevisionID 0xa1 + +# OS: TASK_SIZE (os-interface.c:1128-1131) with CONFIG_ARM64_VA_BITS=48 (OBSERVED /boot/config); osGetPageSize = 4096 +# (CONFIG_ARM64_4K_PAGES=y, getconf PAGESIZE, OBSERVED). +maxUserVa 0x1000000000000 +hostPageSize 4096 + +# PCIe link capabilities register of the GPU (config 0x6c = Express cap 0x60 + 0xc), OBSERVED setpci 6c.l. +pcieConfigReg.linkCap 0x00457901 + +# CPU architecture: enum g_gpu_nvoc.h:361-366 (X86_64 0, PPC64LE 1, ARM 2, AARCH64 3), assigned gpu_mgr.c:1539. DOCUMENTED. +oorArch 0x3 + +# Chipset: the root port 000f:00:00.0 is 10de:22d1 (OBSERVED). nvcst.h:300 maps NVIDIA 0x22D1 to CS_NVIDIA_T254; its enum +# value printed by a probe compiled against nvdevid.h on 2026-10-21: T254=0x106d (DOCUMENTED, compiled). +Chipset 0x106d +# First host bridge and chipset id: chipset.c:253-368 copies the upstream port's ids; config bytes de 10 d1 22, class +# 0x0604, no subsystem capability on the type-1 bridge (OBSERVED lspci -xxx), so subsystem and revision fields stay 0. +# INFERRED (path read, not run). +FHBBusInfo.deviceID 0x22d1 +FHBBusInfo.vendorID 0x10de +chipsetIDInfo.deviceID 0x22d1 +chipsetIDInfo.vendorID 0x10de +# Chipset property bits 0, 6, 7, 13, 23, 27, 32 (clSyncWithGsp_IMPL chipset.c:760-815; each bit's setter read by the +# L332 research pass 2026-10-21): sum calc:9bed9176ce8fde2e4e1720279ef0388df38e8af58d36851fa354482d1dec7e4f = 4437582017. +# INFERRED (which setters fire on this box was read from source, not observed from NVIDIA's driver). +clPdbProperties 0x1088020c1 + +# GPU PCIe features. FLR: kernel_bif_gh100.c:1099 tests bit 28 of config 0x64, the GPU reads 0x10008021 (OBSERVED). +# 64-bit BAR0: kernel_bif_gh100.c:1131, BAR0 dword 0x2400000c (OBSERVED). MNOC: kbifCacheMnocSupport is GB100/102/110/112 +# only, GB10B takes the no-op (DOCUMENTED). L1SS: the root port has no L1 PM Substates capability (OBSERVED lspci). +bFlrSupported 1 +b64bBar0Supported 1 +bMnocAvailable 0 +chipsetL1ssEnable 0 +# Config-space mirror: GB10B uses kbifGetPciConfigSpacePriMirror_GH100 (g_kernel_bif_nvoc.c:966-969, ChipHal list +# "GH100 | GB10B | GB202 ..."), which returns DEVICE_BASE/EXTENT of NV_EP_PCFGM = 0x92FFF:0x92000 (kernel_bif_gh100.c:593-604, +# dev_xtl_ep_pri.h:26). The rpc.c:10544 "mirror removed on Blackwell+" comment covers GB100/102/110/112 (the _48d5a7 stub), +# not GB10B. DOCUMENTED. +pciConfigMirrorBase 0x92000 +pciConfigMirrorSize 0x1000 +# Atomics: requester mask NVBIT(0..2) from kbifProbePcieReqAtomicCaps_GH100 (kernel_bif_gh100.c:620) via os-pci.c:151; +# root port DevCap2 0x80711ba0 has atomic completer bits 7-9, GPU DevCtl2 shows AtomicOpsCtl ReqEn+ (OBSERVED). INFERRED. +# Completer mask: kernel_bif_gb10b.c:30-66 reads the GPU's own DevCap2 0x00670813, bits 7-9 clear (OBSERVED) -> 0. +pcieAtomicsOpMask 0x7 + +# Hypervisor: OS_HYPERVISOR_UNKNOWN = 4 is the constructor default (nv-hypervisor.h:32-38, hypervisor.c:58); bare metal +# (SMBIOS 0x13 byte 0x0D, VM bit clear, OBSERVED). No SR-IOV capability (lspci, OBSERVED): gspVFInfo stays 0. +hypervisorType 4 + +# ACPI: _acpiCacheMethodData (acpi_common.c:1120-1180) sets bValid unconditionally, sets acpiIdListLen to +# sizeof(acpiIdList) = 16 x 4 = 64 before calling _DOD, and stores each call's status (DOCUMENTED). The GPU's ACPI node +# \_SB_.PCIF.RP0_.IGPU exists (sysfs firmware_node/path, OBSERVED) with only _ADR and _CRS, so _DOD fails and +# nv_acpi_dod_method returns NV_ERR_GENERIC 0xFFFF (nv-acpi.c:1026-1032; nvstatuscodes.h:28), list length untouched. +# JT and Optimus caps go through checkDsmCall, whose not-present paths return NV_ERR_NOT_SUPPORTED 0x56 +# (acpi_common.c checkDsmCall; nvstatuscodes.h:115): INFERRED (no _DSM on the node; which exit fires was not run). +# With _DOD failed the mux table stays empty (tableLen 0). Without these, 0 would read as NV_OK (success). +acpiMethodData.bValid 1 +acpiMethodData.dodMethodData.status 0xffff +acpiMethodData.dodMethodData.acpiIdListLen 64 +acpiMethodData.jtMethodData.status 0x56 +acpiMethodData.capsMethodData.status 0x56 + +# Upstream port: the GPU sits directly under the root port (bGpuBehindBridge 0, chipset_pcie.c:1313-1322, INFERRED); +# upstreamAddressValid set by chipset_pcie.c:1205-1212 (DOCUMENTED). ASPM POR flags are Intel-only, stay 0 (INFERRED). +upstreamAddressValid 1 + +# Display: GB10B has DISPv0501 (g_chips2halspec_nvoc.h:148-149), so KernelDisplay exists and its constructor value +# bWindowChannelAlwaysMapped = 1 (g_kern_disp_nvoc.c:305) is sent (INFERRED). HDMI FRL compliance flag is set +# unconditionally (g_gpu_nvoc.c:350, DOCUMENTED). +bWindowChannelAlwaysMapped 1 +bIsUnixHdmiFrlComplianceEnabled 1 + +# Fields left 0 on purpose (every unlisted field is 0): +# - simAccessBufPhysAddr: not a simulator (DOCUMENTED). isGridBuild/gridBuildCsp: not a GRID build (INFERRED). +# - bPreserveVideoMemoryAllocations: GB10B's bUseVirtualCopyOnSuspend HAL default is TRUE (g_mem_mgr_nvoc.c:466-482), +# which blocks osinit.c:842 (INFERRED). bEnableDynamicGranularityPageArrays, bFeatureStretchVblankCapable, +# bClockBoostSupported, bIsCmcBasedHws, bGspNocatEnabled: constructor/no-op/Windows-only (DOCUMENTED). bTdrEventSupported: +# no setter (INFERRED). bS0ixSupport: regkey EnableS0ixPowerManagement 0 (OBSERVED). +# - notifyOpSharedSurfacePhysAddr: left 0 HERE on purpose; aien_gsp_boot fills it with the zeroed first page of the arena, +# as NVIDIA's _kgspAllocNotifyOpSharedSurface (kernel_gsp.c:3489-3526) does, and saves what it sent as +# system_info.sent.bin in the run directory. +# +# UNKNOWN (said out loud; window 1 shows whether any of them matters): +# - consoleMemSize: 0 chosen. NVIDIA preserves the console only when the framebuffer sits in a GPU BAR (nv.c:6172-6308); +# here the framebuffer is at 0x300000000, outside BAR0, and GB10 has no FB BAR, so 0 is most likely (INFERRED). +# - bIsPrimary: 0 chosen. Follows primary_vga (nv.c:5105-5121), false on arm64 in the reading; boot_vga reads 1 (OBSERVED), +# so not settled. +# - sysTimerOffsetNs: 0 chosen. NVIDIA computes OS ns minus GPU PTIMER ns just before the call (timer_gb10b.c:36-79); +# PTIMER is not on the module's allowlist. 0 makes GSP log timestamps PTIMER time instead of wall time. ASSUMED harmless +# for INIT_DONE; window 2 adds the read if it is not. diff --git a/evidence/own-gpu-driver/rung2/window-boot.sh b/evidence/own-gpu-driver/rung2/window-boot.sh new file mode 100755 index 00000000..60959fe2 --- /dev/null +++ b/evidence/own-gpu-driver/rung2/window-boot.sh @@ -0,0 +1,103 @@ +#!/usr/bin/env bash +# window-boot.sh: the self-reverting boot path for L332 GPU windows (NoNvDriver review, 2026-10-26). +# +# Replaces "write /etc/modprobe.d/zz-aien-gpu-window*.conf and reboot". That file persists: if part 2 never runs, every +# later boot (watchdog reset, power cycle) comes up WITHOUT NVIDIA's driver until a person deletes it. Here instead: +# - GRUB default stays entry 0 (NVIDIA's driver). GRUB_DEFAULT is not touched; grub.cfg is not regenerated. +# - /boot/grub/custom.cfg (sourced by /etc/grub.d/41_custom) adds ONE extra entry 'aien-gpu-window'. 'arm' selects it +# for the next boot only, via grub-reboot (grubenv next_entry; 00_header honours it with GRUB_DEFAULT=0 and clears +# it on use). +# - That entry adds: aien.gpuwindow=1 (activates the two inert units), systemd.watchdog_sec=30 (PID 1 arms the SBSA +# hardware watchdog for this boot: a hard hang resets the box into the default entry), panic=10 oops=panic +# (a kernel panic or oops reboots after 10 s into the default entry). +# - aien-gpu-window-hold.service writes the "do not load NVIDIA" file to /run/modprobe.d (tmpfs: this boot only). +# - aien-gpu-window-lease.service reboots 25 min after boot (L405 lease 20 min + 5 min restore margin). +# Any reboot after the window boot, wanted or not, lands on NVIDIA's driver with nothing to clean up. +# +# Usage: +# window-boot.sh check (default) read-only: builds the entry and units into a temp dir, runs grub-script-check +# and systemd-analyze verify, shows what install would change. Writes nothing outside /tmp. +# window-boot.sh install --yes copies custom.cfg and the two units (inert on normal boots). Coordinator + Drake approval. +# window-boot.sh arm --yes next boot only = 'aien-gpu-window' (grub-reboot). Inside the window only. +# window-boot.sh status what is installed / armed now. +# window-boot.sh uninstall --yes removes custom.cfg and the units. +set -euo pipefail +export PATH=$PATH:/usr/sbin:/sbin +HERE=$(cd "$(dirname "$0")" && pwd) +ENTRY=aien-gpu-window +UNITS="aien-gpu-window-hold.service aien-gpu-window-lease.service" +KVER=$(uname -r) +CUSTOM=/boot/grub/custom.cfg +die() { echo "WINDOW_BOOT: FAIL ($*)" >&2; exit 1; } + +# The entry repeats the running kernel's command line (minus GRUB's BOOT_IMAGE) and adds the window flags. +build_entry() { + local uuid cmd + uuid=$(sed -n 's/.*root=UUID=\([0-9a-fA-F-]\{36\}\).*/\1/p' /proc/cmdline) + [[ -n $uuid ]] || die "no root=UUID= in /proc/cmdline" + [[ $(findmnt -no UUID -T /boot) == "$uuid" ]] || die "/boot is not on the root filesystem $uuid; entry paths would be wrong" + [[ -f /boot/vmlinuz-$KVER && -f /boot/initrd.img-$KVER ]] || die "kernel or initrd for $KVER missing in /boot" + cmd=$(sed 's/^BOOT_IMAGE=[^ ]* //' /proc/cmdline) + case " $cmd " in *" aien.gpuwindow="*|*" module_blacklist="*|*" modprobe.blacklist="*) die "running cmdline already carries window flags";; esac + cat < "$t/custom.cfg" + grub-script-check "$t/custom.cfg" || die "grub-script-check refused $t/custom.cfg" + echo "entry: grub-script-check PASS ($t/custom.cfg)" + grep -q 'custom.cfg' /etc/grub.d/41_custom || die "/etc/grub.d/41_custom does not source custom.cfg" + grep -q 'next_entry' /etc/grub.d/00_header || die "/etc/grub.d/00_header has no next_entry (grub-reboot would not work)" + echo "grub: 41_custom sources custom.cfg; 00_header honours next_entry; GRUB_DEFAULT=$(sed -n 's/^GRUB_DEFAULT=//p' /etc/default/grub) unchanged" + [[ -e /sys/class/watchdog/watchdog0 ]] && echo "watchdog: $(cat /sys/class/watchdog/watchdog0/identity) present ($(cat /sys/class/watchdog/watchdog0/state))" \ + || echo "watchdog: NONE (systemd.watchdog_sec has no device; hangs need a power cycle)" + for u in $UNITS; do cp "$HERE/window-boot/$u" "$t/$u"; done + (cd "$t" && systemd-analyze verify --man=no $UNITS) || die "systemd-analyze verify refused the units" + echo "units: systemd-analyze verify PASS" + local initrd; initrd=$(lsinitramfs "/boot/initrd.img-$KVER") && [[ -n $initrd ]] || die "cannot list /boot/initrd.img-$KVER: initramfs check would pass silently" + grep -qE '/nvidia(_uvm|_modeset|_drm)?\.ko' <<< "$initrd" && die "nvidia modules in initramfs: /run/modprobe.d would come too late" + echo "initramfs: no nvidia modules" + if [[ -e $CUSTOM ]]; then diff -u "$CUSTOM" "$t/custom.cfg" && echo "custom.cfg: installed copy identical" || echo "custom.cfg: install would REPLACE the file above"; else echo "custom.cfg: not installed (install would create it)"; fi + echo "WINDOW_BOOT CHECK: PASS (nothing written outside $t)" +} + +need_yes() { [[ ${1:-} == --yes ]] || die "$2 needs --yes"; } + +case ${1:-check} in + check) check ;; + install) need_yes "${2:-}" install; check + t=$(mktemp -d /tmp/window-boot.XXXXXX); build_entry > "$t/custom.cfg" + [[ ! -e $CUSTOM ]] || cmp -s "$CUSTOM" "$t/custom.cfg" || die "$CUSTOM exists with other content; refusing to overwrite" + sudo install -m 0644 "$t/custom.cfg" "$CUSTOM" + for u in $UNITS; do sudo install -m 0644 "$HERE/window-boot/$u" "/etc/systemd/system/$u"; done + sudo systemctl daemon-reload; sudo systemctl enable $UNITS + echo "WINDOW_BOOT INSTALL: PASS (inert until 'arm')" ;; + arm) need_yes "${2:-}" arm + [[ -f $CUSTOM ]] && grep -qF -- "--id $ENTRY" "$CUSTOM" || die "entry not installed" + for u in $UNITS; do systemctl is-enabled -q "$u" || die "$u not enabled"; done + sudo grub-reboot "$ENTRY" + [[ $(grub-editenv /boot/grub/grubenv list | sed -n 's/^next_entry=//p') == "$ENTRY" ]] || die "grubenv next_entry not set" + echo "WINDOW_BOOT ARM: PASS (next boot only: $ENTRY; every later boot: default entry with NVIDIA)" ;; + status) + echo "default: GRUB_DEFAULT=$(sed -n 's/^GRUB_DEFAULT=//p' /etc/default/grub); grubenv: $(grub-editenv /boot/grub/grubenv list | tr '\n' ' ')" + [[ -f $CUSTOM ]] && echo "custom.cfg: installed" || echo "custom.cfg: absent" + for u in $UNITS; do echo "$u: $(systemctl is-enabled "$u" 2>/dev/null || true) $(systemctl is-active "$u" 2>/dev/null || true)"; done + grep -q 'aien.gpuwindow=1' /proc/cmdline && echo "this boot: WINDOW BOOT" || echo "this boot: normal" ;; + uninstall) need_yes "${2:-}" uninstall + sudo systemctl disable $UNITS || true + for u in $UNITS; do sudo rm -f "/etc/systemd/system/$u"; done + sudo rm -f "$CUSTOM"; sudo systemctl daemon-reload + echo "WINDOW_BOOT UNINSTALL: PASS" ;; + *) die "unknown command ${1}" ;; +esac diff --git a/evidence/own-gpu-driver/rung2/window-boot/aien-gpu-window-hold.service b/evidence/own-gpu-driver/rung2/window-boot/aien-gpu-window-hold.service new file mode 100644 index 00000000..bf373122 --- /dev/null +++ b/evidence/own-gpu-driver/rung2/window-boot/aien-gpu-window-hold.service @@ -0,0 +1,18 @@ +# Inert on every normal boot. Runs only when GRUB booted the one-shot entry 'aien-gpu-window' (kernel flag +# aien.gpuwindow=1). It holds NVIDIA's modules back for THIS boot only: the file lives in /run (tmpfs), so any later +# boot (lease reboot, watchdog reset, panic reboot, power cycle) is the default entry with NVIDIA's driver loaded. +[Unit] +Description=AIEN GPU window: hold NVIDIA modules back for this boot only +DefaultDependencies=no +ConditionKernelCommandLine=aien.gpuwindow=1 +Before=systemd-udev-trigger.service systemd-modules-load.service nvidia-persistenced.service +After=local-fs-pre.target + +[Service] +Type=oneshot +RemainAfterExit=yes +ExecStart=/bin/mkdir -p /run/modprobe.d +ExecStart=/bin/sh -c 'printf "# aien-gpu-window: this boot only (tmpfs). window*-post.sh removes it.\\ninstall nvidia /bin/false\\ninstall nvidia_uvm /bin/false\\ninstall nvidia_modeset /bin/false\\ninstall nvidia_drm /bin/false\\ninstall nvidiafb /bin/false\\n" > /run/modprobe.d/zz-aien-gpu-window.conf' + +[Install] +WantedBy=sysinit.target diff --git a/evidence/own-gpu-driver/rung2/window-boot/aien-gpu-window-lease.service b/evidence/own-gpu-driver/rung2/window-boot/aien-gpu-window-lease.service new file mode 100644 index 00000000..fd419ab0 --- /dev/null +++ b/evidence/own-gpu-driver/rung2/window-boot/aien-gpu-window-lease.service @@ -0,0 +1,13 @@ +# Inert on every normal boot. In the window boot (aien.gpuwindow=1) it reboots the box 25 minutes after start, which +# returns to the default GRUB entry with NVIDIA's driver (L405 caps leases at 20 min; 5 min margin for the restore). +# window*-post.sh logs and may stop it only to reboot sooner; nobody extends it without the coordinator. +[Unit] +Description=AIEN GPU window: lease, reboot to the default (NVIDIA) entry after 25 min +ConditionKernelCommandLine=aien.gpuwindow=1 + +[Service] +Type=simple +ExecStart=/bin/sh -c 'sleep 1500; logger -t aien-gpu-window "lease expired: rebooting to the default entry"; systemctl reboot' + +[Install] +WantedBy=multi-user.target diff --git a/evidence/own-gpu-driver/rung2/window0-20261021T215956Z.log b/evidence/own-gpu-driver/rung2/window0-20261021T215956Z.log new file mode 100644 index 00000000..7e1094de --- /dev/null +++ b/evidence/own-gpu-driver/rung2/window0-20261021T215956Z.log @@ -0,0 +1,9 @@ +2026-10-21T21:59:56.481510628Z pre start, commit d58913898feb48169f519a1621ba8dc74d41e790, kernel 7.0.0-1019-nvidia +nvidia_uvm 1912832 8 +nvidia_drm 143360 0 +nvidia_modeset 1892352 2 nvidia_drm +nvidia 14688256 1394 nvidia_uvm,nvidia_modeset +GPU 0: NVIDIA GB10 (UUID: GPU-fb8e53f0-3207-e89b-d02f-acdfe2695b59) +BOOT_IMAGE=/boot/vmlinuz-7.0.0-1019-nvidia root=UUID=d27bfd26-ff30-400e-9eca-9cdf73de9406 ro init_on_alloc=0 iommu.passthrough=0 console=tty0 plymouth.ignore-serial-consoles plymouth.use-simpledrm earlycon=uart,mmio32,0x16A00000 console=tty0 console=ttyS0,921600 crashkernel=1G-:0M quiet splash initcall_blacklist=tegra234_cbb_init pci=pcie_bus_safe vt.handoff=7 +da858c000744f04e4d8d7338a3013fbcb3b3959b812152c6ac0456eb04975550 /home/drakestapleton/workspace/aienos-own-gpu-driver/native/linux/aien-gpu/aien_gpu.ko +2026-10-21T22:00:21.965947152Z PRE FAIL: nvidia modules in initramfs: the modprobe.d file would not hold them back diff --git a/evidence/own-gpu-driver/rung2/window0-20261021T220118Z.log b/evidence/own-gpu-driver/rung2/window0-20261021T220118Z.log new file mode 100644 index 00000000..8a1eec8f --- /dev/null +++ b/evidence/own-gpu-driver/rung2/window0-20261021T220118Z.log @@ -0,0 +1,14 @@ +2026-10-21T22:01:18.854744017Z pre start, commit d58913898feb48169f519a1621ba8dc74d41e790, kernel 7.0.0-1019-nvidia +nvidia_uvm 1912832 8 +nvidia_drm 143360 0 +nvidia_modeset 1892352 2 nvidia_drm +nvidia 14688256 1394 nvidia_uvm,nvidia_modeset +GPU 0: NVIDIA GB10 (UUID: GPU-fb8e53f0-3207-e89b-d02f-acdfe2695b59) +BOOT_IMAGE=/boot/vmlinuz-7.0.0-1019-nvidia root=UUID=d27bfd26-ff30-400e-9eca-9cdf73de9406 ro init_on_alloc=0 iommu.passthrough=0 console=tty0 plymouth.ignore-serial-consoles plymouth.use-simpledrm earlycon=uart,mmio32,0x16A00000 console=tty0 console=ttyS0,921600 crashkernel=1G-:0M quiet splash initcall_blacklist=tegra234_cbb_init pci=pcie_bus_safe vt.handoff=7 +da858c000744f04e4d8d7338a3013fbcb3b3959b812152c6ac0456eb04975550 /home/drakestapleton/workspace/aienos-own-gpu-driver/native/linux/aien-gpu/aien_gpu.ko +2026-10-21T22:01:43.247343439Z holder pid 108356 drakest+ aien-serve-http +2026-10-21T22:01:43.265120652Z holder pid 1816 root nvidia-persiste +2026-10-21T22:01:43.288098149Z holder pid 2587647 drakest+ aien-serve-http +2026-10-21T22:01:43.340077365Z WARN still held by: 108356 +2587647 +2026-10-21T22:01:43.342542914Z checks only (no --go): PASS diff --git a/evidence/own-gpu-driver/rung2/window0-post.sh b/evidence/own-gpu-driver/rung2/window0-post.sh new file mode 100755 index 00000000..d9b66f84 --- /dev/null +++ b/evidence/own-gpu-driver/rung2/window0-post.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# L332 rung 2 window 0, part 2 (after the reboot from part 1). First removes the temporary blacklist, then: our module reads +# the chip and gives it back, NVIDIA's driver is loaded again (timed: today's load-to-ready baseline), Omega proves the chip +# works, and a normal reboot restores the box exactly (display modules included). Usage: window0-post.sh [--no-reboot] +set -u +export PATH=$PATH:/usr/sbin:/sbin # modinfo, lsmod and friends live in sbin; a normal user shell may not list it +here=$(cd "$(dirname "$0")" && pwd); repo=$(cd "$here/../../.." && pwd) +log=$here/$(readlink "$here/window0-current.log") +ts() { echo "$(date -u +%FT%T.%NZ) $*" | tee -a "$log"; } +BLK=/run/modprobe.d/zz-aien-gpu-window.conf +grep -q 'aien.gpuwindow=1' /proc/cmdline || { ts "WINDOW0 ABORT: this is not the one-shot window boot (no aien.gpuwindow=1); nothing done"; exit 1; } +ts "post start; window boot; hold-back file present: $([ -e "$BLK" ] && echo yes || echo NO) (kept until our module is gone); lease: $(systemctl is-active aien-gpu-window-lease.service)" +ts "boot: $(uptime -s) (uptime $(cut -d' ' -f1 /proc/uptime) s), systemd: $(systemd-analyze 2>/dev/null | head -1)" +ts "lsmod nvidia: [$(lsmod | grep -cE '^nvidia')] lspci: $(lspci -k -s 000f:01:00.0 | grep -c 'in use')" +sudo sysctl -q -w kernel.panic=10 kernel.panic_on_oops=1; ts "panic auto-reboot 10 s set (runtime only)" +rc=0 +ts "insmod aien_gpu allow_bind=1"; sudo insmod "$repo/native/linux/aien-gpu/aien_gpu.ko" allow_bind=1 || rc=1 +sudo dmesg | grep -i aien-gpu | tee -a "$log" +CHK=$here/aien_gpu_check; [ -x "$CHK" ] || gcc -O2 -o "$CHK" "$repo/native/linux/aien-gpu/aien_gpu_check.c" +sudo "$CHK" 2>&1 | tee -a "$log"; [ "${PIPESTATUS[0]}" = 0 ] || rc=1 +ts "rmmod aien_gpu"; sudo rmmod aien_gpu || rc=1 +ts "aien-gpu part rc=$rc" +# Recovery proof for later windows (NoNvDriver review). Opt-in, Drake decides: AIEN_W0_FLR=1 window0-post.sh. +# With no driver bound, reset the function by the kernel's own reset_method (measured "flr bus"); NVIDIA's stock driver +# must then bind and answer below. If it does, "FLR + stock rebind" is a tested recovery path for window 1; if not, +# window 1 may only end in a reboot or a power cycle. A failed FLR leaves the lease/watchdog/restore reboot as the way out. +D=/sys/bus/pci/devices/000f:01:00.0 +if [ "${AIEN_W0_FLR:-0}" != 1 ]; then ts "FLR test not requested (AIEN_W0_FLR unset): recovery-by-FLR stays NOT_RUN" +elif [ -e "$D/driver" ]; then ts "FLR test skipped: a driver is still bound ($(basename "$(readlink "$D/driver")"))"; rc=1 +else ts "reset_method: $(cat "$D/reset_method")"; echo 1 | sudo tee "$D/reset" > /dev/null && ts "FLR via $D/reset: done" || { ts "FLR via $D/reset: FAILED"; rc=1; }; fi +sudo rm -f "$BLK"; ts "hold-back file removed before the stock reload: $([ -e "$BLK" ] && echo NO || echo yes)" +t0=$(date +%s%N); sudo modprobe nvidia && sudo modprobe nvidia_uvm; t1=$(date +%s%N); nvidia-smi -L >> "$log" 2>&1; t2=$(date +%s%N) +ts "nvidia modprobe ms $(( (t1 - t0) / 1000000 )), first nvidia-smi answer ms $(( (t2 - t1) / 1000000 )) (load-to-ready baseline)" +BIN=$HOME/workspace/targets/l332-omega/gpu_launch_cost_test +t0=$(date +%s%N); "$BIN" --reps 3 >> "$log" 2>&1; orc=$?; t1=$(date +%s%N) +ts "omega launch-cost test exit $orc wall ms $(( (t1 - t0) / 1000000 )) (first open after driver load)" +ts "WINDOW0 $( [ $rc = 0 ] && [ $orc = 0 ] && echo PASS || echo FAIL )" +[ "${1:-}" = --no-reboot ] && exit 0 +ts "normal reboot to restore nvidia_modeset/nvidia_drm and the services"; sync; sudo systemctl reboot diff --git a/evidence/own-gpu-driver/rung2/window0-pre.sh b/evidence/own-gpu-driver/rung2/window0-pre.sh new file mode 100755 index 00000000..7f088c63 --- /dev/null +++ b/evidence/own-gpu-driver/rung2/window0-pre.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# L332 rung 2 window 0, part 1 (before the reboot). Run ONLY inside the coordinator-scheduled window, after the GPU users +# on the coordinator's list are stopped. Records the box, checks the module, writes a temporary "do not load NVIDIA" +# file (removed by part 2 as its first action) and reboots. Usage: window0-pre.sh [--go] (without --go: checks only). +set -u +export PATH=$PATH:/usr/sbin:/sbin # modinfo, lsmod and friends live in sbin; a normal user shell may not list it +here=$(cd "$(dirname "$0")" && pwd); repo=$(cd "$here/../../.." && pwd) +log=$here/window0-$(date -u +%Y%m%dT%H%M%SZ).log; ln -sfn "$(basename "$log")" "$here/window0-current.log" +ts() { echo "$(date -u +%FT%T.%NZ) $*" | tee -a "$log"; } +fail() { ts "PRE FAIL: $*"; exit 1; } +KO=$repo/native/linux/aien-gpu/aien_gpu.ko +ts "pre start, commit $(git -C "$repo" rev-parse HEAD), kernel $(uname -r)" +{ lsmod | grep -E '^nvidia'; nvidia-smi -L; cat /proc/cmdline; sha256sum "$KO"; } >> "$log" 2>&1 +[ -f "$KO" ] || fail "no $KO (make -C native/linux/aien-gpu)" +[ "$(modinfo -F vermagic "$KO" | cut -d' ' -f1)" = "$(uname -r)" ] || fail "aien_gpu.ko vermagic does not match $(uname -r)" +[ "$(mokutil --sb-state 2>/dev/null)" = "SecureBoot disabled" ] || fail "Secure Boot state changed: unsigned module would be refused" +initrd=$(lsinitramfs "/boot/initrd.img-$(uname -r)") && [ -n "$initrd" ] || fail "cannot list the initramfs: the nvidia-in-initramfs check would pass silently" +grep -qE '/nvidia(_uvm|_modeset|_drm)?\.ko' <<< "$initrd" && fail "nvidia modules in initramfs: the modprobe.d file would not hold them back" +holders=$(sudo fuser /dev/nvidia* 2>/dev/null | tr -s ' ' '\n' | grep -E '^[0-9]+$' | sort -u) +for p in $holders; do ts "holder pid $p $(ps -o user=,comm= -p "$p")"; done +other=$(for p in $holders; do [ "$(ps -o comm= -p "$p")" = nvidia-persiste ] || echo "$p"; done) +[ -z "$other" ] || { [ "${1:-}" = --go ] && fail "GPU still held by: $other (coordinator stops them first)"; ts "WARN still held by: $other"; } +[ "${1:-}" = --go ] || { ts "checks only (no --go): PASS"; exit 0; } +# Self-reverting hold-back (window-boot.sh): one-shot GRUB entry, /run/modprobe.d file, hardware watchdog, panic reboot, +# 25-min lease. Every boot after the window boot is the default entry with NVIDIA's driver; nothing to delete by hand. +"$here/window-boot.sh" check >> "$log" 2>&1 || fail "window-boot.sh check failed (see log); was 'window-boot.sh install --yes' run in prep?" +"$here/window-boot.sh" arm --yes >> "$log" 2>&1 || fail "window-boot.sh arm failed: not rebooting" +sync; ts "one-shot window entry armed; rebooting (part 2: window0-post.sh after ssh is back)" +sudo systemctl reboot diff --git a/evidence/own-gpu-driver/rung2/window1-check.sh b/evidence/own-gpu-driver/rung2/window1-check.sh new file mode 100755 index 00000000..b03c03dc --- /dev/null +++ b/evidence/own-gpu-driver/rung2/window1-check.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# L332 rung 2 window 1, part 3 (after the restore reboot): the box is back as before. Read-only. +set -u +export PATH=$PATH:/usr/sbin:/sbin # modinfo, lsmod and friends live in sbin; a normal user shell may not list it +here=$(cd "$(dirname "$0")" && pwd) +log=$here/$(readlink "$here/window1-current.log") +ts() { echo "$(date -u +%FT%T.%NZ) $*" | tee -a "$log"; } +ok=1 +ts "check start; boot $(uptime -s)" +grep -q 'aien.gpuwindow=1' /proc/cmdline && { ts "still the window boot (aien.gpuwindow=1): the restore reboot did not happen; reboot"; ok=0; } +[ -e /run/modprobe.d/zz-aien-gpu-window.conf ] && { ts "hold-back file still in /run: unexpected outside the window boot"; ok=0; } +next=$(grub-editenv /boot/grub/grubenv list | sed -n 's/^next_entry=//p'); [ -z "$next" ] || { ts "grubenv next_entry still set ($next): clear it with 'sudo grub-editenv /boot/grub/grubenv unset next_entry'"; ok=0; } +n=$(lsmod | grep -cE '^nvidia'); ts "nvidia modules loaded: $n (want 4)"; [ "$n" = 4 ] || ok=0 +lsmod | grep -q '^aien_gpu' && { ts "aien_gpu loaded after reboot: unexpected"; ok=0; } +nvidia-smi -L >> "$log" 2>&1 || { ts "nvidia-smi failed: GPU not back on NVIDIA's driver"; ok=0; } +ts "WINDOW1 RESTORE $([ $ok = 1 ] && echo PASS || echo FAIL)" diff --git a/evidence/own-gpu-driver/rung2/window1-package.sh b/evidence/own-gpu-driver/rung2/window1-package.sh new file mode 100755 index 00000000..1b4d12e9 --- /dev/null +++ b/evidence/own-gpu-driver/rung2/window1-package.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +# window1-package.sh: build the boot package aien_gsp_boot reads (L332 rung 2 window 1). Reads only; writes only into OUT. +# NVIDIA's signed firmware stays on loan: every byte comes from the pinned 580.173.02 files on this box, cut out by our +# own extractors and checked against the pins in native/kernel/Makefile (GSP_FW_SHA256, GSP_BINDATA_BOOT_PROD_SHA256, +# GSP_BINDATA_FMC_IMAGE_SHA256). Nothing is sent to any device. +# +# window1-package.sh OUT [TOOLS] [SYSINFO_TXT] +# TOOLS directory with ck_gsp_fw_inspect, ck_gsp_bindata_extract, ck_gsp_sysinfo_encode +# (default /tmp/l332-k/host, from make -C native/kernel OUT=/tmp/l332-k gsp-fw-inspect +# gsp-bindata-extract $OUT/host/ck_gsp_sysinfo_encode) +# SYSINFO_TXT the GspSystemInfo field values (default rung2/system_info.txt next to this script) +# OUT gets rm_elf.bin rm_sig.bin bootloader.bin fmc.bin fmc_hash.bin fmc_pkey.bin fmc_sig.bin system_info.bin, +# app_version.txt and MANIFEST.txt (sizes + SHA-256 + where each came from). Exit 0 only when every check holds. +set -euo pipefail +OUT=$1 +HERE=$(cd "$(dirname "$0")" && pwd) +REPO=$(cd "$HERE/../../.." && pwd) +TOOLS=${2:-/tmp/l332-k/host} +SI_TXT=${3:-$HERE/system_info.txt} +FW=/lib/firmware/nvidia/580.173.02/gsp_ga10x.bin +GEN=${OGKM_DIR:-$HOME/workspace/_ext/open-gpu-kernel-modules-580.173.02}/src/nvidia/generated +MK=$REPO/native/kernel/Makefile +pin() { sed -n "s/^$1 := \([0-9a-f]\{64\}\)$/\1/p" "$MK"; } +die() { echo "WINDOW1_PACKAGE: FAIL ($*)"; exit 1; } +sha() { sha256sum "$1" | cut -d' ' -f1; } +for t in ck_gsp_fw_inspect ck_gsp_bindata_extract ck_gsp_sysinfo_encode; do [[ -x $TOOLS/$t ]] || die "missing tool $TOOLS/$t"; done +mkdir -p "$OUT" +[[ -z $(ls -A "$OUT") ]] || die "$OUT is not empty" +W=$OUT/work; mkdir "$W" + +# 1. GSP-RM: the .fwimage section and the gb10y signature section of the container +[[ $(sha "$FW") == $(pin GSP_FW_SHA256) ]] || die "$FW does not match GSP_FW_SHA256" +"$TOOLS/ck_gsp_fw_inspect" inspect "$FW" --family gb10y --expect-version 580.173.02 > "$W/inspect.txt" || die "fw inspect refused" +grep -q '^RESULT OK' "$W/inspect.txt" || die "fw inspect not OK" +cutsec() { # section-name out + local off size + read -r off size < <(awk -v n="$1" '$1=="section" && $3==n { sub("offset=","",$5); sub("size=","",$6); print $5, $6 }' "$W/inspect.txt") + [[ -n ${off:-} && -n ${size:-} ]] || die "section $1 not in the inspect output" + dd if="$FW" of="$2" bs=64k iflag=skip_bytes,count_bytes skip="$off" count="$size" status=none + [[ $(stat -c %s "$2") -eq $size ]] || die "short cut of $1" +} +cutsec .fwimage "$OUT/rm_elf.bin" +cutsec .fwsignature_gb10y "$OUT/rm_sig.bin" +[[ $(sha "$OUT/rm_elf.bin") == $(awk '$1=="sha256_fwimage"{print $2}' "$W/inspect.txt") ]] || die ".fwimage cut differs from the inspected hash" +[[ $(sha "$OUT/rm_sig.bin") == $(awk '$1=="sha256_signature"{print $2}' "$W/inspect.txt") ]] || die "signature cut differs from the inspected hash" + +# 2. GspRmBoot_GB10B (PROD image + its descriptor) and GspRmFmcGfwProdSigned_GB10B (image, hash, key, signature) +"$TOOLS/ck_gsp_bindata_extract" extract "$GEN/g_bindata_kgspGetBinArchiveGspRmBoot_GB10B.c" --out "$W" > "$W/boot.txt" || die "boot bindata refused" +"$TOOLS/ck_gsp_bindata_extract" extract "$GEN/g_bindata_kgspGetBinArchiveGspRmFmcGfwProdSigned_GB10B.c" --out "$W" > "$W/fmc.txt" || die "fmc bindata refused" +B=$W/kgspGetBinArchiveGspRmBoot_GB10B M=$W/kgspGetBinArchiveGspRmFmcGfwProdSigned_GB10B +cp "$B.UCODE_IMAGE_PROD.bin" "$OUT/bootloader.bin" +cp "$M.UCODE_IMAGE.bin" "$OUT/fmc.bin" +cp "$M.UCODE_HASH.bin" "$OUT/fmc_hash.bin" +cp "$M.UCODE_PKEY.bin" "$OUT/fmc_pkey.bin" +cp "$M.UCODE_SIG.bin" "$OUT/fmc_sig.bin" +[[ $(sha "$OUT/bootloader.bin") == $(pin GSP_BINDATA_BOOT_PROD_SHA256) ]] || die "boot PROD image does not match its pin" +[[ $(sha "$OUT/fmc.bin") == $(pin GSP_BINDATA_FMC_IMAGE_SHA256) ]] || die "FMC image does not match its pin" +grep -q '^hash384 UCODE_HASH equals sha384(UCODE_IMAGE)' "$W/fmc.txt" || die "FMC hash not checked against the image" +app=$(sed -n 's/^desc UCODE_DESC_PROD .* app_version=\([0-9]*\) .*/\1/p' "$W/boot.txt") +[[ -n $app ]] || die "no app_version in the PROD descriptor" +echo "$app" > "$OUT/app_version.txt" + +# 3. GspSystemInfo +"$TOOLS/ck_gsp_sysinfo_encode" encode "$SI_TXT" "$OUT/system_info.bin" > "$W/sysinfo.txt" || die "system info refused: $(tail -1 "$W/sysinfo.txt")" + +# 4. manifest +{ + echo "# window-1 boot package, built $(date -u +%FT%TZ) on $(hostname) from repo $(git -C "$REPO" rev-parse HEAD)" + echo "# firmware $FW sha256 $(sha "$FW"); bindata from $GEN; system info from $SI_TXT sha256 $(sha "$SI_TXT")" + echo "app_version $app (RM_RISCV_UCODE_DESC.appVersion of UCODE_DESC_PROD, GspRmBoot_GB10B)" + for f in rm_elf rm_sig bootloader fmc fmc_hash fmc_pkey fmc_sig system_info; do + printf '%-16s %10s %s\n' "$f.bin" "$(stat -c %s "$OUT/$f.bin")" "$(sha "$OUT/$f.bin")" + done +} > "$OUT/MANIFEST.txt" +cat "$OUT/MANIFEST.txt" +echo "WINDOW1_PACKAGE: PASS ($OUT)" diff --git a/evidence/own-gpu-driver/rung2/window1-post.sh b/evidence/own-gpu-driver/rung2/window1-post.sh new file mode 100755 index 00000000..e12ce962 --- /dev/null +++ b/evidence/own-gpu-driver/rung2/window1-post.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# L332 rung 2 window 1, part 2 (after the reboot from part 1). First removes the temporary blacklist. Then our module takes +# the GPU with both switches on, and aien_gsp_boot hands NVIDIA's signed GSP firmware to the chip through SEC2 (one +# attempt: the module refuses a second doorbell) and waits for GSP-RM's INIT_DONE. The module is NOT unloaded afterwards +# (GSP may still use its memory); a normal reboot gives the GPU back to NVIDIA's driver, and part 3 checks that. +# Usage: window1-post.sh [--no-reboot] +set -u +export PATH=$PATH:/usr/sbin:/sbin # modinfo, lsmod and friends live in sbin; a normal user shell may not list it +here=$(cd "$(dirname "$0")" && pwd); repo=$(cd "$here/../../.." && pwd) +log=$here/$(readlink "$here/window1-current.log") +ts() { echo "$(date -u +%FT%T.%NZ) $*" | tee -a "$log"; } +# The /run hold-back file stays for the whole window boot (tmpfs: gone at the restore reboot), so nothing can load +# NVIDIA's driver beside ours. +grep -q 'aien.gpuwindow=1' /proc/cmdline || { ts "WINDOW1 ABORT: this is not the one-shot window boot (no aien.gpuwindow=1); nothing done"; exit 1; } +ts "post start; window boot; hold-back file present: $([ -e /run/modprobe.d/zz-aien-gpu-window.conf ] && echo yes || echo NO); lease: $(systemctl is-active aien-gpu-window-lease.service)" +ts "boot: $(uptime -s) (uptime $(cut -d' ' -f1 /proc/uptime) s)" +ts "lsmod nvidia: [$(lsmod | grep -cE '^nvidia')] driver in use on the GPU: $(lspci -k -s 000f:01:00.0 | grep -c 'in use')" +[ "$(lsmod | grep -cE '^nvidia')" = 0 ] || { ts "WINDOW1 ABORT: an NVIDIA module is loaded; two drivers on one GPU must never happen"; exit 1; } +PKG=$(cat "$here/window1-package.path"); SHIM=$repo/native/linux/aien-gpu +# arena: everything the builder places, plus 8 MiB for the logs, queues and page tables (the tool refuses if short) +bytes=$(cat "$PKG"/rm_elf.bin "$PKG"/rm_sig.bin "$PKG"/bootloader.bin "$PKG"/fmc.bin | wc -c) +arena_mib=$(( bytes / 1048576 + 8 + 1 )) +sudo sysctl -q -w kernel.panic=10 kernel.panic_on_oops=1; ts "panic auto-reboot 10 s set (runtime only)" +ts "insmod aien_gpu allow_bind=1 allow_boot=1 arena_mib=$arena_mib heap_mib=512" +sudo insmod "$SHIM/aien_gpu.ko" allow_bind=1 allow_boot=1 arena_mib="$arena_mib" heap_mib=512 || { ts "WINDOW1 FAIL: insmod"; sudo dmesg | grep -i aien-gpu | tee -a "$log"; exit 1; } +sudo dmesg | grep -i aien-gpu | tee -a "$log" +out=$here/window1-$(date -u +%Y%m%dT%H%M%SZ)-run; app=$(cat "$PKG/app_version.txt") +ts "aien_gsp_boot --pkg $PKG --app-version $app --out $out" +t0=$(date +%s%N) +sudo "$SHIM/build/aien_gsp_boot" --pkg "$PKG" --app-version "$app" --out "$out" --polls 50000 --pause-us 100 --wait-ms 30000 2>&1 | tee -a "$log" +brc=${PIPESTATUS[0]}; t1=$(date +%s%N) +sudo chown -R "$(id -un)" "$out" +ts "aien_gsp_boot exit $brc wall ms $(( (t1 - t0) / 1000000 ))" +cat "$out/result.txt" >> "$log" 2>/dev/null +sudo dmesg | tail -40 > "$out/dmesg-tail.txt" +ts "WINDOW1 $( [ "$brc" = 0 ] && echo 'PASS (GSP-RM INIT_DONE on our driver)' || echo "STOPPED (see $out/result.txt)" )" +[ "${1:-}" = --no-reboot ] && exit 0 +ts "normal reboot: gives the GPU back to NVIDIA's driver (aien_gpu is not unloaded; GSP may still use its memory)" +sync; sudo systemctl reboot diff --git a/evidence/own-gpu-driver/rung2/window1-pre.sh b/evidence/own-gpu-driver/rung2/window1-pre.sh new file mode 100755 index 00000000..28432c1a --- /dev/null +++ b/evidence/own-gpu-driver/rung2/window1-pre.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# L332 rung 2 window 1, part 1 (before the reboot). Run ONLY inside the coordinator-scheduled window 1, after window 0 +# passed and the GPU users on the coordinator's list are stopped. Checks everything part 2 needs, records the box, writes +# a temporary "do not load NVIDIA" file (removed by part 2 as its first action) and reboots. +# Usage: window1-pre.sh PKG_DIR [--go] (without --go: checks only; PKG_DIR from window1-package.sh) +set -u +export PATH=$PATH:/usr/sbin:/sbin # modinfo, lsmod and friends live in sbin; a normal user shell may not list it +here=$(cd "$(dirname "$0")" && pwd); repo=$(cd "$here/../../.." && pwd) +PKG=${1:?usage: window1-pre.sh PKG_DIR [--go]}; PKG=$(cd "$PKG" && pwd) +log=$here/window1-$(date -u +%Y%m%dT%H%M%SZ).log; ln -sfn "$(basename "$log")" "$here/window1-current.log" +ts() { echo "$(date -u +%FT%T.%NZ) $*" | tee -a "$log"; } +fail() { ts "PRE FAIL: $*"; exit 1; } +SHIM=$repo/native/linux/aien-gpu +KO=$SHIM/aien_gpu.ko BOOT=$SHIM/build/aien_gsp_boot +ts "pre start, commit $(git -C "$repo" rev-parse HEAD), kernel $(uname -r), package $PKG" +{ lsmod | grep -E '^nvidia'; nvidia-smi -L; cat /proc/cmdline; sha256sum "$KO" "$BOOT"; cat "$PKG/MANIFEST.txt"; } >> "$log" 2>&1 +ls "$here"/window0-*.log 2>/dev/null | xargs -r grep -l 'WINDOW0 PASS' | grep -q . || fail "no window-0 log with WINDOW0 PASS: window 0 comes first" +# Chip identity gate (NoNvDriver review 2026-10-26). The package carries the GB10B images (GspRmBoot_GB10B, +# GspRmFmcGfwProdSigned_GB10B, .fwsignature_gb10y). NVIDIA's 580.173.02 source also has GB20B (arch 0x1B, impl 0xB, +# family gb20y) with DIFFERENT images, and the Spark's sm_121 points at the GB2XX line. Window 0 logs PMC_BOOT_42; +# CHIP_ID = bits 29:20 (nv_ref.h:171; ARCHITECTURE 29:24 = 0x1A GB100 / 0x1B GB200, nv_ref.h:182-183; +# IMPLEMENTATION 23:20 = 0xB). Hand SEC2 the GB10B image only when the chip measured 0x1AB. +w0=$(ls "$here"/window0-*.log 2>/dev/null | xargs -r grep -l 'WINDOW0 PASS' | tail -n 1) +b42=$(grep -ho 'PMC_BOOT_42 [0-9a-fA-F]\{8\}' "$w0" | tail -n 1 | cut -d' ' -f2) +[ -n "$b42" ] || fail "window-0 log $w0 has no PMC_BOOT_42 value: chip identity unmeasured" +chip=$(printf '%03x' $(( (0x$b42 >> 20) & 0x3ff ))) +ts "chip identity from $(basename "$w0"): PMC_BOOT_42 0x$b42 CHIP_ID 0x$chip" +[ "$chip" = 1ab ] || fail "chip is 0x$chip, not GB10B (0x1ab); this package holds GB10B images (GB20B is 0x1bb and needs the GB20B archives + gb20y signature): refusing" +[ -f "$KO" ] && [ -x "$BOOT" ] || fail "build first: make -C native/linux/aien-gpu all tools" +[ "$(modinfo -F vermagic "$KO" | cut -d' ' -f1)" = "$(uname -r)" ] || fail "aien_gpu.ko vermagic does not match $(uname -r)" +modinfo -F parm "$KO" | grep -q '^allow_boot:' || fail "aien_gpu.ko has no allow_boot (old build)" +for f in rm_elf rm_sig bootloader fmc fmc_hash fmc_pkey fmc_sig system_info; do [ -s "$PKG/$f.bin" ] || fail "package lacks $f.bin"; done +[ -s "$PKG/app_version.txt" ] || fail "package lacks app_version.txt" +[ "$(mokutil --sb-state 2>/dev/null)" = "SecureBoot disabled" ] || fail "Secure Boot state changed: unsigned module would be refused" +initrd=$(lsinitramfs "/boot/initrd.img-$(uname -r)") && [ -n "$initrd" ] || fail "cannot list the initramfs: the nvidia-in-initramfs check would pass silently" +grep -qE '/nvidia(_uvm|_modeset|_drm)?\.ko' <<< "$initrd" && fail "nvidia modules in initramfs: the modprobe.d file would not hold them back" +holders=$(sudo fuser /dev/nvidia* 2>/dev/null | tr -s ' ' '\n' | grep -E '^[0-9]+$' | sort -u) +for p in $holders; do ts "holder pid $p $(ps -o user=,comm= -p "$p")"; done +other=$(for p in $holders; do [ "$(ps -o comm= -p "$p")" = nvidia-persiste ] || echo "$p"; done) +[ -z "$other" ] || { [ "${2:-}" = --go ] && fail "GPU still held by: $other (coordinator stops them first)"; ts "WARN still held by: $other"; } +[ "${2:-}" = --go ] || { ts "checks only (no --go): PASS"; exit 0; } +echo "$PKG" > "$here/window1-package.path" +# Self-reverting hold-back (window-boot.sh): see window0-pre.sh. +"$here/window-boot.sh" check >> "$log" 2>&1 || fail "window-boot.sh check failed (see log); was 'window-boot.sh install --yes' run in prep?" +"$here/window-boot.sh" arm --yes >> "$log" 2>&1 || fail "window-boot.sh arm failed: not rebooting" +sync; ts "one-shot window entry armed; rebooting (part 2: window1-post.sh after ssh is back)" +sudo systemctl reboot diff --git a/evidence/own-gpu-driver/rung2/window1_sim_test.sh b/evidence/own-gpu-driver/rung2/window1_sim_test.sh new file mode 100755 index 00000000..44b92f75 --- /dev/null +++ b/evidence/own-gpu-driver/rung2/window1_sim_test.sh @@ -0,0 +1,86 @@ +#!/usr/bin/env bash +# window1_sim_test.sh: host check of the window-1 start-up tool (native/linux/aien-gpu/aien_gsp_boot.c) built against the +# simulated SEC2 + GSP and a fake GSP on the status queue (-DAIEN_GSP_BOOT_SIM). No GPU, no module. +# 1. every verdict path: INIT-DONE, sequencer request, no answer, corrupt queue, SEC2 busy, FMC error, core dead, +# plan only, a package with a wrong-size file, an arena too small for the plan; +# 2. every register the tool touched in those runs is on the module's allowlist (aien_gpu.c AIEN-GPU-ALLOW block): +# reads on the read list, writes on the write list, and one SEC2 doorbell per start-up. +# Usage: window1_sim_test.sh SIM_BINARY AIEN_GPU_C +set -u +BIN=$1 SHIM=$2 +T=$(mktemp -d) +trap 'rm -r "$T"' EXIT +fail=0 +ok() { echo "PASS $*"; } +bad() { echo "FAIL $*"; fail=1; } + +# fake package: fixed bytes of the right sizes (the simulator checks none of the firmware content) +P=$T/pkg; mkdir "$P" +mk() { head -c "$2" /dev/zero | tr '\0' "$3" > "$P/$1"; } +mk rm_elf.bin 3000000 '\001'; mk rm_sig.bin 4096 '\002'; mk bootloader.bin 196608 '\003'; mk fmc.bin 9000 '\004' +mk fmc_hash.bin 48 '\005'; mk fmc_pkey.bin 384 '\006'; mk fmc_sig.bin 384 '\007'; mk system_info.bin 936 '\010' + +run() { # name expected-verdict expected-exit args... + local name=$1 want=$2 wexit=$3; shift 3 + local out rc + out=$("$BIN" --pkg "$P" --app-version 7 --out "$T/$name" --polls 50 --pause-us 0 --wait-ms 300 "$@" 2>"$T/$name.err") + rc=$? + if [[ "$out" == *"AIEN_GSP_BOOT: $want"* && $rc -eq $wexit ]]; then ok "$name: $want (exit $rc)" + else bad "$name: got '$out' exit $rc, want '$want' exit $wexit ($(head -c 300 "$T/$name.err"))"; fi +} +run init "INIT-DONE" 0 --sim-events init +run seq "SEQUENCER-REQUESTED" 1 --sim-events seq +run seqregs "INIT-DONE" 0 --sim-events seq-regs +run silent "NO-INIT-DONE" 1 --sim-events none +run junk "STATUS-QUEUE-ERROR" 1 --sim-events junk +run busy "STOPPED-AT E_BUSY" 1 --sim-cfg busy +run fmcerr "STOPPED-AT E_FMC" 1 --sim-cfg fmc-error +run dead "STOPPED-AT E_RISCV" 1 --sim-cfg riscv-dead +run planonly "PLAN-ONLY" 0 --plan-only +run small "BUILD-REFUSED" 2 --sim-arena-mib 2 +[[ ! -s "$T/small/regs.txt" ]] && ok "arena too small: no register touched" || bad "arena too small touched registers" + +# the INIT-DONE run kept its evidence +for f in plan.txt result.txt messages.txt regs.txt cot_packet.bin log-LOGINIT.bin rpc-shared.bin; do + [[ -s "$T/init/$f" ]] && ok "init wrote $f" || bad "init did not write $f" +done +grep -q "function=0x1001" "$T/init/messages.txt" && ok "INIT_DONE recorded in messages.txt" || bad "INIT_DONE not in messages.txt" +[[ $(stat -c %s "$T/init/cot_packet.bin") -eq 868 ]] && ok "COT packet 868 bytes" || bad "COT packet size" +grep -q "verdict=INIT-DONE" "$T/init/result.txt" && ok "result.txt carries the verdict" || bad "result.txt verdict" + +# notify page: a package value is sent as is; a zero field gets the first arena page (sim arena pa 0x4000000000) +q64() { od -An -tx8 -j48 -N8 "$1" | tr -d ' '; } +[[ $(q64 "$T/init/system_info.sent.bin") == 0808080808080808 ]] && ok "package notify address sent unchanged" || bad "notify field changed: $(q64 "$T/init/system_info.sent.bin")" +cp -r "$P" "$T/pkg3"; printf '\0\0\0\0\0\0\0\0' | dd of="$T/pkg3/system_info.bin" bs=1 seek=48 conv=notrunc status=none +"$BIN" --pkg "$T/pkg3" --app-version 7 --out "$T/notify" --plan-only > /dev/null 2>&1 +[[ $(q64 "$T/notify/system_info.sent.bin") == 0000004000000000 ]] && grep -q "notify_page pa=0x4000000000" "$T/notify/plan.txt" \ + && ok "zero notify field filled with the zeroed first arena page" || bad "notify page: $(q64 "$T/notify/system_info.sent.bin")" +cmp -s <(head -c 48 "$T/pkg3/system_info.bin") <(head -c 48 "$T/notify/system_info.sent.bin") \ + && cmp -s <(tail -c +57 "$T/pkg3/system_info.bin") <(tail -c +57 "$T/notify/system_info.sent.bin") \ + && ok "no other GspSystemInfo byte changed" || bad "notify patch touched other bytes" + +# refusal before any register access: a 935-byte GspSystemInfo +cp -r "$P" "$T/pkg2"; head -c 935 "$P/system_info.bin" > "$T/pkg2/system_info.bin" +out=$("$BIN" --pkg "$T/pkg2" --app-version 7 --out "$T/short" 2>/dev/null); rc=$? +[[ "$out" == *"PACKAGE-REFUSED"* && $rc -eq 2 && ! -s "$T/short/regs.txt" ]] && ok "935-byte GspSystemInfo refused, no register touched" || bad "short system_info: '$out' rc $rc" + +# allowlist: the module must let through what the tool uses, and nothing else it writes +sed -n '/AIEN-GPU-ALLOW-BEGIN/,/AIEN-GPU-ALLOW-END/p' "$SHIM" > "$T/allow.c" +rdl=$(sed -n '/aien_gpu_rd_ok/,/};/p' "$T/allow.c" | grep -o '0x[0-9a-f]\{8\}' | sed 's/^0x00//' | sort -u) +wrl=$(sed -n '/aien_gpu_wr_ok/,/};/p' "$T/allow.c" | grep -o '0x[0-9a-f]\{8\}' | sed 's/^0x00//' | sort -u) +used_r=$(cat "$T"/*/regs.txt | awk '$1=="R"{print $2}' | sort -u) +used_w=$(cat "$T"/*/regs.txt | awk '$1=="W"{print $2}' | sort -u) +miss_r=$(comm -23 <(echo "$used_r") <(echo "$rdl")); miss_w=$(comm -23 <(echo "$used_w") <(echo "$wrl")) +[[ -n "$rdl" && -z "$miss_r" ]] && ok "every read the tool made is on the module read list ($(echo "$used_r" | wc -l) registers)" || bad "reads not allowed: $miss_r" +[[ -n "$wrl" && -z "$miss_w" ]] && ok "every write the tool made is on the module write list ($(echo "$used_w" | wc -l) registers)" || bad "writes not allowed: $miss_w" +extra_w=$(comm -13 <(echo "$used_w") <(echo "$wrl") | tr '\n' ' ') +[[ -z "$extra_w" ]] && ok "every write-allowlist register is used by some path" || bad "write list extras: '$extra_w'" +init_qh=$(awk '$1=="W" && $2=="110c00"' "$T/init/regs.txt" | wc -l) +[[ $init_qh -eq 0 ]] && ok "start-up itself does not write GSP QHEAD0" || bad "init wrote QHEAD0 $init_qh times" +seq_qh=$(awk '$1=="W" && $2=="110c00"' "$T/seqregs/regs.txt" | wc -l) +[[ $seq_qh -ge 1 ]] && ok "sequencer path wrote GSP QHEAD0" || bad "seqregs did not write QHEAD0" +doorbells=$(awk '$1=="W" && $2=="840c00"' "$T/init/regs.txt" | wc -l) +[[ $doorbells -eq 1 ]] && ok "one SEC2 doorbell per start-up" || bad "doorbells in one start-up: $doorbells" + +echo "WINDOW1_SIM_TEST: $([[ $fail -eq 0 ]] && echo PASS || echo FAIL)" +exit $fail diff --git a/native/.crumb b/native/.crumb index ea5b32e6..e71592b5 100644 --- a/native/.crumb +++ b/native/.crumb @@ -79,8 +79,8 @@ "purpose": "Directory native/disk. Purpose not yet described by a human." }, { - "digest": "a5403bcaa92fcbea01f9907073a94127801891c012f049e59ecf212d833d3ff8", - "last_commit": "41119ceb", + "digest": "841902488000d892f5d4f699fe9aae17207557e31b012892fa2859a659ab0626", + "last_commit": "93fe68cf", "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:bb4101d2fe074a88e1c3a40626d52c7021dc99f404d7cc7379c1341c385fd201", - "compiled_at": "2026-10-26T15:49:35Z", + "children_root": "sha256:c39f22cb40742bdba6cb2348c781677e26cc1b4fd8279c12dde983627e7ddc5b", + "compiled_at": "2026-10-30T03:02:40Z", "compiler": "crumb-compile/1", - "digest": "sha256:220236525b9d03bf1f6c7bd065edcf54abfdb8125989c5cc3c26a5d0981cfac1", + "digest": "sha256:fa20ea43bdf23a6f9340106e859687ee83a41ac11b1628b5be2574aa4d395123", "evidence_files": 4, "evidence_root": "sha256:e410b845507e00568e15b51a5797af32a97e0e4b8ab4e8487bb7c98e7e0cf335", - "files": 606, - "generated_at_commit": "d70127557fd45192a9f24fc092963f72f15e9e29", - "source_tree": "sha256:b9bda10cf627c0b1be956102d42ac49a86569a827d5cebb86db7f23536677257" + "files": 644, + "generated_at_commit": "93fe68cfd18e0d3768be442776a3c4ebaf7f0667", + "source_tree": "sha256:58bc285795dcd11830814ca5c341829ce5c349714b36fba744f59d2a9149bca8" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/.crumb b/native/kernel/.crumb index 0dafd85f..0bc9092e 100644 --- a/native/kernel/.crumb +++ b/native/kernel/.crumb @@ -63,8 +63,8 @@ "purpose": "Directory native/kernel/core. Purpose not yet described by a human." }, { - "digest": "eb3146a026248b54faa150003192fcc43ab2bd9b01d3c0d0c120c2d5bbe2b453", - "last_commit": "f45d00ad", + "digest": "78d9e03459dc3add82984b62b85f38b429bc60ef201787d54e077de634414092", + "last_commit": "93fe68cf", "name": "dev", "purpose": "Directory native/kernel/dev. Purpose not yet described by a human." }, @@ -87,27 +87,27 @@ "purpose": "Directory native/kernel/svc. Purpose not yet described by a human." }, { - "digest": "3d8d13940b9e77faa860d813f783060abb1a4664080e76d2d28b0004ab739b5f", - "last_commit": "4b897d35", + "digest": "acfa2498911bb31a591f115cfde818686f9e80cba2c7a3902da5ecd5a90a7aa1", + "last_commit": "93fe68cf", "name": "tests", "purpose": "Directory native/kernel/tests. Purpose not yet described by a human." }, { - "digest": "8d2be0298cc545f92db0a775b87769099a9fed6cc8cbe36add355be73bd4943d", - "last_commit": "4b897d35", + "digest": "ed6cc3ec701e8ce11300e1ef78ca45b2f74c01be130f71554f15f3b4380cd37b", + "last_commit": "93fe68cf", "name": "tools", "purpose": "Hosted (Linux-built) checkers for the native kernel, run by `make -C native/kernel test`; nothin" } ], - "children_root": "sha256:1abb490a30293d27f4d109e5a9320a947de33e5bce557c9606906794984e20c0", - "compiled_at": "2026-10-26T14:20:54Z", + "children_root": "sha256:3f6c6aca83fa046438133aa73e9636d6fc4662a9fecb9ab1ac5c5edd75f85745", + "compiled_at": "2026-10-30T03:02:40Z", "compiler": "crumb-compile/1", - "digest": "sha256:a5403bcaa92fcbea01f9907073a94127801891c012f049e59ecf212d833d3ff8", + "digest": "sha256:841902488000d892f5d4f699fe9aae17207557e31b012892fa2859a659ab0626", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 421, - "generated_at_commit": "d13599d9b6251f30d3cd91b1e313a7e0c54e0f15", - "source_tree": "sha256:a887d43f2c32126bf4030db0c72a9505081cdc18b3c925b531aac1e235e0f389" + "files": 451, + "generated_at_commit": "93fe68cfd18e0d3768be442776a3c4ebaf7f0667", + "source_tree": "sha256:e087af4cc3afa26feed47b7696422158544e00cc99c51ceee83d81195cba6153" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/Makefile b/native/kernel/Makefile index d50191f3..a31fd2a8 100644 --- a/native/kernel/Makefile +++ b/native/kernel/Makefile @@ -1332,7 +1332,8 @@ HOST_SRCS := $(KDIR)/core/fmt.c $(KDIR)/core/acpi.c $(KDIR)/core/smmu.c $(KDIR)/ $(KDIR)/core/line_rx.c $(KDIR)/core/klog.c $(KDIR)/core/klog_slot.c $(KDIR)/core/cpufeat.c $(KDIR)/core/unlock_req.c $(KDIR)/core/agent_cmd.c $(KDIR)/core/artifact_card.c TESTS := test_fmt test_frames test_pt test_acpi test_acpi_dev test_heap test_smmu test_sched test_ipc test_artifact test_osc_unit test_osc_launch test_osc_admit test_osc_receipt test_entropy test_handoff test_fbcon test_osh_op \ test_continuity_codec test_continuity_resolve test_continuity_commit test_continuity_recovery test_continuity_geometry \ - test_continuity_subject test_continuity_subject_provision test_lifecycle test_console_rx test_klog test_klog_slot test_pi5 test_pi5_marker test_pi5_rng test_cpufeat test_dma_window test_pi5_pcie test_pi5_net test_pi5_gem test_unlock_req test_context test_agent_cmd test_artifact_card + test_continuity_subject test_continuity_subject_provision test_lifecycle test_console_rx test_klog test_klog_slot test_pi5 test_pi5_marker test_pi5_rng test_cpufeat test_dma_window test_pi5_pcie test_pi5_net test_pi5_gem test_unlock_req test_context test_agent_cmd test_artifact_card test_gb10_gsp_boot +TESTS += test_gpu_sim test_gsp_mmio HCFLAGS := -std=gnu11 -O1 -g -Wall -Wextra -Werror -I$(KDIR)/core -I$(KDIR)/mm -I$(KDIR)/tests -I$(BOOT) SANFLAGS := -fsanitize=address,undefined -fno-sanitize-recover=all -fno-omit-frame-pointer @@ -1484,8 +1485,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)) osc-receipt-mutants osc-receipt-release handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants osh-op-mutant context-mutant agent-cmd-mutant artifact-card-mutant artifact-tier-pi5 artifact-tier-mutant test-continuity-subject-restart gsp-fw-inspect-test gsp-cot-test gsp-bindata-test gsp-bootargs-test gsp-rpc-test slot-test slot-free package-test slot-loader-check - @fail=0; for t in $(filter-out osc-receipt-mutants osc-receipt-release handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants osh-op-mutant context-mutant agent-cmd-mutant artifact-card-mutant artifact-tier-pi5 artifact-tier-mutant test-continuity-subject-restart gsp-fw-inspect-test gsp-cot-test gsp-bindata-test gsp-bootargs-test gsp-rpc-test slot-test slot-free package-test slot-loader-check,$^); do $$t || fail=1; done; \ +test: $(addprefix $(OUT)/host/,$(TESTS)) osc-receipt-mutants osc-receipt-release handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants osh-op-mutant context-mutant agent-cmd-mutant artifact-card-mutant artifact-tier-pi5 artifact-tier-mutant test-continuity-subject-restart gsp-fw-inspect-test gsp-cot-test gsp-bindata-test gsp-bootargs-test gsp-rpc-test gb10-gsp-free gb10-gsp-nvhdr-check gb10-gsp-mutants slot-test slot-free package-test slot-loader-check + @fail=0; for t in $(filter-out osc-receipt-mutants osc-receipt-release handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants osh-op-mutant context-mutant agent-cmd-mutant artifact-card-mutant artifact-tier-pi5 artifact-tier-mutant test-continuity-subject-restart gsp-fw-inspect-test gsp-cot-test gsp-bindata-test gsp-bootargs-test gsp-rpc-test gb10-gsp-free gb10-gsp-nvhdr-check gb10-gsp-mutants slot-test slot-free package-test slot-loader-check,$^); 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)) @@ -2037,6 +2038,84 @@ 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 +# ---- GspSystemInfo encoder (L332 rung 2 window 1): the 936 bytes of GSP_SET_SYSTEM_INFO from a +# "field value" text file. gsp-sysinfo-test = anchors, a known encoding, every refusal. +# gsp-sysinfo-nvhdr-test = our field list against NVIDIA's own struct text, cut out of the pinned +# tree (OGKM_DIR) at build time by line range; each cut is checked to start and end where expected. +GSP_SI_TOOL := $(OUT)/host/ck_gsp_sysinfo_encode +$(GSP_SI_TOOL): $(KDIR)/tools/ck_gsp_sysinfo_encode.c + @mkdir -p $(dir $@) + $(HOSTCC) -std=gnu11 -O2 -Wall -Wextra -Werror -o $@ $< +gsp-sysinfo-test: $(GSP_SI_TOOL) + $(GSP_SI_TOOL) selftest | grep -E '^CK_GSP_SYSINFO_ENCODE_SELFTEST: (PASS|FAIL)' | grep -q PASS || { $(GSP_SI_TOOL) selftest | grep -E 'FAIL|SELFTEST'; exit 1; } + @$(GSP_SI_TOOL) selftest | tail -1 +GSP_SI_NV := $(OUT)/host/gsp_sysinfo_nvidia.h +gsp-sysinfo-nvhdr-test: $(KDIR)/tools/ck_gsp_sysinfo_encode.c + @test -d $(OGKM_SRC) || { echo "GSP_SYSINFO_NVHDR: FAIL (no open-gpu-kernel-modules 580.173.02 tree at OGKM_DIR=$(OGKM_DIR))"; exit 1; } + @mkdir -p $(OUT)/host + @cut() { sed -n "$$2,$$3p" "$(OGKM_SRC)/$$1" > $(GSP_SI_NV).part; \ + head -1 $(GSP_SI_NV).part | grep -q "$$4" && tail -1 $(GSP_SI_NV).part | grep -q "$$5" || \ + { echo "GSP_SYSINFO_NVHDR: FAIL ($$1:$$2-$$3 is not $$4 .. $$5)"; exit 1; }; cat $(GSP_SI_NV).part >> $(GSP_SI_NV); }; \ + : > $(GSP_SI_NV); \ + cut common/sdk/nvidia/inc/ctrl/ctrl0073/ctrl0073system.h 747 747 'NV0073_CTRL_SYSTEM_ACPI_ID_MAP_MAX_DISPLAYS' '(16U)' && \ + cut nvidia/inc/kernel/gpu/gpu_acpi_data.h 72 115 'typedef struct DOD_METHOD_DATA' '} ACPI_METHOD_DATA;' && \ + cut nvidia/generated/g_chipset_nvoc.h 220 227 'typedef struct' '} BUSINFO;' && \ + cut nvidia/inc/kernel/gpu/gsp/gsp_static_config.h 45 62 'typedef struct GSP_VF_INFO' '} GSP_PCIE_CONFIG_REG;' && \ + cut nvidia/inc/kernel/gpu/gsp/gsp_static_config.h 172 227 'typedef struct GspSystemInfo' '} GspSystemInfo;' + $(HOSTCC) -std=gnu11 -O2 -Wall -Wextra -Werror $(OGKM_INC) -DCK_SYSINFO_NVHDR='"$(GSP_SI_NV)"' \ + -o $(OUT)/host/ck_gsp_sysinfo_nvhdr $(KDIR)/tools/ck_gsp_sysinfo_encode.c + $(OUT)/host/ck_gsp_sysinfo_nvhdr nvhdr + +# ---- GB10 GSP boot builder, freestanding (L192, aienos#286 cut C host side) ---- +# dev/gb10_gsp_boot.c composes every block above into one arena plus the SEC2 COT packet and the +# post-init RPCs (GSP_RM_ALLOC / CONTROL / FREE, GET_GSP_STATIC_INFO). Bytes in memory only: no +# MMIO, no firmware load. Not linked into any image yet. docs/GB10_FIRMWARE_INVENTORY.md section 14. +# test_gb10_gsp_boot (in TESTS): layout, cross-links, ring, refusals, decoded at hand-written offsets +# gb10-gsp-free: compiles with KCFLAGS, no undefined symbols, every frame <= 4 KiB of stack +# gb10-gsp-nvhdr-test: mirrors vs the NVIDIA headers themselves (OGKM_DIR, MIT); FAILS if absent +# gb10-gsp-nvhdr-check: same, NOT_RUN when OGKM_DIR is absent (used by make test) +# gb10-gsp-mutants: each test-only mutant must make test_gb10_gsp_boot or the nvhdr test FAIL +GSPB_SRCS := $(KDIR)/dev/gb10_gsp_boot.c +GSPB_DEPS := $(KDIR)/tests/test_gb10_gsp_boot.c $(GSPB_SRCS) $(KDIR)/dev/gb10_gsp_boot.h $(KDIR)/tests/ck_test.h +$(OUT)/host/test_gb10_gsp_boot: $(GSPB_DEPS) + @mkdir -p $(dir $@) + $(HOSTCC) $(HCFLAGS) -I$(KDIR)/dev -o $@ $< $(GSPB_SRCS) +$(OUT)/host-san/test_gb10_gsp_boot: $(GSPB_DEPS) + @mkdir -p $(dir $@) + $(HOSTCC) $(HCFLAGS) $(SANFLAGS) -I$(KDIR)/dev -o $@ $< $(GSPB_SRCS) +test-gb10-gsp-boot: $(OUT)/host/test_gb10_gsp_boot + $< +gb10-gsp-free: $(GSPB_SRCS) $(KDIR)/dev/gb10_gsp_boot.h + @mkdir -p $(OUT)/free + $(KCC) $(KCFLAGS) -Wstack-usage=4096 -c $(GSPB_SRCS) -o $(OUT)/free/gb10_gsp_boot.o + @bad=$$($(CROSS)nm -u $(OUT)/free/gb10_gsp_boot.o | awk '{print $$2}' | grep -vxF -e _GLOBAL_OFFSET_TABLE_ || true); \ + if [ -n "$$bad" ]; then echo "GB10_GSP_FREE: FAIL unexpected undefined symbols: $$bad"; exit 1; fi; \ + echo "GB10_GSP_FREE: PASS (no undefined symbols, stack <= 4096 per function)" +OGKM_DIR ?= $(HOME)/workspace/_ext/open-gpu-kernel-modules-580.173.02 +OGKM_SRC := $(OGKM_DIR)/src +OGKM_INC := -I$(OGKM_SRC)/common/sdk/nvidia/inc -I$(OGKM_SRC)/nvidia/arch/nvalloc/common/inc \ + -I$(OGKM_SRC)/common/uproc/os/common/include -I$(OGKM_SRC)/nvidia/inc/kernel -I$(OGKM_SRC)/nvidia/inc \ + -I$(OGKM_SRC)/nvidia/generated -I$(OGKM_SRC)/common/shared/msgq/inc -I$(OGKM_SRC)/nvidia/interface \ + -I$(OGKM_SRC)/common/inc +GSPB_NV_DEPS := $(KDIR)/tests/test_gb10_gsp_nvhdr.c $(GSPB_SRCS) $(KDIR)/dev/gb10_gsp_boot.h $(KDIR)/tests/ck_test.h +gb10-gsp-nvhdr-test: $(GSPB_NV_DEPS) + @test -r $(OGKM_SRC)/nvidia/arch/nvalloc/common/inc/gsp/gsp_fw_wpr_meta.h || \ + { echo "GB10_GSP_NVHDR: FAIL (no open-gpu-kernel-modules 580.173.02 tree at OGKM_DIR=$(OGKM_DIR))"; exit 1; } + @mkdir -p $(OUT)/host-san + $(HOSTCC) $(HCFLAGS) $(SANFLAGS) -I$(KDIR)/dev $(OGKM_INC) -o $(OUT)/host-san/test_gb10_gsp_nvhdr $< $(GSPB_SRCS) + $(OUT)/host-san/test_gb10_gsp_nvhdr +gb10-gsp-nvhdr-check: + @if [ -r $(OGKM_SRC)/nvidia/arch/nvalloc/common/inc/gsp/gsp_fw_wpr_meta.h ]; then $(MAKE) --no-print-directory gb10-gsp-nvhdr-test; \ + else echo "GB10_GSP_NVHDR: NOT_RUN (no open-gpu-kernel-modules 580.173.02 tree at OGKM_DIR=$(OGKM_DIR))"; fi +GSPB_MUTANTS := SWAPRX CKSUM RADIX ALLOCLEN +gb10-gsp-mutants: $(GSPB_DEPS) $(GSPB_NV_DEPS) + @mkdir -p $(OUT)/host + @fail=0; for m in $(GSPB_MUTANTS); do \ + $(HOSTCC) $(HCFLAGS) -DGSP_MUTANT_HOST -DGSP_MUTANT_$$m -I$(KDIR)/dev -o $(OUT)/host/test_gb10_gsp_boot_mut_$$m $(KDIR)/tests/test_gb10_gsp_boot.c $(GSPB_SRCS) || exit 1; \ + if $(OUT)/host/test_gb10_gsp_boot_mut_$$m >/dev/null; then echo "MUTANT SURVIVED: $$m"; fail=1; else echo "mutant killed: $$m"; fi; \ + done; test $$fail -eq 0 +.PHONY: test-gb10-gsp-boot gb10-gsp-free gb10-gsp-nvhdr-test gb10-gsp-nvhdr-check gb10-gsp-mutants + # ---- native image slots: host tool + freestanding check (native v1 plan P11 cut 1, gate N7) ---- # native/boot/slot_format.h + slot_select.c: the A/B slot manifest, control record and the # loader's selection rules (bounded candidate tries, generation floor, no boot loop, an @@ -2467,6 +2546,127 @@ dma-window-mutants: done; test $$fail -eq 0 .PHONY: test-dma-window dma-window-mutants +# AIENOS-GB10 cut D, host side: GPU page tables, allocator and channel over a simulated GB10 +# (gpu/gpu_sim.c). Host test only, not linked into any image (dependency map: kernel-side D code waits for #163/B). +GPU_SIM_SRCS := $(KDIR)/gpu/gmmu.c $(KDIR)/gpu/gpu_mem.c $(KDIR)/gpu/gpu_chan.c $(KDIR)/gpu/gpu_sim.c +GPU_SIM_HDRS := $(KDIR)/gpu/gmmu.h $(KDIR)/gpu/gpu_mem.h $(KDIR)/gpu/gpu_chan.h $(KDIR)/gpu/gpu_sim.h +GPU_SIM_DEPS := $(KDIR)/tests/test_gpu_sim.c $(GPU_SIM_SRCS) $(GPU_SIM_HDRS) $(KDIR)/tests/ck_test.h +$(OUT)/host/test_gpu_sim: $(GPU_SIM_DEPS) + @mkdir -p $(dir $@) + $(HOSTCC) $(HCFLAGS) -I$(KDIR)/gpu -o $@ $< $(GPU_SIM_SRCS) +$(OUT)/host-san/test_gpu_sim: $(GPU_SIM_DEPS) + @mkdir -p $(dir $@) + $(HOSTCC) $(HCFLAGS) $(SANFLAGS) -I$(KDIR)/gpu -o $@ $< $(GPU_SIM_SRCS) +test-gpu-sim: $(OUT)/host/test_gpu_sim + $< +# The three files that would run in the kernel must build with the kernel compiler and KCFLAGS and need no symbol from outside. +gpu-freestanding: + @mkdir -p $(OUT)/host/gpu-fs + @for f in gmmu gpu_mem gpu_chan; do \ + $(KCC) $(KCFLAGS) -I$(KDIR)/gpu -c -o $(OUT)/host/gpu-fs/$$f.o $(KDIR)/gpu/$$f.c || exit 1; \ + done; \ + $(CROSS)ld -r -o $(OUT)/host/gpu-fs/gpu.o $(OUT)/host/gpu-fs/gmmu.o $(OUT)/host/gpu-fs/gpu_mem.o $(OUT)/host/gpu-fs/gpu_chan.o || exit 1; \ + if nm -u $(OUT)/host/gpu-fs/gpu.o | grep -v " _GLOBAL_OFFSET_TABLE_$$" | grep -q .; then nm -u $(OUT)/host/gpu-fs/gpu.o; echo "gpu-freestanding: FAIL (undefined symbols)"; exit 1; fi; \ + echo "gpu-freestanding: PASS (gmmu gpu_mem gpu_chan built with KCC/KCFLAGS, linked -r, no undefined symbol except the PIE GOT)" +# Each mutant removes one check; test_gpu_sim must FAIL for every one. +GPU_SIM_MUTANTS := NO_OVERLAP NO_PA_RANGE NO_VA_BITS NO_POOL_COUNT NO_INVAL_POLL NO_TIMEOUT_LATCH NO_QUARANTINE \ + NO_POLLED_UNCACHED NO_GP_VA40 NO_RING_FULL NO_IDLE_QUARANTINE NO_MIXED_PAGES NO_INST_PDB NO_CHID_WIDTH NO_USERD_WIDTH NO_DISABLE +gpu-sim-mutants: + @mkdir -p $(OUT)/host + @fail=0; for m in $(GPU_SIM_MUTANTS); do \ + $(HOSTCC) $(HCFLAGS) -DCK_GPU_MUTANT_$$m -I$(KDIR)/gpu -o $(OUT)/host/test_gpu_sim_mut_$$m $(KDIR)/tests/test_gpu_sim.c $(GPU_SIM_SRCS) || exit 1; \ + if $(OUT)/host/test_gpu_sim_mut_$$m >/dev/null; then echo "MUTANT SURVIVED: $$m"; fail=1; else echo "mutant killed: $$m"; fi; \ + done; test $$fail -eq 0 +.PHONY: test-gpu-sim gpu-freestanding gpu-sim-mutants + +# L332 rung 1: the same channel as a device contract (gpu/contract/gb10_chan.devc, ADR 0021 class gpu-chan), compiled by +# crates/aienos-devc into gpu/contract/gen/gch_contract.c (committed; the kernel build never runs cargo). The generated twin +# must pass test_gpu_sim like the hand one, and the differential trace (every register access and a hash of all simulated +# memory after each of ~330 operations) must be byte-identical between the two. +GPU_CONTRACT_C := $(KDIR)/gpu/contract/gen/gch_contract.c +GPU_SIM_SRCS_CONTRACT := $(filter-out $(KDIR)/gpu/gpu_chan.c,$(GPU_SIM_SRCS)) $(GPU_CONTRACT_C) +$(OUT)/host/test_gpu_sim_contract: $(KDIR)/tests/test_gpu_sim.c $(GPU_SIM_SRCS_CONTRACT) $(GPU_SIM_HDRS) $(KDIR)/tests/ck_test.h + @mkdir -p $(dir $@) + $(HOSTCC) $(HCFLAGS) -I$(KDIR)/gpu -o $@ $< $(GPU_SIM_SRCS_CONTRACT) +$(OUT)/host-san/test_gpu_sim_contract: $(KDIR)/tests/test_gpu_sim.c $(GPU_SIM_SRCS_CONTRACT) $(GPU_SIM_HDRS) $(KDIR)/tests/ck_test.h + @mkdir -p $(dir $@) + $(HOSTCC) $(HCFLAGS) $(SANFLAGS) -I$(KDIR)/gpu -o $@ $< $(GPU_SIM_SRCS_CONTRACT) +$(OUT)/host/gpu_chan_trace_hand: $(KDIR)/tests/gpu_chan_trace.c $(GPU_SIM_SRCS) $(GPU_SIM_HDRS) + @mkdir -p $(dir $@) + $(HOSTCC) $(HCFLAGS) $(SANFLAGS) -I$(KDIR)/gpu -o $@ $< $(GPU_SIM_SRCS) +$(OUT)/host/gpu_chan_trace_contract: $(KDIR)/tests/gpu_chan_trace.c $(GPU_SIM_SRCS_CONTRACT) $(GPU_SIM_HDRS) + @mkdir -p $(dir $@) + $(HOSTCC) $(HCFLAGS) $(SANFLAGS) -I$(KDIR)/gpu -o $@ $< $(GPU_SIM_SRCS_CONTRACT) +test-gpu-contract: $(OUT)/host/test_gpu_sim_contract $(OUT)/host-san/test_gpu_sim_contract + $(OUT)/host/test_gpu_sim_contract + $(OUT)/host-san/test_gpu_sim_contract +gpu-contract-trace: $(OUT)/host/gpu_chan_trace_hand $(OUT)/host/gpu_chan_trace_contract + @$(OUT)/host/gpu_chan_trace_hand > $(OUT)/host/gpu_chan_trace_hand.txt + @$(OUT)/host/gpu_chan_trace_contract > $(OUT)/host/gpu_chan_trace_contract.txt + @cmp $(OUT)/host/gpu_chan_trace_hand.txt $(OUT)/host/gpu_chan_trace_contract.txt \ + && echo "gpu-contract-trace: PASS ($$(wc -l < $(OUT)/host/gpu_chan_trace_hand.txt) lines identical, hand vs contract)" +gpu-contract-freestanding: + @mkdir -p $(OUT)/host/gpu-fs + @$(KCC) $(KCFLAGS) -I$(KDIR)/gpu -c -o $(OUT)/host/gpu-fs/gch_contract.o $(GPU_CONTRACT_C) || exit 1; \ + if nm -u $(OUT)/host/gpu-fs/gch_contract.o | grep -v " _GLOBAL_OFFSET_TABLE_$$" | grep -vE " ck_gmem_(alloc|free|quarantine)$$" | grep -q .; then \ + nm -u $(OUT)/host/gpu-fs/gch_contract.o; echo "gpu-contract-freestanding: FAIL"; exit 1; fi; \ + echo "gpu-contract-freestanding: PASS (gch_contract.c with KCC/KCFLAGS, needs only the ck_gmem allocator)" +.PHONY: test-gpu-contract gpu-contract-trace gpu-contract-freestanding + +# L332 / L346: the GB10B GSP start-up on BAR0 (gpu/gsp_mmio.c, steps and driver-source lines in gsp_mmio.h) against a +# simulated SEC2 + GSP falcon (gpu/gsp_sim.c). Host only. gsp-mmio-freestanding: gsp_mmio.c with KCC/KCFLAGS, no symbol needed. +GSP_MMIO_SRCS := $(KDIR)/gpu/gsp_mmio.c $(KDIR)/gpu/gsp_sim.c +GSP_MMIO_DEPS := $(KDIR)/tests/test_gsp_mmio.c $(GSP_MMIO_SRCS) $(KDIR)/gpu/gsp_mmio.h $(KDIR)/gpu/gsp_sim.h $(KDIR)/gpu/gmmu.h $(KDIR)/tests/ck_test.h +$(OUT)/host/test_gsp_mmio: $(GSP_MMIO_DEPS) + @mkdir -p $(dir $@) + $(HOSTCC) $(HCFLAGS) -I$(KDIR)/gpu -o $@ $< $(GSP_MMIO_SRCS) +$(OUT)/host-san/test_gsp_mmio: $(GSP_MMIO_DEPS) + @mkdir -p $(dir $@) + $(HOSTCC) $(HCFLAGS) $(SANFLAGS) -I$(KDIR)/gpu -o $@ $< $(GSP_MMIO_SRCS) +test-gsp-mmio: $(OUT)/host/test_gsp_mmio $(OUT)/host-san/test_gsp_mmio + $(OUT)/host/test_gsp_mmio + $(OUT)/host-san/test_gsp_mmio +gsp-mmio-freestanding: + @mkdir -p $(OUT)/host/gpu-fs + @$(KCC) $(KCFLAGS) -I$(KDIR)/gpu -c -o $(OUT)/host/gpu-fs/gsp_mmio.o $(KDIR)/gpu/gsp_mmio.c || exit 1; \ + if nm -u $(OUT)/host/gpu-fs/gsp_mmio.o | grep -v " _GLOBAL_OFFSET_TABLE_$$" | grep -q .; then \ + nm -u $(OUT)/host/gpu-fs/gsp_mmio.o; echo "gsp-mmio-freestanding: FAIL"; exit 1; fi; \ + echo "gsp-mmio-freestanding: PASS (gsp_mmio.c with KCC/KCFLAGS, no undefined symbol)" +.PHONY: test-gsp-mmio gsp-mmio-freestanding +# The same start-up written from gpu/contract/gb10_gsp.devc (aienos-devc class gpu-boot, branch feat/devc-gpu): +# gen/gsb_contract.c has the gsp_mmio.h API with the contract's own offsets. It must pass test_gsp_mmio and match +# the hand twin access for access in every gsp_boot_trace scenario. +GSP_CONTRACT_C := $(KDIR)/gpu/contract/gen/gsb_contract.c +GSP_TRACE_DEPS := $(KDIR)/tests/gsp_boot_trace.c $(KDIR)/gpu/gsp_sim.c $(KDIR)/gpu/gsp_mmio.h $(KDIR)/gpu/gsp_sim.h $(KDIR)/gpu/gmmu.h +$(OUT)/host/test_gsp_mmio_contract: $(GSP_MMIO_DEPS) $(GSP_CONTRACT_C) + @mkdir -p $(dir $@) + $(HOSTCC) $(HCFLAGS) -I$(KDIR)/gpu -o $@ $< $(GSP_CONTRACT_C) $(KDIR)/gpu/gsp_sim.c +$(OUT)/host-san/test_gsp_mmio_contract: $(GSP_MMIO_DEPS) $(GSP_CONTRACT_C) + @mkdir -p $(dir $@) + $(HOSTCC) $(HCFLAGS) $(SANFLAGS) -I$(KDIR)/gpu -o $@ $< $(GSP_CONTRACT_C) $(KDIR)/gpu/gsp_sim.c +$(OUT)/host/gsp_boot_trace_hand: $(GSP_TRACE_DEPS) $(KDIR)/gpu/gsp_mmio.c + @mkdir -p $(dir $@) + $(HOSTCC) $(HCFLAGS) -I$(KDIR)/gpu -o $@ $< $(KDIR)/gpu/gsp_mmio.c $(KDIR)/gpu/gsp_sim.c +$(OUT)/host/gsp_boot_trace_contract: $(GSP_TRACE_DEPS) $(GSP_CONTRACT_C) + @mkdir -p $(dir $@) + $(HOSTCC) $(HCFLAGS) -I$(KDIR)/gpu -o $@ $< $(GSP_CONTRACT_C) $(KDIR)/gpu/gsp_sim.c +test-gsp-contract: $(OUT)/host/test_gsp_mmio_contract $(OUT)/host-san/test_gsp_mmio_contract + $(OUT)/host/test_gsp_mmio_contract + $(OUT)/host-san/test_gsp_mmio_contract +gsp-contract-trace: $(OUT)/host/gsp_boot_trace_hand $(OUT)/host/gsp_boot_trace_contract + @$(OUT)/host/gsp_boot_trace_hand > $(OUT)/host/gsp_boot_trace_hand.txt + @$(OUT)/host/gsp_boot_trace_contract > $(OUT)/host/gsp_boot_trace_contract.txt + @cmp $(OUT)/host/gsp_boot_trace_hand.txt $(OUT)/host/gsp_boot_trace_contract.txt \ + && echo "gsp-contract-trace: PASS ($$(wc -l < $(OUT)/host/gsp_boot_trace_hand.txt) lines identical, hand vs contract)" +gsp-contract-freestanding: + @mkdir -p $(OUT)/host/gpu-fs + @$(KCC) $(KCFLAGS) -I$(KDIR)/gpu -c -o $(OUT)/host/gpu-fs/gsb_contract.o $(GSP_CONTRACT_C) || exit 1; \ + if nm -u $(OUT)/host/gpu-fs/gsb_contract.o | grep -v " _GLOBAL_OFFSET_TABLE_$$" | grep -q .; then \ + nm -u $(OUT)/host/gpu-fs/gsb_contract.o; echo "gsp-contract-freestanding: FAIL"; exit 1; fi; \ + echo "gsp-contract-freestanding: PASS (gsb_contract.c with KCC/KCFLAGS, no undefined symbol)" +.PHONY: test-gsp-contract gsp-contract-trace gsp-contract-freestanding + + # AIENOS-PI5 PCIe root complex / RP1 enumerator logic over a fake register file. Not the hardware. PI5PCIE_SRCS := $(KDIR)/dev/pi5_pcie.c PI5PCIE_DEPS := $(KDIR)/tests/test_pi5_pcie.c $(PI5PCIE_SRCS) $(KDIR)/tests/ck_test.h $(KDIR)/dev/pi5_pcie.h diff --git a/native/kernel/README.md b/native/kernel/README.md index 18164592..608dc488 100644 --- a/native/kernel/README.md +++ b/native/kernel/README.md @@ -12,6 +12,7 @@ QEMU qualifies nothing physical: a PASS here says nothing about real hardware. | `arch/` | Vectors, EL2 -> EL1h entry (ADR 0009), recoverable probe, exception and IRQ dispatch, GICv3 or GICv2 (picked from the MADT; GICv2 is the Raspberry Pi 5 GIC-400 shape, QEMU gate `AIENOS_QEMU_GIC=2 scripts/qemu_ck_boot_test.sh`), EL1 physical timer. | | `mm/` | Frame allocator (UEFI map), 4 KiB-granule page-table builder, heap, the kernel address space (`mmu.c`). | | `core/` | Console, printf, ACPI, reports/panic/PSCI reset, M3 (threads, scheduler, EL0, capabilities, IPC), `kmain.c`. | +| `gpu/` | GB10 GPU memory side, cut D, host only: GPU page tables in the format the NVIDIA driver uses for GB10, a bounded GPU buffer allocator with per-buffer cache policy and quarantine, one compute channel (ring, USERD, instance block, doorbell), and a simulated GB10 to test them on. Not linked into any image; never run on the chip. See "GB10 GPU memory (simulated)" below. | | `tests/` | Host unit tests. | | `third_party/omega/` | The canonical Omega Cortex store, byte for byte from the omega commit in `omega.lock` (checked by `scripts/omega_lock_check.sh`); built freestanding by `svc/cortex_store.c` over the sealed Store through `svc/cortex_journal.c` (native v1 plan P06). | | `x86/` | x86_64 port, first cut (AIENOS-IMAC-KERNEL-0, 2017 iMac): UEFI stub, descriptor tables and interrupt stubs, page tables, local APIC timer, ACPI power off, console, secondary-core start, PCI walk, read-only AHCI and NVMe disks, BCM57766 Ethernet link detection; a lab-only, opt-in network report (`CK_X86_REPORT=1`). | @@ -272,6 +273,24 @@ tree with uncommitted changes to tracked files stamps `aienos_commit: -dir `run.log`, and says "NOT commit-bound (dirty build)" for a `-dirty` image. Hardware receipts from earlier runs are in `evidence/pi5_hardware_runs_2026-10-13/`. +## GB10 GPU boot package builder (host only, not in any image) + +`dev/gb10_gsp_boot.c` builds, in plain memory, everything NVIDIA's Linux driver +(open-gpu-kernel-modules 580.173.02) hands the GB10 to start its GPU management +processor (GSP): the WprMeta page, libos arguments, log buffers, RPC queues with the two +pre-boot messages, the radix-3 firmware table, the bootloader, signature and FMC copies, +the FMC boot parameters, the one SEC2 chain-of-trust packet, and the messages a native +kernel sends after GSP is up (object alloc, control, free, static info) plus a reader for +GSP's replies. It is freestanding kernel C but writes no register and loads nothing; no +part of it has run on the GB10. Host checks: + + make -C native/kernel test-gb10-gsp-boot # layout, ring, refusals (also in make test) + make -C native/kernel gb10-gsp-nvhdr-test # every field vs the NVIDIA headers (needs OGKM_DIR) + make -C native/kernel gb10-gsp-free # kernel flags, no hidden library calls, small stack + make -C native/kernel gb10-gsp-mutants # four broken variants, each must fail + +What is known and what still needs the chip: `docs/GB10_FIRMWARE_INVENTORY.md` section 14. + ## Known hardware risk: disk footprint (CK gate DISK_LAYOUT: NOT_RUN) **Do not boot the C kernel on a disk holding data until CK gate `DISK_LAYOUT` @@ -641,3 +660,51 @@ low-water free bytes. (no FP/SIMD; EL0 FP/SIMD traps). Placement is computed from the MADT; no secondary core is started (same as Rust). See GATES.md rows 16-20. - MAIR adds a Normal Non-cacheable attribute (index 2) for the DMA pool. + +## GB10 GPU memory (simulated) + +`gpu/` holds the part of a native GB10 GPU driver that the Linux NVIDIA +driver (RM and UVM) does for us today: GPU page tables, the GPU TLB +invalidate, GPU-visible buffers, and the memory and doorbell of one compute +channel. It is cut D of `docs/GB10_NATIVE_DEPENDENCY_MAP.md`, host side only. + +- `gmmu.c`: GB10 page tables (57-bit GPU addresses, 4 KiB, 64 KiB and + 2 MiB pages) and the TLB invalidate register sequence, as + open-gpu-kernel-modules 580.173.02 programs them for GB10B. +- `gpu_mem.c`: a bounded GPU buffer allocator. Each buffer has a CPU address + and a separate GPU address. A buffer the CPU polls must be GPU-uncached + (the allocator refuses otherwise). Freed memory is reused only after the + GPU confirms the invalidate; if it never does, the memory is quarantined. +- `gpu_chan.c`: one compute channel: ring, USERD, instance block with the + page-directory pointer, runlist USERD pointer, work-submit token, doorbell. + A channel that does not go idle on teardown has its memory quarantined. +- `gpu_sim.c`: a simulated GB10 for the tests (memory array, logged + registers, a page walker written separately from `gmmu.c`, a TLB that only + an invalidate empties, fault records). Test only. + +Run: `make -C native/kernel test-gpu-sim` (also part of `make test`), +`gpu-sim-mutants` (each mutant removes one check; all must be caught) and +`gpu-freestanding` (the three driver files build with the kernel compiler +and flags). What this shows: the code follows the driver's layouts and +refuses what it should, on a simulator. What it does not show: anything on +the real chip. Which register sequences still need the chip is listed in the +`gpu_chan.h` and `gmmu.h` header comments (UNKNOWN / UNVERIFIED). + +### The channel as a device contract (L332) + +`gpu/contract/gb10_chan.devc` is the same compute channel written as a device +contract (ADR 0021, class `gpu-chan`): constants, the doorbell register, the +packed formats (doorbell token, GPFIFO entry, runlist USERD pointer, instance +block page directory), the three buffers with their cache policy, and the +steps of create, submit and teardown. Each number cites a line of NVIDIA's +driver source. `crates/aienos-devc` (branch feat/devc-gpu) compiles it into +`gpu/contract/gen/gch_contract.c`, which has the API of `gpu_chan.h`. The +compiler refuses unsafe contracts (doorbell before publish, no fence between +them, no ring-room check, GPU-cached memory the CPU writes or polls, a +channel id bound wider than its token field, teardown that frees before idle). + +Run: `make -C native/kernel test-gpu-contract` (test_gpu_sim against the +generated twin, plain and sanitized), `gpu-contract-trace` (every register +access and a hash of all simulated memory after each of ~390 operations, +hand vs generated, must be byte-identical), `gpu-contract-freestanding`. +Mutants of the contract itself: `evidence/own-gpu-driver/rung1/contract_mutants.sh`. diff --git a/native/kernel/dev/.crumb b/native/kernel/dev/.crumb index a91c0ebd..0eaf7440 100644 --- a/native/kernel/dev/.crumb +++ b/native/kernel/dev/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-24T04:15:32Z", + "compiled_at": "2026-10-30T03:02:40Z", "compiler": "crumb-compile/1", - "digest": "sha256:eb3146a026248b54faa150003192fcc43ab2bd9b01d3c0d0c120c2d5bbe2b453", + "digest": "sha256:78d9e03459dc3add82984b62b85f38b429bc60ef201787d54e077de634414092", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 43, - "generated_at_commit": "621c9e6fe430ee689836bee3ee2689d7d32e0f7d", - "source_tree": "sha256:9db341c086c64aa37699da6fd2026b9f6c960a70a01c246b845b1ea240ea3824" + "files": 45, + "generated_at_commit": "93fe68cfd18e0d3768be442776a3c4ebaf7f0667", + "source_tree": "sha256:3795d93ae7fef6967f0a0633a7997c5529a91a9099cdadcd01261264118986f5" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/dev/gb10_gsp_boot.c b/native/kernel/dev/gb10_gsp_boot.c new file mode 100644 index 00000000..e7ca2670 --- /dev/null +++ b/native/kernel/dev/gb10_gsp_boot.c @@ -0,0 +1,554 @@ +/* gb10_gsp_boot.c -- GB10 GSP boot builder (see gb10_gsp_boot.h). Freestanding: no libc, no + * MMIO, no device access; writes little-endian bytes into a caller-owned arena only. */ +#include "gb10_gsp_boot.h" + +/* TEST-ONLY mutants (make gb10-gsp-mutants): each breaks one rule the host tests must catch. */ +#if (defined(GSP_MUTANT_SWAPRX) || defined(GSP_MUTANT_CKSUM) || defined(GSP_MUTANT_RADIX) || \ + defined(GSP_MUTANT_ALLOCLEN)) && !defined(GSP_MUTANT_HOST) +#error "GSP mutants are host-test builds only" +#endif + +/* ---- layout asserts: every offset the builder writes is taken from these mirrors, and the + * host test compares the mirrors with the NVIDIA headers themselves (test_gb10_gsp_nvhdr). ---- */ +_Static_assert(sizeof(gsp_mirror_wpr_meta) == GSP_WPR_META_SIZE, "GspFwWprMeta is 256 bytes"); +_Static_assert(offsetof(gsp_mirror_wpr_meta, sysmemAddrOfSignature) == 72, "WprMeta signature at 72"); +_Static_assert(offsetof(gsp_mirror_wpr_meta, gspFwHeapSize) == 128, "WprMeta heap size at 128"); +_Static_assert(offsetof(gsp_mirror_wpr_meta, gspFwHeapVfPartitionCount) == 240, "WprMeta VF count at 240"); +_Static_assert(offsetof(gsp_mirror_wpr_meta, verified) == 248, "WprMeta verified at 248"); +_Static_assert(sizeof(gsp_mirror_libos_arg) == GSP_LIBOS_ENTRY_SIZE, "LibosMemoryRegionInitArgument is 32"); +_Static_assert(offsetof(gsp_mirror_libos_arg, kind) == 24 && offsetof(gsp_mirror_libos_arg, loc) == 25, "libos kind/loc"); +_Static_assert(sizeof(gsp_mirror_args_cached) == GSP_ARGS_CACHED_SIZE, "GSP_ARGUMENTS_CACHED is 88"); +_Static_assert(offsetof(gsp_mirror_args_cached, sr) == 32 && offsetof(gsp_mirror_args_cached, gpuInstance) == 44 && + offsetof(gsp_mirror_args_cached, bDmemStack) == 48 && offsetof(gsp_mirror_args_cached, profilerArgs) == 56 && + offsetof(gsp_mirror_args_cached, sysmemHeapArgs) == 72, "GSP_ARGUMENTS_CACHED offsets"); +_Static_assert(sizeof(gsp_mirror_msgq_tx) == 32, "msgqTxHeader is 32"); +_Static_assert(sizeof(gsp_mirror_rpc_hdr) == GSP_RPC_HDR_SIZE, "rpc_message_header_v03_00 is 32"); +_Static_assert(offsetof(gsp_mirror_elem, rpc) == GSP_ELEM_HDR_SIZE && sizeof(gsp_mirror_elem) == GSP_ELEM_MIN_LEN, "GSP_MSG_QUEUE_ELEMENT"); +_Static_assert(sizeof(gsp_mirror_rm_alloc) == GSP_RM_ALLOC_FIXED, "rpc_gsp_rm_alloc_v03_00 fixed part"); +_Static_assert(sizeof(gsp_mirror_rm_control) == GSP_RM_CONTROL_FIXED, "rpc_gsp_rm_control_v03_00 fixed part"); +_Static_assert(sizeof(gsp_mirror_rm_free) == GSP_RM_FREE_SIZE, "rpc_free_v03_00"); +_Static_assert(sizeof(gsp_mirror_reg_entry) == 16, "PACKED_REGISTRY_ENTRY is 16"); +_Static_assert(sizeof(gsp_mirror_fmc_params) == GSP_FMC_PARAMS_SIZE, "GSP_FMC_BOOT_PARAMS is 88"); +_Static_assert(offsetof(gsp_mirror_fmc_params, boot.bIsGspRmBoot) == 36 && offsetof(gsp_mirror_fmc_params, rm) == 40 && + offsetof(gsp_mirror_fmc_params, spdm) == 56 && offsetof(gsp_mirror_fmc_params, mem) == 80, "FMC params offsets"); +_Static_assert(sizeof(gsp_mirror_cot) == GSP_COT_PAYLOAD_SIZE, "NVDM_PAYLOAD_COT is 860 packed"); +_Static_assert(offsetof(gsp_mirror_cot, gspBootArgsSysmemOffset) == 852, "COT boot args at 852"); + +#define OFF(T, f) ((uint32_t)offsetof(T, f)) +#define WM(f) OFF(gsp_mirror_wpr_meta, f) + +/* GB10B log set, registration order (kernel_gsp.c:3150-3240): seven buffers then RMARGS. */ +static const struct { const char *id; uint32_t size; } gb10b_logs[GSP_GB10B_LOG_COUNT] = { + {"LOGINIT", 0x10000}, {"LOGINTR", 0x10000}, {"LOGRM", 0x10000}, {"LOGMNOC", 0x10000}, + {"LOGDBG", 0x10000}, {"LOGROOT", 0x1000}, {"LOGKRNL", 0x10000}, +}; + +/* ---- byte helpers ---- */ +static void wr16(uint8_t *p, uint16_t v) { p[0] = (uint8_t)v; p[1] = (uint8_t)(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; } } +static void wr64(uint8_t *p, uint64_t v) { for (int i = 0; i < 8; i++) { p[i] = (uint8_t)v; v >>= 8; } } +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 uint64_t rd64(const uint8_t *p) { return (uint64_t)rd32(p) | ((uint64_t)rd32(p + 4) << 32); } +static void bcopy_(uint8_t *d, const uint8_t *s, uint64_t n) { for (uint64_t i = 0; i < n; i++) d[i] = s[i]; } +static void bzero_(uint8_t *d, uint64_t n) { for (uint64_t i = 0; i < n; i++) d[i] = 0; } +static uint64_t up(uint64_t v, uint64_t a) { return (v + a - 1) & ~(a - 1); } +static uint32_t slen(const char *s) { uint32_t n = 0; while (s[n]) n++; return n; } + +uint32_t gsp_checksum32(const uint8_t *p, uint32_t len) +{ + uint64_t x = 0; + for (uint32_t i = 0; i < len; i += 8) + x ^= rd64(p + i); + return (uint32_t)(x >> 32) ^ (uint32_t)x; +} + +/* _kgspGenerateInitArgId: up to 8 ASCII bytes, first byte most significant. */ +uint64_t gsp_init_arg_id(const char *name) +{ + uint64_t id = 0; + for (int i = 0; i < 8 && name[i]; i++) + id = (id << 8) | (uint8_t)name[i]; + return id; +} + +/* ---- arena ---- */ +int gsp_arena_init(gsp_arena *a, void *base, uint64_t pa, uint64_t cap) +{ + if (!a || !base || ((uintptr_t)base & (GSP_PAGE - 1)) || (pa & (GSP_PAGE - 1)) || pa + cap < pa) + return -1; + a->base = base; + a->pa = pa; + a->cap = cap; + a->used = 0; + return 0; +} + +/* Reserve size bytes, 4 KiB aligned, zeroed. Returns the host pointer and the PA. */ +static uint8_t *take(gsp_arena *a, uint64_t size, uint64_t *pa) +{ + uint64_t off = up(a->used, GSP_PAGE); + uint64_t sz = up(size, GSP_PAGE); + if (off < a->used || sz < size || off + sz < off || off + sz > a->cap) + return NULL; + a->used = off + sz; + bzero_(a->base + off, sz); + *pa = a->pa + off; + return a->base + off; +} + +static int fits_dma(uint64_t pa, uint64_t size, unsigned bits) +{ + if (bits >= 64) return 1; + uint64_t lim = 1ULL << bits; + return pa < lim && size <= lim - pa; +} + +/* ---- registry table (PACKED_REGISTRY_TABLE, RmPackageRegistry) ---- */ +uint32_t gsp_reg_table_size(const gsp_reg_entry *e, uint32_t n) +{ + if (n == 0 || n > GSP_REG_MAX_ENTRIES) return 0; + uint64_t size = 8 + 16ULL * n; + for (uint32_t i = 0; i < n; i++) { + if (!e[i].name || !e[i].name[0]) return 0; + if (e[i].type == GSP_REG_DWORD) { if (e[i].len) return 0; } + else if (e[i].type == GSP_REG_BINARY || e[i].type == GSP_REG_STRING) { if (!e[i].len || !e[i].bytes) return 0; } + else return 0; + size += slen(e[i].name) + 1ULL + e[i].len; + } + return size > GSP_RPC_SIZE_MAX - GSP_RPC_HDR_SIZE ? 0 : (uint32_t)size; +} + +/* Writes the table header and entry array into head (8 + 16 n bytes) and describes the whole + * table as segments: head, then per entry its NUL-terminated name and, for BINARY / STRING, the + * value bytes (the driver's string area order). Returns the segment count. */ +static uint32_t reg_write(const gsp_reg_entry *e, uint32_t n, uint32_t size, uint8_t *head, gsp_seg *segs) +{ + uint32_t ns = 0; + bzero_(head, 8 + 16 * n); + wr32(head, size); + wr32(head + 4, n); + segs[ns++] = (gsp_seg){ head, 8 + 16 * n }; + uint32_t off = 8 + 16 * n; + for (uint32_t i = 0; i < n; i++) { + uint8_t *ent = head + 8 + 16 * i; + uint32_t nl = slen(e[i].name) + 1; + wr32(ent + OFF(gsp_mirror_reg_entry, nameOffset), off); + segs[ns++] = (gsp_seg){ e[i].name, nl }; + off += nl; + ent[OFF(gsp_mirror_reg_entry, type)] = e[i].type; + if (e[i].type == GSP_REG_DWORD) { + wr32(ent + OFF(gsp_mirror_reg_entry, data), e[i].dword); + wr32(ent + OFF(gsp_mirror_reg_entry, length), 4); + } else { + wr32(ent + OFF(gsp_mirror_reg_entry, data), off); + wr32(ent + OFF(gsp_mirror_reg_entry, length), e[i].len); + segs[ns++] = (gsp_seg){ e[i].bytes, e[i].len }; + off += e[i].len; + } + } + return ns; +} + +/* ---- message queue ---- */ +#define TXH(f) OFF(gsp_mirror_msgq_tx, f) +#define RH(f) (GSP_ELEM_HDR_SIZE + OFF(gsp_mirror_rpc_hdr, f)) + +static uint32_t ring_free(uint32_t rd, uint32_t wr) { return (rd + GSP_MQ_MSG_COUNT - wr - 1) % GSP_MQ_MSG_COUNT; } + +int gsp_mq_attach(gsp_mq *q, const gsp_arena *a, const gsp_boot_plan *plan) +{ + if (!q || !a || !plan || plan->cmdq_pa < a->pa || plan->statq_pa < a->pa || + plan->statq_pa - a->pa + GSP_MQ_QUEUE_SIZE > a->used || plan->cmdq_pa - a->pa + GSP_MQ_QUEUE_SIZE > a->used) + return -1; + q->cmdq = a->base + (plan->cmdq_pa - a->pa); + q->statq = a->base + (plan->statq_pa - a->pa); + q->tx_seq = plan->tx_seq; + q->rx_seq = 0; + q->rpc_seq = 0; + return 0; +} + +/* Sequential reader over the 80-byte element+RPC header followed by the payload segments. */ +typedef struct { + const uint8_t *hdr; + const gsp_seg *segs; + uint32_t nsegs, seg, off, pos; +} cursor; + +static uint8_t next_byte(cursor *c) +{ + if (c->pos < GSP_ELEM_HDR_SIZE + GSP_RPC_HDR_SIZE) + return c->hdr[c->pos++]; + c->pos++; + while (c->seg < c->nsegs && c->off >= c->segs[c->seg].len) { c->seg++; c->off = 0; } + if (c->seg >= c->nsegs) return 0; + const uint8_t *p = c->segs[c->seg].p; + uint8_t v = p ? p[c->off] : 0; + c->off++; + return v; +} + +int gsp_mq_send(gsp_mq *q, uint32_t function, const gsp_seg *segs, uint32_t nsegs, uint32_t rpc_len, + int sync, uint32_t *sequence_out, const char **why) +{ + *why = 0; + if (!q || (nsegs && !segs)) { *why = "null argument"; return -1; } + uint64_t copy_len = 0; + for (uint32_t i = 0; i < nsegs; i++) copy_len += segs[i].len; + if (copy_len < rpc_len) { *why = "payload shorter than the RPC length"; return -1; } + uint64_t msg_len = (uint64_t)GSP_ELEM_HDR_SIZE + GSP_RPC_HDR_SIZE + rpc_len; + if (msg_len < GSP_ELEM_MIN_LEN || msg_len > GSP_ELEM_SIZE_MAX) { *why = "message length out of range"; return -1; } + uint32_t elems = (uint32_t)((msg_len + GSP_MQ_MSG_SIZE - 1) / GSP_MQ_MSG_SIZE); + uint64_t placed = (uint64_t)GSP_ELEM_HDR_SIZE + GSP_RPC_HDR_SIZE + copy_len; + if (placed > (uint64_t)elems * GSP_MQ_MSG_SIZE) { *why = "payload beyond the elements the length covers"; return -1; } + uint32_t wr = rd32(q->cmdq + TXH(writePtr)); +#ifdef GSP_MUTANT_SWAPRX + uint32_t rd = rd32(q->cmdq + GSP_MQ_RXHDR_OFF); +#else + uint32_t rd = rd32(q->statq + GSP_MQ_RXHDR_OFF); /* GSP's readPtr lives in GSP's own queue (SWAP_RX) */ +#endif + if (wr >= GSP_MQ_MSG_COUNT || rd >= GSP_MQ_MSG_COUNT) { *why = "ring pointer corrupt"; return -1; } + if (ring_free(rd, wr) < elems) { *why = "command queue full"; return -1; } + + uint32_t seq = sync ? q->rpc_seq : 0; + uint8_t hdr[GSP_ELEM_HDR_SIZE + GSP_RPC_HDR_SIZE]; + bzero_(hdr, sizeof hdr); + wr32(hdr + OFF(gsp_mirror_elem, seqNum), q->tx_seq); + wr32(hdr + OFF(gsp_mirror_elem, elemCount), elems); + wr32(hdr + RH(header_version), GSP_RPC_HEADER_VERSION); + wr32(hdr + RH(signature), GSP_RPC_SIGNATURE); + wr32(hdr + RH(length), GSP_RPC_HDR_SIZE + rpc_len); + wr32(hdr + RH(function), function); + wr32(hdr + RH(rpc_result), GSP_RPC_PENDING); + wr32(hdr + RH(rpc_result_private), GSP_RPC_PENDING); + wr32(hdr + RH(sequence), seq); + + /* _checkSum32 over msg_len, zero-padded to 8 (message_queue_cpu.c), checkSum field 0. */ + cursor c = { hdr, segs, nsegs, 0, 0, 0 }; + uint64_t x = 0; + for (uint64_t i = 0; i < up(msg_len, 8); i += 8) { + uint8_t w[8]; + for (uint32_t k = 0; k < 8; k++) { + uint8_t v = next_byte(&c); + w[k] = i + k < msg_len ? v : 0; + } + x ^= rd64(w); + } +#ifndef GSP_MUTANT_CKSUM + wr32(hdr + OFF(gsp_mirror_elem, checkSum), (uint32_t)(x >> 32) ^ (uint32_t)x); +#endif + + /* Slot e of the message gets bytes [e*4096, e*4096 + 4096): header, payload, zeros. */ + c = (cursor){ hdr, segs, nsegs, 0, 0, 0 }; + for (uint32_t e = 0; e < elems; e++) { + uint8_t *slot = q->cmdq + GSP_MQ_ENTRY_OFF + ((wr + e) % GSP_MQ_MSG_COUNT) * GSP_MQ_MSG_SIZE; + for (uint32_t k = 0; k < GSP_MQ_MSG_SIZE; k++) { + uint64_t b = (uint64_t)e * GSP_MQ_MSG_SIZE + k; + slot[k] = b < placed ? next_byte(&c) : 0; + } + } + /* message_queue_cpu.c:574-576: store fence before the writePtr publish (the doorbell after it is + * the caller's; this file writes no register). */ + __atomic_thread_fence(__ATOMIC_SEQ_CST); + wr32(q->cmdq + TXH(writePtr), (wr + elems) % GSP_MQ_MSG_COUNT); + q->tx_seq++; + if (sync) q->rpc_seq++; + if (sequence_out) *sequence_out = seq; + return 0; +} + +int gsp_rpc_rm_alloc(gsp_mq *q, uint32_t hClient, uint32_t hParent, uint32_t hObject, uint32_t hClass, + const void *params, uint32_t params_size, uint32_t *seq, const char **why) +{ + uint8_t fixed[GSP_RM_ALLOC_FIXED]; + if (params_size && !params) { *why = "null argument"; return -1; } + bzero_(fixed, sizeof fixed); + wr32(fixed + OFF(gsp_mirror_rm_alloc, hClient), hClient); + wr32(fixed + OFF(gsp_mirror_rm_alloc, hParent), hParent); + wr32(fixed + OFF(gsp_mirror_rm_alloc, hObject), hObject); + wr32(fixed + OFF(gsp_mirror_rm_alloc, hClass), hClass); + wr32(fixed + OFF(gsp_mirror_rm_alloc, paramsSize), params_size); + gsp_seg s[2] = { { fixed, sizeof fixed }, { params, params_size } }; + /* rpcRmApiAlloc_GSP: rpcWriteCommonHeader(.., sizeof(rpc_gsp_rm_alloc_v03_00)); the params + * follow outside the length. Kept as the driver does it (inventory section 14). */ +#ifdef GSP_MUTANT_ALLOCLEN + return gsp_mq_send(q, GSP_FN_GSP_RM_ALLOC, s, 2, GSP_RM_ALLOC_FIXED + params_size, 1, seq, why); +#else + return gsp_mq_send(q, GSP_FN_GSP_RM_ALLOC, s, 2, GSP_RM_ALLOC_FIXED, 1, seq, why); +#endif +} + +int gsp_rpc_rm_control(gsp_mq *q, uint32_t hClient, uint32_t hObject, uint32_t cmd, + const void *params, uint32_t params_size, uint32_t *seq, const char **why) +{ + uint8_t fixed[GSP_RM_CONTROL_FIXED]; + if (params_size && !params) { *why = "null argument"; return -1; } + if (params_size > GSP_RPC_SIZE_MAX - GSP_RPC_HDR_SIZE - GSP_RM_CONTROL_FIXED) { + *why = "control params need continuation records (not built)"; + return -1; + } + bzero_(fixed, sizeof fixed); + wr32(fixed + OFF(gsp_mirror_rm_control, hClient), hClient); + wr32(fixed + OFF(gsp_mirror_rm_control, hObject), hObject); + wr32(fixed + OFF(gsp_mirror_rm_control, cmd), cmd); + wr32(fixed + OFF(gsp_mirror_rm_control, paramsSize), params_size); + gsp_seg s[2] = { { fixed, sizeof fixed }, { params, params_size } }; + return gsp_mq_send(q, GSP_FN_GSP_RM_CONTROL, s, 2, GSP_RM_CONTROL_FIXED + params_size, 1, seq, why); +} + +int gsp_rpc_rm_free(gsp_mq *q, uint32_t hClient, uint32_t hObject, uint32_t *seq, const char **why) +{ + uint8_t buf[GSP_RM_FREE_SIZE]; + bzero_(buf, sizeof buf); + wr32(buf + OFF(gsp_mirror_rm_free, hRoot), hClient); + wr32(buf + OFF(gsp_mirror_rm_free, hObjectParent), 0); /* NV01_NULL_OBJECT */ + wr32(buf + OFF(gsp_mirror_rm_free, hObjectOld), hObject); + gsp_seg s = { buf, sizeof buf }; + return gsp_mq_send(q, GSP_FN_FREE, &s, 1, sizeof buf, 1, seq, why); +} + +int gsp_rpc_get_static_info(gsp_mq *q, uint32_t static_info_size, uint32_t *seq, const char **why) +{ + /* rpcGetGspStaticInfo_v14_00: zeroed request, length = 32 + sizeof(GspStaticConfigInfo), + * refused by the driver above maxRpcSize. The size is a parameter: the struct pulls in + * RM-internal headers that do not compile standalone (inventory section 14). */ + if (static_info_size == 0 || static_info_size > GSP_RPC_SIZE_MAX - GSP_RPC_HDR_SIZE) { + *why = "static info size out of range"; + return -1; + } + gsp_seg s = { 0, static_info_size }; + return gsp_mq_send(q, GSP_FN_GET_GSP_STATIC_INFO, &s, 1, static_info_size, 1, seq, why); +} + +int gsp_mq_recv(gsp_mq *q, uint8_t *out, uint32_t cap, uint32_t *function, uint32_t *rpc_result, + const char **why) +{ + *why = 0; + if (!q || !out) { *why = "null argument"; return -1; } + const uint8_t *tx = q->statq; + if (rd32(tx + TXH(version)) != 0 || rd32(tx + TXH(size)) != GSP_MQ_QUEUE_SIZE || + rd32(tx + TXH(msgSize)) != GSP_MQ_MSG_SIZE || rd32(tx + TXH(msgCount)) != GSP_MQ_MSG_COUNT || + rd32(tx + TXH(rxHdrOff)) < 32 || rd32(tx + TXH(entryOff)) != GSP_MQ_ENTRY_OFF) { + *why = "status queue header not the driver's shape"; + return -1; + } + uint32_t wr = rd32(tx + TXH(writePtr)); + __atomic_thread_fence(__ATOMIC_SEQ_CST); /* read the slots only after the writePtr that covers them */ + uint8_t *rdp = q->cmdq + GSP_MQ_RXHDR_OFF; /* our readPtr lives in our own queue (SWAP_RX) */ + uint32_t rd = rd32(rdp); + if (wr >= GSP_MQ_MSG_COUNT || rd >= GSP_MQ_MSG_COUNT) { *why = "ring pointer corrupt"; return -1; } + uint32_t avail = (wr + GSP_MQ_MSG_COUNT - rd) % GSP_MQ_MSG_COUNT; + if (avail == 0) return 0; + const uint8_t *first = tx + GSP_MQ_ENTRY_OFF + rd * GSP_MQ_MSG_SIZE; + uint32_t elems = rd32(first + OFF(gsp_mirror_elem, elemCount)); + uint32_t len = rd32(first + RH(length)); + if (elems == 0 || elems > avail || elems > GSP_ELEM_SIZE_MAX / GSP_MQ_MSG_SIZE) { *why = "element count bad"; return -1; } + if (len < GSP_RPC_HDR_SIZE || GSP_ELEM_HDR_SIZE + len > elems * GSP_MQ_MSG_SIZE) { *why = "rpc length bad"; return -1; } + uint32_t msg_len = GSP_ELEM_HDR_SIZE + len; + if (cap < up(msg_len, 8)) { *why = "output too small"; return -1; } + for (uint32_t b = 0; b < (uint32_t)up(msg_len, 8); b++) { + uint32_t e = b / GSP_MQ_MSG_SIZE; + out[b] = b < msg_len ? tx[GSP_MQ_ENTRY_OFF + ((rd + e) % GSP_MQ_MSG_COUNT) * GSP_MQ_MSG_SIZE + b % GSP_MQ_MSG_SIZE] : 0; + } + if (gsp_checksum32(out, (uint32_t)up(msg_len, 8)) != 0) { *why = "checksum not zero"; return -1; } + if (rd32(out + OFF(gsp_mirror_elem, seqNum)) != q->rx_seq) { *why = "bad sequence number"; return -1; } + if (rd32(out + RH(signature)) != GSP_RPC_SIGNATURE) { *why = "rpc signature bad"; return -1; } + __atomic_thread_fence(__ATOMIC_SEQ_CST); /* finish reading before handing the slots back */ + wr32(rdp, (rd + elems) % GSP_MQ_MSG_COUNT); + q->rx_seq++; + if (function) *function = rd32(out + RH(function)); + if (rpc_result) *rpc_result = rd32(out + RH(rpc_result)); + return 1; +} + +/* ---- the boot build ---- */ +#define FAIL(s) do { *why = (s); return -1; } while (0) + +int gsp_boot_build(gsp_arena *a, const gsp_boot_in *in, gsp_boot_plan *out, const char **why) +{ + *why = 0; + if (!a || !in || !out) FAIL("null argument"); + if (!in->rm_elf || !in->rm_elf_size) FAIL("GSP-RM ELF missing"); + if (!in->rm_sig || !in->rm_sig_size) FAIL("GSP-RM signature missing"); + if (!in->bootloader || in->bootloader_size != GSP_GB10B_BOOTLOADER_SIZE) FAIL("bootloader is not the GB10B GspRmBoot image size"); + if (in->bl_code_off != GSP_GB10B_BL_CODE_OFF || in->bl_data_off != GSP_GB10B_BL_DATA_OFF || + in->bl_manifest_off != GSP_GB10B_BL_MANIFEST_OFF) FAIL("bootloader descriptor offsets are not the GB10B values"); + if (!in->fmc || !in->fmc_size) FAIL("GSP-FMC image missing"); + if (!in->fmc_hash || !in->fmc_pubkey || !in->fmc_sig) FAIL("GSP-FMC hash, key or signature missing"); + if (!in->sysmem_heap_pa || (in->sysmem_heap_pa & (GSP_PAGE - 1)) || !in->sysmem_heap_size || + (in->sysmem_heap_size & (GSP_PAGE - 1))) FAIL("sysmem heap zero or not 4 KiB aligned"); + if (!in->system_info) FAIL("GspSystemInfo missing"); + uint32_t reg_size = 0; + if (in->nregs) { + if (!in->regs || !(reg_size = gsp_reg_table_size(in->regs, in->nregs))) FAIL("registry entry invalid or too large"); + } + if (in->dma_bits == 0 || in->dma_bits > 64) FAIL("dma_bits out of range"); + if (a->used) FAIL("arena not empty"); + + bzero_((uint8_t *)out, sizeof *out); + uint64_t pa; + uint8_t *p; + + /* 1. WprMeta page (filled last, needs the other addresses). */ + uint8_t *wpr = take(a, GSP_PAGE, &pa); + if (!wpr) FAIL("arena too small"); + out->wpr_meta = (gsp_region){pa, GSP_WPR_META_SIZE}; + + /* 2. libos init-argument page. */ + uint8_t *libos = take(a, GSP_PAGE, &pa); + if (!libos) FAIL("arena too small"); + out->libos_args = (gsp_region){pa, GSP_PAGE}; + + /* 3. log buffers: u64 put pointer 0, then one u64 PA per 4 KiB page. */ + for (uint32_t i = 0; i < GSP_GB10B_LOG_COUNT; i++) { + uint32_t sz = gb10b_logs[i].size; + if (!(p = take(a, sz, &pa))) FAIL("arena too small"); + for (uint32_t k = 0; k < sz / GSP_PAGE; k++) + wr64(p + 8 + 8 * k, pa + (uint64_t)k * GSP_PAGE); + out->log[i] = (gsp_region){pa, sz}; + } + + /* 4. GSP_ARGUMENTS_CACHED page. */ + uint8_t *args = take(a, GSP_PAGE, &pa); + if (!args) FAIL("arena too small"); + out->args_cached = (gsp_region){pa, GSP_PAGE}; + + /* 5. RPC shared buffer: page table, command queue, status queue. */ + uint8_t *shared = take(a, GSP_MQ_SHARED_SIZE, &pa); + if (!shared) FAIL("arena too small"); + out->rpc_shared = (gsp_region){pa, GSP_MQ_SHARED_SIZE}; + for (uint32_t k = 0; k < GSP_MQ_NUM_PTES; k++) + wr64(shared + 8 * k, pa + (uint64_t)k * GSP_PAGE); + out->cmdq_pa = pa + GSP_MQ_CMDQ_OFF; + out->statq_pa = pa + GSP_MQ_STATQ_OFF; + uint8_t *cmdq = shared + GSP_MQ_CMDQ_OFF; + wr32(cmdq + TXH(version), 0); + wr32(cmdq + TXH(size), GSP_MQ_QUEUE_SIZE); + wr32(cmdq + TXH(msgSize), GSP_MQ_MSG_SIZE); + wr32(cmdq + TXH(msgCount), GSP_MQ_MSG_COUNT); + wr32(cmdq + TXH(writePtr), 0); + wr32(cmdq + TXH(flags), GSP_MQ_FLAGS_SWAP_RX); + wr32(cmdq + TXH(rxHdrOff), GSP_MQ_RXHDR_OFF); + wr32(cmdq + TXH(entryOff), GSP_MQ_ENTRY_OFF); + + /* libos entries: logs in order, then RMARGS -> GSP_ARGUMENTS_CACHED. */ + for (uint32_t i = 0; i <= GSP_GB10B_LOG_COUNT; i++) { + uint8_t *e = libos + i * GSP_LIBOS_ENTRY_SIZE; + int rm = i == GSP_GB10B_LOG_COUNT; + wr64(e + OFF(gsp_mirror_libos_arg, id8), gsp_init_arg_id(rm ? "RMARGS" : gb10b_logs[i].id)); + wr64(e + OFF(gsp_mirror_libos_arg, pa), rm ? out->args_cached.pa : out->log[i].pa); + wr64(e + OFF(gsp_mirror_libos_arg, size), rm ? GSP_PAGE : out->log[i].size); + e[OFF(gsp_mirror_libos_arg, kind)] = GSP_LIBOS_KIND_CONTIGUOUS; + e[OFF(gsp_mirror_libos_arg, loc)] = GSP_LIBOS_LOC_SYSMEM; + } + + /* GSP_ARGUMENTS_CACHED fill. */ + wr64(args + OFF(gsp_mirror_args_cached, mq.sharedMemPhysAddr), out->rpc_shared.pa); + wr32(args + OFF(gsp_mirror_args_cached, mq.pageTableEntryCount), GSP_MQ_NUM_PTES); + wr64(args + OFF(gsp_mirror_args_cached, mq.cmdQueueOffset), GSP_MQ_CMDQ_OFF); + wr64(args + OFF(gsp_mirror_args_cached, mq.statQueueOffset), GSP_MQ_STATQ_OFF); + wr32(args + OFF(gsp_mirror_args_cached, gpuInstance), in->gpu_instance); + args[OFF(gsp_mirror_args_cached, bDmemStack)] = 1; + wr64(args + OFF(gsp_mirror_args_cached, sysmemHeapArgs.pa), in->sysmem_heap_pa); + wr64(args + OFF(gsp_mirror_args_cached, sysmemHeapArgs.size), in->sysmem_heap_size); + + /* 6. radix-3: levels 0..2 back to back, then the ELF data pages. */ + uint64_t np[4], lvl_off[4] = {0, 0, 0, 0}, n = 0; + np[3] = (in->rm_elf_size + GSP_PAGE - 1) / GSP_PAGE; + for (int i = 3; i > 0; i--) np[i - 1] = ((np[i] - 1) >> 9) + 1; + if (np[0] != 1) FAIL("ELF too large for a 3-level radix table"); + for (int i = 1; i < 4; i++) { n += np[i - 1]; lvl_off[i] = n * GSP_PAGE; } + uint64_t r3_size = n * GSP_PAGE + np[3] * GSP_PAGE; + if (!(p = take(a, r3_size, &pa))) FAIL("arena too small"); + for (int i = 0; i < 3; i++) + for (uint64_t k = 0; k < np[i + 1]; k++) +#ifdef GSP_MUTANT_RADIX + wr64(p + lvl_off[i] + k * 8, pa + lvl_off[i + 1] + (k + 1) * GSP_PAGE); +#else + wr64(p + lvl_off[i] + k * 8, pa + lvl_off[i + 1] + k * GSP_PAGE); +#endif + bcopy_(p + lvl_off[3], in->rm_elf, in->rm_elf_size); + out->radix3 = (gsp_region){pa, r3_size}; + out->radix3_root_pa = pa; + out->elf_data_pa = pa + lvl_off[3]; + for (int i = 0; i < 4; i++) out->radix3_level_pages[i] = (uint32_t)np[i]; + + /* 7. bootloader, 8. signature (size rounded up to 256), 9. FMC image. */ + if (!(p = take(a, in->bootloader_size, &pa))) FAIL("arena too small"); + bcopy_(p, in->bootloader, in->bootloader_size); + out->bootloader = (gsp_region){pa, in->bootloader_size}; + uint64_t sig_sz = up(in->rm_sig_size, 256); + if (!(p = take(a, sig_sz, &pa))) FAIL("arena too small"); + bcopy_(p, in->rm_sig, in->rm_sig_size); + out->signature = (gsp_region){pa, sig_sz}; + if (!(p = take(a, in->fmc_size, &pa))) FAIL("arena too small"); + bcopy_(p, in->fmc, in->fmc_size); + out->fmc = (gsp_region){pa, in->fmc_size}; + + /* 10. GSP_FMC_BOOT_PARAMS. */ + uint8_t *fp = take(a, GSP_PAGE, &pa); + if (!fp) FAIL("arena too small"); + out->fmc_params = (gsp_region){pa, GSP_FMC_PARAMS_SIZE}; +#define FP(f) OFF(gsp_mirror_fmc_params, f) + wr32(fp + FP(regkeys), in->fmc_regkeys); + wr32(fp + FP(boot.target), GSP_DMA_TARGET_COHERENT); /* WprMeta page is cached sysmem */ + wr32(fp + FP(boot.gspRmDescSize), GSP_WPR_META_SIZE); + wr64(fp + FP(boot.gspRmDescOffset), out->wpr_meta.pa); + fp[FP(boot.bIsGspRmBoot)] = 1; + wr32(fp + FP(rm.target), GSP_DMA_TARGET_NONCOHERENT); /* libos args page is uncached */ + wr64(fp + FP(rm.bootArgsOffset), out->libos_args.pa); + + /* WprMeta (gh100 populate + GB10B overrides; everything FMC-owned stays 0). */ + wr64(wpr + WM(magic), GSP_WPR_META_MAGIC); + wr64(wpr + WM(revision), GSP_WPR_META_REVISION); + wr64(wpr + WM(sysmemAddrOfRadix3Elf), out->radix3_root_pa); + wr64(wpr + WM(sizeOfRadix3Elf), in->rm_elf_size); + wr64(wpr + WM(sysmemAddrOfBootloader), out->bootloader.pa); + wr64(wpr + WM(sizeOfBootloader), in->bootloader_size); + wr64(wpr + WM(bootloaderCodeOffset), in->bl_code_off); + wr64(wpr + WM(bootloaderDataOffset), in->bl_data_off); + wr64(wpr + WM(bootloaderManifestOffset), in->bl_manifest_off); + wr64(wpr + WM(sysmemAddrOfSignature), out->signature.pa); + wr64(wpr + WM(sizeOfSignature), sig_sz); + wr64(wpr + WM(gspFwHeapSize), GSP_GB10B_FW_HEAP_SIZE); + + /* Every chip-visible address must fit the DMA window. */ + if (!fits_dma(a->pa, a->used, in->dma_bits) || !fits_dma(in->sysmem_heap_pa, in->sysmem_heap_size, in->dma_bits)) + FAIL("address beyond the DMA window"); + + /* Pre-boot RPCs, async (sequence 0), in kgspInitRm order. */ + gsp_mq q = { .cmdq = cmdq, .statq = shared + GSP_MQ_STATQ_OFF, .tx_seq = 0, .rx_seq = 0, .rpc_seq = 0 }; + /* The status queue is GSP's to create; until then its rx header (GSP's readPtr) is 0. */ + gsp_seg si = { in->system_info, GSP_SYSTEM_INFO_SIZE }; + if (gsp_mq_send(&q, GSP_FN_SET_SYSTEM_INFO, &si, 1, GSP_SYSTEM_INFO_SIZE, 0, 0, why)) + return -1; + if (in->nregs) { + uint8_t head[8 + 16 * GSP_REG_MAX_ENTRIES]; + gsp_seg segs[1 + 2 * GSP_REG_MAX_ENTRIES]; + uint32_t ns = reg_write(in->regs, in->nregs, reg_size, head, segs); + if (gsp_mq_send(&q, GSP_FN_SET_REGISTRY, segs, ns, reg_size, 0, 0, why)) + return -1; + } + out->tx_seq = q.tx_seq; + out->cmdq_write_ptr = rd32(cmdq + TXH(writePtr)); + + /* SEC2 packet: MCTP dword, NVDM dword (type 0x7e, vendor 0x10de, NVDM type COT 0x14), then the + * 860-byte payload; tail = padded length - 4. The MCTP dword on GB10B is the constant 1, not SOM|EOM: + * kernel_sec2.c:320 via ksec2CreateMctpHeader_HAL; on GB10B the HAL is ksec2CreateMctpHeader_539ab4 = `return 1;` (g_kernel_sec2_nvoc.c:786-788, g_kernel_sec2_nvoc.h:853-855); only GB20B/GB20C build SOM|EOM (kernel_sec2_gb20b.c:206-219). */ + uint8_t *pk = out->cot_packet; + wr32(pk, 1u); + wr32(pk + 4, 0x7eu | (0x10deu << 8) | (0x14u << 24)); + uint8_t *cot = pk + 8; +#define CO(f) OFF(gsp_mirror_cot, f) + wr16(cot + CO(version), GSP_COT_VERSION); + wr16(cot + CO(size), GSP_COT_PAYLOAD_SIZE); + wr64(cot + CO(gspFmcSysmemOffset), out->fmc.pa); + wr32(cot + CO(frtsSysmemSize), in->fmc_size); /* sic: the driver stores the FMC size here */ + bcopy_(cot + CO(hash384), in->fmc_hash, GSP_COT_HASH_SIZE); + bcopy_(cot + CO(publicKey), in->fmc_pubkey, GSP_COT_KEY_SIZE); + bcopy_(cot + CO(signature), in->fmc_sig, GSP_COT_SIG_SIZE); + wr64(cot + CO(gspBootArgsSysmemOffset), out->fmc_params.pa); + out->cot_packet_len = 8 + GSP_COT_PAYLOAD_SIZE; + out->emem_queue_tail = (uint32_t)up(out->cot_packet_len, 4) - 4; + return 0; +} diff --git a/native/kernel/dev/gb10_gsp_boot.h b/native/kernel/dev/gb10_gsp_boot.h new file mode 100644 index 00000000..d747163f --- /dev/null +++ b/native/kernel/dev/gb10_gsp_boot.h @@ -0,0 +1,266 @@ +/* gb10_gsp_boot.h -- GB10 (GB10B) GSP boot builder, cut C host side (aienos#286, L192). + * + * Freestanding C that lays out, in plain memory only, everything the pinned Linux driver + * (open-gpu-kernel-modules tag 580.173.02) hands the chip to boot GSP-RM on the GB10B through + * the SEC2-boots-GSP-FMC path, plus the RPC messages a native kernel sends afterwards. + * Nothing here touches a device: no MMIO, no register write, no firmware load, no DMA start. + * The caller decides where the arena lives and what physical address it has; this file only + * writes bytes into it and reports the addresses the chip would be given. + * + * Blocks, in arena order (every one 4 KiB aligned), with the driver function that fills each: + * GspFwWprMeta page kgspPopulateWprMeta_GH100 + _GB10B (gsp_fw_wpr_meta.h) + * libos init-argument page kgspSetupLibosInitArgs_IMPL (libos_init_args.h) + * 7 log buffers + PTE prefix kgspInitLogging / log registration + * GSP_ARGUMENTS_CACHED page kgspPopulateGspRmInitArgs_IMPL (gsp_init_args.h) + * RPC shared buffer (129 pg) GspMsgQueuesInit (message_queue_cpu.c), msgqTxCreate (msgq.c) + * radix-3 table + ELF copy kgspCreateRadix3 + * GspRmBoot bootloader copy kgspPrepareForBootstrap_GH100 + * GSP-RM signature copy kgspPrepareForBootstrap_GH100 (256-aligned, NV_ALIGN_UP 256) + * GSP-FMC image copy ksec2SetupGspImages_GB10B + * GSP_FMC_BOOT_PARAMS page kgspSetupGspFmcArgs_GH100 (gspifpub.h) + * and, outside the arena, the single SEC2 EMEM packet (MCTP + NVDM COT header + NVDM_PAYLOAD_COT) + * ksec2PrepareBootCommands_GB10B / ksec2SendMessage would write. The two RPCs the driver queues + * before boot (GSP_SET_SYSTEM_INFO 72, SET_REGISTRY 73) are placed in the command ring. + * + * docs/GB10_FIRMWARE_INVENTORY.md sections 10-14 cite the source line for every value. The hosted + * tools native/kernel/tools/ck_gsp_*_encode.c are the earlier per-block encoders; this file is + * the composed, freestanding form the kernel can link. */ +#ifndef GB10_GSP_BOOT_H +#define GB10_GSP_BOOT_H + +#include +#include + +/* ---- driver constants (580.173.02) ---- */ +#define GSP_PAGE 4096u +#define GSP_WPR_META_MAGIC 0xdc3aae21371a60b3ULL +#define GSP_WPR_META_REVISION 1ULL +#define GSP_WPR_META_SIZE 256u +#define GSP_GB10B_BOOTLOADER_SIZE 196608u +#define GSP_GB10B_BL_CODE_OFF 0xb000u +#define GSP_GB10B_BL_DATA_OFF 0xa00u +#define GSP_GB10B_BL_MANIFEST_OFF 0x0u +#define GSP_GB10B_FW_HEAP_SIZE (133ULL << 20) +#define GSP_GB10B_LOG_COUNT 7u +#define GSP_LIBOS_ENTRY_SIZE 32u +#define GSP_LIBOS_KIND_CONTIGUOUS 1u +#define GSP_LIBOS_LOC_SYSMEM 1u +#define GSP_ARGS_CACHED_SIZE 88u +#define GSP_MQ_QUEUE_SIZE 0x40000u +#define GSP_MQ_MSG_SIZE 4096u +#define GSP_MQ_NUM_PTES 129u +#define GSP_MQ_SHARED_SIZE (GSP_MQ_NUM_PTES * GSP_PAGE) +#define GSP_MQ_CMDQ_OFF GSP_PAGE +#define GSP_MQ_STATQ_OFF (GSP_PAGE + GSP_MQ_QUEUE_SIZE) +#define GSP_MQ_RXHDR_OFF 32u +#define GSP_MQ_ENTRY_OFF 4096u +#define GSP_MQ_MSG_COUNT 63u +#define GSP_MQ_FLAGS_SWAP_RX 1u +#define GSP_ELEM_HDR_SIZE 48u +#define GSP_ELEM_MIN_LEN 80u /* sizeof(GSP_MSG_QUEUE_ELEMENT) */ +#define GSP_ELEM_SIZE_MAX 65536u +#define GSP_RPC_HDR_SIZE 32u +#define GSP_RPC_SIZE_MAX (GSP_ELEM_SIZE_MAX - GSP_ELEM_HDR_SIZE) +#define GSP_RPC_HEADER_VERSION 0x03000000u +#define GSP_RPC_SIGNATURE 0x43505256u /* "VRPC" */ +#define GSP_RPC_PENDING 0xFFFFFFFFu +#define GSP_SYSTEM_INFO_SIZE 936u +#define GSP_FMC_PARAMS_SIZE 88u +#define GSP_COT_PAYLOAD_SIZE 860u +#define GSP_COT_VERSION 1u +#define GSP_COT_HASH_SIZE 48u +#define GSP_COT_KEY_SIZE 384u +#define GSP_COT_SIG_SIZE 384u +#define GSP_EMEM_CHANNEL_SIZE 1024u +#define GSP_DMA_TARGET_COHERENT 1u /* GSP_DMA_TARGET_COHERENT_SYSTEM: cached sysmem */ +#define GSP_DMA_TARGET_NONCOHERENT 2u /* GSP_DMA_TARGET_NONCOHERENT_SYSTEM: uncached */ + +/* RPC function numbers (rpc_global_enums.h) and the GSP events a native kernel reads back. */ +#define GSP_FN_FREE 10u +#define GSP_FN_GET_GSP_STATIC_INFO 65u +#define GSP_FN_CONTINUATION 71u +#define GSP_FN_SET_SYSTEM_INFO 72u +#define GSP_FN_SET_REGISTRY 73u +#define GSP_FN_GSP_RM_CONTROL 76u +#define GSP_FN_GSP_RM_ALLOC 103u +#define GSP_EV_INIT_DONE 0x1001u +#define GSP_EV_RUN_CPU_SEQUENCER 0x1002u + +/* Fixed parts of the post-init RPC payloads (g_rpc-structures.h, g_sdk-structures.h). */ +#define GSP_RM_ALLOC_FIXED 32u /* rpc_gsp_rm_alloc_v03_00 before params[] */ +#define GSP_RM_CONTROL_FIXED 40u /* rpc_gsp_rm_control_v03_00 before params[] */ +#define GSP_RM_FREE_SIZE 16u /* rpc_free_v03_00 = NVOS00_PARAMETERS_v03_00 */ + +/* Registry value kinds (PACKED_REGISTRY_TABLE). */ +#define GSP_REG_DWORD 1u +#define GSP_REG_BINARY 2u +#define GSP_REG_STRING 3u + +/* ---- natural-layout mirrors (LP64, little endian) for size/offset asserts ---- */ +typedef struct { + uint64_t magic, revision; + uint64_t sysmemAddrOfRadix3Elf, sizeOfRadix3Elf; + uint64_t sysmemAddrOfBootloader, sizeOfBootloader; + uint64_t bootloaderCodeOffset, bootloaderDataOffset, bootloaderManifestOffset; + uint64_t sysmemAddrOfSignature, sizeOfSignature; + uint64_t gspFwRsvdStart, nonWprHeapOffset, nonWprHeapSize, gspFwWprStart; + uint64_t gspFwHeapOffset, gspFwHeapSize, gspFwOffset, bootBinOffset; + uint64_t frtsOffset, frtsSize, gspFwWprEnd, fbSize; + uint64_t vgaWorkspaceOffset, vgaWorkspaceSize, bootCount; + uint64_t partitionRpcAddr; + uint16_t partitionRpcRequestOffset, partitionRpcReplyOffset; + uint32_t elfCodeOffset, elfDataOffset, elfCodeSize, elfDataSize, lsUcodeVersion; + uint8_t gspFwHeapVfPartitionCount, flags, padding[2]; + uint32_t pmuReservedSize; + uint64_t verified; +} gsp_mirror_wpr_meta; + +typedef struct { uint64_t id8, pa, size; uint8_t kind, loc; } gsp_mirror_libos_arg; + +typedef struct { + struct { uint64_t sharedMemPhysAddr; uint32_t pageTableEntryCount; uint64_t cmdQueueOffset, statQueueOffset; } mq; + struct { uint32_t oldLevel, flags; uint8_t bInPMTransition; } sr; + uint32_t gpuInstance; + uint8_t bDmemStack; + struct { uint64_t pa, size; } profilerArgs; + struct { uint64_t pa, size; } sysmemHeapArgs; +} gsp_mirror_args_cached; + +typedef struct { uint32_t version, size, msgSize, msgCount, writePtr, flags, rxHdrOff, entryOff; } gsp_mirror_msgq_tx; +typedef struct { uint32_t header_version, signature, length, function, rpc_result, rpc_result_private, sequence, cpuRmGfid; } gsp_mirror_rpc_hdr; +typedef struct { uint8_t authTag[16], aad[16]; uint32_t checkSum, seqNum, elemCount; _Alignas(8) gsp_mirror_rpc_hdr rpc; } gsp_mirror_elem; +typedef struct { uint32_t hClient, hParent, hObject, hClass, status, paramsSize, flags; uint8_t reserved[4]; } gsp_mirror_rm_alloc; +typedef struct { uint32_t hClient, hObject, cmd, status, paramsSize, rmapiRpcFlags, rmctrlFlags, rmctrlAccessRight; _Alignas(8) uint64_t reserved0; } gsp_mirror_rm_control; +typedef struct { uint32_t hRoot, hObjectParent, hObjectOld, status; } gsp_mirror_rm_free; +typedef struct { uint32_t nameOffset; uint8_t type; uint32_t data, length; } gsp_mirror_reg_entry; + +typedef struct { + uint32_t regkeys; + struct { uint32_t target, gspRmDescSize; uint64_t gspRmDescOffset, wprCarveoutOffset; uint32_t wprCarveoutSize; uint8_t bIsGspRmBoot; } boot; + struct { uint32_t target; uint64_t bootArgsOffset; } rm; + struct { uint32_t target; uint64_t payloadBufferOffset; uint32_t payloadBufferSize; } spdm; + struct { uint32_t flushSysmemAddrValLo, flushSysmemAddrValHi; } mem; +} gsp_mirror_fmc_params; + +typedef struct __attribute__((packed)) { + uint16_t version, size; + uint64_t gspFmcSysmemOffset, frtsSysmemOffset; + uint32_t frtsSysmemSize; + uint64_t frtsVidmemOffset; + uint32_t frtsVidmemSize; + uint8_t hash384[48], publicKey[384], signature[384]; + uint64_t gspBootArgsSysmemOffset; +} gsp_mirror_cot; + +/* ---- the arena: zeroed host memory whose first byte has physical address pa ---- */ +typedef struct { + uint8_t *base; + uint64_t pa; + uint64_t cap; + uint64_t used; +} gsp_arena; + +/* Fails (returns -1) on a NULL base, a base or pa that is not 4 KiB aligned, or pa + cap wrapping. */ +int gsp_arena_init(gsp_arena *a, void *base, uint64_t pa, uint64_t cap); + +typedef struct { + const char *name; /* NUL-terminated, non-empty */ + uint8_t type; /* GSP_REG_DWORD / _BINARY / _STRING */ + uint32_t dword; /* DWORD value */ + const uint8_t *bytes; /* BINARY / STRING value (STRING includes its NUL) */ + uint32_t len; +} gsp_reg_entry; + +typedef struct { + /* GSP-RM firmware: the .fwimage section and this chip's signature section (container parsed + * elsewhere, ck_gsp_fw_inspect). Copied into the arena; never modified. */ + const uint8_t *rm_elf; uint64_t rm_elf_size; + const uint8_t *rm_sig; uint32_t rm_sig_size; + /* GspRmBoot_GB10B image and its RM_RISCV_UCODE_DESC offsets (ck_gsp_bindata_extract). */ + const uint8_t *bootloader; uint32_t bootloader_size; + uint32_t bl_code_off, bl_data_off, bl_manifest_off; + /* GspRmFmcGfwProdSigned_GB10B: image, hash 48, public key 384, signature 384. */ + const uint8_t *fmc; uint32_t fmc_size; + const uint8_t *fmc_hash, *fmc_pubkey, *fmc_sig; + /* ZERO_FB sysmem heap (512 MiB on the driver), contiguous uncached; caller's carve-out. */ + uint64_t sysmem_heap_pa, sysmem_heap_size; + /* GspSystemInfo bytes (936): content comes from the real PCI/BAR/ACPI state. */ + const uint8_t *system_info; + /* Registry for SET_REGISTRY; nregs 0 = the driver's NV_WARN_NOTHING_TO_DO, RPC not queued. */ + const gsp_reg_entry *regs; uint32_t nregs; + uint32_t gpu_instance; + uint32_t fmc_regkeys; /* GSP_FMC_BOOT_PARAMS.initParams.regkeys (0 without CC/NVLink) */ + unsigned dma_bits; /* every chip-visible address must be below 1 << dma_bits */ +} gsp_boot_in; + +typedef struct { + uint64_t pa, size; +} gsp_region; + +typedef struct { + gsp_region wpr_meta, libos_args, log[GSP_GB10B_LOG_COUNT], args_cached; + gsp_region rpc_shared; /* page-table page + command queue + status queue */ + uint64_t cmdq_pa, statq_pa; + gsp_region radix3; /* levels 0..2 then the ELF data pages */ + uint64_t radix3_root_pa, elf_data_pa; + uint32_t radix3_level_pages[4]; + gsp_region bootloader, signature, fmc, fmc_params; + /* command ring state after the pre-boot RPCs (the driver's txSeqNum / writePtr) */ + uint32_t cmdq_write_ptr, tx_seq; + /* the SEC2 EMEM packet: header dword 0 (MCTP), dword 1 (NVDM COT), then the COT payload */ + uint8_t cot_packet[GSP_EMEM_CHANNEL_SIZE]; + uint32_t cot_packet_len; /* bytes written at EMEM offset 0 */ + uint32_t emem_queue_tail; /* QUEUE_TAIL value, QUEUE_HEAD = 0 */ +} gsp_boot_plan; + +/* Builds every block into the arena and the COT packet into *out. Returns 0, or -1 with *why set + * to a fixed reason string (the test oracle). On failure the arena may hold partial bytes. */ +int gsp_boot_build(gsp_arena *a, const gsp_boot_in *in, gsp_boot_plan *out, const char **why); + +/* ---- message queue over the RPC shared buffer (post-boot RPCs and status reads) ---- */ +typedef struct { + uint8_t *cmdq; /* host view of the command queue (producer: CPU) */ + uint8_t *statq; /* host view of the status queue (producer: GSP) */ + uint32_t tx_seq; /* next element seqNum on the command queue */ + uint32_t rx_seq; /* next expected seqNum on the status queue */ + uint32_t rpc_seq; /* next header sequence for synchronous RPCs */ +} gsp_mq; + +/* Attach to the queues of a built plan (arena must be the one passed to gsp_boot_build). */ +int gsp_mq_attach(gsp_mq *q, const gsp_arena *a, const gsp_boot_plan *plan); + +/* One piece of an RPC payload; p NULL means len zero bytes. */ +typedef struct { const void *p; uint32_t len; } gsp_seg; +#define GSP_REG_MAX_ENTRIES 32u /* builder bound: keeps the registry staging on a small stack */ + +/* Queue one message, streamed into the ring slot by slot (it may wrap the ring end, as + * msgqTxGetWriteBuffer allows). The payload is the segments back to back. rpc_len is the header + * length field minus 32 (what the driver passes to rpcWriteCommonHeader); the segments may be + * longer than rpc_len (the driver's GSP_RM_ALLOC leaves params outside the length) but must fit + * the elements the length covers. sync != 0 takes the next RPC sequence, 0 sends sequence 0 (the + * driver's async RPCs). Refuses a full ring. */ +int gsp_mq_send(gsp_mq *q, uint32_t function, const gsp_seg *segs, uint32_t nsegs, uint32_t rpc_len, + int sync, uint32_t *sequence_out, const char **why); + +/* Post-init RPCs, byte-for-byte as rpcRmApiAlloc_GSP / rpcRmApiControl_GSP / rpcRmApiFree_GSP / + * rpcGetGspStaticInfo_v14_00 (rpc.c) build them; all synchronous. */ +int gsp_rpc_rm_alloc(gsp_mq *q, uint32_t hClient, uint32_t hParent, uint32_t hObject, uint32_t hClass, + const void *params, uint32_t params_size, uint32_t *seq, const char **why); +int gsp_rpc_rm_control(gsp_mq *q, uint32_t hClient, uint32_t hObject, uint32_t cmd, + const void *params, uint32_t params_size, uint32_t *seq, const char **why); +int gsp_rpc_rm_free(gsp_mq *q, uint32_t hClient, uint32_t hObject, uint32_t *seq, const char **why); +int gsp_rpc_get_static_info(gsp_mq *q, uint32_t static_info_size, uint32_t *seq, const char **why); + +/* Read one status-queue message if one is waiting: checks writePtr bounds, elemCount, the zero + * checksum over 48 + rpc.length and seqNum == rx_seq, then copies 48 + rpc.length bytes to out + * and advances the CPU's readPtr (kept in the command queue at rxHdrOff, SWAP_RX). Returns 1 on a + * message, 0 when the queue is empty, -1 with *why on a corrupt queue or message. */ +int gsp_mq_recv(gsp_mq *q, uint8_t *out, uint32_t cap, uint32_t *function, uint32_t *rpc_result, + const char **why); + +/* Shared helpers, also used by the tests. */ +uint32_t gsp_checksum32(const uint8_t *p, uint32_t len); +uint64_t gsp_init_arg_id(const char *name); +uint32_t gsp_reg_table_size(const gsp_reg_entry *e, uint32_t n); + +#endif diff --git a/native/kernel/gpu/contract/gb10_chan.devc b/native/kernel/gpu/contract/gb10_chan.devc new file mode 100644 index 00000000..7bec7a49 --- /dev/null +++ b/native/kernel/gpu/contract/gb10_chan.devc @@ -0,0 +1,97 @@ +# gb10_chan.devc -- one GB10 compute channel (GPFIFO ring, USERD, instance block, doorbell) +# as a device contract (ADR 0021 devc 1, class gpu-chan; L332 rung 1). +# +# This file is the channel driver. crates/aienos-devc (branch feat/devc-gpu) compiles it into +# gen/gch_contract.c the same API as ../gpu_chan.h (ck_gpu_chan_*), swapped in with +# `make CK_GPU_CHAN_IMPL=contract test-gpu-sim` +# gen/gb10_chan.md the documentation page +# The hand-written ../gpu_chan.c (L193) stays as the reference twin; both must pass +# test_gpu_sim (225 checks) and produce the same register and memory trace. +# +# Grammar (class gpu-chan): one statement per line, "#" to end of line is a comment, +# strings in double quotes, numbers decimal or 0x hex. Steps inside create/submit/ +# teardown come from a closed list; the checker refuses unsafe orders (see gen/gb10_chan.md). + +devc 1 +device gb10-gpu-channel +prefix ck_gpu +class gpu-chan +transport pci-bar +ring-kind gpfifo + +# ---- evidence: the driver-source lines this contract is written from ---- +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/sdk/nvidia/inc/class/clc96f.h:95" "#define NVC96F_GP_ENTRY0_GET 31:2" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/sdk/nvidia/inc/class/clc96f.h:98" "#define NVC96F_GP_ENTRY1_GET_HI 7:0" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/sdk/nvidia/inc/class/clc96f.h:102" "#define NVC96F_GP_ENTRY1_LENGTH 30:10" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/sdk/nvidia/inc/class/clc96f.h:31" "NvU32 GPPut; /* GP FIFO put offset 008c-008f*/" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/blackwell/gb100/dev_vm.h:620" "#define NV_VIRTUAL_FUNCTION_DOORBELL 0x30090 /* -W-4R */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/blackwell/gb100/dev_vm.h:622" "#define NV_VIRTUAL_FUNCTION_DOORBELL_VECTOR 11:0 /* -WXUF */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/blackwell/gb100/dev_vm.h:624" "#define NV_VIRTUAL_FUNCTION_DOORBELL_RUNLIST_ID 22:16 /* -WXUF */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/blackwell/gb10b/dev_ram.h:27" "#define NV_RAMRL_ENTRY_CHAN_USERD_PTR_LO (31+0*32):(8+0*32) /* RWXUF */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/blackwell/gb10b/dev_ram.h:28" "#define NV_RAMRL_ENTRY_CHAN_USERD_PTR_HI_HW (19+1*32):(0+1*32) /* RWXUF */" +# No chip has run this contract. GB10 silicon behaviour is UNVERIFIED (L193 UNKNOWN list 1-9). +proven gpu-sim aienos-host 2026-10-21 test_gpu_sim pending + +# ---- constants (C: CK_GPU_ in the generated file) ---- +const CHID_MAX 0xFFF +const RUNLIST_INVALID 0x7F +const ENTRIES_MIN 2 +const ENTRIES_MAX 65536 +const GP_LEN_MAX 0x1FFFFF +const GP_VA_BITS 40 +const USERD_BYTES 512 +const USERD_GPPUT 0x8C +const INST_BYTES 4096 +const RAMIN_PDB_WORD 128 +const TARGET_SYS_COH 2 + +# ---- register window and registers: window NAME bar N base B size S ---- +window vf bar 0 base 0xB80000 size 0x40000 +reg vf DOORBELL 0x30090 4 wo + +# ---- packed formats: format NAME BITS then fields NAME HI:LO [place] ---- +# `place` = the value already sits at its bit position (an address); otherwise it is shifted in. +format TOKEN 32 RUNLIST_ID 22:16 VECTOR 11:0 +format GP_ENTRY 64 GET 39:2 place LEVEL 41:41 LENGTH 62:42 +format RL_USERD 64 PTR_LO 31:8 place PTR_HI 51:32 place +format RAMIN_PDB 64 TARGET 1:0 BIG_PAGE_64K 11:11 ADDR 63:12 place + +# ---- buffers the channel owns: buffer NAME size (CONST | entries xN) cache flags ---- +# The CPU writes the ring and USERD while the GPU reads them: uncached (spark-hardware-manual 4.2). +buffer GPFIFO entries x8 uncached gpu-ro +buffer USERD USERD_BYTES uncached host-polled +buffer INST INST_BYTES uncached none + +# ---- the three operations ---- +create + refuse chid > CHID_MAX else EINVAL + refuse runlist_id >= RUNLIST_INVALID else EINVAL + refuse-entries pow2 ENTRIES_MIN ENTRIES_MAX else EINVAL + alloc GPFIFO USERD INST else ENOMEM + zero GPFIFO USERD INST + store-pdb INST RAMIN_PDB_WORD RAMIN_PDB TARGET=TARGET_SYS_COH BIG_PAGE_64K=1 + token TOKEN RUNLIST_ID=runlist_id VECTOR=chid + runlist-userd RL_USERD USERD else ENOMEM + fence + bind else EBIND +end + +submit + require-open else ESTATE + require-buffer else EINVAL + require-span GP_LEN_MAX else EINVAL + require-va GP_VA_BITS else EINVAL + require-room else EFULL + ring-write GP_ENTRY GET=va LENGTH=nwords LEVEL=1 # LEVEL 1 = SUBROUTINE, as physics sets it (chip-proven there; L216) + fence + publish USERD USERD_GPPUT + fence + doorbell DOORBELL TOKEN +end + +teardown + require-open else ESTATE + disable + poll-idle + release INST USERD GPFIFO +end diff --git a/native/kernel/gpu/contract/gb10_gsp.devc b/native/kernel/gpu/contract/gb10_gsp.devc new file mode 100644 index 00000000..3ea36794 --- /dev/null +++ b/native/kernel/gpu/contract/gb10_gsp.devc @@ -0,0 +1,99 @@ +# gb10_gsp.devc -- the GB10B GSP start-up on BAR0 as a device contract (ADR 0021 devc 1, class gpu-boot; +# L332 rung 1, L346). +# +# This file is the second, independent statement of what ../gsp_mmio.c does. crates/aienos-devc +# (branch feat/devc-gpu) compiles it into +# gen/gsb_contract.c the same API as ../gsp_mmio.h (ck_gsp_mmio_boot, ck_gsp_mmio_notify), with +# its own register offsets and bits taken from the lines below, not from gsp_mmio.h +# gen/gb10_gsp_boot.md the documentation page +# The hand-written ../gsp_mmio.c stays as the reference twin. Both must pass test_gsp_mmio against the +# simulated SEC2 + GSP and produce the same register trace in every scenario of gsp_boot_trace. +# +# Grammar (class gpu-boot): one statement per line, "#" to end of line is a comment, strings in double +# quotes, numbers decimal or 0x hex. Steps in `boot` and `notify` come from a closed list; the checker +# refuses unsafe orders (see gen/gb10_gsp_boot.md). + +devc 1 +device gb10-gsp-boot +prefix ck_gsp +class gpu-boot +transport pci-bar + +# ---- evidence: the driver-source lines this contract is written from ---- +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/blackwell/gb10b/dev_sec_pri.h:27" "#define NV_PSEC_FALCON_MAILBOX0 0x00840040 /* RW-4R */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/blackwell/gb10b/dev_sec_pri.h:30" "#define NV_PSEC_FALCON_MAILBOX1 0x00840044 /* RW-4R */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/blackwell/gb10b/dev_sec_pri.h:32" "#define NV_PSEC_QUEUE_HEAD(i) (0x00840c00+(i)*8) /* RW-4A */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/blackwell/gb10b/dev_sec_pri.h:36" "#define NV_PSEC_QUEUE_TAIL(i) (0x00840c04+(i)*8) /* RW-4A */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/blackwell/gb10b/dev_sec_pri.h:40" "#define NV_PSEC_EMEMC(i) (0x00840ac0+(i)*8) /* RW-4A */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/blackwell/gb10b/dev_sec_pri.h:42" "#define NV_PSEC_EMEMC_OFFS 7:2 /* RWIVF */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/blackwell/gb10b/dev_sec_pri.h:44" "#define NV_PSEC_EMEMC_BLK 15:8 /* RWIVF */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/blackwell/gb10b/dev_sec_pri.h:46" "#define NV_PSEC_EMEMC_AINCW 24:24 /* RWIVF */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/blackwell/gb10b/dev_sec_pri.h:54" "#define NV_PSEC_EMEMD(i) (0x00840ac4+(i)*8) /* RW-4A */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/blackwell/gb10b/dev_gsp.h:27" "#define NV_PGSP 0x113fff:0x110000 /* RW--D */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/hopper/gh100/dev_falcon_v4.h:27" "#define NV_PFALCON_FALCON_MAILBOX0 0x00000040 /* RW-4R */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/hopper/gh100/dev_falcon_v4.h:30" "#define NV_PFALCON_FALCON_MAILBOX1 0x00000044 /* RW-4R */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/hopper/gh100/dev_falcon_v4.h:34" "#define NV_PFALCON_FALCON_OS 0x00000080 /* RW-4R */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/hopper/gh100/dev_falcon_v4.h:39" "#define NV_PFALCON_FALCON_HWCFG2 0x000000f4 /* R--4R */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/hopper/gh100/dev_falcon_v4.h:79" "#define NV_PFALCON_FALCON_HWCFG2_RISCV_BR_PRIV_LOCKDOWN 13:13 /* R--VF */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/ampere/ga102/dev_riscv_pri.h:27" "#define NV_FALCON2_GSP_BASE 0x00111000" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/hopper/gh100/dev_riscv_pri.h:58" "#define NV_PRISCV_RISCV_CPUCTL 0x00000388 /* RW-4R */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/hopper/gh100/dev_riscv_pri.h:68" "#define NV_PRISCV_RISCV_CPUCTL_ACTIVE_STAT 7:7 /* R-IVF */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/common/inc/swref/published/blackwell/gb20b/dev_gsp.h:33" "#define NV_PGSP_QUEUE_HEAD(i) (0x00110c00+(i)*8) /* RW-4A */" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/nvidia/src/kernel/gpu/sec2/arch/blackwell/kernel_sec2_gb10b.c:39" "#define SEC2_EMEM_CHANNEL_RM_SIZE 1024" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/nvidia/src/kernel/gpu/sec2/arch/blackwell/kernel_sec2_gb10b.c:271" "const NvU32 privErrTargetLocked = 0xBADF4100U;" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/nvidia/src/kernel/gpu/sec2/arch/blackwell/kernel_sec2_gb10b.c:272" "const NvU32 privErrTargetLockedMask = 0xFFFFFF00U;" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/nvidia/src/kernel/gpu/sec2/arch/blackwell/kernel_sec2_gb10b.c:292" "const NvU32 cmdHandlingState = 0xc001cafe;" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/nvidia/src/kernel/gpu/sec2/arch/blackwell/kernel_sec2_gb10b.c:730" "_ksec2UpdateQueueHeadTail_GB10B(pGpu, pKernelSec2, 0, paddedSize - sizeof(NvU32));" +manual "NVIDIA open-gpu-kernel-modules 580.173.02" "src/nvidia/src/kernel/gpu/gsp/arch/hopper/kernel_gsp_gh100.c:956" "kflcnRegWrite_HAL(pGpu, pKernelFalcon, NV_PFALCON_FALCON_OS, pRiscvDesc->appVersion);" +# No chip has run this contract. GB10B silicon behaviour beyond the driver source is UNVERIFIED. +proven gpu-sim aienos-host 2026-10-21 test_gsp_mmio pending + +# ---- constants (C: GSB_ in the generated file) ---- +const EMEM_CHANNEL_BYTES 1024 +const EMEM_DW_PER_BLK 64 +const SEC2_CMD_BUSY 0xc001cafe +const PRIV_LOCKED 0xBADF4100 +const PRIV_LOCKED_MASK 0xFFFFFF00 + +# ---- register windows and registers: window NAME bar N base B size S; reg WIN NAME OFF WIDTH ACCESS ---- +window sec2 bar 0 base 0x840000 size 0x1000 +window gsp bar 0 base 0x110000 size 0x4000 +reg sec2 SEC2_MAILBOX0 0x040 4 rw +reg sec2 SEC2_MAILBOX1 0x044 4 rw +reg sec2 EMEMC0 0xac0 4 rw +reg sec2 EMEMD0 0xac4 4 rw +reg sec2 QHEAD0 0xc00 4 rw +reg sec2 QTAIL0 0xc04 4 rw +reg gsp GSP_MAILBOX0 0x040 4 rw +reg gsp GSP_MAILBOX1 0x044 4 rw +reg gsp FALCON_OS 0x080 4 rw +reg gsp HWCFG2 0x0f4 4 ro +reg gsp GSP_QHEAD0 0xc00 4 rw +reg gsp CPUCTL 0x1388 4 rw + +# ---- register bits and fields: bit NAME REG N; field NAME REG HI:LO ---- +bit AINCW EMEMC0 24 +bit LOCKDOWN HWCFG2 13 +bit ACTIVE CPUCTL 7 +field OFFS EMEMC0 7:2 +field BLK EMEMC0 15:8 + +# ---- the start-up (ck_gsp_mmio_boot) ---- +boot + require-packet EMEM_CHANNEL_BYTES else E_ARG + wait-equal QHEAD0 QTAIL0 budget polls_can_send else E_BUSY + emem-send EMEMC0 EMEMD0 AINCW OFFS BLK EMEM_DW_PER_BLK else E_EMEM + post-tail QTAIL0 + doorbell QHEAD0 + wait-not SEC2_MAILBOX0 SEC2_CMD_BUSY budget polls_cmd into sec2_mb0 timeout-read SEC2_MAILBOX1 sec2_mb1 else E_SEC2 + wait-released HWCFG2 PRIV_LOCKED PRIV_LOCKED_MASK budget polls_mask into hwcfg2 else E_MASK + wait-lockdown GSP_MAILBOX0 GSP_MAILBOX1 LOCKDOWN budget polls_lockdown else E_LOCKDOWN + refuse-nonzero GSP_MAILBOX0 into gsp_mb0 else E_FMC + write FALCON_OS app_version + require-bit ACTIVE into cpuctl else E_RISCV +end + +# ---- new command-queue elements for GSP-RM (ck_gsp_mmio_notify) ---- +notify + write GSP_QHEAD0 0 +end diff --git a/native/kernel/gpu/contract/gen/gb10_gpu_channel.md b/native/kernel/gpu/contract/gen/gb10_gpu_channel.md new file mode 100644 index 00000000..379f1df3 --- /dev/null +++ b/native/kernel/gpu/contract/gen/gb10_gpu_channel.md @@ -0,0 +1,44 @@ +# gb10-gpu-channel (generated from gb10_chan.devc) + +Contract sha256 `a138c84a7dbacf025cd3ee2a600c87476f52c07395eb85bcd0238056d3e69289`. Class `gpu-chan`, transport `pci-bar`, ring `gpfifo`. +66 statements compile to 196 lines of C with the API of `native/kernel/gpu/gpu_chan.h`. + +## What the compiler refuses (class gpu-chan) + +- a doorbell before the put pointer is published, or anything after the doorbell +- no fence between the ring write and the publish, or between the publish and the doorbell +- a ring write with no room, buffer, span or address check before it +- a ring size that is not a power of two, or no ring-size check at all +- a channel or runlist bound that does not fit the doorbell token field it lands in +- an address check that differs from the width of the GPFIFO address field, a length check that differs from the length field +- memory the CPU writes while the GPU reads it (or that the CPU polls) that is GPU-cached +- a buffer never zeroed, a page-directory store before the zeroing +- binding before a fence, or anything after the bind +- teardown that frees before disable and idle, or does not release every buffer + +## Evidence + +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/sdk/nvidia/inc/class/clc96f.h:95`: "#define NVC96F_GP_ENTRY0_GET 31:2" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/sdk/nvidia/inc/class/clc96f.h:98`: "#define NVC96F_GP_ENTRY1_GET_HI 7:0" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/sdk/nvidia/inc/class/clc96f.h:102`: "#define NVC96F_GP_ENTRY1_LENGTH 30:10" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/sdk/nvidia/inc/class/clc96f.h:31`: "NvU32 GPPut; /* GP FIFO put offset 008c-008f*/" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/blackwell/gb100/dev_vm.h:620`: "#define NV_VIRTUAL_FUNCTION_DOORBELL 0x30090 /* -W-4R */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/blackwell/gb100/dev_vm.h:622`: "#define NV_VIRTUAL_FUNCTION_DOORBELL_VECTOR 11:0 /* -WXUF */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/blackwell/gb100/dev_vm.h:624`: "#define NV_VIRTUAL_FUNCTION_DOORBELL_RUNLIST_ID 22:16 /* -WXUF */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/blackwell/gb10b/dev_ram.h:27`: "#define NV_RAMRL_ENTRY_CHAN_USERD_PTR_LO (31+0*32):(8+0*32) /* RWXUF */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/blackwell/gb10b/dev_ram.h:28`: "#define NV_RAMRL_ENTRY_CHAN_USERD_PTR_HI_HW (19+1*32):(0+1*32) /* RWXUF */" + +## Proof on machines + +- gpu-sim aienos-host 2026-10-21 test_gpu_sim pending + +## Registers + +- DOORBELL at bar 0 + 0xbb0090 (4 bytes, wo) + +## Formats + +- TOKEN (32 bits): RUNLIST_ID 22:16, VECTOR 11:0 +- GP_ENTRY (64 bits): GET 39:2 (address bits in place), LEVEL 41:41, LENGTH 62:42 +- RL_USERD (64 bits): PTR_LO 31:8 (address bits in place), PTR_HI 51:32 (address bits in place) +- RAMIN_PDB (64 bits): TARGET 1:0, BIG_PAGE_64K 11:11, ADDR 63:12 (address bits in place) diff --git a/native/kernel/gpu/contract/gen/gb10_gsp_boot.md b/native/kernel/gpu/contract/gen/gb10_gsp_boot.md new file mode 100644 index 00000000..1d1a4b71 --- /dev/null +++ b/native/kernel/gpu/contract/gen/gb10_gsp_boot.md @@ -0,0 +1,84 @@ +# gb10-gsp-boot (generated from gb10_gsp.devc) + +Contract sha256 `0bc4fee8da8fa819dd3230c3f3ff9c9d4cf35476b2684676c9b3f8de55b98cc0`. Class `gpu-boot`, transport `pci-bar`. +71 statements compile to 142 lines of C with the API of `native/kernel/gpu/gsp_mmio.h`. + +## What the compiler refuses (class gpu-boot) + +- any chip access before the packet length is checked against the EMEM channel +- writing EMEM before the SEC2 channel is seen empty (HEAD equal to TAIL) +- the doorbell (HEAD) before the packet and TAIL are written, or a SEC2 write after it +- an EMEM layout where the dword offset field and the dwords-per-block constant disagree +- touching any GSP register before SEC2 releases the GSP target mask +- a write to the GSP (FALCON_OS) before the FMC error mailbox is checked +- a wait with no poll budget, or budgets out of the API's slot order +- writing a read-only register or reading a write-only one + +## Steps + +- RequirePacket { max: "EMEM_CHANNEL_BYTES", err: "E_ARG" } +- WaitEqual { a: "QHEAD0", b: "QTAIL0", budget: "polls_can_send", err: "E_BUSY" } +- EmemSend { ctrl: "EMEMC0", data: "EMEMD0", ainc: "AINCW", offs: "OFFS", blk: "BLK", per_blk: "EMEM_DW_PER_BLK", err: "E_EMEM" } +- PostTail("QTAIL0") +- Doorbell("QHEAD0") +- WaitNot { reg: "SEC2_MAILBOX0", val: "SEC2_CMD_BUSY", budget: "polls_cmd", into: "sec2_mb0", tread: Some(("SEC2_MAILBOX1", "sec2_mb1")), err: "E_SEC2" } +- WaitReleased { reg: "HWCFG2", locked: "PRIV_LOCKED", mask: "PRIV_LOCKED_MASK", budget: "polls_mask", into: "hwcfg2", err: "E_MASK" } +- WaitLockdown { mb0: "GSP_MAILBOX0", mb1: "GSP_MAILBOX1", bit: "LOCKDOWN", budget: "polls_lockdown", err: "E_LOCKDOWN" } +- RefuseNonzero { reg: "GSP_MAILBOX0", into: "gsp_mb0", err: "E_FMC" } +- Write { reg: "FALCON_OS", val: "app_version" } +- RequireBit { bit: "ACTIVE", into: "cpuctl", err: "E_RISCV" } + +## Evidence + +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/blackwell/gb10b/dev_sec_pri.h:27`: "#define NV_PSEC_FALCON_MAILBOX0 0x00840040 /* RW-4R */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/blackwell/gb10b/dev_sec_pri.h:30`: "#define NV_PSEC_FALCON_MAILBOX1 0x00840044 /* RW-4R */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/blackwell/gb10b/dev_sec_pri.h:32`: "#define NV_PSEC_QUEUE_HEAD(i) (0x00840c00+(i)*8) /* RW-4A */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/blackwell/gb10b/dev_sec_pri.h:36`: "#define NV_PSEC_QUEUE_TAIL(i) (0x00840c04+(i)*8) /* RW-4A */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/blackwell/gb10b/dev_sec_pri.h:40`: "#define NV_PSEC_EMEMC(i) (0x00840ac0+(i)*8) /* RW-4A */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/blackwell/gb10b/dev_sec_pri.h:42`: "#define NV_PSEC_EMEMC_OFFS 7:2 /* RWIVF */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/blackwell/gb10b/dev_sec_pri.h:44`: "#define NV_PSEC_EMEMC_BLK 15:8 /* RWIVF */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/blackwell/gb10b/dev_sec_pri.h:46`: "#define NV_PSEC_EMEMC_AINCW 24:24 /* RWIVF */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/blackwell/gb10b/dev_sec_pri.h:54`: "#define NV_PSEC_EMEMD(i) (0x00840ac4+(i)*8) /* RW-4A */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/blackwell/gb10b/dev_gsp.h:27`: "#define NV_PGSP 0x113fff:0x110000 /* RW--D */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/hopper/gh100/dev_falcon_v4.h:27`: "#define NV_PFALCON_FALCON_MAILBOX0 0x00000040 /* RW-4R */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/hopper/gh100/dev_falcon_v4.h:30`: "#define NV_PFALCON_FALCON_MAILBOX1 0x00000044 /* RW-4R */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/hopper/gh100/dev_falcon_v4.h:34`: "#define NV_PFALCON_FALCON_OS 0x00000080 /* RW-4R */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/hopper/gh100/dev_falcon_v4.h:39`: "#define NV_PFALCON_FALCON_HWCFG2 0x000000f4 /* R--4R */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/hopper/gh100/dev_falcon_v4.h:79`: "#define NV_PFALCON_FALCON_HWCFG2_RISCV_BR_PRIV_LOCKDOWN 13:13 /* R--VF */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/ampere/ga102/dev_riscv_pri.h:27`: "#define NV_FALCON2_GSP_BASE 0x00111000" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/hopper/gh100/dev_riscv_pri.h:58`: "#define NV_PRISCV_RISCV_CPUCTL 0x00000388 /* RW-4R */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/hopper/gh100/dev_riscv_pri.h:68`: "#define NV_PRISCV_RISCV_CPUCTL_ACTIVE_STAT 7:7 /* R-IVF */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/common/inc/swref/published/blackwell/gb20b/dev_gsp.h:33`: "#define NV_PGSP_QUEUE_HEAD(i) (0x00110c00+(i)*8) /* RW-4A */" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/nvidia/src/kernel/gpu/sec2/arch/blackwell/kernel_sec2_gb10b.c:39`: "#define SEC2_EMEM_CHANNEL_RM_SIZE 1024" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/nvidia/src/kernel/gpu/sec2/arch/blackwell/kernel_sec2_gb10b.c:271`: "const NvU32 privErrTargetLocked = 0xBADF4100U;" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/nvidia/src/kernel/gpu/sec2/arch/blackwell/kernel_sec2_gb10b.c:272`: "const NvU32 privErrTargetLockedMask = 0xFFFFFF00U;" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/nvidia/src/kernel/gpu/sec2/arch/blackwell/kernel_sec2_gb10b.c:292`: "const NvU32 cmdHandlingState = 0xc001cafe;" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/nvidia/src/kernel/gpu/sec2/arch/blackwell/kernel_sec2_gb10b.c:730`: "_ksec2UpdateQueueHeadTail_GB10B(pGpu, pKernelSec2, 0, paddedSize - sizeof(NvU32));" +- NVIDIA open-gpu-kernel-modules 580.173.02, `src/nvidia/src/kernel/gpu/gsp/arch/hopper/kernel_gsp_gh100.c:956`: "kflcnRegWrite_HAL(pGpu, pKernelFalcon, NV_PFALCON_FALCON_OS, pRiscvDesc->appVersion);" + +## Proof on machines + +- gpu-sim aienos-host 2026-10-21 test_gsp_mmio pending + +## Registers + +- SEC2_MAILBOX0 at bar 0 + 0x840040 (4 bytes, rw) +- SEC2_MAILBOX1 at bar 0 + 0x840044 (4 bytes, rw) +- EMEMC0 at bar 0 + 0x840ac0 (4 bytes, rw) +- EMEMD0 at bar 0 + 0x840ac4 (4 bytes, rw) +- QHEAD0 at bar 0 + 0x840c00 (4 bytes, rw) +- QTAIL0 at bar 0 + 0x840c04 (4 bytes, rw) +- GSP_MAILBOX0 at bar 0 + 0x110040 (4 bytes, rw) +- GSP_MAILBOX1 at bar 0 + 0x110044 (4 bytes, rw) +- FALCON_OS at bar 0 + 0x110080 (4 bytes, rw) +- HWCFG2 at bar 0 + 0x1100f4 (4 bytes, ro) +- GSP_QHEAD0 at bar 0 + 0x110c00 (4 bytes, rw) +- CPUCTL at bar 0 + 0x111388 (4 bytes, rw) + +## Bits and fields + +- AINCW: EMEMC0 bit 24 +- LOCKDOWN: HWCFG2 bit 13 +- ACTIVE: CPUCTL bit 7 +- OFFS: EMEMC0 bits 7:2 +- BLK: EMEMC0 bits 15:8 diff --git a/native/kernel/gpu/contract/gen/gch_contract.c b/native/kernel/gpu/contract/gen/gch_contract.c new file mode 100644 index 00000000..c00c0384 --- /dev/null +++ b/native/kernel/gpu/contract/gen/gch_contract.c @@ -0,0 +1,196 @@ +/* GENERATED by aienos-devc from gb10_chan.devc (sha256 a138c84a7dbacf025cd3ee2a600c87476f52c07395eb85bcd0238056d3e69289). + * Do not edit: change the contract and run `make -C native/kernel gpu-contract-gen`. + * Device gb10-gpu-channel (class gpu-chan, transport pci-bar, ring gpfifo). API: ../../gpu_chan.h (L193 twin). + * Evidence: 9 manual line(s) in the contract. */ +#include "gpu_chan.h" + +#define GCH_CHID_MAX 0xfffull +#define GCH_RUNLIST_INVALID 0x7full +#define GCH_ENTRIES_MIN 0x2ull +#define GCH_ENTRIES_MAX 0x10000ull +#define GCH_GP_LEN_MAX 0x1fffffull +#define GCH_GP_VA_BITS 0x28ull +#define GCH_USERD_BYTES 0x200ull +#define GCH_USERD_GPPUT 0x8cull +#define GCH_INST_BYTES 0x1000ull +#define GCH_RAMIN_PDB_WORD 0x80ull +#define GCH_TARGET_SYS_COH 0x2ull +#define GCH_WIN_VF 0xb80000u /* bar 0 */ +#define GCH_REG_DOORBELL_OFF (GCH_WIN_VF + 0x30090u) + +static inline uint32_t gch_enc_token(uint64_t runlist_id, uint64_t vector) +{ + return (uint32_t)(((runlist_id & 0x7full) << 16) | ((vector & 0xfffull) << 0)); +} + +static inline uint64_t gch_enc_gp_entry(uint64_t get, uint64_t level, uint64_t length) +{ + return (uint64_t)((get & 0xfffffffffcull) | ((level & 0x1ull) << 41) | ((length & 0x1fffffull) << 42)); +} + +static inline uint64_t gch_enc_rl_userd(uint64_t ptr_lo, uint64_t ptr_hi) +{ + return (uint64_t)((ptr_lo & 0xffffff00ull) | (ptr_hi & 0xfffff00000000ull)); +} + +static inline uint64_t gch_enc_ramin_pdb(uint64_t target, uint64_t big_page_64k, uint64_t addr) +{ + return (uint64_t)(((target & 0x3ull) << 0) | ((big_page_64k & 0x1ull) << 11) | (addr & 0xfffffffffffff000ull)); +} + +uint32_t ck_gpu_submit_token(uint32_t runlist_id, uint32_t chid) +{ + return gch_enc_token(runlist_id, chid); +} + +int ck_gpu_rl_userd(uint32_t out[2], uint64_t userd_pa) +{ + if ((userd_pa & 0xffull) || userd_pa >= (1ull << 52)) + return CK_GCHAN_EINVAL; + uint64_t v = gch_enc_rl_userd(userd_pa, userd_pa); + out[0] = (uint32_t)v; + out[1] = (uint32_t)(v >> 32); + return CK_GCHAN_OK; +} + +static void fence(void) +{ + __atomic_thread_fence(__ATOMIC_SEQ_CST); +} + +static void zero(uint8_t *p, uint64_t n) +{ + for (uint64_t i = 0; i < n; i++) + ((volatile uint8_t *)p)[i] = 0; +} + +static int buf_of(const struct ck_gmem *m, const struct ck_gmem_buf *b) +{ + for (uint32_t i = 0; i < CK_GMEM_MAX_BUF; i++) + if (&m->buf[i] == b) + return b->state == CK_GMEM_LIVE; + return 0; +} + +int ck_gpu_chan_create(struct ck_gpu_chan *c, struct ck_gmem *mem, const struct ck_gpu_regs *regs, + const struct ck_gpu_chan_ops *ops, void *ops_ctx, uint32_t chid, uint32_t runlist_id, + uint32_t entries) +{ + if (!c || !mem || !regs || !ops || !ops->bind || !ops->disable || !ops->is_idle) + return CK_GCHAN_EINVAL; + if (chid > GCH_CHID_MAX) + return CK_GCHAN_EINVAL; + if (runlist_id >= GCH_RUNLIST_INVALID) + return CK_GCHAN_EINVAL; + if (entries < GCH_ENTRIES_MIN || entries > GCH_ENTRIES_MAX || (entries & (entries - 1u))) + return CK_GCHAN_EINVAL; + c->open = 0; + c->mem = mem; + c->regs = regs; + c->ops = *ops; + c->ops_ctx = ops_ctx; + c->put = c->retired = 0; + c->gpfifo = c->userd = c->inst = 0; + if (ck_gmem_alloc(mem, (uint64_t)entries * 8u, CK_GMEM_UNCACHED, CK_GMEM_GPU_RO, &c->gpfifo) != CK_GMEM_OK) + goto nomem; + if (ck_gmem_alloc(mem, GCH_USERD_BYTES, CK_GMEM_UNCACHED, CK_GMEM_HOST_POLLED, &c->userd) != CK_GMEM_OK) + goto nomem; + if (ck_gmem_alloc(mem, GCH_INST_BYTES, CK_GMEM_UNCACHED, 0, &c->inst) != CK_GMEM_OK) + goto nomem; + zero(c->gpfifo->cpu, c->gpfifo->size); + zero(c->userd->cpu, c->userd->size); + zero(c->inst->cpu, c->inst->size); + { + volatile uint32_t *w = (volatile uint32_t *)c->inst->cpu; + uint64_t v = gch_enc_ramin_pdb(GCH_TARGET_SYS_COH, 1, mem->as->root_pa); + w[GCH_RAMIN_PDB_WORD] = (uint32_t)v; + w[GCH_RAMIN_PDB_WORD + 1u] = (uint32_t)(v >> 32); + } + c->d.chid = chid; + c->d.runlist_id = runlist_id; + c->d.token = ck_gpu_submit_token(runlist_id, chid); + c->d.entries = entries; + c->d.pdb = mem->as->root_pa; + c->d.gpfifo_va = c->gpfifo->gpu_va; + c->d.userd_pa = c->userd->pa; + c->d.inst_pa = c->inst->pa; + if (ck_gpu_rl_userd(c->d.rl_entry, c->userd->pa) != CK_GCHAN_OK) + goto nomem; + fence(); + if (c->ops.bind(c->ops_ctx, &c->d) != 0) { + (void)ck_gmem_free(mem, c->inst); + (void)ck_gmem_free(mem, c->userd); + (void)ck_gmem_free(mem, c->gpfifo); + return CK_GCHAN_EBIND; + } + c->open = 1; + return CK_GCHAN_OK; +nomem: + if (c->inst) + (void)ck_gmem_free(mem, c->inst); + if (c->userd) + (void)ck_gmem_free(mem, c->userd); + if (c->gpfifo) + (void)ck_gmem_free(mem, c->gpfifo); + c->gpfifo = c->userd = c->inst = 0; + return CK_GCHAN_ENOMEM; +} + +int ck_gpu_chan_submit(struct ck_gpu_chan *c, const struct ck_gmem_buf *pb, uint32_t off, uint32_t nwords) +{ + if (!c || !c->open) + return CK_GCHAN_ESTATE; + if (!buf_of(c->mem, pb)) + return CK_GCHAN_EINVAL; + if ((off & 3u) || nwords == 0 || nwords > GCH_GP_LEN_MAX) + return CK_GCHAN_EINVAL; + uint64_t span = (uint64_t)nwords * 4u; + if ((uint64_t)off > pb->size || span > pb->size - off) + return CK_GCHAN_EINVAL; + uint64_t va = pb->gpu_va + off; + if (va >= (1ull << GCH_GP_VA_BITS) || span > (1ull << GCH_GP_VA_BITS) - va) + return CK_GCHAN_EINVAL; + if (c->put - c->retired >= c->d.entries - 1u) + return CK_GCHAN_EFULL; + volatile uint64_t *ring = (volatile uint64_t *)c->gpfifo->cpu; + ring[c->put % c->d.entries] = gch_enc_gp_entry(va, 1, nwords); + c->put++; + fence(); + *(volatile uint32_t *)(c->userd->cpu + GCH_USERD_GPPUT) = c->put % c->d.entries; + fence(); + c->regs->wr(c->regs->ctx, GCH_REG_DOORBELL_OFF, c->d.token); + return CK_GCHAN_OK; +} + +void ck_gpu_chan_retire(struct ck_gpu_chan *c, uint32_t upto) +{ + if (c && upto - c->retired <= c->put - c->retired) + c->retired = upto; +} + +int ck_gpu_chan_teardown(struct ck_gpu_chan *c, uint32_t idle_budget, struct ck_gmem_buf **extra, uint32_t nextra) +{ + if (!c || !c->open) + return CK_GCHAN_ESTATE; + c->open = 0; + (void)c->ops.disable(c->ops_ctx, c->d.chid); + int idle = 0; + for (uint32_t i = 0; i < idle_budget && !idle; i++) + idle = c->ops.is_idle(c->ops_ctx, c->d.chid) != 0; + struct ck_gmem_buf *own[3] = {c->inst, c->userd, c->gpfifo}; + int rc = CK_GCHAN_OK; + for (uint32_t i = 0; i < 3; i++) { + if (!idle) + (void)ck_gmem_quarantine(c->mem, own[i]); + else if (ck_gmem_free(c->mem, own[i]) != CK_GMEM_OK) + rc = CK_GCHAN_ETIMEDOUT; + } + if (!idle) { + for (uint32_t i = 0; extra && i < nextra; i++) + if (extra[i] && extra[i]->state == CK_GMEM_LIVE) + (void)ck_gmem_quarantine(c->mem, extra[i]); + rc = CK_GCHAN_ETIMEDOUT; + } + c->inst = c->userd = c->gpfifo = 0; + return rc; +} diff --git a/native/kernel/gpu/contract/gen/gsb_contract.c b/native/kernel/gpu/contract/gen/gsb_contract.c new file mode 100644 index 00000000..cd313d02 --- /dev/null +++ b/native/kernel/gpu/contract/gen/gsb_contract.c @@ -0,0 +1,142 @@ +/* GENERATED by aienos-devc from gb10_gsp.devc (sha256 0bc4fee8da8fa819dd3230c3f3ff9c9d4cf35476b2684676c9b3f8de55b98cc0). + * Do not edit: change the contract and run `aienos-devc gen gpu/contract/gb10_gsp.devc gpu/contract/gen`. + * Device gb10-gsp-boot (class gpu-boot, transport pci-bar). API: ../../gsp_mmio.h (the hand twin is ../../gsp_mmio.c). + * Register offsets and bits below come from the contract only; gsp_mmio.h's CK_GSP_ values are not used. + * Evidence: 25 manual line(s) in the contract. */ +#include "gsp_mmio.h" + +#define GSB_EMEM_CHANNEL_BYTES 0x400u +#define GSB_EMEM_DW_PER_BLK 0x40u +#define GSB_SEC2_CMD_BUSY 0xc001cafeu +#define GSB_PRIV_LOCKED 0xbadf4100u +#define GSB_PRIV_LOCKED_MASK 0xffffff00u +#define GSB_WIN_SEC2 0x840000u /* bar 0 */ +#define GSB_WIN_GSP 0x110000u /* bar 0 */ +#define GSB_REG_SEC2_MAILBOX0 (GSB_WIN_SEC2 + 0x40u) +#define GSB_REG_SEC2_MAILBOX1 (GSB_WIN_SEC2 + 0x44u) +#define GSB_REG_EMEMC0 (GSB_WIN_SEC2 + 0xac0u) +#define GSB_REG_EMEMD0 (GSB_WIN_SEC2 + 0xac4u) +#define GSB_REG_QHEAD0 (GSB_WIN_SEC2 + 0xc00u) +#define GSB_REG_QTAIL0 (GSB_WIN_SEC2 + 0xc04u) +#define GSB_REG_GSP_MAILBOX0 (GSB_WIN_GSP + 0x40u) +#define GSB_REG_GSP_MAILBOX1 (GSB_WIN_GSP + 0x44u) +#define GSB_REG_FALCON_OS (GSB_WIN_GSP + 0x80u) +#define GSB_REG_HWCFG2 (GSB_WIN_GSP + 0xf4u) +#define GSB_REG_GSP_QHEAD0 (GSB_WIN_GSP + 0xc00u) +#define GSB_REG_CPUCTL (GSB_WIN_GSP + 0x1388u) +#define GSB_BIT_AINCW (1u << 24) +#define GSB_BIT_LOCKDOWN (1u << 13) +#define GSB_BIT_ACTIVE (1u << 7) +#define GSB_FLD_OFFS(v) (((v) >> 2) & 0x3fu) +#define GSB_FLD_BLK(v) (((v) >> 8) & 0xffu) + +static uint32_t rd(const struct ck_gpu_regs *r, uint32_t off) +{ + return r->rd(r->ctx, off); +} + +static void wr(const struct ck_gpu_regs *r, uint32_t off, uint32_t v) +{ + r->wr(r->ctx, off, v); +} + +static void between_polls(const struct ck_gsp_mmio_in *in) +{ + if (in->pause) + in->pause(in->pause_ctx); +} + +int ck_gsp_mmio_boot(const struct ck_gpu_regs *r, const struct ck_gsp_mmio_in *in, struct ck_gsp_mmio_out *o) +{ + uint32_t i, n; + + for (i = 0; i < sizeof(*o); i++) + ((uint8_t *)o)[i] = 0; + if (!r || !in || !in->packet || in->len == 0 || in->len > GSB_EMEM_CHANNEL_BYTES) + return o->stage = CK_GSP_E_ARG; + for (n = 0;; n++) { + uint32_t v = rd(r, GSB_REG_QHEAD0); + if (v == rd(r, GSB_REG_QTAIL0)) + break; + if (n >= in->polls_can_send) { + o->polls[0] = n; + return o->stage = CK_GSP_E_BUSY; + } + between_polls(in); + } + o->polls[0] = n; + wr(r, GSB_REG_EMEMC0, GSB_BIT_AINCW); + uint32_t c0 = rd(r, GSB_REG_EMEMC0); + uint32_t start = (GSB_FLD_BLK(c0) * GSB_EMEM_DW_PER_BLK + GSB_FLD_OFFS(c0)); + for (i = 0; i + 4 <= in->len; i += 4) + wr(r, GSB_REG_EMEMD0, (uint32_t)in->packet[i] | (uint32_t)in->packet[i + 1] << 8 | + (uint32_t)in->packet[i + 2] << 16 | (uint32_t)in->packet[i + 3] << 24); + if (i < in->len) { + uint32_t v = 0; + for (uint32_t k = 0; i + k < in->len; k++) + v |= (uint32_t)in->packet[i + k] << (8 * k); + wr(r, GSB_REG_EMEMD0, v); + } + o->dwords = (in->len + 3) / 4; + o->ememc_after = rd(r, GSB_REG_EMEMC0); + if ((GSB_FLD_BLK(o->ememc_after) * GSB_EMEM_DW_PER_BLK + GSB_FLD_OFFS(o->ememc_after)) - start != o->dwords) + return o->stage = CK_GSP_E_EMEM; + wr(r, GSB_REG_QTAIL0, o->dwords * 4 - 4); + wr(r, GSB_REG_QHEAD0, 0); + for (n = 0;; n++) { + o->sec2_mb0 = rd(r, GSB_REG_SEC2_MAILBOX0); + if (o->sec2_mb0 != GSB_SEC2_CMD_BUSY) + break; + if (n >= in->polls_cmd) { + o->polls[1] = n; + o->sec2_mb1 = rd(r, GSB_REG_SEC2_MAILBOX1); + return o->stage = CK_GSP_E_SEC2; + } + between_polls(in); + } + o->polls[1] = n; + for (n = 0;; n++) { + o->hwcfg2 = rd(r, GSB_REG_HWCFG2); + if (o->hwcfg2 != 0 && (o->hwcfg2 & GSB_PRIV_LOCKED_MASK) != GSB_PRIV_LOCKED) + break; + if (n >= in->polls_mask) { + o->polls[2] = n; + return o->stage = CK_GSP_E_MASK; + } + between_polls(in); + } + o->polls[2] = n; + for (n = 0;; n++) { + int args_unread = 0; + o->gsp_mb0 = rd(r, GSB_REG_GSP_MAILBOX0); + if (o->gsp_mb0 != 0 && o->gsp_mb0 == (uint32_t)in->fmc_args_pa) { + o->gsp_mb1 = rd(r, GSB_REG_GSP_MAILBOX1); + args_unread = o->gsp_mb1 == (uint32_t)(in->fmc_args_pa >> 32); + } + if (!args_unread) { + o->hwcfg2 = rd(r, GSB_REG_HWCFG2); + if (!(o->hwcfg2 & GSB_BIT_LOCKDOWN) || o->gsp_mb0 != 0) + break; + } + if (n >= in->polls_lockdown) { + o->polls[3] = n; + o->gsp_mb1 = rd(r, GSB_REG_GSP_MAILBOX1); + return o->stage = CK_GSP_E_LOCKDOWN; + } + between_polls(in); + } + o->polls[3] = n; + o->gsp_mb0 = rd(r, GSB_REG_GSP_MAILBOX0); + if (o->gsp_mb0 != 0) + return o->stage = CK_GSP_E_FMC; + wr(r, GSB_REG_FALCON_OS, in->app_version); + o->cpuctl = rd(r, GSB_REG_CPUCTL); + if (!(o->cpuctl & GSB_BIT_ACTIVE)) + return o->stage = CK_GSP_E_RISCV; + return o->stage = CK_GSP_OK; +} + +void ck_gsp_mmio_notify(const struct ck_gpu_regs *r) +{ + wr(r, GSB_REG_GSP_QHEAD0, 0x0u); +} diff --git a/native/kernel/gpu/gmmu.c b/native/kernel/gpu/gmmu.c new file mode 100644 index 00000000..d1bd2aee --- /dev/null +++ b/native/kernel/gpu/gmmu.c @@ -0,0 +1,303 @@ +/* gmmu.c -- GB10 GPU page tables over a CPU view of the GPU-visible window. + * Format and register sources: see gmmu.h. Freestanding: no libc. */ +#include "gmmu.h" + +#define PDE_ADDR_MASK 0x000FFFFFFFFFF000ull /* NV_MMU_VER3_PDE_ADDRESS 51:12 */ +#define DUAL_BIG_ADDR_MASK 0x000FFFFFFFFFFF00ull /* NV_MMU_VER3_DUAL_PDE_ADDRESS_BIG 51:8 */ +#define PTE_ADDR_MASK 0x000FFFFFFFFFF000ull /* NV_MMU_VER3_PTE_ADDRESS 51:12 */ + +/* Level layout (kgmmuFmtInitLevels_GH10X / _GB10X). Index 5 is PT_BIG, + * index 6 PT_SMALL; both hang off the PD0 dual PDE. */ +static const uint8_t lv_lo[7] = {56, 47, 38, 29, 21, 16, 12}; +static const uint8_t lv_hi[7] = {56, 55, 46, 37, 28, 20, 20}; +#define LV_PD0 4u +#define LV_BIG 5u +#define LV_SMALL 6u + +uint64_t ck_gmmu_pde(uint64_t pa, uint32_t aperture) +{ + return (pa & PDE_ADDR_MASK) | ((uint64_t)CK_GMMU_PDE_PCF_CACHED_NO_ATS << 3) | ((uint64_t)(aperture & 3u) << 1); +} + +void ck_gmmu_dual_pde(uint64_t out[2], uint64_t big_pa, uint32_t big_ap, uint64_t small_pa, uint32_t small_ap) +{ + /* Big half: APERTURE_BIG 2:1, PCF_BIG 5:3, ADDRESS_BIG 51:8 (shift 8). + * Small half: APERTURE_SMALL 66:65, PCF_SMALL 69:67, ADDRESS_SMALL 115:76 (shift 12). */ + out[0] = 0; + out[1] = 0; + if (big_ap != CK_GMMU_PDE_AP_INVALID) + out[0] = (big_pa & DUAL_BIG_ADDR_MASK) | ((uint64_t)CK_GMMU_PDE_PCF_CACHED_NO_ATS << 3) | ((uint64_t)(big_ap & 3u) << 1); + if (small_ap != CK_GMMU_PDE_AP_INVALID) + out[1] = (small_pa & PTE_ADDR_MASK) | ((uint64_t)CK_GMMU_PDE_PCF_CACHED_NO_ATS << 3) | ((uint64_t)(small_ap & 3u) << 1); +} + +uint64_t ck_gmmu_pte(uint64_t pa, uint32_t aperture, uint32_t pcf, uint32_t kind) +{ + /* VALID 0:0, APERTURE 2:1, PCF 7:3, KIND 11:8, ADDRESS 51:12, PEER_ID 63:61 = 0. */ + return 1ull | ((uint64_t)(aperture & 3u) << 1) | ((uint64_t)(pcf & 0x1Fu) << 3) | ((uint64_t)(kind & 0xFu) << 8) | + (pa & PTE_ADDR_MASK); +} + +static uint32_t lv_index(uint32_t lv, uint64_t va) +{ + uint32_t bits = (uint32_t)(lv_hi[lv] - lv_lo[lv] + 1u); + return (uint32_t)((va >> lv_lo[lv]) & ((1ull << bits) - 1ull)); +} + +static volatile uint64_t *ent(const struct ck_gmmu_as *as, uint64_t table_pa, uint32_t idx, uint32_t esize) +{ + return (volatile uint64_t *)(as->win->cpu + (table_pa - as->win->pa_base) + (uint64_t)idx * esize); +} + +static int pa_in_window(const struct ck_gpu_window *w, uint64_t pa, uint64_t size) +{ + return size != 0 && pa >= w->pa_base && pa - w->pa_base <= w->size && size <= w->size - (pa - w->pa_base); +} + +static void zero_page(const struct ck_gmmu_as *as, uint64_t pa) +{ + volatile uint64_t *p = ent(as, pa, 0, 8); + for (uint32_t i = 0; i < CK_GMMU_PT_BYTES / 8u; i++) + p[i] = 0; +} + +static int pt_alloc(struct ck_gmmu_as *as, uint64_t *pa) +{ + for (uint32_t i = 0; i < as->pt_count; i++) { + if (!as->pt_used[i]) { + as->pt_used[i] = 1; + zero_page(as, as->pt_pa[i]); + *pa = as->pt_pa[i]; + return CK_GMMU_OK; + } + } + return CK_GMMU_ENOMEM; +} + +static uint32_t pt_free_count(const struct ck_gmmu_as *as) +{ + uint32_t n = 0; + for (uint32_t i = 0; i < as->pt_count; i++) + n += as->pt_used[i] ? 0u : 1u; + return n; +} + +int ck_gmmu_as_init(struct ck_gmmu_as *as, const struct ck_gpu_window *win, uint64_t pool_pa, uint32_t pool_pages) +{ + if (!as || !win || !win->cpu || pool_pages < 2 || pool_pages > CK_GMMU_MAX_PT || (pool_pa & 0xFFFu)) + return CK_GMMU_EINVAL; + if (!pa_in_window(win, pool_pa, (uint64_t)pool_pages * CK_GMMU_PT_BYTES)) + return CK_GMMU_ERANGE; + as->win = win; + as->pt_count = pool_pages; + as->dead = 0; + for (uint32_t i = 0; i < CK_GMMU_MAX_PT; i++) { + as->pt_pa[i] = i < pool_pages ? pool_pa + (uint64_t)i * CK_GMMU_PT_BYTES : 0; + as->pt_used[i] = 0; + } + return pt_alloc(as, &as->root_pa); +} + +enum walk_r { W_FREE, W_MAPPED, W_MISSING, W_CONFLICT }; + +/* Walk to the leaf slot for `va` at page size `page`. With create=0 nothing + * is written; *miss_lv gets the first level whose table does not exist yet + * (W_MISSING). With create=1 missing tables are allocated (the caller has + * already checked the pool). *leaf is the PTE slot on W_FREE / W_MAPPED. */ +static enum walk_r walk(struct ck_gmmu_as *as, uint64_t va, uint64_t page, int create, uint32_t *miss_lv, + volatile uint64_t **leaf) +{ + uint64_t tbl = as->root_pa; + for (uint32_t lv = 0; lv < LV_PD0; lv++) { + volatile uint64_t *e = ent(as, tbl, lv_index(lv, va), 8); + uint64_t v = *e; + if (v & 1u) + return W_CONFLICT; /* a 512 MiB / 256 GiB PTE covers this VA */ + if (((v >> 1) & 3u) == CK_GMMU_PDE_AP_INVALID) { + if (!create) { + *miss_lv = lv + 1u; + return W_MISSING; + } + uint64_t npa; + if (pt_alloc(as, &npa) != CK_GMMU_OK) + return W_CONFLICT; /* unreachable: pool checked by the caller */ + *e = ck_gmmu_pde(npa, CK_GMMU_PDE_AP_SYS_COH); + v = *e; + } + tbl = v & PDE_ADDR_MASK; + } + volatile uint64_t *d = ent(as, tbl, lv_index(LV_PD0, va), 16); + uint64_t w0 = d[0], w1 = d[1]; + uint32_t big_ap = (uint32_t)((w0 >> 1) & 3u), small_ap = (uint32_t)((w1 >> 1) & 3u); + if (page == CK_GMMU_SZ_2M) { + if (w0 & 1u) { + *leaf = &d[0]; + return W_MAPPED; + } + if (big_ap || small_ap) + return W_CONFLICT; /* page tables already hang here */ + *leaf = &d[0]; + return W_FREE; + } + if (w0 & 1u) + return W_CONFLICT; /* covered by a 2 MiB PTE */ + int big = page == CK_GMMU_SZ_64K; + /* One page size per 2 MiB region: the dual PDE lets hardware walk both + * halves in parallel, and which one wins on overlap is not something + * this code wants to depend on (DOCS SILENT on overlap priority). */ +#ifndef CK_GPU_MUTANT_NO_MIXED_PAGES + if ((big && small_ap) || (!big && big_ap)) + return W_CONFLICT; +#endif + uint32_t ap = big ? big_ap : small_ap; + uint64_t pt; + if (ap == CK_GMMU_PDE_AP_INVALID) { + if (!create) { + *miss_lv = big ? LV_BIG : LV_SMALL; + return W_MISSING; + } + if (pt_alloc(as, &pt) != CK_GMMU_OK) + return W_CONFLICT; + uint64_t nd[2]; + if (big) + ck_gmmu_dual_pde(nd, pt, CK_GMMU_PDE_AP_SYS_COH, 0, CK_GMMU_PDE_AP_INVALID); + else + ck_gmmu_dual_pde(nd, 0, CK_GMMU_PDE_AP_INVALID, pt, CK_GMMU_PDE_AP_SYS_COH); + d[1] = nd[1]; + d[0] = nd[0]; + } else { + pt = big ? (w0 & DUAL_BIG_ADDR_MASK) : (w1 & PTE_ADDR_MASK); + } + volatile uint64_t *p = ent(as, pt, lv_index(big ? LV_BIG : LV_SMALL, va), 8); + *leaf = p; + return (*p & 1u) ? W_MAPPED : W_FREE; +} + +static int check_args(const struct ck_gmmu_as *as, uint64_t va, uint64_t size, uint64_t page) +{ + if (!as) + return CK_GMMU_EINVAL; + if (as->dead) + return CK_GMMU_EDEAD; + if (page != CK_GMMU_SZ_4K && page != CK_GMMU_SZ_64K && page != CK_GMMU_SZ_2M) + return CK_GMMU_EINVAL; + if (size == 0) + return CK_GMMU_EINVAL; + if ((va | size) & (page - 1u)) + return CK_GMMU_EALIGN; +#ifndef CK_GPU_MUTANT_NO_VA_BITS + if (va >= (1ull << CK_GMMU_VA_BITS) || size > (1ull << CK_GMMU_VA_BITS) - va) + return CK_GMMU_ERANGE; +#endif + return CK_GMMU_OK; +} + +int ck_gmmu_map(struct ck_gmmu_as *as, uint64_t va, uint64_t pa, uint64_t size, uint64_t page, uint32_t aperture, + uint32_t pcf) +{ + int rc = check_args(as, va, size, page); + if (rc != CK_GMMU_OK) + return rc; + if (aperture > 3u || pcf > 0x1Fu) + return CK_GMMU_EINVAL; + if (pa & (page - 1u)) + return CK_GMMU_EALIGN; +#ifndef CK_GPU_MUTANT_NO_PA_RANGE + if (pa >= (1ull << CK_GMMU_PA_BITS) || !pa_in_window(as->win, pa, size)) + return CK_GMMU_ERANGE; +#endif + + /* Dry run: every page must be free, and count the page-table pages the + * map would create. Pages run in VA order, so a table instance at level + * j (key va >> (hi_j + 1)) is counted once. */ + uint64_t last_key[7]; + for (uint32_t j = 0; j < 7; j++) + last_key[j] = ~0ull; + uint32_t need = 0; + for (uint64_t off = 0; off < size; off += page) { + uint32_t miss = 0; + volatile uint64_t *leaf = 0; + enum walk_r w = walk(as, va + off, page, 0, &miss, &leaf); +#ifndef CK_GPU_MUTANT_NO_OVERLAP + if (w == W_MAPPED || w == W_CONFLICT) +#else + if (w == W_CONFLICT) +#endif + return CK_GMMU_EBUSY; + if (w == W_MISSING) { + uint32_t last = page == CK_GMMU_SZ_2M ? LV_PD0 : (page == CK_GMMU_SZ_64K ? LV_BIG : LV_SMALL); + for (uint32_t j = miss; j <= last; j++) { + uint64_t key = (va + off) >> (lv_hi[j] + 1u); + if (key != last_key[j]) { + last_key[j] = key; + need++; + } + if (j == LV_PD0 && last == LV_SMALL) + j = LV_BIG; /* skip PT_BIG on the small path */ + } + } + } +#ifndef CK_GPU_MUTANT_NO_POOL_COUNT + if (need > pt_free_count(as)) + return CK_GMMU_ENOMEM; +#else + (void)pt_free_count(as); +#endif + + for (uint64_t off = 0; off < size; off += page) { + uint32_t miss = 0; + volatile uint64_t *leaf = 0; + enum walk_r w = walk(as, va + off, page, 1, &miss, &leaf); +#ifdef CK_GPU_MUTANT_NO_OVERLAP + if (w == W_MAPPED) + w = W_FREE; +#endif + if (w != W_FREE) + return CK_GMMU_EBUSY; /* unreachable after the dry run */ + *leaf = ck_gmmu_pte(pa + off, aperture, pcf, 0); + } + return CK_GMMU_OK; +} + +int ck_gmmu_unmap(struct ck_gmmu_as *as, uint64_t va, uint64_t size, uint64_t page) +{ + int rc = check_args(as, va, size, page); + if (rc != CK_GMMU_OK) + return rc; + for (uint64_t off = 0; off < size; off += page) { + uint32_t miss = 0; + volatile uint64_t *leaf = 0; + if (walk(as, va + off, page, 0, &miss, &leaf) != W_MAPPED) + return CK_GMMU_ENOENT; + } + for (uint64_t off = 0; off < size; off += page) { + uint32_t miss = 0; + volatile uint64_t *leaf = 0; + (void)walk(as, va + off, page, 0, &miss, &leaf); + *leaf = 0; /* VALID=0; page-table pages stay until the AS is torn down */ + } + return CK_GMMU_OK; +} + +int ck_gmmu_invalidate(struct ck_gmmu_as *as, const struct ck_gpu_regs *r, uint32_t poll_budget) +{ + if (!as || !r || !r->rd || !r->wr) + return CK_GMMU_EINVAL; + if (as->dead) + return CK_GMMU_EDEAD; + uint64_t pdb = as->root_pa >> 12; /* MMU_INVALIDATE_PDB_ADDR_ALIGNMENT 12 */ + r->wr(r->ctx, CK_GPU_REG_INVAL_PDB, (uint32_t)((pdb & 0x0FFFFFFFull) << 4) | CK_GPU_INVAL_PDB_AP_SYS); + r->wr(r->ctx, CK_GPU_REG_INVAL_UPPER, (uint32_t)((pdb >> 28) & 0xFFFFFull)); + r->wr(r->ctx, CK_GPU_REG_INVAL, CK_GPU_INVAL_ALL_VA | CK_GPU_INVAL_TRIGGER); +#ifdef CK_GPU_MUTANT_NO_INVAL_POLL + return CK_GMMU_OK; +#endif + for (uint32_t i = 0; i < poll_budget; i++) { + if (!(r->rd(r->ctx, CK_GPU_REG_INVAL) & CK_GPU_INVAL_TRIGGER)) + return CK_GMMU_OK; + } +#ifndef CK_GPU_MUTANT_NO_TIMEOUT_LATCH + as->dead = 1; +#endif + return CK_GMMU_ETIMEDOUT; +} diff --git a/native/kernel/gpu/gmmu.h b/native/kernel/gpu/gmmu.h new file mode 100644 index 00000000..6a5d0a26 --- /dev/null +++ b/native/kernel/gpu/gmmu.h @@ -0,0 +1,148 @@ +/* gmmu.h -- GB10 GPU page tables (cut D, host side), freestanding. + * + * Format source (DOCUMENTED, open-gpu-kernel-modules tag 580.173.02): for + * GB10B the driver HAL picks kgmmuFmtInitLevels_GB10X and + * kgmmuFmtInitPte/Pde_GH10X (src/nvidia/generated/g_kern_gmmu_nvoc.c, the + * "else" branch after T234D/T264D, TU/GA/AD and GH100); field layouts are + * NV_MMU_VER3_* in src/common/inc/swref/published/hopper/gh100/dev_mmu.h. + * + * 57-bit VA. PD4 [56] PD3 [55:47] PD2 [46:38] PD1 [37:29] + * PD0 [28:21] (dual 16-byte PDE: big half, small half; or a 2 MiB PTE) + * PT_BIG [20:16] (64 KiB pages) PT_SMALL [20:12] (4 KiB pages) + * + * PD1 may hold a 512 MiB PTE and PD2 a 256 GiB PTE on GB10X; this code never + * writes those (it maps 4 KiB, 64 KiB and 2 MiB pages only) but the walker + * in gpu_sim.c decodes them so a stray big PTE is still translated the way + * the format says. + * + * Names: this code calls the bit-56 level PD4 and the dual level PD0, as the + * ASCII diagram in kern_gmmu_fmt_gh10x.c does. The driver's pageLevelIdTag + * runs the other way (bit 56 is MMU_FMT_PT_SURF_ID_PD0, the dual level + * PD4); tests assert bit ranges, not names. + * + * A 2 MiB PTE sits in the low 8 bytes of the 16-byte PD0 slot, high 8 bytes + * zero: the driver's VER3 PTE descriptor (kgmmuFmtInitPte_GH10X) places its + * fields at bits 0..63 of the entry. Driver-sourced; the chip must confirm. + * + * Whether the GB10 silicon walks exactly this format is UNKNOWN until a chip + * run; it is what the pinned driver programs for it. + */ +#ifndef CK_GMMU_H +#define CK_GMMU_H + +#include + +#define CK_GMMU_VA_BITS 57u +#define CK_GMMU_PA_BITS 52u /* NV_MMU_VER3_PTE_ADDRESS 51:12 */ +#define CK_GMMU_SZ_4K 0x1000ull +#define CK_GMMU_SZ_64K 0x10000ull +#define CK_GMMU_SZ_2M 0x200000ull +#define CK_GMMU_PT_BYTES 4096u /* every level instance this code allocates */ + +/* PDE aperture (NV_MMU_VER3_PDE_APERTURE 2:1). */ +#define CK_GMMU_PDE_AP_INVALID 0u +#define CK_GMMU_PDE_AP_VIDMEM 1u +#define CK_GMMU_PDE_AP_SYS_COH 2u +#define CK_GMMU_PDE_AP_SYS_NC 3u +/* PTE aperture (NV_MMU_VER3_PTE_APERTURE 2:1); note the different numbering. */ +#define CK_GMMU_PTE_AP_VIDMEM 0u +#define CK_GMMU_PTE_AP_PEER 1u +#define CK_GMMU_PTE_AP_SYS_COH 2u +#define CK_GMMU_PTE_AP_SYS_NC 3u +/* PTE PCF (NV_MMU_VER3_PTE_PCF 7:3), the values this code uses. */ +#define CK_GMMU_PCF_RW_CACHED 0x00u /* REGULAR_RW_ATOMIC_CACHED_ACE */ +#define CK_GMMU_PCF_RW_UNCACHED 0x01u /* REGULAR_RW_ATOMIC_UNCACHED_ACE */ +#define CK_GMMU_PCF_RO_CACHED 0x04u /* REGULAR_RO_ATOMIC_CACHED_ACE */ +#define CK_GMMU_PCF_RO_UNCACHED 0x05u /* REGULAR_RO_ATOMIC_UNCACHED_ACE */ +/* PDE PCF (NV_MMU_VER3_PDE_PCF 5:3): VALID_CACHED_ATS_NOT_ALLOWED. */ +#define CK_GMMU_PDE_PCF_CACHED_NO_ATS 0x2u + +/* Entry encoders: pure bit packing, exactly the dev_mmu.h fields. */ +uint64_t ck_gmmu_pde(uint64_t pa, uint32_t aperture); +void ck_gmmu_dual_pde(uint64_t out[2], uint64_t big_pa, uint32_t big_ap, uint64_t small_pa, uint32_t small_ap); +uint64_t ck_gmmu_pte(uint64_t pa, uint32_t aperture, uint32_t pcf, uint32_t kind); + +/* The CPU's view of the GPU-visible physical window. GB10 memory is unified + * (one LPDDR5x pool); `cpu` is where the CPU sees the bytes at `pa_base`. + * The CPU address and the GPU physical address are carried as distinct + * values; nothing here assumes they are equal. */ +struct ck_gpu_window { + uint8_t *cpu; + uint64_t pa_base; + uint64_t size; +}; + +/* Register access. Offsets are absolute BAR0 offsets (the driver writes + * them window-relative through GPU_VREG_WR32; this code adds the window + * base itself). A kernel would back this with + * ck_mmio_map; the host tests back it with the simulator in gpu_sim.c. */ +struct ck_gpu_regs { + uint32_t (*rd)(void *ctx, uint32_t off); + void (*wr)(void *ctx, uint32_t off, uint32_t val); + void *ctx; +}; + +/* TLB invalidate registers as the driver programs them on GB10B + * (kgmmuCommitTlbInvalidate_GB100 + kgmmuSetPdbToInvalidate_TU102 + + * kgmmuCheckPendingInvalidates_TU102; gb100/dev_vm.h; window base + * gpuGetVirtRegPhysOffset_TU102 = DRF_BASE(NV_VIRTUAL_FUNCTION_FULL_PHYS_OFFSET)). */ +#define CK_GPU_VF_BASE 0x00B80000u +#define CK_GPU_REG_INVAL_PDB (CK_GPU_VF_BASE + 0x30A0u) +#define CK_GPU_REG_INVAL_UPPER (CK_GPU_VF_BASE + 0x30A4u) +#define CK_GPU_REG_INVAL (CK_GPU_VF_BASE + 0x30B0u) +#define CK_GPU_INVAL_ALL_VA (1u << 0) +#define CK_GPU_INVAL_ALL_PDB (1u << 1) +#define CK_GPU_INVAL_SYS_MEMBAR (1u << 6) +#define CK_GPU_INVAL_TRIGGER (1u << 31) +#define CK_GPU_INVAL_PDB_AP_SYS (1u << 1) /* MMU_INVALIDATE_PDB_APERTURE 1:1 SYS_MEM */ +/* Fields left 0 on purpose, matching the driver's plain invalidate: + * HUBTLB_ONLY, REPLAY (NONE), ACK (NONE_REQUIRED), CACHE_LEVEL (ALL), + * ALL_PDB (one PDB), INVAL_SCOPE 16:15 (ALL_TLBS; GB10B sets it through + * kgmmuSetTlbInvalidationScope_GA100), SYS_MEMBAR (set only by the Turing + * membar workaround; a stub on GB10B: g_kern_gmmu_nvoc.c). The PDB aperture for GB10 unified memory is taken as + * SYS_MEM: UNKNOWN on the chip. */ + +enum ck_gmmu_status { + CK_GMMU_OK = 0, + CK_GMMU_EINVAL, /* bad argument: size, page size, flags */ + CK_GMMU_EALIGN, /* VA, PA or size not aligned to the page size */ + CK_GMMU_ERANGE, /* VA beyond 57 bits, or PA outside the window */ + CK_GMMU_EBUSY, /* overlaps an existing mapping or a different page size */ + CK_GMMU_ENOMEM, /* page-table pool exhausted */ + CK_GMMU_ENOENT, /* unmap of a range that is not fully mapped */ + CK_GMMU_ETIMEDOUT, /* invalidate never completed */ + CK_GMMU_EDEAD, /* the address space latched a failure; refuses everything */ +}; + +#define CK_GMMU_MAX_PT 64u /* page-table pages per address space (bounded) */ + +struct ck_gmmu_as { + const struct ck_gpu_window *win; + uint64_t root_pa; /* PD4 page */ + uint64_t pt_pa[CK_GMMU_MAX_PT]; /* page-table pool, carved by the caller */ + uint8_t pt_used[CK_GMMU_MAX_PT]; + uint32_t pt_count; + uint32_t dead; /* latched after an invalidate timeout */ +}; + +/* pool_pa: CK_GMMU_MAX_PT * 4 KiB inside the window, 4 KiB aligned; pages + * are zeroed here. The first page becomes the PD4 root. */ +int ck_gmmu_as_init(struct ck_gmmu_as *as, const struct ck_gpu_window *win, uint64_t pool_pa, uint32_t pool_pages); + +/* Map [va, va+size) -> [pa, pa+size) with one page size (4K, 64K or 2M). + * Refuses: zero size, wrap, misalignment, VA >= 2^57, PA outside the window, + * any page already mapped (any size), a 2 MiB page over an existing page + * table, small/big pages under an existing 2 MiB PTE, pool exhaustion. + * All-or-nothing: on refusal no entry is left changed. */ +int ck_gmmu_map(struct ck_gmmu_as *as, uint64_t va, uint64_t pa, uint64_t size, uint64_t page, uint32_t aperture, uint32_t pcf); +/* Unmap a range mapped with `page`; refuses (no change) unless every page + * in it is mapped with that page size. Caller must invalidate after. */ +int ck_gmmu_unmap(struct ck_gmmu_as *as, uint64_t va, uint64_t size, uint64_t page); + +/* Invalidate this address space's TLB entries (ALL_VA, one PDB), + * then poll TRIGGER until clear for at most `poll_budget` reads. On timeout + * the address space latches dead (UNKNOWN whether the GPU still uses stale + * translations, so nothing mapped through it may be reused). */ +int ck_gmmu_invalidate(struct ck_gmmu_as *as, const struct ck_gpu_regs *r, uint32_t poll_budget); + +#endif diff --git a/native/kernel/gpu/gpu_chan.c b/native/kernel/gpu/gpu_chan.c new file mode 100644 index 00000000..91613b96 --- /dev/null +++ b/native/kernel/gpu/gpu_chan.c @@ -0,0 +1,182 @@ +/* gpu_chan.c -- see gpu_chan.h. Freestanding: no libc. */ +#include "gpu_chan.h" + +uint32_t ck_gpu_submit_token(uint32_t runlist_id, uint32_t chid) +{ + return ((runlist_id & 0x7Fu) << 16) | (chid & CK_GPU_CHID_MAX); +} + +int ck_gpu_rl_userd(uint32_t out[2], uint64_t userd_pa) +{ +#ifndef CK_GPU_MUTANT_NO_USERD_WIDTH + if ((userd_pa & 0xFFu) || userd_pa >= (1ull << 52)) + return CK_GCHAN_EINVAL; +#endif + out[0] = (uint32_t)userd_pa & 0xFFFFFF00u; + out[1] = (uint32_t)(userd_pa >> 32) & 0xFFFFFu; + return CK_GCHAN_OK; +} + +static void fence(void) +{ + /* physics nvrm_enqueue uses "dsb sy" around the GPPut store; on the + * kernel target this is the same full barrier. */ + __atomic_thread_fence(__ATOMIC_SEQ_CST); +} + +static void zero(uint8_t *p, uint64_t n) +{ + for (uint64_t i = 0; i < n; i++) + ((volatile uint8_t *)p)[i] = 0; +} + +int ck_gpu_chan_create(struct ck_gpu_chan *c, struct ck_gmem *mem, const struct ck_gpu_regs *regs, + const struct ck_gpu_chan_ops *ops, void *ops_ctx, uint32_t chid, uint32_t runlist_id, + uint32_t entries) +{ + if (!c || !mem || !regs || !ops || !ops->bind || !ops->disable || !ops->is_idle) + return CK_GCHAN_EINVAL; +#ifndef CK_GPU_MUTANT_NO_CHID_WIDTH + if (chid > CK_GPU_CHID_MAX || runlist_id >= CK_GPU_RUNLIST_INVALID) + return CK_GCHAN_EINVAL; +#endif + if (entries < 2 || entries > 65536u || (entries & (entries - 1u))) + return CK_GCHAN_EINVAL; + c->open = 0; + c->mem = mem; + c->regs = regs; + c->ops = *ops; + c->ops_ctx = ops_ctx; + c->put = c->retired = 0; + c->gpfifo = c->userd = c->inst = 0; + + /* Ring and USERD are written by the CPU while the GPU reads them, so + * GPU-uncached (spark-hardware-manual 4.2); USERD is also host-polled + * state in general. */ + if (ck_gmem_alloc(mem, (uint64_t)entries * 8u, CK_GMEM_UNCACHED, CK_GMEM_GPU_RO, &c->gpfifo) != CK_GMEM_OK) + goto nomem; + if (ck_gmem_alloc(mem, CK_GPU_USERD_BYTES, CK_GMEM_UNCACHED, CK_GMEM_HOST_POLLED, &c->userd) != CK_GMEM_OK) + goto nomem; + if (ck_gmem_alloc(mem, CK_GPU_INST_BYTES, CK_GMEM_UNCACHED, 0, &c->inst) != CK_GMEM_OK) + goto nomem; + zero(c->gpfifo->cpu, c->gpfifo->size); + zero(c->userd->cpu, c->userd->size); + zero(c->inst->cpu, c->inst->size); +#ifndef CK_GPU_MUTANT_NO_INST_PDB + /* The channel's address space, as kgmmuInstBlkPageDirBaseGet_GP100 writes it. + * FAULT_REPLAY_* and VOL stay 0 (replay disabled, non-volatile). */ + volatile uint32_t *ramin = (volatile uint32_t *)c->inst->cpu; + uint64_t pdb = mem->as->root_pa; + ramin[CK_GPU_RAMIN_PDB_WORD] = ((uint32_t)pdb & 0xFFFFF000u) | CK_GPU_RAMIN_BIG_PAGE_64K | CK_GPU_RAMIN_TARGET_SYS_COH; + /* USE_NEW_PT_FORMAT (bit 10) stays FALSE: GP100 sets it only for GMMU_FMT_VERSION_2 + * and GB10B uses VERSION_3 (kern_gmmu_gp100.c:165, kern_gmmu_fmt_gh10x.c). */ + ramin[CK_GPU_RAMIN_PDB_WORD + 1u] = (uint32_t)(pdb >> 32); +#endif + + c->d.chid = chid; + c->d.runlist_id = runlist_id; + c->d.token = ck_gpu_submit_token(runlist_id, chid); + c->d.entries = entries; + c->d.pdb = mem->as->root_pa; + c->d.gpfifo_va = c->gpfifo->gpu_va; + c->d.userd_pa = c->userd->pa; + c->d.inst_pa = c->inst->pa; + if (ck_gpu_rl_userd(c->d.rl_entry, c->userd->pa) != CK_GCHAN_OK) + goto nomem; + fence(); + if (c->ops.bind(c->ops_ctx, &c->d) != 0) { + (void)ck_gmem_free(mem, c->inst); + (void)ck_gmem_free(mem, c->userd); + (void)ck_gmem_free(mem, c->gpfifo); + return CK_GCHAN_EBIND; + } + c->open = 1; + return CK_GCHAN_OK; +nomem: + if (c->inst) + (void)ck_gmem_free(mem, c->inst); + if (c->userd) + (void)ck_gmem_free(mem, c->userd); + if (c->gpfifo) + (void)ck_gmem_free(mem, c->gpfifo); + c->gpfifo = c->userd = c->inst = 0; + return CK_GCHAN_ENOMEM; +} + +static int buf_of(const struct ck_gmem *m, const struct ck_gmem_buf *b) +{ + for (uint32_t i = 0; i < CK_GMEM_MAX_BUF; i++) + if (&m->buf[i] == b) + return b->state == CK_GMEM_LIVE; + return 0; +} + +int ck_gpu_chan_submit(struct ck_gpu_chan *c, const struct ck_gmem_buf *pb, uint32_t off, uint32_t nwords) +{ + if (!c || !c->open) + return CK_GCHAN_ESTATE; + if (!buf_of(c->mem, pb)) + return CK_GCHAN_EINVAL; + if ((off & 3u) || nwords == 0 || nwords > CK_GPU_GP_LEN_MAX) + return CK_GCHAN_EINVAL; + uint64_t span = (uint64_t)nwords * 4u; + if ((uint64_t)off > pb->size || span > pb->size - off) + return CK_GCHAN_EINVAL; + uint64_t va = pb->gpu_va + off; +#ifndef CK_GPU_MUTANT_NO_GP_VA40 + if (va >= CK_GPU_GP_VA_LIMIT || span > CK_GPU_GP_VA_LIMIT - va) + return CK_GCHAN_EINVAL; /* GP_ENTRY1_GET_HI is 8 bits: 40-bit pushbuffer address */ +#endif +#ifndef CK_GPU_MUTANT_NO_RING_FULL + if (c->put - c->retired >= c->d.entries - 1u) + return CK_GCHAN_EFULL; +#endif + + volatile uint64_t *ring = (volatile uint64_t *)c->gpfifo->cpu; + ring[c->put % c->d.entries] = ck_gpu_gp_entry(va, nwords); + c->put++; + fence(); + *(volatile uint32_t *)(c->userd->cpu + CK_GPU_USERD_GPPUT) = c->put % c->d.entries; + fence(); + c->regs->wr(c->regs->ctx, CK_GPU_REG_DOORBELL, c->d.token); + return CK_GCHAN_OK; +} + +void ck_gpu_chan_retire(struct ck_gpu_chan *c, uint32_t upto) +{ + /* Same wrap-safe rule as physics nvrm_retire: only move forward, never past put. */ + if (c && upto - c->retired <= c->put - c->retired) + c->retired = upto; +} + +int ck_gpu_chan_teardown(struct ck_gpu_chan *c, uint32_t idle_budget, struct ck_gmem_buf **extra, uint32_t nextra) +{ + if (!c || !c->open) + return CK_GCHAN_ESTATE; + c->open = 0; +#ifndef CK_GPU_MUTANT_NO_DISABLE + (void)c->ops.disable(c->ops_ctx, c->d.chid); +#endif + int idle = 0; + for (uint32_t i = 0; i < idle_budget && !idle; i++) + idle = c->ops.is_idle(c->ops_ctx, c->d.chid) != 0; +#ifdef CK_GPU_MUTANT_NO_IDLE_QUARANTINE + idle = 1; +#endif + struct ck_gmem_buf *own[3] = {c->inst, c->userd, c->gpfifo}; + int rc = CK_GCHAN_OK; + for (uint32_t i = 0; i < 3; i++) { + if (!idle) + (void)ck_gmem_quarantine(c->mem, own[i]); + else if (ck_gmem_free(c->mem, own[i]) != CK_GMEM_OK) + rc = CK_GCHAN_ETIMEDOUT; /* free failed (invalidate timeout or dead address space): ck_gmem quarantined it */ + } + if (!idle) { + for (uint32_t i = 0; extra && i < nextra; i++) + if (extra[i] && extra[i]->state == CK_GMEM_LIVE) + (void)ck_gmem_quarantine(c->mem, extra[i]); + rc = CK_GCHAN_ETIMEDOUT; + } + c->gpfifo = c->userd = c->inst = 0; + return rc; +} diff --git a/native/kernel/gpu/gpu_chan.h b/native/kernel/gpu/gpu_chan.h new file mode 100644 index 00000000..b50bb1da --- /dev/null +++ b/native/kernel/gpu/gpu_chan.h @@ -0,0 +1,131 @@ +/* gpu_chan.h -- one GB10 compute channel's memory and doorbell (cut D, host + * side), freestanding. + * + * DOCUMENTED (open-gpu-kernel-modules 580.173.02): + * - GPFIFO entry: 8 bytes, NVC96F_GP_ENTRY0_GET 31:2, GP_ENTRY1_GET_HI 7:0, + * LEVEL 9:9, LENGTH 30:10 (class/clc96f.h). So the pushbuffer address + * field is 40 bits and the length 21 bits. + * - USERD: Nvc96fControl, GPPut at byte 0x8c, 512 bytes (clc96f.h). It has + * no GPGet, so consumption is tracked by the caller (as physics does). + * - Runlist entry USERD pointer on GB10B: NV_RAMRL_ENTRY_CHAN_USERD_PTR_LO + * 31:8 of word 0, USERD_PTR_HI_HW 19:0 of word 1 + * (swref/published/blackwell/gb10b/dev_ram.h, checked by + * kchannelIsUserdAddrSizeValid_GB10B). + * - Work-submit token: kfifoGenerateWorkSubmitTokenHal_GB100 (the HAL GB10B + * gets): DOORBELL_RUNLIST_ID 22:16 = runlist id, DOORBELL_VECTOR 11:0 = + * channel id (blackwell/gb100/dev_vm.h). RUNLIST_ID 0x7F is INVALID. + * - Doorbell register: NV_VIRTUAL_FUNCTION_DOORBELL at 0x30090 in the VF + * space (gb100/dev_vm.h); usermode class NVC361_NOTIFY_CHANNEL_PENDING is + * the same 0x90 inside the 0x30000 usermode page. + * - Instance block size 4096 (NV_RAMIN_ALLOC_SIZE, ampere/ga100/dev_ram.h). + * - Instance block page directory: for GB10B the driver uses + * kgmmuInstBlkPageDirBaseGet_GV100 -> _GP100 (kern_gmmu_gp100.c): word 128 = + * TARGET 1:0 | VOL 2 | FAULT_REPLAY_TEX 4 | FAULT_REPLAY_GCC 5 | + * USE_NEW_PT_FORMAT 10 (TRUE only for format VERSION_2, so FALSE on GB10B) | + * BIG_PAGE_SIZE 11 (1 = 64 KiB) | LO 31:12 = pa >> 12; + * word 129 = HI = pa >> 32 (pascal/gp100 and volta/gv100 dev_ram.h). Driver + * behaviour, DOCUMENTED; that the GB10 silicon reads it there is UNVERIFIED. + * + * UNKNOWN for GB10B (no public header): the subcontext PDB table + * (NV_RAMIN_SC_* exists on GV100; which entries GB10B needs is not + * checked here), the rest of the instance block, the other runlist-entry words, the USERD target/aperture bits, + * and how the channel is made runnable. On GB10 RM asks GSP to do that + * (channel allocation RPC); here it is the `bind` op, filled by the + * simulator in tests and by the GSP lane (L192) on hardware. + * + * Encoders carried bit-identical from physics (aien-spark/physics + * nvrm/nvrm.h:135 nvrm_mthd, nvrm/nvrm.c:809 nvrm_gp_entry): they live in a + * Linux-only header there and Omega has not moved them to a shared header + * yet (dependency map cut A). Keep them byte-for-byte equal. */ +#ifndef CK_GPU_CHAN_H +#define CK_GPU_CHAN_H + +#include +#include "gmmu.h" +#include "gpu_mem.h" + +/* nvrm_mthd: incrementing method header (bits 31:29 = 1, INC_METHOD). */ +static inline uint32_t ck_gpu_mthd(uint32_t subc, uint32_t mthd, uint32_t count) +{ + return (2u << 28) | (count << 16) | (subc << 13) | (mthd >> 2); +} + +/* nvrm_gp_entry: GET/GET_HI = va, LEVEL bit (41) set as physics does, + * LENGTH = nwords. Callers must check va < 2^40 and nwords <= 0x1fffff + * (ck_gpu_chan_submit does). */ +static inline uint64_t ck_gpu_gp_entry(uint64_t va, uint32_t nwords) +{ + return (va & ~3ull) | ((uint64_t)(nwords & 0x1fffff) << 42) | (1ull << 41); +} + +#define CK_GPU_GP_VA_LIMIT (1ull << 40) +#define CK_GPU_GP_LEN_MAX 0x1fffffu +#define CK_GPU_USERD_BYTES 512u +#define CK_GPU_USERD_GPPUT 0x8cu +#define CK_GPU_INST_BYTES 4096u +#define CK_GPU_RAMIN_PDB_WORD 128u +#define CK_GPU_RAMIN_TARGET_SYS_COH 2u +#define CK_GPU_RAMIN_NEW_PT_FORMAT (1u << 10) +#define CK_GPU_RAMIN_BIG_PAGE_64K (1u << 11) +#define CK_GPU_REG_DOORBELL (CK_GPU_VF_BASE + 0x30090u) +#define CK_GPU_CHID_MAX 0xFFFu +#define CK_GPU_RUNLIST_INVALID 0x7Fu + +uint32_t ck_gpu_submit_token(uint32_t runlist_id, uint32_t chid); +/* Encode the USERD pointer words of a runlist channel entry. Refuses a + * pointer that is not 256-byte aligned or does not fit 52 bits. Other bits + * of the entry are UNKNOWN on GB10B and left zero. */ +int ck_gpu_rl_userd(uint32_t out[2], uint64_t userd_pa); + +/* What the device side needs to make the channel runnable (what a GSP + * channel-allocation request would carry). */ +struct ck_gpu_chan_desc { + uint32_t chid, runlist_id, token, entries; + uint64_t pdb; /* PD4 physical address of the channel's address space */ + uint64_t gpfifo_va; /* GPU VA of the ring */ + uint64_t userd_pa, inst_pa; + uint32_t rl_entry[2]; +}; + +struct ck_gpu_chan_ops { + int (*bind)(void *ctx, const struct ck_gpu_chan_desc *d); + int (*disable)(void *ctx, uint32_t chid); + int (*is_idle)(void *ctx, uint32_t chid); +}; + +enum ck_gpu_chan_status { + CK_GCHAN_OK = 0, + CK_GCHAN_EINVAL, + CK_GCHAN_ENOMEM, + CK_GCHAN_ESTATE, /* not open, or faulted */ + CK_GCHAN_EFULL, /* ring full: retire first */ + CK_GCHAN_EBIND, /* device refused the channel */ + CK_GCHAN_ETIMEDOUT, /* teardown: never idle; memory quarantined */ +}; + +struct ck_gpu_chan { + struct ck_gmem *mem; + const struct ck_gpu_regs *regs; + struct ck_gpu_chan_ops ops; + void *ops_ctx; + struct ck_gpu_chan_desc d; + struct ck_gmem_buf *gpfifo, *userd, *inst; + uint32_t put, retired; + uint32_t open; +}; + +/* entries: power of two, 2..65536. */ +int ck_gpu_chan_create(struct ck_gpu_chan *c, struct ck_gmem *mem, const struct ck_gpu_regs *regs, + const struct ck_gpu_chan_ops *ops, void *ops_ctx, uint32_t chid, uint32_t runlist_id, + uint32_t entries); +/* Queue nwords of pb starting at byte off, publish GPPut, ring the doorbell. + * pb must be a live buffer of the same allocator. */ +int ck_gpu_chan_submit(struct ck_gpu_chan *c, const struct ck_gmem_buf *pb, uint32_t off, uint32_t nwords); +/* The caller saw entries up to `upto` complete (e.g. a semaphore it polled). */ +void ck_gpu_chan_retire(struct ck_gpu_chan *c, uint32_t upto); +/* Disable, wait for idle at most idle_budget polls. Idle: free the ring, + * USERD and instance block. Not idle: quarantine them and every buffer in + * extra[] (pushbuffers, semaphores the GPU may still write). */ +int ck_gpu_chan_teardown(struct ck_gpu_chan *c, uint32_t idle_budget, struct ck_gmem_buf **extra, uint32_t nextra); + +#endif diff --git a/native/kernel/gpu/gpu_mem.c b/native/kernel/gpu/gpu_mem.c new file mode 100644 index 00000000..4854590f --- /dev/null +++ b/native/kernel/gpu/gpu_mem.c @@ -0,0 +1,145 @@ +/* gpu_mem.c -- see gpu_mem.h. Freestanding: no libc. */ +#include "gpu_mem.h" + +int ck_gmem_init(struct ck_gmem *m, struct ck_gmmu_as *as, const struct ck_gpu_regs *regs, uint32_t poll_budget, + uint64_t pa_base, uint32_t pages, uint64_t va_base) +{ + if (!m || !as || !as->win || !regs || pages == 0 || pages > CK_GMEM_MAX_PAGES || (pa_base & (CK_GMEM_PAGE - 1u)) || + (va_base & (CK_GMMU_SZ_2M - 1u)) || poll_budget == 0) + return CK_GMEM_EINVAL; + const struct ck_gpu_window *w = as->win; + uint64_t bytes = (uint64_t)pages * CK_GMEM_PAGE; + if (pa_base < w->pa_base || pa_base - w->pa_base > w->size || bytes > w->size - (pa_base - w->pa_base)) + return CK_GMEM_EINVAL; + if (va_base >= (1ull << CK_GMMU_VA_BITS) || bytes > (1ull << CK_GMMU_VA_BITS) - va_base) + return CK_GMEM_EINVAL; + /* The page-table pool must not overlap the data pages. */ + for (uint32_t i = 0; i < as->pt_count; i++) + if (as->pt_pa[i] + CK_GMMU_PT_BYTES > pa_base && as->pt_pa[i] < pa_base + bytes) + return CK_GMEM_EINVAL; + m->as = as; + m->regs = regs; + m->poll_budget = poll_budget; + m->pa_base = pa_base; + m->va_base = va_base; + m->pages = pages; + for (uint32_t i = 0; i < CK_GMEM_MAX_PAGES; i++) + m->page_state[i] = CK_GMEM_FREE; + for (uint32_t i = 0; i < CK_GMEM_MAX_BUF; i++) { + m->buf[i].state = CK_GMEM_FREE; + m->buf[i].gen = 0; + } + return CK_GMEM_OK; +} + +static int live_buf(const struct ck_gmem *m, const struct ck_gmem_buf *b) +{ + if (!m || !b || b < &m->buf[0] || b >= &m->buf[CK_GMEM_MAX_BUF]) + return 0; + return (uint64_t)((const uint8_t *)b - (const uint8_t *)&m->buf[0]) % sizeof(m->buf[0]) == 0 && + b->state == CK_GMEM_LIVE; +} + +static void set_pages(struct ck_gmem *m, const struct ck_gmem_buf *b, uint8_t st) +{ + uint32_t first = (uint32_t)((b->pa - m->pa_base) / CK_GMEM_PAGE); + uint32_t n = (uint32_t)(b->size / CK_GMEM_PAGE); + for (uint32_t i = 0; i < n; i++) + m->page_state[first + i] = st; +} + +int ck_gmem_alloc(struct ck_gmem *m, uint64_t size, uint32_t cache, uint32_t flags, struct ck_gmem_buf **out) +{ + if (!m || !out || size == 0 || size > (uint64_t)CK_GMEM_MAX_PAGES * CK_GMEM_PAGE || cache > CK_GMEM_UNCACHED || + (flags & ~(CK_GMEM_HOST_POLLED | CK_GMEM_GPU_RO))) + return CK_GMEM_EINVAL; +#ifndef CK_GPU_MUTANT_NO_POLLED_UNCACHED + if ((flags & CK_GMEM_HOST_POLLED) && cache != CK_GMEM_UNCACHED) + return CK_GMEM_EINVAL; /* host-polled words must be GPU-uncached */ +#endif + *out = 0; + uint32_t n = (uint32_t)((size + CK_GMEM_PAGE - 1u) / CK_GMEM_PAGE); + + struct ck_gmem_buf *b = 0; + for (uint32_t i = 0; i < CK_GMEM_MAX_BUF && !b; i++) + if (m->buf[i].state == CK_GMEM_FREE) + b = &m->buf[i]; + if (!b) + return CK_GMEM_ENOMEM; + + /* First fit over FREE pages only; QUARANTINED pages are never taken. */ + uint32_t run = 0, start = 0; + int found = 0; + for (uint32_t i = 0; i < m->pages && !found; i++) { + if (m->page_state[i] != CK_GMEM_FREE) { + run = 0; + continue; + } + if (run == 0) + start = i; + if (++run == n) + found = 1; + } + if (!found) + return CK_GMEM_ENOMEM; + + uint64_t off = (uint64_t)start * CK_GMEM_PAGE; + uint32_t ro = (flags & CK_GMEM_GPU_RO) ? 1u : 0u; + uint32_t pcf = cache == CK_GMEM_UNCACHED ? (ro ? CK_GMMU_PCF_RO_UNCACHED : CK_GMMU_PCF_RW_UNCACHED) + : (ro ? CK_GMMU_PCF_RO_CACHED : CK_GMMU_PCF_RW_CACHED); + if (ck_gmmu_map(m->as, m->va_base + off, m->pa_base + off, (uint64_t)n * CK_GMEM_PAGE, CK_GMMU_SZ_4K, + CK_GMMU_PTE_AP_SYS_COH, pcf) != CK_GMMU_OK) + return CK_GMEM_EMAP; + + b->pa = m->pa_base + off; + b->gpu_va = m->va_base + off; + b->cpu = m->as->win->cpu + (b->pa - m->as->win->pa_base); + b->size = (uint64_t)n * CK_GMEM_PAGE; + b->cache = cache; + b->flags = flags; + b->state = CK_GMEM_LIVE; + b->gen++; + set_pages(m, b, CK_GMEM_LIVE); + *out = b; + return CK_GMEM_OK; +} + +static int retire(struct ck_gmem *m, struct ck_gmem_buf *b, int reuse) +{ + if (!live_buf(m, b)) + return CK_GMEM_ESTATE; + int um = ck_gmmu_unmap(m->as, b->gpu_va, b->size, CK_GMMU_SZ_4K); + int iv = um == CK_GMMU_OK ? ck_gmmu_invalidate(m->as, m->regs, m->poll_budget) : um; + if (reuse && iv == CK_GMMU_OK) { + set_pages(m, b, CK_GMEM_FREE); + b->state = CK_GMEM_FREE; + return CK_GMEM_OK; + } +#ifndef CK_GPU_MUTANT_NO_QUARANTINE + set_pages(m, b, CK_GMEM_QUARANTINED); +#else + set_pages(m, b, CK_GMEM_FREE); +#endif + b->state = CK_GMEM_FREE; /* the slot is reusable; the pages are not */ + if (!reuse) + return CK_GMEM_OK; + return iv == CK_GMMU_ETIMEDOUT || iv == CK_GMMU_EDEAD ? CK_GMEM_ETIMEDOUT : CK_GMEM_EMAP; +} + +int ck_gmem_free(struct ck_gmem *m, struct ck_gmem_buf *b) +{ + return retire(m, b, 1); +} + +int ck_gmem_quarantine(struct ck_gmem *m, struct ck_gmem_buf *b) +{ + return retire(m, b, 0); +} + +uint32_t ck_gmem_count(const struct ck_gmem *m, uint32_t page_state) +{ + uint32_t n = 0; + for (uint32_t i = 0; m && i < m->pages; i++) + n += m->page_state[i] == page_state ? 1u : 0u; + return n; +} diff --git a/native/kernel/gpu/gpu_mem.h b/native/kernel/gpu/gpu_mem.h new file mode 100644 index 00000000..83303d41 --- /dev/null +++ b/native/kernel/gpu/gpu_mem.h @@ -0,0 +1,71 @@ +/* gpu_mem.h -- bounded, reclaiming GPU-visible buffer allocator (cut D, host + * side), freestanding. Pages come from one physical window; each buffer + * gets a CPU address and a separate GPU virtual address, mapped through + * gmmu with the buffer's cache policy. + * + * Cache policy (spark-hardware-manual section 4, nvos.h NVOS32_ATTR2_ + * GPU_CACHEABLE comment): a word the host polls must be GPU-uncached, so + * CK_GMEM_HOST_POLLED forces CK_GMEM_UNCACHED and refuses CACHED. The CPU + * side stays coherent (PTE aperture SYS_COH: kern_gmmu.c picks SYS_COH for + * CPU-cached system memory). + * + * Free = unmap, invalidate, then the pages are reusable. If the invalidate + * does not complete, the pages are QUARANTINED: never handed out again for + * the life of this allocator, because the GPU may still hold translations + * to them. Only a device reset (operator step) can clear that. */ +#ifndef CK_GPU_MEM_H +#define CK_GPU_MEM_H + +#include +#include "gmmu.h" + +#define CK_GMEM_MAX_BUF 64u +#define CK_GMEM_MAX_PAGES 1024u /* 4 KiB pages: 4 MiB window max */ +#define CK_GMEM_PAGE CK_GMMU_SZ_4K + +enum ck_gmem_cache { CK_GMEM_CACHED = 0, CK_GMEM_UNCACHED = 1 }; +#define CK_GMEM_HOST_POLLED 0x1u /* the CPU polls a word in it */ +#define CK_GMEM_GPU_RO 0x2u /* GPU may only read */ + +enum ck_gmem_state { CK_GMEM_FREE = 0, CK_GMEM_LIVE = 1, CK_GMEM_QUARANTINED = 2 }; + +enum ck_gmem_status { + CK_GMEM_OK = 0, + CK_GMEM_EINVAL, + CK_GMEM_ENOMEM, /* no buffer slot or no run of free pages */ + CK_GMEM_ESTATE, /* not a live buffer of this allocator (double free, stale) */ + CK_GMEM_EMAP, /* gmmu refused; nothing changed */ + CK_GMEM_ETIMEDOUT, /* invalidate timed out; buffer quarantined */ +}; + +struct ck_gmem_buf { + uint64_t pa; /* GPU physical address */ + uint64_t gpu_va; /* what the GPU uses */ + uint8_t *cpu; /* what the CPU uses; never equal to gpu_va by construction */ + uint64_t size; /* rounded up to 4 KiB */ + uint32_t cache, flags, state, gen; +}; + +struct ck_gmem { + struct ck_gmmu_as *as; + const struct ck_gpu_regs *regs; + uint32_t poll_budget; + uint64_t pa_base, va_base; + uint32_t pages; + uint8_t page_state[CK_GMEM_MAX_PAGES]; /* ck_gmem_state per page */ + struct ck_gmem_buf buf[CK_GMEM_MAX_BUF]; +}; + +/* pa_base: start of the data pages (inside as->win, 4 KiB aligned, not + * overlapping the page-table pool); va_base: GPU VA of page 0 (2 MiB + * aligned, so a page's VA never equals its CPU address by accident: the + * tests also check that directly). */ +int ck_gmem_init(struct ck_gmem *m, struct ck_gmmu_as *as, const struct ck_gpu_regs *regs, uint32_t poll_budget, + uint64_t pa_base, uint32_t pages, uint64_t va_base); +int ck_gmem_alloc(struct ck_gmem *m, uint64_t size, uint32_t cache, uint32_t flags, struct ck_gmem_buf **out); +int ck_gmem_free(struct ck_gmem *m, struct ck_gmem_buf *b); +/* Retire without reuse: unmap and invalidate best-effort, pages stay QUARANTINED. */ +int ck_gmem_quarantine(struct ck_gmem *m, struct ck_gmem_buf *b); +uint32_t ck_gmem_count(const struct ck_gmem *m, uint32_t page_state); + +#endif diff --git a/native/kernel/gpu/gpu_sim.c b/native/kernel/gpu/gpu_sim.c new file mode 100644 index 00000000..e354c0c8 --- /dev/null +++ b/native/kernel/gpu/gpu_sim.c @@ -0,0 +1,355 @@ +/* gpu_sim.c -- see gpu_sim.h. A model for host tests, not the chip. + * The page walker below is written from dev_mmu.h (NV_MMU_VER3_*) and the + * GB10X level table on its own, so it cross-checks gmmu.c instead of + * sharing its code. */ +#include "gpu_sim.h" + +static void logev(struct ck_gsim *s, uint32_t off, uint32_t val, uint8_t write) +{ + if (s->nlog < CK_GSIM_LOG_MAX) { + s->log[s->nlog].off = off; + s->log[s->nlog].val = val; + s->log[s->nlog].write = write; + s->nlog++; + } else { + s->log_dropped++; + } +} + +void ck_gsim_init(struct ck_gsim *s, uint8_t *mem, uint64_t pa_base, uint64_t size) +{ + uint8_t *p = (uint8_t *)s; + for (uint64_t i = 0; i < sizeof(*s); i++) + p[i] = 0; + s->mem.cpu = mem; + s->mem.pa_base = pa_base; + s->mem.size = size; + s->inval_latency = 3; /* SIM-CHOICE: TRIGGER reads back set for 3 polls */ +} + +static int in_mem(const struct ck_gsim *s, uint64_t pa, uint64_t n) +{ + return pa >= s->mem.pa_base && pa - s->mem.pa_base <= s->mem.size && n <= s->mem.size - (pa - s->mem.pa_base); +} + +static uint64_t rd64(const struct ck_gsim *s, uint64_t pa) +{ + const uint8_t *p = s->mem.cpu + (pa - s->mem.pa_base); + uint64_t v = 0; + for (int i = 7; i >= 0; i--) + v = (v << 8) | p[i]; + return v; +} + +/* GB10X levels: PD4[56] PD3[55:47] PD2[46:38] PD1[37:29] PD0[28:21]. */ +static const uint8_t lo[5] = {56, 47, 38, 29, 21}; +static const uint8_t hi[5] = {56, 55, 46, 37, 28}; + +static uint32_t pte_check(uint64_t pte, int write) +{ + uint32_t ap = (uint32_t)(pte >> 1) & 3u, pcf = (uint32_t)(pte >> 3) & 0x1Fu; + if (ap == 0u || ap == 1u) /* PTE VIDEO_MEMORY / PEER_MEMORY */ + return CK_GSIM_F_APERTURE; + if (write && (pcf & 0x4u)) /* the RO PCF values all have bit 2 set (dev_mmu.h 0x4-0x7, 0xC-0xF, ...) */ + return CK_GSIM_F_RO_WRITE; + return 0; +} + +uint32_t ck_gsim_walk(const struct ck_gsim *s, uint64_t pdb, uint64_t va, int write, uint64_t *pa, uint64_t *page, + uint32_t *pte_lo) +{ + if (va >> 57) + return CK_GSIM_F_UNMAPPED; + uint64_t tbl = pdb; + for (uint32_t lv = 0; lv < 5; lv++) { + uint32_t esz = lv == 4 ? 16u : 8u; + uint64_t idx = (va >> lo[lv]) & ((1ull << (hi[lv] - lo[lv] + 1u)) - 1ull); + if (!in_mem(s, tbl + idx * esz, esz)) + return CK_GSIM_F_OUTSIDE; + uint64_t e = rd64(s, tbl + idx * esz); + if (e & 1u) { + if (lv < 2) + return CK_GSIM_F_BAD_PDE; /* PD4/PD3 cannot hold a PTE */ + uint64_t psz = 1ull << lo[lv]; /* PD2 256 GiB, PD1 512 MiB, PD0 2 MiB */ + uint32_t f = pte_check(e, write); + if (f) + return f; + *pa = (e & 0x000FFFFFFFFFF000ull & ~(psz - 1u)) + (va & (psz - 1u)); + *page = psz; + *pte_lo = (uint32_t)e & 0xFFFu; + return in_mem(s, *pa, 4) ? 0u : CK_GSIM_F_OUTSIDE; + } + if (lv < 4) { + uint32_t ap = (uint32_t)(e >> 1) & 3u; + if (ap == 0) + return CK_GSIM_F_UNMAPPED; + if (ap == 1) + return CK_GSIM_F_APERTURE; + tbl = e & 0x000FFFFFFFFFF000ull; + continue; + } + /* PD0 dual PDE: small half in the second word, big half in the first. + * SIM-CHOICE (DOCS SILENT on overlap priority): a valid small PTE wins, + * then a valid big PTE. gmmu.c never builds both for one 2 MiB region. */ + uint64_t e1 = rd64(s, tbl + idx * 16u + 8u); + uint32_t sap = (uint32_t)(e1 >> 1) & 3u, bap = (uint32_t)(e >> 1) & 3u; + for (int half = 0; half < 2; half++) { + uint32_t ap = half == 0 ? sap : bap; + if (ap == 0) + continue; + if (ap == 1) + return CK_GSIM_F_APERTURE; + uint64_t pt = half == 0 ? (e1 & 0x000FFFFFFFFFF000ull) : (e & 0x000FFFFFFFFFFF00ull); + uint32_t shift = half == 0 ? 12u : 16u; + uint64_t pidx = (va >> shift) & ((1ull << (21u - shift)) - 1ull); + if (!in_mem(s, pt + pidx * 8u, 8)) + return CK_GSIM_F_OUTSIDE; + uint64_t pte = rd64(s, pt + pidx * 8u); + if (!(pte & 1u)) + continue; + uint32_t f = pte_check(pte, write); + if (f) + return f; + uint64_t psz = 1ull << shift; + *pa = (pte & 0x000FFFFFFFFFF000ull & ~(psz - 1u)) + (va & (psz - 1u)); + *page = psz; + *pte_lo = (uint32_t)pte & 0xFFFu; + return in_mem(s, *pa, 4) ? 0u : CK_GSIM_F_OUTSIDE; + } + return CK_GSIM_F_UNMAPPED; + } + return CK_GSIM_F_UNMAPPED; +} + +static void fault(struct ck_gsim *s, uint64_t pdb, uint64_t va, uint32_t kind, int write) +{ + if (s->nfaults < CK_GSIM_FAULTS) { + s->faults[s->nfaults].va = va; + s->faults[s->nfaults].pdb = pdb; + s->faults[s->nfaults].kind = kind; + s->faults[s->nfaults].write = (uint8_t)write; + } + s->nfaults++; +} + +static uint32_t xlate(struct ck_gsim *s, uint64_t pdb, uint64_t va, int write, uint64_t *pa) +{ + for (uint32_t i = 0; i < CK_GSIM_TLB; i++) { + struct ck_gsim_tlb *t = &s->tlb[i]; + if (t->valid && t->pdb == pdb && va - t->va_page < t->page) { + /* A cached translation keeps working until an invalidate, + * even after the PTE in memory was cleared. */ + uint32_t f = pte_check(t->pte_lo, write); + if (f) { + fault(s, pdb, va, f, write); + return f; + } + s->tlb_hits++; + *pa = t->pa_page + (va - t->va_page); + return 0; + } + } + uint64_t page = 0; + uint32_t pte_lo = 0; + uint32_t f = ck_gsim_walk(s, pdb, va, write, pa, &page, &pte_lo); + if (f) { + fault(s, pdb, va, f, write); + return f; + } + struct ck_gsim_tlb *t = &s->tlb[s->tlb_next++ % CK_GSIM_TLB]; + t->valid = 1; + t->pdb = pdb; + t->page = page; + t->va_page = va & ~(page - 1u); + t->pa_page = *pa - (va - t->va_page); + t->pte_lo = pte_lo; + return 0; +} + +uint32_t ck_gsim_gpu_read32(struct ck_gsim *s, uint64_t pdb, uint64_t va, uint32_t *out) +{ + uint64_t pa = 0; + uint32_t f = xlate(s, pdb, va, 0, &pa); + if (f) + return f; + const uint8_t *p = s->mem.cpu + (pa - s->mem.pa_base); + *out = (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24; + return 0; +} + +uint32_t ck_gsim_gpu_write32(struct ck_gsim *s, uint64_t pdb, uint64_t va, uint32_t val) +{ + uint64_t pa = 0; + uint32_t f = xlate(s, pdb, va, 1, &pa); + if (f) + return f; + uint8_t *p = s->mem.cpu + (pa - s->mem.pa_base); + for (int i = 0; i < 4; i++) + p[i] = (uint8_t)(val >> (8 * i)); + return 0; +} + +static struct ck_gsim_chan *chan_by_id(struct ck_gsim *s, uint32_t chid) +{ + for (uint32_t i = 0; i < CK_GSIM_CHANS; i++) + if (s->chan[i].bound && s->chan[i].d.chid == chid) + return &s->chan[i]; + return 0; +} + +const struct ck_gsim_chan *ck_gsim_chan(const struct ck_gsim *s, uint32_t chid) +{ + return chan_by_id((struct ck_gsim *)s, chid); +} + +/* Fetch GP entries get..put through the GMMU and read every pushbuffer word. + * SIM-CHOICE: methods are not executed; the model proves the GPU could + * reach every byte the CPU queued, and faults the channel if not. */ +static void consume(struct ck_gsim *s, struct ck_gsim_chan *c) +{ + if (c->faulted || c->disabled || s->hang) + return; + uint64_t upa = c->d.userd_pa + CK_GPU_USERD_GPPUT; + if (!in_mem(s, upa, 4)) { + c->faulted = 1; + return; + } + const uint8_t *u = s->mem.cpu + (upa - s->mem.pa_base); + uint32_t put = (uint32_t)u[0] | (uint32_t)u[1] << 8 | (uint32_t)u[2] << 16 | (uint32_t)u[3] << 24; + if (put >= c->d.entries) { + c->faulted = 1; + return; + } + while (c->gp_get != put) { + uint64_t eva = c->d.gpfifo_va + (uint64_t)c->gp_get * 8u; + uint32_t lo32 = 0, hi32 = 0; + if (ck_gsim_gpu_read32(s, c->d.pdb, eva, &lo32) || ck_gsim_gpu_read32(s, c->d.pdb, eva + 4u, &hi32)) { + c->faulted = 1; + return; + } + uint64_t pbva = (uint64_t)(lo32 & ~3u) | ((uint64_t)(hi32 & 0xFFu) << 32); /* GET 31:2, GET_HI 7:0 */ + uint32_t len = (hi32 >> 10) & 0x1FFFFFu; /* LENGTH 30:10 */ + for (uint32_t w = 0; w < len; w++) { + uint32_t word = 0; + if (ck_gsim_gpu_read32(s, c->d.pdb, pbva + (uint64_t)w * 4u, &word)) { + c->faulted = 1; + return; + } + c->words_read++; + } + c->gp_get = (c->gp_get + 1u) % c->d.entries; + } +} + +static uint32_t sim_rd(void *ctx, uint32_t off) +{ + struct ck_gsim *s = ctx; + uint32_t v = 0; + if (off == CK_GPU_REG_INVAL) { + if (s->inval_pending && !s->inval_stuck) { + if (s->inval_left == 0) { + /* ALL_VA for the latched PDB: drop that PDB's TLB entries. */ + uint64_t pdb = (((uint64_t)(s->pdb_lo >> 4) & 0x0FFFFFFFull) | ((uint64_t)(s->pdb_hi & 0xFFFFFu) << 28)) << 12; + for (uint32_t i = 0; i < CK_GSIM_TLB; i++) + if (s->inval_all || s->tlb[i].pdb == pdb) + s->tlb[i].valid = 0; + s->inval_pending = 0; + s->inval_done++; + } else { + s->inval_left--; + } + } + v = s->inval_pending ? CK_GPU_INVAL_TRIGGER : 0u; + } + logev(s, off, v, 0); + return v; +} + +static void sim_wr(void *ctx, uint32_t off, uint32_t val) +{ + struct ck_gsim *s = ctx; + logev(s, off, val, 1); + if (off == CK_GPU_REG_INVAL_PDB) { + s->pdb_lo = val; + } else if (off == CK_GPU_REG_INVAL_UPPER) { + s->pdb_hi = val; + } else if (off == CK_GPU_REG_INVAL && (val & CK_GPU_INVAL_TRIGGER)) { + s->inval_pending = 1; + s->inval_left = s->inval_latency; + s->inval_all = (val & CK_GPU_INVAL_ALL_PDB) != 0; + } else if (off == CK_GPU_REG_DOORBELL) { + s->doorbells++; + struct ck_gsim_chan *c = 0; + for (uint32_t i = 0; i < CK_GSIM_CHANS && !c; i++) + if (s->chan[i].bound && s->chan[i].d.token == val) + c = &s->chan[i]; + if (!c) + s->doorbell_unknown++; + else + consume(s, c); + } +} + +struct ck_gpu_regs ck_gsim_regs(struct ck_gsim *s) +{ + struct ck_gpu_regs r = {sim_rd, sim_wr, s}; + return r; +} + +static int sim_bind(void *ctx, const struct ck_gpu_chan_desc *d) +{ + struct ck_gsim *s = ctx; + if (chan_by_id(s, d->chid)) + return -1; /* channel id already live */ + /* Take the page directory from the instance block, the way the hardware + * would, not from the descriptor: proves the channel code wrote it. */ + uint64_t ipa = d->inst_pa + CK_GPU_RAMIN_PDB_WORD * 4u; + if (!in_mem(s, ipa, 8)) + return -1; + uint64_t w = rd64(s, ipa); + uint32_t lo32 = (uint32_t)w, target = lo32 & 3u; + if ((target != CK_GPU_RAMIN_TARGET_SYS_COH && target != 3u) || (lo32 & CK_GPU_RAMIN_NEW_PT_FORMAT)) + return -1; /* GB10 has only system memory; SIM-CHOICE: bit 10 set means VERSION_2 tables, not GB10X */ + uint64_t pdb = ((w >> 32) << 32) | (lo32 & 0xFFFFF000u); + for (uint32_t i = 0; i < CK_GSIM_CHANS; i++) { + if (!s->chan[i].bound) { + struct ck_gsim_chan *c = &s->chan[i]; + c->d = *d; + c->d.pdb = pdb; /* from the instance block */ + c->gp_get = 0; + c->words_read = 0; + c->faulted = c->disabled = 0; + c->bound = 1; + return 0; + } + } + return -1; +} + +static int sim_disable(void *ctx, uint32_t chid) +{ + struct ck_gsim_chan *c = chan_by_id(ctx, chid); + if (!c) + return -1; + c->disabled = 1; + return 0; +} + +static int sim_is_idle(void *ctx, uint32_t chid) +{ + struct ck_gsim *s = ctx; + s->idle_polls++; + struct ck_gsim_chan *c = chan_by_id(s, chid); + if (!c) + return 1; + if (s->hang || !c->disabled) + return 0; /* never idle before a disable */ + c->bound = 0; /* idle and disabled: the id may be reused */ + return 1; +} + +struct ck_gpu_chan_ops ck_gsim_chan_ops(void) +{ + struct ck_gpu_chan_ops o = {sim_bind, sim_disable, sim_is_idle}; + return o; +} diff --git a/native/kernel/gpu/gpu_sim.h b/native/kernel/gpu/gpu_sim.h new file mode 100644 index 00000000..9bcde2f5 --- /dev/null +++ b/native/kernel/gpu/gpu_sim.h @@ -0,0 +1,95 @@ +/* gpu_sim.h -- a simulated GB10 for host tests of gpu/ (cut D). NOT the chip. + * + * Memory: one array the tests own (the unified LPDDR window). Registers: + * every read and write is logged in order. GPU-side accesses translate + * through the page tables in that memory with a decoder written separately + * from gmmu.c (from dev_mmu.h directly), through a small TLB that only a + * completed invalidate empties, so a missing invalidate shows up as a stale + * translation. A fault is recorded and the access does not touch memory. + * + * Simulator choices where the docs are silent are marked SIM-CHOICE. + * Limitation: a completed invalidate matches TLB entries by PDB address + * only; the PDB aperture bit is not checked here (the register-log test + * in test_gpu_sim.c is the guard for its encoding). */ +#ifndef CK_GPU_SIM_H +#define CK_GPU_SIM_H + +#include +#include "gmmu.h" +#include "gpu_chan.h" + +#define CK_GSIM_LOG_MAX 512u +#define CK_GSIM_TLB 16u +#define CK_GSIM_FAULTS 16u +#define CK_GSIM_CHANS 4u + +enum ck_gsim_fault_kind { + CK_GSIM_F_UNMAPPED = 1, /* PDE aperture INVALID or PTE VALID=0 */ + CK_GSIM_F_BAD_PDE, /* PTE bit set at PD4/PD3, where the format has no PTE */ + CK_GSIM_F_APERTURE, /* VIDMEM or PEER: GB10 has neither (INFERRED, unified memory) */ + CK_GSIM_F_RO_WRITE, /* write through a read-only PCF */ + CK_GSIM_F_OUTSIDE, /* table or page physical address outside the memory array */ +}; + +struct ck_gsim_reg_ev { + uint32_t off; + uint32_t val; + uint8_t write; +}; + +struct ck_gsim_fault { + uint64_t va; + uint64_t pdb; + uint32_t kind; + uint8_t write; +}; + +struct ck_gsim_tlb { + uint64_t pdb, va_page, pa_page, page; + uint32_t pte_lo; /* low 12 bits of the PTE: aperture, PCF, kind */ + uint8_t valid; +}; + +struct ck_gsim_chan { + struct ck_gpu_chan_desc d; + uint32_t gp_get; + uint32_t words_read; + uint8_t bound, faulted, disabled; +}; + +struct ck_gsim { + struct ck_gpu_window mem; + struct ck_gsim_reg_ev log[CK_GSIM_LOG_MAX]; + uint32_t nlog, log_dropped; + /* invalidate engine */ + uint32_t pdb_lo, pdb_hi; + uint32_t inval_pending, inval_left, inval_latency, inval_stuck, inval_done, inval_all; + /* TLB and faults */ + struct ck_gsim_tlb tlb[CK_GSIM_TLB]; + uint32_t tlb_next, tlb_hits; + struct ck_gsim_fault faults[CK_GSIM_FAULTS]; + uint32_t nfaults; + /* channels */ + struct ck_gsim_chan chan[CK_GSIM_CHANS]; + uint32_t doorbells, doorbell_unknown; + uint32_t hang; /* channels never go idle and never consume (teardown timeout tests) */ + uint32_t idle_polls; +}; + +void ck_gsim_init(struct ck_gsim *s, uint8_t *mem, uint64_t pa_base, uint64_t size); +/* Register file for the code under test. */ +struct ck_gpu_regs ck_gsim_regs(struct ck_gsim *s); +/* Channel control the code under test calls (stands in for GSP RPC/CHRAM). */ +struct ck_gpu_chan_ops ck_gsim_chan_ops(void); + +/* GPU-side 32-bit access through the address space whose PD4 is at pdb. + * Returns 0 or the fault kind (and records it). */ +uint32_t ck_gsim_gpu_read32(struct ck_gsim *s, uint64_t pdb, uint64_t va, uint32_t *out); +uint32_t ck_gsim_gpu_write32(struct ck_gsim *s, uint64_t pdb, uint64_t va, uint32_t val); +/* Translate without touching the TLB or recording a fault (test oracle). */ +uint32_t ck_gsim_walk(const struct ck_gsim *s, uint64_t pdb, uint64_t va, int write, uint64_t *pa, uint64_t *page, + uint32_t *pte_lo); + +const struct ck_gsim_chan *ck_gsim_chan(const struct ck_gsim *s, uint32_t chid); + +#endif diff --git a/native/kernel/gpu/gsp_mmio.c b/native/kernel/gpu/gsp_mmio.c new file mode 100644 index 00000000..c55a4018 --- /dev/null +++ b/native/kernel/gpu/gsp_mmio.c @@ -0,0 +1,143 @@ +/* gsp_mmio.c -- the register-level GSP start-up on GB10B (see gsp_mmio.h for the steps and sources). */ +#include "gsp_mmio.h" + +static uint32_t rd(const struct ck_gpu_regs *r, uint32_t off) +{ + return r->rd(r->ctx, off); +} + +static void wr(const struct ck_gpu_regs *r, uint32_t off, uint32_t v) +{ + r->wr(r->ctx, off, v); +} + +static void between_polls(const struct ck_gsp_mmio_in *in) +{ + if (in->pause) + in->pause(in->pause_ctx); +} + +static uint32_t emem_dwords(uint32_t ememc) +{ + return ((ememc >> 8) & 0xFFu) * CK_GSP_EMEM_DW_PER_BLK + ((ememc >> 2) & 0x3Fu); +} + +static int mask_released(uint32_t hwcfg2) +{ + return hwcfg2 != 0 && (hwcfg2 & CK_GSP_PRIV_LOCKED_MASK) != CK_GSP_PRIV_LOCKED; +} + +/* Step 8 condition. Reads MAILBOX0, MAILBOX1 only on a match, then HWCFG2, in the driver's order. */ +static int lockdown_done(const struct ck_gpu_regs *r, const struct ck_gsp_mmio_in *in, struct ck_gsp_mmio_out *o) +{ + o->gsp_mb0 = rd(r, CK_GSP_FLCN_MAILBOX0); + if (o->gsp_mb0 != 0 && o->gsp_mb0 == (uint32_t)in->fmc_args_pa) { + o->gsp_mb1 = rd(r, CK_GSP_FLCN_MAILBOX1); + if (o->gsp_mb1 == (uint32_t)(in->fmc_args_pa >> 32)) + return 0; /* boot arguments not read by the FMC yet */ + } + o->hwcfg2 = rd(r, CK_GSP_FLCN_HWCFG2); + return !(o->hwcfg2 & CK_GSP_HWCFG2_LOCKDOWN) || o->gsp_mb0 != 0; +} + +int ck_gsp_mmio_boot(const struct ck_gpu_regs *r, const struct ck_gsp_mmio_in *in, struct ck_gsp_mmio_out *o) +{ + uint32_t i, n; + + for (i = 0; i < sizeof(*o); i++) + ((uint8_t *)o)[i] = 0; + o->stage = CK_GSP_E_ARG; + if (!r || !in || !in->packet || in->len == 0 || in->len > CK_GSP_EMEM_CHANNEL_BYTES) + return o->stage; + + /* 1 */ + for (n = 0;; n++) { + uint32_t head = rd(r, CK_GSP_SEC2_QHEAD0); /* HEAD then TAIL, as _ksec2GetQueueHeadTail_GB10B :103-104 */ + if (head == rd(r, CK_GSP_SEC2_QTAIL0)) + break; + if (n >= in->polls_can_send) { + o->polls[0] = n; + return o->stage = CK_GSP_E_BUSY; + } + between_polls(in); + } + o->polls[0] = n; + + /* 2, 3, 4 */ + wr(r, CK_GSP_SEC2_EMEMC0, CK_GSP_EMEMC_AINCW); + uint32_t start = emem_dwords(rd(r, CK_GSP_SEC2_EMEMC0)); + for (i = 0; i + 4 <= in->len; i += 4) + wr(r, CK_GSP_SEC2_EMEMD0, (uint32_t)in->packet[i] | (uint32_t)in->packet[i + 1] << 8 | + (uint32_t)in->packet[i + 2] << 16 | (uint32_t)in->packet[i + 3] << 24); + if (i < in->len) { + uint32_t v = 0; + for (uint32_t k = 0; i + k < in->len; k++) + v |= (uint32_t)in->packet[i + k] << (8 * k); + wr(r, CK_GSP_SEC2_EMEMD0, v); + } + o->dwords = (in->len + 3) / 4; + o->ememc_after = rd(r, CK_GSP_SEC2_EMEMC0); + if (emem_dwords(o->ememc_after) - start != o->dwords) + return o->stage = CK_GSP_E_EMEM; + + /* 5: TAIL first, HEAD last (HEAD interrupts SEC2) */ + wr(r, CK_GSP_SEC2_QTAIL0, o->dwords * 4 - 4); + wr(r, CK_GSP_SEC2_QHEAD0, 0); + + /* 6 */ + for (n = 0;; n++) { + o->sec2_mb0 = rd(r, CK_GSP_SEC2_MAILBOX0); + if (o->sec2_mb0 != CK_GSP_SEC2_CMD_BUSY) + break; + if (n >= in->polls_cmd) { + o->polls[1] = n; + o->sec2_mb1 = rd(r, CK_GSP_SEC2_MAILBOX1); + return o->stage = CK_GSP_E_SEC2; + } + between_polls(in); + } + o->polls[1] = n; + + /* 7 */ + for (n = 0;; n++) { + o->hwcfg2 = rd(r, CK_GSP_FLCN_HWCFG2); + if (mask_released(o->hwcfg2)) + break; + if (n >= in->polls_mask) { + o->polls[2] = n; + return o->stage = CK_GSP_E_MASK; + } + between_polls(in); + } + o->polls[2] = n; + + /* 8 */ + for (n = 0;; n++) { + if (lockdown_done(r, in, o)) + break; + if (n >= in->polls_lockdown) { + o->polls[3] = n; + o->gsp_mb1 = rd(r, CK_GSP_FLCN_MAILBOX1); + return o->stage = CK_GSP_E_LOCKDOWN; + } + between_polls(in); + } + o->polls[3] = n; + + /* 9 */ + o->gsp_mb0 = rd(r, CK_GSP_FLCN_MAILBOX0); + if (o->gsp_mb0 != 0) + return o->stage = CK_GSP_E_FMC; + + /* 10, 11 */ + wr(r, CK_GSP_FLCN_OS, in->app_version); + o->cpuctl = rd(r, CK_GSP_RISCV_CPUCTL); + if (!(o->cpuctl & CK_GSP_CPUCTL_ACTIVE)) + return o->stage = CK_GSP_E_RISCV; + return o->stage = CK_GSP_OK; +} + +void ck_gsp_mmio_notify(const struct ck_gpu_regs *r) +{ + wr(r, CK_GSP_QHEAD0, 0); +} diff --git a/native/kernel/gpu/gsp_mmio.h b/native/kernel/gpu/gsp_mmio.h new file mode 100644 index 00000000..c99185c1 --- /dev/null +++ b/native/kernel/gpu/gsp_mmio.h @@ -0,0 +1,99 @@ +/* gsp_mmio.h -- the register-level GSP start-up on GB10B (L332 rung 1, L346), freestanding. + * + * What NVIDIA's driver (open-gpu-kernel-modules 580.173.02) does on BAR0 to start GSP-RM on the GB10B + * once the boot package is built in memory (L192 gb10_gsp_boot.c builds it; this file only talks to + * the chip). GB10B has no FSP: SEC2 boots the GSP-FMC (kgspBootstrap_GH100, kernel_gsp_gh100.c:833-995, + * SEC2 branch :868-872; GB10B timer setup is read-only, timer_gb10b.c:46-80, so there is no other + * register write before it): + * + * 1. wait until SEC2 EMEM channel 0 is empty: QUEUE_HEAD(0) == QUEUE_TAIL(0) + * (ksec2CanSendPacket_GB10B, kernel_sec2_gb10b.c:343-357; polled by ksec2PollForCanSend) + * 2. EMEMC(0) = offset 0, auto-increment on write (_ksec2ConfigEmemc_GB10B :118-154, ksec2SendPacket_GB10B :700-733, call :723) + * 3. EMEMD(0) = the packet, one dword at a time, a short tail zero-padded (_ksec2WriteToEmem_GB10B :166-213) + * 4. EMEMC(0) read back: the write pointer moved by exactly the dwords written (:204-210) + * 5. QUEUE_TAIL(0) = padded size - 4, THEN QUEUE_HEAD(0) = 0 (HEAD interrupts SEC2) (_ksec2UpdateQueueHeadTail_GB10B :72-84, called :730) + * 6. wait until SEC2 MAILBOX0 no longer reads 0xc001cafe (command handled) (:285-311, called from ksec2SendBootCommands_GB10B :640) + * 7. wait until GSP HWCFG2 reads non-zero and not 0xBADF41xx (GSP target mask released by SEC2) + * (_ksec2IsGspTargetMaskReleased :264-283, ksec2WaitForGspTargetMaskReleased_GB10B :367-379) + * 8. wait until GSP HWCFG2.RISCV_BR_PRIV_LOCKDOWN (bit 13) is UNLOCK or GSP MAILBOX0 is non-zero, + * where MAILBOX0:MAILBOX1 equal to the FMC boot-argument address means "not read yet, keep waiting" + * (_kgspLockdownReleasedOrFmcError, kernel_gsp_gh100.c:492-533) + * 9. GSP MAILBOX0 non-zero after that = the FMC reported an error: stop (:940-946) + * 10. GSP FALCON_OS = the GspRmBoot descriptor's appVersion (:954-956) + * 11. RISC-V CPUCTL.ACTIVE_STAT (bit 7) must read ACTIVE (kflcnIsRiscvActive_GA102, kernel_falcon_ga102.c:47-55) + * then the host links the status queue and waits for GSP_EV_INIT_DONE over the message queue (L192 + * gsp_mq_recv); every later command is announced by GSP QUEUE_HEAD(0) = 0 (kgspSetCmdQueueHead_TU102, + * kernel_gsp_tu102.c:343-355; GB10B takes that HAL, g_kernel_gsp_nvoc.c:664-680). + * + * Polling only, no interrupts. Each wait has a poll budget; `pause` (optional) runs between polls so + * the caller sets the time per poll (udelay on Linux, nothing on the simulator). + * Nothing here has run on the chip: register behaviour beyond the driver source is UNVERIFIED. */ +#ifndef CK_GSP_MMIO_H +#define CK_GSP_MMIO_H + +#include +#include "gmmu.h" /* struct ck_gpu_regs */ + +/* BAR0 offsets, GB10B (published/blackwell/gb10b/dev_sec_pri.h:27-56; dev_gsp.h:27 NV_PGSP 0x110000; + * hopper/gh100/dev_falcon_v4.h:27,30,34,79 relative to NV_PGSP; NV_FALCON2_GSP_BASE 0x111000 + + * hopper/gh100/dev_riscv_pri.h:58,68 NV_PRISCV_RISCV_CPUCTL 0x388; gb20b/dev_gsp.h:33 QUEUE_HEAD). */ +#define CK_GSP_SEC2_MAILBOX0 0x00840040u +#define CK_GSP_SEC2_MAILBOX1 0x00840044u +#define CK_GSP_SEC2_EMEMC0 0x00840ac0u +#define CK_GSP_SEC2_EMEMD0 0x00840ac4u +#define CK_GSP_SEC2_QHEAD0 0x00840c00u +#define CK_GSP_SEC2_QTAIL0 0x00840c04u +#define CK_GSP_FLCN_MAILBOX0 0x00110040u +#define CK_GSP_FLCN_MAILBOX1 0x00110044u +#define CK_GSP_FLCN_OS 0x00110080u +#define CK_GSP_FLCN_HWCFG2 0x001100f4u +#define CK_GSP_QHEAD0 0x00110c00u +#define CK_GSP_RISCV_CPUCTL 0x00111388u + +#define CK_GSP_EMEMC_AINCW (1u << 24) +#define CK_GSP_EMEM_DW_PER_BLK 64u +#define CK_GSP_EMEM_CHANNEL_BYTES 1024u /* SEC2_EMEM_CHANNEL_RM_SIZE, kernel_sec2_gb10b.c:39 */ +#define CK_GSP_SEC2_CMD_BUSY 0xc001cafeu /* cmdHandlingState :292 */ +#define CK_GSP_PRIV_LOCKED 0xBADF4100u /* privErrTargetLocked :271 */ +#define CK_GSP_PRIV_LOCKED_MASK 0xFFFFFF00u +#define CK_GSP_HWCFG2_LOCKDOWN (1u << 13) +#define CK_GSP_CPUCTL_ACTIVE (1u << 7) + +/* Where the boot stopped. 0 = GSP-RM's RISC-V core runs (step 11 passed). */ +enum ck_gsp_mmio_err { + CK_GSP_OK = 0, + CK_GSP_E_ARG = -1, /* packet empty, over 1 KiB, NULL */ + CK_GSP_E_BUSY = -2, /* step 1: SEC2 channel never emptied */ + CK_GSP_E_EMEM = -3, /* step 4: write pointer did not move by the dwords written */ + CK_GSP_E_SEC2 = -4, /* step 6: SEC2 never handled the command */ + CK_GSP_E_MASK = -5, /* step 7: target mask never released */ + CK_GSP_E_LOCKDOWN = -6, /* step 8: neither lockdown release nor an FMC code */ + CK_GSP_E_FMC = -7, /* step 9: FMC error code in GSP MAILBOX0 (out.gsp_mb0) */ + CK_GSP_E_RISCV = -8, /* step 11: RISC-V core not active */ +}; + +struct ck_gsp_mmio_in { + const uint8_t *packet; /* the SEC2 EMEM packet (MCTP + NVDM COT header + payload, L192 plan.cot_packet) */ + uint32_t len; /* bytes, 1..1024 (L192: 868) */ + uint64_t fmc_args_pa; /* GSP_FMC_BOOT_PARAMS address the COT payload points at */ + uint32_t app_version; /* RM_RISCV_UCODE_DESC.appVersion of GspRmBoot_GB10B */ + /* poll budgets for steps 1, 6, 7, 8 (0 = check once) */ + uint32_t polls_can_send, polls_cmd, polls_mask, polls_lockdown; + void (*pause)(void *ctx); + void *pause_ctx; +}; + +struct ck_gsp_mmio_out { + int32_t stage; /* enum ck_gsp_mmio_err */ + uint32_t polls[4]; /* polls used by steps 1, 6, 7, 8 */ + uint32_t dwords, ememc_after; /* step 3/4 */ + uint32_t sec2_mb0, sec2_mb1; /* after step 6 (or at its timeout) */ + uint32_t hwcfg2, gsp_mb0, gsp_mb1, cpuctl; +}; + +/* Steps 1-11. Returns out->stage. */ +int ck_gsp_mmio_boot(const struct ck_gpu_regs *r, const struct ck_gsp_mmio_in *in, struct ck_gsp_mmio_out *out); +/* Announce new command-queue elements to GSP-RM (after the ring write and its fence). */ +void ck_gsp_mmio_notify(const struct ck_gpu_regs *r); + +#endif diff --git a/native/kernel/gpu/gsp_seq.c b/native/kernel/gpu/gsp_seq.c new file mode 100644 index 00000000..69cc768e --- /dev/null +++ b/native/kernel/gpu/gsp_seq.c @@ -0,0 +1,65 @@ +/* gsp_seq.c -- see gsp_seq.h. Opcode sizes from rmgspseq.h GSP_SEQUENCER_PAYLOAD_SIZE_DWORDS. + * REG_MODIFY is (old & ~mask) | val, as kernel_gsp.c writes it. REG_POLL waits until + * (reg & mask) == val. REG_STORE refuses an index of 8 or more (GSP_SEQ_BUF_REG_SAVE_SIZE is 8). */ +#include "gsp_seq.h" + +static uint32_t payload_dwords(uint32_t op) +{ + switch (op) { + case GSP_SEQ_REG_WRITE: return 2; + case GSP_SEQ_REG_MODIFY: return 3; + case GSP_SEQ_REG_POLL: return 5; + case GSP_SEQ_DELAY_US: return 1; + case GSP_SEQ_REG_STORE: return 2; + case GSP_SEQ_CORE_RESET: + case GSP_SEQ_CORE_START: + case GSP_SEQ_CORE_WAIT: + case GSP_SEQ_CORE_RESUME: return 0; + default: return 0xffffffffu; + } +} + +int gsp_seq_run(const uint32_t *buf, uint32_t nwords, uint32_t end, gsp_seq_io *io, const char **why) +{ + if (why) *why = 0; + if (!buf || !io || !io->rd || !io->wr) { if (why) *why = "null argument"; return -1; } + if (nwords == 0) { if (why) *why = "empty buffer"; return -1; } + if (end >= nwords) { if (why) *why = "cmdIndex not inside the buffer"; return -1; } + uint32_t i = 0; + while (i < end) { + uint32_t op = buf[i++]; + uint32_t n = payload_dwords(op); + if (n == 0xffffffffu) { if (why) *why = "unknown opcode"; return -1; } + if (i + n > end) { if (why) *why = "opcode overruns cmdIndex"; return -1; } + const uint32_t *a = buf + i; + if (op == GSP_SEQ_REG_WRITE) { + io->wr(io->ctx, a[0], a[1]); + } else if (op == GSP_SEQ_REG_MODIFY) { + uint32_t v = io->rd(io->ctx, a[0]); + io->wr(io->ctx, a[0], (v & ~a[1]) | a[2]); + } else if (op == GSP_SEQ_REG_POLL) { + uint32_t left = io->poll_budget ? io->poll_budget : 1; + uint32_t v = io->rd(io->ctx, a[0]); + while ((v & a[1]) != a[2]) { + if (left == 0) { if (why) *why = "poll timed out"; return -1; } + left--; + v = io->rd(io->ctx, a[0]); + } + } else if (op == GSP_SEQ_DELAY_US) { + if (io->delay_us) io->delay_us(io->ctx, a[0]); + } else if (op == GSP_SEQ_REG_STORE) { +#ifdef GSP_SEQ_MUTANT_INDEX + /* planted bug: an index past the save area is accepted */ + if (a[1] < GSP_SEQ_REG_SAVE) io->save[a[1]] = io->rd(io->ctx, a[0]); +#else + if (a[1] >= GSP_SEQ_REG_SAVE) { if (why) *why = "save index out of range"; return -1; } + io->save[a[1]] = io->rd(io->ctx, a[0]); +#endif + } else { + if (!io->core) { if (why) *why = "core opcode with no core callback"; return -1; } + if (io->core(io->ctx, op)) { if (why) *why = "core opcode failed"; return -1; } + } + i += n; + } + return 0; +} diff --git a/native/kernel/gpu/gsp_seq.h b/native/kernel/gpu/gsp_seq.h new file mode 100644 index 00000000..b7b2ef38 --- /dev/null +++ b/native/kernel/gpu/gsp_seq.h @@ -0,0 +1,40 @@ +/* gsp_seq.h -- our CPU-side GSP sequencer. Replaces NVIDIA's kgspExecuteSequencerBuffer + * (open-gpu-kernel-modules 580.173.02, kernel_gsp.c:5297) for the opcodes in rmgspseq.h. + * Register and core operations are callbacks: this file never touches a device. + * Core opcodes (reset, start, wait, resume) refuse unless the caller supplies core(), + * because those restart the chip and must not be guessed. */ +#ifndef AIEN_GSP_SEQ_H +#define AIEN_GSP_SEQ_H +#include + +enum { + GSP_SEQ_REG_WRITE = 0, + GSP_SEQ_REG_MODIFY = 1, + GSP_SEQ_REG_POLL = 2, + GSP_SEQ_DELAY_US = 3, + GSP_SEQ_REG_STORE = 4, + GSP_SEQ_CORE_RESET = 5, + GSP_SEQ_CORE_START = 6, + GSP_SEQ_CORE_WAIT = 7, + GSP_SEQ_CORE_RESUME = 8 +}; + +#define GSP_SEQ_REG_SAVE 8 + +typedef struct gsp_seq_io { + uint32_t (*rd)(void *ctx, uint32_t addr); + void (*wr)(void *ctx, uint32_t addr, uint32_t val); + /* 0 = done, -1 = failed. NULL refuses every core opcode. */ + int (*core)(void *ctx, uint32_t opcode); + void (*delay_us)(void *ctx, uint32_t us); + void *ctx; + uint32_t poll_budget; /* reads allowed per REG_POLL before it refuses */ + uint32_t save[GSP_SEQ_REG_SAVE]; +} gsp_seq_io; + +/* buf is commandBuffer, nwords is bufferSizeDWord, end is cmdIndex. + * Matches the driver: end must be < nwords, and the walk stops at end. + * Returns 0, or -1 with *why set. */ +int gsp_seq_run(const uint32_t *buf, uint32_t nwords, uint32_t end, gsp_seq_io *io, const char **why); + +#endif diff --git a/native/kernel/gpu/gsp_sim.c b/native/kernel/gpu/gsp_sim.c new file mode 100644 index 00000000..3cf26172 --- /dev/null +++ b/native/kernel/gpu/gsp_sim.c @@ -0,0 +1,192 @@ +/* gsp_sim.c -- simulated GB10B SEC2 + GSP falcon (see gsp_sim.h). NOT the chip. */ +#include "gsp_sim.h" +#include "gsp_mmio.h" + +#define PHASE_IDLE 0u +#define PHASE_POSTED 1u +#define PHASE_MASK 2u +#define PHASE_FMC 3u +#define PHASE_UP 4u +#define PHASE_REJECTED 9u + +static void logev(struct ck_gspsim *s, uint32_t off, uint32_t val, uint8_t write) +{ + if (s->nlog < CK_GSPSIM_LOG_MAX) { + s->log[s->nlog].off = off; + s->log[s->nlog].val = val; + s->log[s->nlog].write = write; + } + s->nlog++; +} + +void ck_gspsim_init(struct ck_gspsim *s, const struct ck_gspsim_cfg *cfg) +{ + for (uint32_t i = 0; i < sizeof(*s); i++) + ((uint8_t *)s)[i] = 0; + s->cfg = *cfg; + /* An old message still in the channel: HEAD != TAIL until busy_reads HEAD reads have passed. */ + if (cfg->busy_reads) { + s->qhead = 0; + s->qtail = 16; + } + s->hwcfg2 = CK_GSP_PRIV_LOCKED | 0xA7u; /* SIM-CHOICE: target locked to SEC2; low byte = "extra error information" (:272) */ + s->sec2_mb0 = 0; /* SIM-CHOICE: idle SEC2 mailbox value unknown; 0 */ + s->left = cfg->busy_reads; +} + +/* SEC2 checks the packet the driver's way round: MCTP dword 1 (the GB10B HAL constant, ksec2CreateMctpHeader_539ab4), NVDM vendor PCI 0x10de type COT, payload + * version 1, size 860 (kernel_sec2.c:305-325, fsp_mctp_format.h, kern_fsp_cot_payload.h). Anything else: + * SIM-CHOICE, SEC2 consumes it and never releases the target mask (a refused chain of trust). */ +static uint32_t packet_ok(const struct ck_gspsim *s) +{ + return s->qtail == 864u && s->emem[0] == 0x00000001u && s->emem[1] == 0x1410DE7Eu && + (s->emem[2] & 0xFFFFu) == 1u && (s->emem[2] >> 16) == 860u; +} + +static uint32_t sim_rd(void *ctx, uint32_t off) +{ + struct ck_gspsim *s = ctx; + uint32_t v = 0; + + switch (off) { + case CK_GSP_SEC2_QHEAD0: + if (s->phase == PHASE_IDLE && s->qhead != s->qtail) { + if (s->left == 0) + s->qhead = s->qtail; /* busy_reads busy reads have passed: SEC2 drained the channel */ + else if (s->left != CK_GSPSIM_NO_END) + s->left--; + } + v = s->qhead; + break; + case CK_GSP_SEC2_QTAIL0: v = s->qtail; break; + case CK_GSP_SEC2_EMEMC0: v = s->ememc; break; + case CK_GSP_SEC2_EMEMD0: v = s->emem[(((s->ememc >> 8) & 0xFFu) * 64u + ((s->ememc >> 2) & 0x3Fu)) & 255u]; break; + case CK_GSP_SEC2_MAILBOX0: + if (s->phase == PHASE_POSTED) { + if (s->left == 0) { + s->sec2_mb0 = 0; + s->qhead = s->qtail; /* consumed */ + if (s->packet_ok) { + s->phase = PHASE_MASK; + s->left = s->cfg.mask_reads; + s->zero_left = s->cfg.hwcfg2_zero_reads; + } else { + s->phase = PHASE_REJECTED; + } + } else if (s->left != CK_GSPSIM_NO_END) { + s->left--; + } + } + v = s->sec2_mb0; + break; + case CK_GSP_SEC2_MAILBOX1: v = s->sec2_mb1; break; + case CK_GSP_FLCN_HWCFG2: + if (s->phase == PHASE_MASK && s->zero_left) { + if (s->zero_left != CK_GSPSIM_NO_END) + s->zero_left--; + logev(s, off, 0, 0); + return 0; /* the driver's mask check treats 0 as not released (kernel_sec2_gb10b.c:282) */ + } + if (s->phase == PHASE_MASK) { + if (s->left == 0) { + s->phase = PHASE_FMC; + s->hwcfg2 = CK_GSP_HWCFG2_LOCKDOWN | 0x5u; /* SIM-CHOICE: other HWCFG2 bits */ + s->gsp_mb0 = (uint32_t)s->cfg.fmc_args_pa; + s->gsp_mb1 = (uint32_t)(s->cfg.fmc_args_pa >> 32); + s->left = s->cfg.lockdown_reads; + } else if (s->left != CK_GSPSIM_NO_END) { + s->left--; + } + } else if (s->phase == PHASE_FMC && s->gsp_mb0 != (uint32_t)s->cfg.fmc_args_pa) { + /* the FMC has read its arguments: count down to release (or the error code) */ + if (s->left == 0) { + if (s->cfg.fmc_error) { + s->gsp_mb0 = s->cfg.fmc_error; + } else { + s->hwcfg2 &= ~CK_GSP_HWCFG2_LOCKDOWN; + s->phase = PHASE_UP; + if (!s->cfg.riscv_dead) + s->cpuctl = CK_GSP_CPUCTL_ACTIVE; + } + } else if (s->left != CK_GSPSIM_NO_END) { + s->left--; + } + } + v = s->hwcfg2; + break; + case CK_GSP_FLCN_MAILBOX0: + if (s->phase == PHASE_FMC && s->gsp_mb0 == (uint32_t)s->cfg.fmc_args_pa) { + if (s->cfg.args_reads == CK_GSPSIM_NO_END) { + } else if (s->cfg.args_reads == 0) { + s->gsp_mb0 = s->gsp_mb1 = 0; + } else { + s->cfg.args_reads--; + } + } + v = s->gsp_mb0; + break; + case CK_GSP_FLCN_MAILBOX1: v = s->gsp_mb1; break; + case CK_GSP_FLCN_OS: v = s->os; break; + case CK_GSP_RISCV_CPUCTL: v = s->cpuctl; break; + default: s->violations++; break; + } + logev(s, off, v, 0); + return v; +} + +static void sim_wr(void *ctx, uint32_t off, uint32_t val) +{ + struct ck_gspsim *s = ctx; + logev(s, off, val, 1); + switch (off) { + case CK_GSP_SEC2_EMEMC0: s->ememc = val; break; + case CK_GSP_SEC2_EMEMD0: { + uint32_t dw = ((s->ememc >> 8) & 0xFFu) * 64u + ((s->ememc >> 2) & 0x3Fu); + if (!(s->ememc & CK_GSP_EMEMC_AINCW) || dw >= 256u || s->phase != PHASE_IDLE) { + s->violations++; + break; + } + s->emem[dw] = val; + if (!s->cfg.emem_no_inc) { + dw++; + s->ememc = (s->ememc & ~0xFFFCu) | ((dw / 64u) & 0xFFu) << 8 | (dw % 64u) << 2; + } + break; + } + case CK_GSP_SEC2_QTAIL0: + if (s->phase != PHASE_IDLE || s->qhead != s->qtail) + s->violations++; /* the driver writes only into an empty channel */ + s->qtail = val; + break; + case CK_GSP_SEC2_QHEAD0: + /* the doorbell: TAIL must already point at the last dword of a message starting at 0 */ + if (s->phase != PHASE_IDLE || val != 0 || s->qtail == s->qhead) + s->violations++; + s->qhead = val; + if (s->phase == PHASE_IDLE) { + s->packet_ok = packet_ok(s); + s->phase = PHASE_POSTED; + s->sec2_mb0 = CK_GSP_SEC2_CMD_BUSY; + s->left = s->cfg.cmd_reads; + } + break; + case CK_GSP_FLCN_OS: + s->os = val; + s->os_written_at_phase = s->phase; + if (s->phase != PHASE_UP) + s->violations++; /* FALCON_OS before lockdown release */ + break; + case CK_GSP_QHEAD0: + s->gsp_qhead_writes++; + if (val != 0) + s->violations++; + break; + default: s->violations++; break; + } +} + +struct ck_gpu_regs ck_gspsim_regs(struct ck_gspsim *s) +{ + struct ck_gpu_regs r = {sim_rd, sim_wr, s}; + return r; +} diff --git a/native/kernel/gpu/gsp_sim.h b/native/kernel/gpu/gsp_sim.h new file mode 100644 index 00000000..15ba47e4 --- /dev/null +++ b/native/kernel/gpu/gsp_sim.h @@ -0,0 +1,52 @@ +/* gsp_sim.h -- a simulated GB10B SEC2 + GSP falcon for host tests of gsp_mmio (L332, L346). NOT the chip. + * + * Models only what the driver source says the host sees on BAR0 during the GSP start-up: SEC2 EMEM + * channel 0 (1 KiB, EMEMC/EMEMD with write auto-increment), its queue HEAD/TAIL and MAILBOX0/1, and the + * GSP falcon's MAILBOX0/1, HWCFG2 (target-mask pattern, lockdown bit 13), FALCON_OS, RISC-V CPUCTL and + * QUEUE_HEAD(0). Timing is counted in register reads of the polled register. Every access is logged in + * order; accesses the driver never makes, and orders it never uses, are counted as violations. + * Choices the source does not settle are marked SIM-CHOICE. */ +#ifndef CK_GSP_SIM_H +#define CK_GSP_SIM_H + +#include +#include "gmmu.h" + +#define CK_GSPSIM_LOG_MAX 1024u +#define CK_GSPSIM_NO_END 0xFFFFFFFFu /* a wait that never ends */ + +struct ck_gspsim_cfg { + uint32_t busy_reads; /* HEAD reads during which the SEC2 channel still holds an old message */ + uint32_t cmd_reads; /* MAILBOX0 reads that return 0xc001cafe after the doorbell */ + uint32_t mask_reads; /* HWCFG2 reads that return 0xBADF41A7 after the command is handled */ + uint32_t args_reads; /* GSP MAILBOX0 reads that still return the boot-argument address */ + uint32_t lockdown_reads; /* HWCFG2 reads with lockdown set after the target mask is released */ + uint32_t fmc_error; /* non-zero: the FMC writes this code to GSP MAILBOX0 instead of releasing */ + uint32_t riscv_dead; /* RISC-V never reports ACTIVE */ + uint32_t emem_no_inc; /* hardware fault: EMEMC does not advance */ + uint64_t fmc_args_pa; /* what SEC2 stuffs in GSP MAILBOX0/1 (SIM-CHOICE: the driver tolerates it) */ + uint32_t hwcfg2_zero_reads; /* HWCFG2 reads that return 0 before the target-mask pattern (SIM-CHOICE) */ +}; + +struct ck_gspsim_ev { + uint32_t off, val; + uint8_t write; +}; + +struct ck_gspsim { + struct ck_gspsim_cfg cfg; + uint32_t emem[256]; + uint32_t ememc, qhead, qtail; + uint32_t sec2_mb0, sec2_mb1; + uint32_t gsp_mb0, gsp_mb1, hwcfg2, os, cpuctl, gsp_qhead_writes; + /* phase: 0 idle, 1 command posted, 2 handled (mask), 3 FMC running (lockdown), 4 released, 9 rejected */ + uint32_t phase, left, zero_left; + uint32_t packet_ok, os_written_at_phase; + struct ck_gspsim_ev log[CK_GSPSIM_LOG_MAX]; + uint32_t nlog, violations; +}; + +void ck_gspsim_init(struct ck_gspsim *s, const struct ck_gspsim_cfg *cfg); +struct ck_gpu_regs ck_gspsim_regs(struct ck_gspsim *s); + +#endif diff --git a/native/kernel/tests/.crumb b/native/kernel/tests/.crumb index bbe12fd3..15762248 100644 --- a/native/kernel/tests/.crumb +++ b/native/kernel/tests/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-25T22:00:40Z", + "compiled_at": "2026-10-30T03:02:40Z", "compiler": "crumb-compile/1", - "digest": "sha256:3d8d13940b9e77faa860d813f783060abb1a4664080e76d2d28b0004ab739b5f", + "digest": "sha256:acfa2498911bb31a591f115cfde818686f9e80cba2c7a3902da5ecd5a90a7aa1", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 189, - "generated_at_commit": "270eb462620d5fe3d7e287024546346719e72a96", - "source_tree": "sha256:1d64dae4e6166aff3597ebee7fd791126c76dc830270e2422a29ca3144f8b7a1" + "files": 196, + "generated_at_commit": "93fe68cfd18e0d3768be442776a3c4ebaf7f0667", + "source_tree": "sha256:ebf8b5349a8dfe6f7e365c8c96819a4ca32ae56b49ca69744f6ec92440768976" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/tests/gpu_chan_trace.c b/native/kernel/tests/gpu_chan_trace.c new file mode 100644 index 00000000..7c4bd2fd --- /dev/null +++ b/native/kernel/tests/gpu_chan_trace.c @@ -0,0 +1,121 @@ +/* gpu_chan_trace: the differential trace for the two channel twins (L332 rung 1). + * + * Runs one fixed script of channel operations on the simulated GB10 (gpu_sim) + * and prints, after every operation, its return code, every register access the + * simulator logged since the last line, and a hash of the whole simulated memory + * (page tables, ring, USERD, instance block, data). Built once with the hand + * channel (gpu/gpu_chan.c, L193) and once with the generated one + * (gpu/contract/gen/gch_contract.c from gpu/contract/gb10_chan.devc); the two + * outputs must be byte-identical (`make gpu-contract-trace`). + * The script covers: refused arguments, create, 300 submits across ring wraps + * with retires, a full ring, a bad span and address, teardown idle, and teardown + * of a hung channel (quarantine). */ +#include "gmmu.h" +#include "gpu_chan.h" +#include "gpu_mem.h" +#include "gpu_sim.h" +#include +#include +#include + +#define MEM_BYTES (8u << 20) +#define PA_BASE 0x80000000ull +#define POOL_PA PA_BASE +#define DATA_PA (PA_BASE + 64ull * 4096u) +#define VA_BASE 0x0000000200000000ull + +static uint8_t *mem; +static struct ck_gsim sim; +static struct ck_gpu_regs regs; +static struct ck_gmmu_as as; +static struct ck_gmem gm; +static uint32_t seen; +static unsigned step; + +static uint64_t fnv(const uint8_t *p, uint64_t n) +{ + uint64_t h = 0xcbf29ce484222325ull; + for (uint64_t i = 0; i < n; i++) + h = (h ^ p[i]) * 0x100000001b3ull; + return h; +} + +static void line(const char *what, int rc) +{ + printf("%04u %-24s rc=%d", step++, what, rc); + for (; seen < sim.nlog; seen++) + printf(" %c%06x=%08x", sim.log[seen].write ? 'W' : 'R', sim.log[seen].off, sim.log[seen].val); + printf(" doorbells=%u mem=%016llx\n", sim.doorbells, (unsigned long long)fnv(mem, MEM_BYTES)); +} + +static void fresh(void) +{ + memset(mem, 0xA5, MEM_BYTES); + ck_gsim_init(&sim, mem, PA_BASE, MEM_BYTES); + regs = ck_gsim_regs(&sim); + seen = 0; + if (ck_gmmu_as_init(&as, &sim.mem, POOL_PA, 64) != CK_GMMU_OK || ck_gmem_init(&gm, &as, ®s, 10, DATA_PA, 128, VA_BASE) != CK_GMEM_OK) { + printf("setup failed\n"); + exit(1); + } + line("setup", 0); +} + +int main(void) +{ + mem = malloc(MEM_BYTES); + if (!mem) + return 1; + struct ck_gpu_chan_ops ops = ck_gsim_chan_ops(); + struct ck_gpu_chan ch; + struct ck_gmem_buf *pb = 0, *sem = 0; + char what[64]; + + fresh(); + line("create chid>max", ck_gpu_chan_create(&ch, &gm, ®s, &ops, &sim, 0x1000, 1, 16)); + line("create runlist=0x7f", ck_gpu_chan_create(&ch, &gm, ®s, &ops, &sim, 3, 0x7F, 16)); + line("create entries=24", ck_gpu_chan_create(&ch, &gm, ®s, &ops, &sim, 3, 1, 24)); + line("create entries=1", ck_gpu_chan_create(&ch, &gm, ®s, &ops, &sim, 3, 1, 1)); + line("create", ck_gpu_chan_create(&ch, &gm, ®s, &ops, &sim, 3, 1, 16)); + printf("token=%08x rl=%08x,%08x\n", ch.d.token, ch.d.rl_entry[0], ch.d.rl_entry[1]); + line("alloc pb", ck_gmem_alloc(&gm, 8192, CK_GMEM_CACHED, CK_GMEM_GPU_RO, &pb)); + line("alloc sem", ck_gmem_alloc(&gm, 4096, CK_GMEM_UNCACHED, CK_GMEM_HOST_POLLED, &sem)); + for (uint32_t i = 0; i < 4096; i++) + pb->cpu[i] = (uint8_t)(i * 7u); + line("submit off=2", ck_gpu_chan_submit(&ch, pb, 2, 4)); + line("submit nwords=0", ck_gpu_chan_submit(&ch, pb, 0, 0)); + line("submit past end", ck_gpu_chan_submit(&ch, pb, 8188, 2)); + line("submit foreign buf", ck_gpu_chan_submit(&ch, (const struct ck_gmem_buf *)&ch, 0, 4)); + for (uint32_t i = 0; i < 300; i++) { + int rc = ck_gpu_chan_submit(&ch, pb, (i % 64u) * 64u, 1u + i % 16u); + snprintf(what, sizeof what, "submit %u", i); + line(what, rc); + if (rc == CK_GCHAN_EFULL || i % 5u == 4u) { + ck_gpu_chan_retire(&ch, ch.put - (i % 3u)); + snprintf(what, sizeof what, "retire put=%u ret=%u", ch.put, ch.retired); + line(what, 0); + } + } + ck_gpu_chan_retire(&ch, ch.put + 5u); /* past put: ignored */ + snprintf(what, sizeof what, "retire past put ret=%u", ch.retired); + line(what, 0); + struct ck_gmem_buf *extra[2] = {pb, sem}; + line("teardown idle", ck_gpu_chan_teardown(&ch, 4, extra, 2)); + line("teardown again", ck_gpu_chan_teardown(&ch, 4, extra, 2)); + line("submit after close", ck_gpu_chan_submit(&ch, pb, 0, 4)); + + fresh(); + line("create (hung run)", ck_gpu_chan_create(&ch, &gm, ®s, &ops, &sim, 7, 2, 8)); + pb = sem = 0; + line("alloc pb", ck_gmem_alloc(&gm, 4096, CK_GMEM_CACHED, CK_GMEM_GPU_RO, &pb)); + for (uint32_t i = 0; i < 9; i++) { + snprintf(what, sizeof what, "submit %u", i); + line(what, ck_gpu_chan_submit(&ch, pb, 0, 8)); + } + sim.hang = 1; + struct ck_gmem_buf *extra2[1] = {pb}; + line("teardown hung", ck_gpu_chan_teardown(&ch, 6, extra2, 1)); + printf("quarantined_pages=%u free_pages=%u\n", ck_gmem_count(&gm, CK_GMEM_QUARANTINED), ck_gmem_count(&gm, CK_GMEM_FREE)); + free(mem); + return 0; +} diff --git a/native/kernel/tests/gsp_boot_trace.c b/native/kernel/tests/gsp_boot_trace.c new file mode 100644 index 00000000..7d09e30f --- /dev/null +++ b/native/kernel/tests/gsp_boot_trace.c @@ -0,0 +1,73 @@ +/* gsp_boot_trace: every register access ck_gsp_mmio_boot and ck_gsp_mmio_notify make against the simulated SEC2 + + * GSP, in a fixed list of scenarios, printed one per line. Built twice (hand gsp_mmio.c, generated gsb_contract.c); + * the two outputs must be byte-identical (make gsp-contract-trace). Host only; nothing here has run on the chip. */ +#include "gsp_mmio.h" +#include "gsp_sim.h" +#include +#include + +#define ARGS_PA 0x0000000123456000ull + +static struct ck_gspsim sim; +static uint8_t pkt[1024]; + +static void nop(void *ctx) +{ + (void)ctx; +} + +static void scenario(const char *name, struct ck_gspsim_cfg c, uint32_t len, uint32_t budget, uint32_t hdr_ok) +{ + static const uint32_t hdr[3] = {0x00000001u, 0x1410DE7Eu, 1u | (860u << 16)}; + for (uint32_t i = 0; i < sizeof(pkt); i++) + pkt[i] = (uint8_t)(i * 13u + 5u); + if (hdr_ok) + memcpy(pkt, hdr, sizeof(hdr)); + struct ck_gsp_mmio_in in = {pkt, len, ARGS_PA, 0x0005f3a1u, budget, budget, budget, budget, nop, 0}; + struct ck_gsp_mmio_out o; + ck_gspsim_init(&sim, &c); + struct ck_gpu_regs r = ck_gspsim_regs(&sim); + int rc = ck_gsp_mmio_boot(&r, &in, &o); + if (rc == CK_GSP_OK) + ck_gsp_mmio_notify(&r); + printf("== %s rc=%d stage=%d polls=%u,%u,%u,%u dwords=%u ememc=%#x sec2=%#x,%#x hwcfg2=%#x gsp=%#x,%#x cpuctl=%#x" + " nlog=%u violations=%u phase=%u\n", + name, rc, o.stage, o.polls[0], o.polls[1], o.polls[2], o.polls[3], o.dwords, o.ememc_after, o.sec2_mb0, + o.sec2_mb1, o.hwcfg2, o.gsp_mb0, o.gsp_mb1, o.cpuctl, sim.nlog, sim.violations, sim.phase); + for (uint32_t i = 0; i < sim.nlog && i < CK_GSPSIM_LOG_MAX; i++) + printf("%c %06x %08x\n", sim.log[i].write ? 'W' : 'R', sim.log[i].off, sim.log[i].val); +} + +int main(void) +{ + const struct ck_gspsim_cfg base = {0, 3, 4, 2, 5, 0, 0, 0, ARGS_PA, 0}; + struct ck_gspsim_cfg c; + + scenario("happy", base, 868, 100, 1); + c = base; c.busy_reads = 3; + scenario("busy3", c, 868, 100, 1); + c = base; c.busy_reads = CK_GSPSIM_NO_END; + scenario("busy-forever", c, 868, 5, 1); + c = base; c.cmd_reads = CK_GSPSIM_NO_END; + scenario("sec2-never", c, 868, 5, 1); + c = base; c.mask_reads = CK_GSPSIM_NO_END; + scenario("mask-never", c, 868, 5, 1); + c = base; c.hwcfg2_zero_reads = 2; + scenario("hwcfg2-zero2", c, 868, 100, 1); + c = base; c.args_reads = CK_GSPSIM_NO_END; + scenario("args-never", c, 868, 6, 1); + c = base; c.lockdown_reads = CK_GSPSIM_NO_END; + scenario("lockdown-never", c, 868, 6, 1); + c = base; c.fmc_error = 0x23; + scenario("fmc-error", c, 868, 100, 1); + c = base; c.riscv_dead = 1; + scenario("riscv-dead", c, 868, 100, 1); + c = base; c.emem_no_inc = 1; + scenario("emem-stuck", c, 868, 100, 1); + scenario("bad-header", base, 868, 3, 0); + scenario("odd-7", base, 7, 3, 1); + scenario("full-1024", base, 1024, 3, 1); + scenario("too-long", base, 1025, 3, 1); + scenario("budget0", base, 868, 0, 1); + return 0; +} diff --git a/native/kernel/tests/test_gb10_gsp_boot.c b/native/kernel/tests/test_gb10_gsp_boot.c new file mode 100644 index 00000000..487fdfa5 --- /dev/null +++ b/native/kernel/tests/test_gb10_gsp_boot.c @@ -0,0 +1,391 @@ +/* test_gb10_gsp_boot -- host test for dev/gb10_gsp_boot.c (L192, aienos#286 cut C host side). + * Synthetic firmware bytes only; no device, no real firmware. Every decode below reads fixed byte + * offsets written out by hand from the NVIDIA headers (inventory sections 10-14), not the builder's + * mirror structs, so a wrong mirror offset fails here as well as in test_gb10_gsp_nvhdr. */ +#include +#include +#include +#include "ck_test.h" +#include "gb10_gsp_boot.h" + +static uint32_t r32(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 uint64_t r64(const uint8_t *p) { return (uint64_t)r32(p) | ((uint64_t)r32(p + 4) << 32); } +static uint16_t r16(const uint8_t *p) { return (uint16_t)(p[0] | (p[1] << 8)); } +static void w32(uint8_t *p, uint32_t v) { for (int i = 0; i < 4; i++) { p[i] = (uint8_t)v; v >>= 8; } } + +#define ARENA_PA 0x80000000ULL +#define ARENA_CAP (8u << 20) +#define ELF_SIZE (3u * 1024 * 1024 + 123) /* 769 data pages: radix levels 1, 1, 2, 769 */ +#define SIG_SIZE 4097u +#define FMC_SIZE 70000u + +static uint8_t *arena_mem, *elf, *bl, *sig, *fmc, hash[48], key[384], fsig[384], sysinfo[GSP_SYSTEM_INFO_SIZE]; +static const uint8_t bin_val[5] = {9, 8, 7, 6, 5}; +static const gsp_reg_entry regs[3] = { + {"RMSecBusResetEnable", GSP_REG_DWORD, 1, 0, 0}, + {"RmTestString", GSP_REG_STRING, 0, (const uint8_t *)"abc", 4}, + {"RmTestBin", GSP_REG_BINARY, 0, bin_val, 5}, +}; + +static void fill(uint8_t *p, size_t n, uint32_t seed) { for (size_t i = 0; i < n; i++) p[i] = (uint8_t)((i * 131u + seed) >> 3); } + +static gsp_boot_in good_input(void) +{ + gsp_boot_in in; + memset(&in, 0, sizeof in); + in.rm_elf = elf; in.rm_elf_size = ELF_SIZE; + in.rm_sig = sig; in.rm_sig_size = SIG_SIZE; + in.bootloader = bl; in.bootloader_size = GSP_GB10B_BOOTLOADER_SIZE; + in.bl_code_off = 0xb000; in.bl_data_off = 0xa00; in.bl_manifest_off = 0; + in.fmc = fmc; in.fmc_size = FMC_SIZE; in.fmc_hash = hash; in.fmc_pubkey = key; in.fmc_sig = fsig; + in.sysmem_heap_pa = 0x100000000ULL; in.sysmem_heap_size = 512u << 20; + in.system_info = sysinfo; + in.regs = regs; in.nregs = 3; + in.gpu_instance = 0; + in.dma_bits = 41; + return in; +} + +static uint8_t *at(uint64_t pa) { return arena_mem + (pa - ARENA_PA); } + +static int build(gsp_arena *a, const gsp_boot_in *in, gsp_boot_plan *plan, const char **why) +{ + memset(arena_mem, 0xA5, ARENA_CAP); /* the builder must zero what it takes */ + gsp_arena_init(a, arena_mem, ARENA_PA, ARENA_CAP); + return gsp_boot_build(a, in, plan, why); +} + +/* Check one element at slot ptr: checksum, header fields. Returns rpc length. */ +static uint32_t check_elem(const uint8_t *e, uint32_t seq_num, uint32_t fn, uint32_t rpc_seq, uint32_t elems) +{ + uint32_t len = r32(e + 48 + 8); + uint32_t msg = 48 + len, padded = (msg + 7) & ~7u; + uint8_t tmp[65536]; + memcpy(tmp, e, padded); + for (uint32_t i = msg; i < padded; i++) tmp[i] = 0; + CHECK(gsp_checksum32(tmp, padded) == 0); + CHECK(r32(e + 36) == seq_num); + CHECK(r32(e + 40) == elems); + CHECK(r32(e + 48) == 0x03000000u); + CHECK(r32(e + 52) == 0x43505256u); + CHECK(r32(e + 60) == fn); + CHECK(r32(e + 64) == 0xFFFFFFFFu && r32(e + 68) == 0xFFFFFFFFu); + CHECK(r32(e + 72) == rpc_seq); + return len; +} + +static void test_layout(void) +{ + gsp_arena a; gsp_boot_plan p; const char *why = 0; + gsp_boot_in in = good_input(); + CHECK(build(&a, &in, &p, &why) == 0); + if (why) printf(" build: %s\n", why); + + /* every region 4 KiB aligned, inside the arena, in order, not overlapping */ + gsp_region rs[] = { p.wpr_meta, p.libos_args, p.log[0], p.log[1], p.log[2], p.log[3], p.log[4], p.log[5], p.log[6], + p.args_cached, p.rpc_shared, p.radix3, p.bootloader, p.signature, p.fmc, p.fmc_params }; + uint64_t end = ARENA_PA; + for (size_t i = 0; i < sizeof rs / sizeof rs[0]; i++) { + CHECK((rs[i].pa & 4095) == 0); + CHECK(rs[i].pa >= end); + end = rs[i].pa + rs[i].size; + } + CHECK(end <= ARENA_PA + a.used && a.used <= ARENA_CAP); + + /* GspFwWprMeta (gsp_fw_wpr_meta.h, natural layout) */ + const uint8_t *w = at(p.wpr_meta.pa); + CHECK(r64(w + 0) == 0xdc3aae21371a60b3ULL && r64(w + 8) == 1); + CHECK(r64(w + 16) == p.radix3_root_pa && r64(w + 24) == ELF_SIZE); + CHECK(r64(w + 32) == p.bootloader.pa && r64(w + 40) == 196608); + CHECK(r64(w + 48) == 0xb000 && r64(w + 56) == 0xa00 && r64(w + 64) == 0); + CHECK(r64(w + 72) == p.signature.pa && r64(w + 80) == 4352 && (p.signature.pa & 255) == 0); + CHECK(r64(w + 128) == (133ULL << 20)); + int fmc_owned_zero = 1; + for (int off = 88; off < 256; off += 8) + if (off != 128 && r64(w + off) != 0) fmc_owned_zero = 0; + CHECK(fmc_owned_zero); /* FB layout, bootCount, flags, verified: FMC's */ + + /* libos init args: seven logs then RMARGS, CONTIGUOUS / SYSMEM */ + static const char *ids[8] = {"LOGINIT", "LOGINTR", "LOGRM", "LOGMNOC", "LOGDBG", "LOGROOT", "LOGKRNL", "RMARGS"}; + static const uint32_t sizes[8] = {0x10000, 0x10000, 0x10000, 0x10000, 0x10000, 0x1000, 0x10000, 0x1000}; + const uint8_t *l = at(p.libos_args.pa); + for (int i = 0; i < 8; i++) { + const uint8_t *e = l + 32 * i; + uint64_t want = 0; + for (const char *c = ids[i]; *c; c++) want = (want << 8) | (uint8_t)*c; + CHECK(r64(e) == want); + CHECK(r64(e + 8) == (i < 7 ? p.log[i].pa : p.args_cached.pa)); + CHECK(r64(e + 16) == sizes[i]); + CHECK(e[24] == 1 && e[25] == 1); + } + CHECK(r64(l) == 0x004C4F47494E4954ULL); /* "LOGINIT" big-endian packed */ + CHECK(r64(l + 32 * 8) == 0 && r64(l + 32 * 8 + 8) == 0); + + /* log buffers: put pointer 0, then one PA per page */ + for (int i = 0; i < 7; i++) { + const uint8_t *b = at(p.log[i].pa); + CHECK(r64(b) == 0); + CHECK(r64(b + 8) == p.log[i].pa); + CHECK(r64(b + 8 * (p.log[i].size / 4096)) == p.log[i].pa + p.log[i].size - 4096); + } + + /* GSP_ARGUMENTS_CACHED */ + const uint8_t *g = at(p.args_cached.pa); + CHECK(r64(g + 0) == p.rpc_shared.pa && r32(g + 8) == 129 && r64(g + 16) == 4096 && r64(g + 24) == 4096 + 0x40000); + CHECK(r32(g + 32) == 0 && r32(g + 36) == 0 && g[40] == 0); + CHECK(r32(g + 44) == 0 && g[48] == 1); + CHECK(r64(g + 56) == 0 && r64(g + 64) == 0); + CHECK(r64(g + 72) == 0x100000000ULL && r64(g + 80) == (512ULL << 20)); + + /* RPC shared buffer page table and command queue header */ + const uint8_t *s = at(p.rpc_shared.pa); + CHECK(p.rpc_shared.size == 129 * 4096); + CHECK(r64(s) == p.rpc_shared.pa && r64(s + 8 * 128) == p.rpc_shared.pa + 128 * 4096 && r64(s + 8 * 129) == 0); + CHECK(p.cmdq_pa == p.rpc_shared.pa + 4096 && p.statq_pa == p.rpc_shared.pa + 4096 + 0x40000); + const uint8_t *cq = at(p.cmdq_pa); + CHECK(r32(cq) == 0 && r32(cq + 4) == 0x40000 && r32(cq + 8) == 4096 && r32(cq + 12) == 63); + CHECK(r32(cq + 16) == 2 && r32(cq + 20) == 1 && r32(cq + 24) == 32 && r32(cq + 28) == 4096); + CHECK(p.cmdq_write_ptr == 2 && p.tx_seq == 2); + const uint8_t *sq = at(p.statq_pa); + int sq_zero = 1; + for (int i = 0; i < 4096; i++) if (sq[i]) sq_zero = 0; + CHECK(sq_zero); /* GSP creates the status queue */ + + /* element 0: GSP_SET_SYSTEM_INFO, async */ + const uint8_t *e0 = cq + 4096; + CHECK(check_elem(e0, 0, 72, 0, 1) == 32 + 936); + CHECK(memcmp(e0 + 80, sysinfo, 936) == 0); + /* element 1: SET_REGISTRY, async, PACKED_REGISTRY_TABLE */ + const uint8_t *e1 = cq + 2 * 4096; + uint32_t rl = check_elem(e1, 1, 73, 0, 1); + const uint8_t *t = e1 + 80; + uint32_t tsize = 8 + 16 * 3 + 20 + 13 + 4 + 10 + 5; + CHECK(rl == 32 + tsize && r32(t) == tsize && r32(t + 4) == 3); + CHECK(r32(t + 8) == 56 && t[12] == 1 && r32(t + 16) == 1 && r32(t + 20) == 4); + CHECK(strcmp((const char *)t + 56, "RMSecBusResetEnable") == 0); + CHECK(r32(t + 24) == 76 && t[28] == 3 && r32(t + 32) == 89 && r32(t + 36) == 4); + CHECK(strcmp((const char *)t + 76, "RmTestString") == 0 && strcmp((const char *)t + 89, "abc") == 0); + CHECK(r32(t + 40) == 93 && t[44] == 2 && r32(t + 48) == 103 && r32(t + 52) == 5); + CHECK(memcmp(t + 103, bin_val, 5) == 0); + CHECK(t[13] == 0 && t[14] == 0 && t[15] == 0); + + /* radix-3: level pages 1, 1, 2, 769; each level points at the next; data is the ELF */ + CHECK(p.radix3_level_pages[0] == 1 && p.radix3_level_pages[1] == 1 && p.radix3_level_pages[2] == 2 && p.radix3_level_pages[3] == 769); + CHECK(p.radix3.size == (4 + 769) * 4096ULL && p.elf_data_pa == p.radix3.pa + 4 * 4096); + const uint8_t *r0 = at(p.radix3.pa), *r1 = r0 + 4096, *r2 = r0 + 2 * 4096; + CHECK(r64(r0) == p.radix3.pa + 4096 && r64(r0 + 8) == 0); + CHECK(r64(r1) == p.radix3.pa + 2 * 4096 && r64(r1 + 8) == p.radix3.pa + 3 * 4096 && r64(r1 + 16) == 0); + CHECK(r64(r2) == p.elf_data_pa && r64(r2 + 8 * 511) == p.elf_data_pa + 511 * 4096ULL); + CHECK(r64(r2 + 4096) == p.elf_data_pa + 512 * 4096ULL && r64(r2 + 4096 + 8 * 256) == p.elf_data_pa + 768 * 4096ULL); + CHECK(r64(r2 + 4096 + 8 * 257) == 0); + CHECK(memcmp(at(p.elf_data_pa), elf, ELF_SIZE) == 0 && at(p.elf_data_pa)[ELF_SIZE] == 0); + + /* firmware copies */ + CHECK(memcmp(at(p.bootloader.pa), bl, 196608) == 0); + CHECK(memcmp(at(p.signature.pa), sig, SIG_SIZE) == 0 && at(p.signature.pa)[SIG_SIZE] == 0); + CHECK(memcmp(at(p.fmc.pa), fmc, FMC_SIZE) == 0); + + /* GSP_FMC_BOOT_PARAMS (gspifpub.h, natural layout) */ + const uint8_t *f = at(p.fmc_params.pa); + CHECK(r32(f + 0) == 0 && r32(f + 8) == 1 && r32(f + 12) == 256 && r64(f + 16) == p.wpr_meta.pa); + CHECK(r64(f + 24) == 0 && r32(f + 32) == 0 && f[36] == 1); + CHECK(r32(f + 40) == 2 && r64(f + 48) == p.libos_args.pa); + CHECK(r32(f + 56) == 0 && r64(f + 64) == 0 && r32(f + 72) == 0 && r32(f + 80) == 0 && r32(f + 84) == 0); + + /* SEC2 packet: MCTP dword 1 (GB10B HAL constant), NVDM 0x7e / 0x10de / COT 0x14, NVDM_PAYLOAD_COT packed */ + const uint8_t *k = p.cot_packet; + CHECK(r32(k) == 0x00000001u && r32(k + 4) == 0x1410de7eu); + CHECK(p.cot_packet_len == 868 && p.emem_queue_tail == 864); + const uint8_t *c = k + 8; + CHECK(r16(c) == 1 && r16(c + 2) == 860); + CHECK(r64(c + 4) == p.fmc.pa && r64(c + 12) == 0 && r32(c + 20) == FMC_SIZE && r64(c + 24) == 0 && r32(c + 32) == 0); + CHECK(memcmp(c + 36, hash, 48) == 0 && memcmp(c + 84, key, 384) == 0 && memcmp(c + 468, fsig, 384) == 0); + CHECK(r64(c + 852) == p.fmc_params.pa); + int tail_zero = 1; + for (int i = 868; i < 1024; i++) if (k[i]) tail_zero = 0; + CHECK(tail_zero); + + /* deterministic: same input, same bytes */ + uint8_t *copy = malloc(a.used); + memcpy(copy, arena_mem, a.used); + gsp_boot_plan p2; gsp_arena a2; + CHECK(build(&a2, &in, &p2, &why) == 0 && a2.used == a.used && memcmp(copy, arena_mem, a.used) == 0 && + memcmp(&p, &p2, sizeof p) == 0); + free(copy); + + /* no registry: only SET_SYSTEM_INFO queued */ + gsp_boot_in nr = in; nr.nregs = 0; nr.regs = 0; + CHECK(build(&a, &nr, &p, &why) == 0 && p.cmdq_write_ptr == 1 && p.tx_seq == 1); +} + +static void expect_refusal(gsp_boot_in in, const char *want) +{ + gsp_arena a; gsp_boot_plan p; const char *why = 0; + int rc = build(&a, &in, &p, &why); + CHECK(rc == -1 && why && strcmp(why, want) == 0); + if (rc != -1 || !why || strcmp(why, want)) printf(" wanted \"%s\", got \"%s\"\n", want, why ? why : "(accepted)"); +} + +static void test_refusals(void) +{ + gsp_boot_in in; + in = good_input(); in.rm_elf = 0; expect_refusal(in, "GSP-RM ELF missing"); + in = good_input(); in.rm_elf_size = 0; expect_refusal(in, "GSP-RM ELF missing"); + in = good_input(); in.rm_sig_size = 0; expect_refusal(in, "GSP-RM signature missing"); + in = good_input(); in.bootloader_size = 196608 + 4096; expect_refusal(in, "bootloader is not the GB10B GspRmBoot image size"); + in = good_input(); in.bl_code_off = 0xa000; expect_refusal(in, "bootloader descriptor offsets are not the GB10B values"); + in = good_input(); in.bl_manifest_off = 0x100; expect_refusal(in, "bootloader descriptor offsets are not the GB10B values"); + in = good_input(); in.fmc_size = 0; expect_refusal(in, "GSP-FMC image missing"); + in = good_input(); in.fmc_hash = 0; expect_refusal(in, "GSP-FMC hash, key or signature missing"); + in = good_input(); in.sysmem_heap_pa = 0x100000800ULL; expect_refusal(in, "sysmem heap zero or not 4 KiB aligned"); + in = good_input(); in.sysmem_heap_size = 0; expect_refusal(in, "sysmem heap zero or not 4 KiB aligned"); + in = good_input(); in.system_info = 0; expect_refusal(in, "GspSystemInfo missing"); + in = good_input(); in.dma_bits = 0; expect_refusal(in, "dma_bits out of range"); + in = good_input(); in.dma_bits = 31; expect_refusal(in, "address beyond the DMA window"); /* arena at 2 GiB */ + in = good_input(); in.dma_bits = 32; expect_refusal(in, "address beyond the DMA window"); /* heap at 4 GiB */ + in = good_input(); in.rm_elf_size = (1ULL << 39) + 1; expect_refusal(in, "ELF too large for a 3-level radix table"); + in = good_input(); in.rm_elf_size = 8u << 20; expect_refusal(in, "arena too small"); + gsp_reg_entry bad[2] = { {"", GSP_REG_DWORD, 1, 0, 0}, {"x", GSP_REG_STRING, 0, 0, 0} }; + in = good_input(); in.regs = bad; in.nregs = 1; expect_refusal(in, "registry entry invalid or too large"); + in = good_input(); in.regs = bad + 1; in.nregs = 1; expect_refusal(in, "registry entry invalid or too large"); + gsp_reg_entry many[GSP_REG_MAX_ENTRIES + 1]; + for (unsigned i = 0; i <= GSP_REG_MAX_ENTRIES; i++) many[i] = (gsp_reg_entry){"k", GSP_REG_DWORD, i, 0, 0}; + in = good_input(); in.regs = many; in.nregs = GSP_REG_MAX_ENTRIES + 1; expect_refusal(in, "registry entry invalid or too large"); + in = good_input(); in.regs = many; in.nregs = GSP_REG_MAX_ENTRIES; + { gsp_arena a; gsp_boot_plan p; const char *why = 0; CHECK(build(&a, &in, &p, &why) == 0); } + /* builder on a used arena */ + { gsp_arena a; gsp_boot_plan p; const char *why = 0; in = good_input(); + CHECK(build(&a, &in, &p, &why) == 0); CHECK(gsp_boot_build(&a, &in, &p, &why) == -1 && strcmp(why, "arena not empty") == 0); } + /* arena init */ + gsp_arena a; + CHECK(gsp_arena_init(&a, arena_mem, ARENA_PA + 8, ARENA_CAP) == -1); + CHECK(gsp_arena_init(&a, arena_mem + 8, ARENA_PA, ARENA_CAP) == -1); + CHECK(gsp_arena_init(&a, arena_mem, ~0ULL - 4095, ARENA_CAP) == -1); + CHECK(gsp_arena_init(&a, 0, ARENA_PA, ARENA_CAP) == -1); +} + +/* Simulated GSP side: create the status queue the way msgqTxCreate would and post one message. */ +static void gsp_post(uint8_t *sq, uint32_t slot, uint32_t seq_num, uint32_t fn, uint32_t result, uint32_t payload_len) +{ + w32(sq + 0, 0); w32(sq + 4, 0x40000); w32(sq + 8, 4096); w32(sq + 12, 63); + w32(sq + 20, 1); w32(sq + 24, 32); w32(sq + 28, 4096); + uint8_t *e = sq + 4096 + slot * 4096; + memset(e, 0, 4096); + w32(e + 36, seq_num); w32(e + 40, 1); + w32(e + 48, 0x03000000u); w32(e + 52, 0x43505256u); w32(e + 56, 32 + payload_len); w32(e + 60, fn); + w32(e + 64, result); w32(e + 68, result); + for (uint32_t i = 0; i < payload_len; i++) e[80 + i] = (uint8_t)(i + 1); + uint32_t padded = (48 + 32 + payload_len + 7) & ~7u; + w32(e + 32, gsp_checksum32(e, padded)); + w32(sq + 16, (slot + 1) % 63); +} + +static void test_rpcs(void) +{ + gsp_arena a; gsp_boot_plan p; const char *why = 0; + gsp_boot_in in = good_input(); + CHECK(build(&a, &in, &p, &why) == 0); + gsp_mq q; + CHECK(gsp_mq_attach(&q, &a, &p) == 0 && q.tx_seq == 2); + uint8_t *cq = at(p.cmdq_pa), *sq = at(p.statq_pa); + uint32_t seq = 99; + + /* GSP_RM_ALLOC: length covers the fixed part only, params follow in the same element */ + uint8_t params[300]; + fill(params, sizeof params, 7); + CHECK(gsp_rpc_rm_alloc(&q, 0xc1d00001, 0xc1d00001, 0xcaf00001, 0x0080, params, sizeof params, &seq, &why) == 0 && seq == 0); + const uint8_t *e = cq + 4096 + 2 * 4096; + CHECK(check_elem(e, 2, 103, 0, 1) == 64); + CHECK(r32(e + 80) == 0xc1d00001 && r32(e + 84) == 0xc1d00001 && r32(e + 88) == 0xcaf00001 && r32(e + 92) == 0x80); + CHECK(r32(e + 96) == 0 && r32(e + 100) == 300 && r32(e + 104) == 0 && r32(e + 108) == 0); + CHECK(memcmp(e + 112, params, 300) == 0 && e[412] == 0); + + /* GSP_RM_CONTROL spanning two elements */ + uint8_t *big = malloc(5000); + fill(big, 5000, 3); + CHECK(gsp_rpc_rm_control(&q, 0xc1d00001, 0xcaf00002, 0x20800110, big, 5000, &seq, &why) == 0 && seq == 1); + e = cq + 4096 + 3 * 4096; + CHECK(r32(e + 40) == 2 && r32(e + 56) == 32 + 40 + 5000); + uint8_t *flat = malloc(8192); + memcpy(flat, e, 8192); /* slots 3 and 4 are adjacent */ + CHECK(check_elem(flat, 3, 76, 1, 2) == 32 + 40 + 5000); + CHECK(r32(flat + 80) == 0xc1d00001 && r32(flat + 84) == 0xcaf00002 && r32(flat + 88) == 0x20800110 && r32(flat + 96) == 5000); + CHECK(r64(flat + 112) == 0 && memcmp(flat + 120, big, 5000) == 0); + + /* free and static-info (3 elements, zero payload) */ + CHECK(gsp_rpc_rm_free(&q, 0xc1d00001, 0xcaf00001, &seq, &why) == 0 && seq == 2); + e = cq + 4096 + 5 * 4096; + CHECK(check_elem(e, 4, 10, 2, 1) == 48); + CHECK(r32(e + 80) == 0xc1d00001 && r32(e + 84) == 0 && r32(e + 88) == 0xcaf00001 && r32(e + 92) == 0); + CHECK(gsp_rpc_get_static_info(&q, 9000, &seq, &why) == 0 && seq == 3); + e = cq + 4096 + 6 * 4096; + CHECK(r32(e + 40) == 3 && r32(e + 56) == 9032 && r32(e + 60) == 65); + CHECK(r32(cq + 16) == 9 && q.tx_seq == 6); + CHECK(gsp_rpc_get_static_info(&q, 0, &seq, &why) == -1); + CHECK(gsp_rpc_get_static_info(&q, 65457, &seq, &why) == -1); + CHECK(gsp_rpc_rm_control(&q, 1, 2, 3, big, 65488 - 32 - 40 + 1, &seq, &why) == -1); + + /* ring full: 62 usable slots, GSP has read none */ + int sent = 0; + while (gsp_rpc_rm_free(&q, 1, 2, &seq, &why) == 0) sent++; + CHECK(sent == 62 - 9 && strcmp(why, "command queue full") == 0); + /* GSP consumes everything (its readPtr is in the status queue at rxHdrOff), then a 2-element + * control wraps the ring end: slot 62 then slot 0 */ + w32(sq + 32, r32(cq + 16)); + CHECK(r32(cq + 16) == 62); + CHECK(gsp_rpc_rm_control(&q, 5, 6, 7, big, 5000, &seq, &why) == 0); + CHECK(r32(cq + 16) == 1); + memcpy(flat, cq + 4096 + 62 * 4096, 4096); + memcpy(flat + 4096, cq + 4096, 4096); + CHECK(check_elem(flat, q.tx_seq - 1, 76, seq, 2) == 32 + 40 + 5000 && memcmp(flat + 120, big, 5000) == 0); + /* corrupt ring pointer refused */ + w32(sq + 32, 63); + CHECK(gsp_rpc_rm_free(&q, 1, 2, &seq, &why) == -1 && strcmp(why, "ring pointer corrupt") == 0); + w32(sq + 32, 1); + + /* payload outside the covered elements refused */ + gsp_seg sg = { big, 4096 }; + CHECK(gsp_mq_send(&q, 1, &sg, 1, 16, 1, &seq, &why) == -1 && strcmp(why, "payload beyond the elements the length covers") == 0); + CHECK(gsp_mq_send(&q, 1, &sg, 1, 4096, 1, &seq, &why) == 0); + gsp_seg zs = { 0, 65457 }; + CHECK(gsp_mq_send(&q, 1, &zs, 1, 65457, 1, &seq, &why) == -1 && strcmp(why, "message length out of range") == 0); + CHECK(gsp_mq_send(&q, 1, &sg, 1, 5000, 1, &seq, &why) == -1 && strcmp(why, "payload shorter than the RPC length") == 0); + free(big); + + /* status queue: empty, then GSP_INIT_DONE, then checks */ + uint8_t out[65536]; + uint32_t fn = 0, res = 0; + CHECK(gsp_mq_recv(&q, out, sizeof out, &fn, &res, &why) == -1); /* not created yet */ + gsp_post(sq, 0, 0, GSP_EV_INIT_DONE, 0, 0); + w32(sq + 16, 0); + CHECK(gsp_mq_recv(&q, out, sizeof out, &fn, &res, &why) == 0); /* created, empty */ + w32(sq + 16, 1); + CHECK(gsp_mq_recv(&q, out, sizeof out, &fn, &res, &why) == 1 && fn == 0x1001 && res == 0); + CHECK(r32(cq + 32) == 1 && q.rx_seq == 1); /* our readPtr, SWAP_RX */ + CHECK(gsp_mq_recv(&q, out, sizeof out, &fn, &res, &why) == 0); + gsp_post(sq, 1, 1, 103, 0, 20); + sq[4096 + 4096 + 90] ^= 1; + CHECK(gsp_mq_recv(&q, out, sizeof out, &fn, &res, &why) == -1 && strcmp(why, "checksum not zero") == 0); + gsp_post(sq, 1, 5, 103, 0, 20); + CHECK(gsp_mq_recv(&q, out, sizeof out, &fn, &res, &why) == -1 && strcmp(why, "bad sequence number") == 0); + gsp_post(sq, 1, 1, 103, 0, 20); + CHECK(gsp_mq_recv(&q, out, 64, &fn, &res, &why) == -1 && strcmp(why, "output too small") == 0); + CHECK(gsp_mq_recv(&q, out, sizeof out, &fn, &res, &why) == 1 && fn == 103 && out[80] == 1 && out[99] == 20); + gsp_post(sq, 2, 2, 103, 0, 20); + w32(sq + 4096 + 2 * 4096 + 40, 5); + CHECK(gsp_mq_recv(&q, out, sizeof out, &fn, &res, &why) == -1 && strcmp(why, "element count bad") == 0); + free(flat); +} + +int main(void) +{ + arena_mem = aligned_alloc(4096, ARENA_CAP); + elf = malloc(ELF_SIZE); bl = malloc(196608); sig = malloc(SIG_SIZE); fmc = malloc(FMC_SIZE); + fill(elf, ELF_SIZE, 1); fill(bl, 196608, 2); fill(sig, SIG_SIZE, 3); fill(fmc, FMC_SIZE, 4); + fill(hash, sizeof hash, 5); fill(key, sizeof key, 6); fill(fsig, sizeof fsig, 7); fill(sysinfo, sizeof sysinfo, 8); + test_layout(); + test_refusals(); + test_rpcs(); + free(arena_mem); free(elf); free(bl); free(sig); free(fmc); + return ck_t_verdict("test_gb10_gsp_boot"); +} diff --git a/native/kernel/tests/test_gb10_gsp_nvhdr.c b/native/kernel/tests/test_gb10_gsp_nvhdr.c new file mode 100644 index 00000000..7f1bd973 --- /dev/null +++ b/native/kernel/tests/test_gb10_gsp_nvhdr.c @@ -0,0 +1,192 @@ +/* test_gb10_gsp_nvhdr -- compares the builder's mirror structs (dev/gb10_gsp_boot.h) with the + * NVIDIA headers themselves, field by field, and decodes a built plan through the NVIDIA types. + * Needs open-gpu-kernel-modules at tag 580.173.02 (MIT) on the include path: the Makefile target + * gb10-gsp-nvhdr-test passes OGKM_DIR (default ~/workspace/_ext/open-gpu-kernel-modules-580.173.02) + * and fails, never skips, when the tree is missing. Host only; nothing NVIDIA is linked or shipped. + * + * Covered from the real headers: GspFwWprMeta, LibosMemoryRegionInitArgument, + * GSP_ARGUMENTS_CACHED (+ MESSAGE_QUEUE_INIT_ARGUMENTS, GSP_SR_INIT_ARGUMENTS), msgqTxHeader, + * msgqRxHeader, rpc_message_header_v03_00, rpc_gsp_rm_alloc_v03_00, rpc_gsp_rm_control_v03_00, + * rpc_free_v03_00, GSP_FMC_BOOT_PARAMS, NVDM_PAYLOAD_COT, the function and event numbers. + * GSP_MSG_QUEUE_ELEMENT (message_queue_priv.h) pulls RM-internal headers (nvassert.h needs an + * NV_PORT_HEADER); its five fields are re-declared here verbatim around NVIDIA's own + * rpc_message_header_v. PACKED_REGISTRY_TABLE (g_os_nvoc.h) and GspSystemInfo / + * GspStaticConfigInfo (gsp_static_config.h) are in the same position and stay checked by the + * hosted tool ck_gsp_rpc_encode (inventory section 13). */ +#include +#include +#include +#include +#include "nvtypes.h" +#include "nvstatus.h" +#include "gsp/gsp_fw_wpr_meta.h" +#include "libos_init_args.h" +#include "gpu/gsp/gsp_init_args.h" +#include "msgq/msgq_priv.h" +#include "gsp/gspifpub.h" +#include "fsp/fsp_nvdm_format.h" +#include "gpu/fsp/kern_fsp_cot_payload.h" +#include "vgpu/rpc_headers.h" +#define RPC_STRUCTURES +#define RPC_GENERIC_UNION +#include "g_rpc-structures.h" +#define RPC_MESSAGE_STRUCTURES +#include "g_rpc-message-header.h" +#include "ck_test.h" +#include "gb10_gsp_boot.h" + +typedef struct { /* message_queue_priv.h:43-51, verbatim fields */ + NvU8 authTagBuffer[16]; + NvU8 aadBuffer[16]; + NvU32 checkSum; + NvU32 seqNum; + NvU32 elemCount; + NV_DECLARE_ALIGNED(rpc_message_header_v rpc, 8); +} NV_GSP_MSG_QUEUE_ELEMENT; + +#define SAME(M, N, fm, fn) CHECK(offsetof(M, fm) == offsetof(N, fn) && sizeof(((M *)0)->fm) == sizeof(((N *)0)->fn)) + +static void test_layouts(void) +{ + CHECK(sizeof(gsp_mirror_wpr_meta) == sizeof(GspFwWprMeta)); +#define W(f) SAME(gsp_mirror_wpr_meta, GspFwWprMeta, f, f) + W(magic); W(revision); W(sysmemAddrOfRadix3Elf); W(sizeOfRadix3Elf); W(sysmemAddrOfBootloader); W(sizeOfBootloader); + W(bootloaderCodeOffset); W(bootloaderDataOffset); W(bootloaderManifestOffset); W(sysmemAddrOfSignature); W(sizeOfSignature); + W(gspFwRsvdStart); W(nonWprHeapOffset); W(nonWprHeapSize); W(gspFwWprStart); W(gspFwHeapOffset); W(gspFwHeapSize); + W(gspFwOffset); W(bootBinOffset); W(frtsOffset); W(frtsSize); W(gspFwWprEnd); W(fbSize); W(vgaWorkspaceOffset); + W(vgaWorkspaceSize); W(bootCount); W(partitionRpcAddr); W(partitionRpcRequestOffset); W(partitionRpcReplyOffset); + W(elfCodeOffset); W(elfDataOffset); W(elfCodeSize); W(elfDataSize); W(lsUcodeVersion); W(gspFwHeapVfPartitionCount); + W(flags); W(padding); W(pmuReservedSize); W(verified); + CHECK(GSP_WPR_META_MAGIC == GSP_FW_WPR_META_MAGIC && GSP_WPR_META_REVISION == GSP_FW_WPR_META_REVISION); + + CHECK(sizeof(gsp_mirror_libos_arg) == sizeof(LibosMemoryRegionInitArgument)); +#define L(f) SAME(gsp_mirror_libos_arg, LibosMemoryRegionInitArgument, f, f) + L(id8); L(pa); L(size); L(kind); L(loc); + CHECK(GSP_LIBOS_KIND_CONTIGUOUS == LIBOS_MEMORY_REGION_CONTIGUOUS && GSP_LIBOS_LOC_SYSMEM == LIBOS_MEMORY_REGION_LOC_SYSMEM); + + CHECK(sizeof(gsp_mirror_args_cached) == sizeof(GSP_ARGUMENTS_CACHED)); +#define A(fm, fn) SAME(gsp_mirror_args_cached, GSP_ARGUMENTS_CACHED, fm, fn) + A(mq.sharedMemPhysAddr, messageQueueInitArguments.sharedMemPhysAddr); + A(mq.pageTableEntryCount, messageQueueInitArguments.pageTableEntryCount); + A(mq.cmdQueueOffset, messageQueueInitArguments.cmdQueueOffset); + A(mq.statQueueOffset, messageQueueInitArguments.statQueueOffset); + A(sr.oldLevel, srInitArguments.oldLevel); A(sr.flags, srInitArguments.flags); + A(sr.bInPMTransition, srInitArguments.bInPMTransition); + A(gpuInstance, gpuInstance); A(bDmemStack, bDmemStack); + A(profilerArgs.pa, profilerArgs.pa); A(profilerArgs.size, profilerArgs.size); + A(sysmemHeapArgs.pa, sysmemHeapArgs.pa); A(sysmemHeapArgs.size, sysmemHeapArgs.size); + + CHECK(sizeof(gsp_mirror_msgq_tx) == sizeof(msgqTxHeader) && sizeof(msgqRxHeader) == 4); +#define T(f) SAME(gsp_mirror_msgq_tx, msgqTxHeader, f, f) + T(version); T(size); T(msgSize); T(msgCount); T(writePtr); T(flags); T(rxHdrOff); T(entryOff); + CHECK(GSP_MQ_FLAGS_SWAP_RX == MSGQ_FLAGS_SWAP_RX && MSGQ_VERSION == 0); + + CHECK(sizeof(gsp_mirror_rpc_hdr) == sizeof(rpc_message_header_v03_00)); +#define R(f) SAME(gsp_mirror_rpc_hdr, rpc_message_header_v03_00, f, f) + R(header_version); R(signature); R(length); R(function); R(rpc_result); R(rpc_result_private); R(sequence); + SAME(gsp_mirror_rpc_hdr, rpc_message_header_v03_00, cpuRmGfid, u.cpuRmGfid); + CHECK(GSP_RPC_SIGNATURE == NV_VGPU_MSG_SIGNATURE_VALID && GSP_RPC_PENDING == NV_VGPU_MSG_RESULT_RPC_PENDING); + CHECK(GSP_RPC_HEADER_VERSION == ((NV_VGPU_MSG_HEADER_VERSION_MAJOR_TOT << 24) | (NV_VGPU_MSG_HEADER_VERSION_MINOR_TOT << 16))); + + CHECK(sizeof(gsp_mirror_elem) == sizeof(NV_GSP_MSG_QUEUE_ELEMENT)); + SAME(gsp_mirror_elem, NV_GSP_MSG_QUEUE_ELEMENT, checkSum, checkSum); + SAME(gsp_mirror_elem, NV_GSP_MSG_QUEUE_ELEMENT, seqNum, seqNum); + SAME(gsp_mirror_elem, NV_GSP_MSG_QUEUE_ELEMENT, elemCount, elemCount); + SAME(gsp_mirror_elem, NV_GSP_MSG_QUEUE_ELEMENT, rpc, rpc); + +#define RA(f) SAME(gsp_mirror_rm_alloc, rpc_gsp_rm_alloc_v03_00, f, f) + RA(hClient); RA(hParent); RA(hObject); RA(hClass); RA(status); RA(paramsSize); RA(flags); RA(reserved); + CHECK(offsetof(rpc_gsp_rm_alloc_v03_00, params) == GSP_RM_ALLOC_FIXED); +#define RC(f) SAME(gsp_mirror_rm_control, rpc_gsp_rm_control_v03_00, f, f) + RC(hClient); RC(hObject); RC(cmd); RC(status); RC(paramsSize); RC(rmapiRpcFlags); RC(rmctrlFlags); + RC(rmctrlAccessRight); RC(reserved0); + CHECK(offsetof(rpc_gsp_rm_control_v03_00, params) == GSP_RM_CONTROL_FIXED); + CHECK(sizeof(rpc_free_v03_00) == GSP_RM_FREE_SIZE); +#define RF(f) SAME(gsp_mirror_rm_free, NVOS00_PARAMETERS_v03_00, f, f) + RF(hRoot); RF(hObjectParent); RF(hObjectOld); RF(status); + + CHECK(GSP_FN_FREE == NV_VGPU_MSG_FUNCTION_FREE && GSP_FN_GET_GSP_STATIC_INFO == NV_VGPU_MSG_FUNCTION_GET_GSP_STATIC_INFO && + GSP_FN_CONTINUATION == NV_VGPU_MSG_FUNCTION_CONTINUATION_RECORD && GSP_FN_SET_SYSTEM_INFO == NV_VGPU_MSG_FUNCTION_GSP_SET_SYSTEM_INFO && + GSP_FN_SET_REGISTRY == NV_VGPU_MSG_FUNCTION_SET_REGISTRY && GSP_FN_GSP_RM_CONTROL == NV_VGPU_MSG_FUNCTION_GSP_RM_CONTROL && + GSP_FN_GSP_RM_ALLOC == NV_VGPU_MSG_FUNCTION_GSP_RM_ALLOC); + CHECK(GSP_EV_INIT_DONE == NV_VGPU_MSG_EVENT_GSP_INIT_DONE && GSP_EV_RUN_CPU_SEQUENCER == NV_VGPU_MSG_EVENT_GSP_RUN_CPU_SEQUENCER); + + CHECK(sizeof(gsp_mirror_fmc_params) == sizeof(GSP_FMC_BOOT_PARAMS)); +#define F(fm, fn) SAME(gsp_mirror_fmc_params, GSP_FMC_BOOT_PARAMS, fm, fn) + F(regkeys, initParams.regkeys); + F(boot.target, bootGspRmParams.target); F(boot.gspRmDescSize, bootGspRmParams.gspRmDescSize); + F(boot.gspRmDescOffset, bootGspRmParams.gspRmDescOffset); F(boot.wprCarveoutOffset, bootGspRmParams.wprCarveoutOffset); + F(boot.wprCarveoutSize, bootGspRmParams.wprCarveoutSize); F(boot.bIsGspRmBoot, bootGspRmParams.bIsGspRmBoot); + F(rm.target, gspRmParams.target); F(rm.bootArgsOffset, gspRmParams.bootArgsOffset); + F(spdm.target, gspSpdmParams.target); F(spdm.payloadBufferOffset, gspSpdmParams.payloadBufferOffset); + F(spdm.payloadBufferSize, gspSpdmParams.payloadBufferSize); + F(mem.flushSysmemAddrValLo, gspRmMemParams.flushSysmemAddrValLo); + F(mem.flushSysmemAddrValHi, gspRmMemParams.flushSysmemAddrValHi); + CHECK(GSP_DMA_TARGET_COHERENT == GSP_DMA_TARGET_COHERENT_SYSTEM && GSP_DMA_TARGET_NONCOHERENT == GSP_DMA_TARGET_NONCOHERENT_SYSTEM); + + CHECK(sizeof(gsp_mirror_cot) == sizeof(NVDM_PAYLOAD_COT)); +#define C(f) SAME(gsp_mirror_cot, NVDM_PAYLOAD_COT, f, f) + C(version); C(size); C(gspFmcSysmemOffset); C(frtsSysmemOffset); C(frtsSysmemSize); C(frtsVidmemOffset); + C(frtsVidmemSize); C(hash384); C(publicKey); C(signature); C(gspBootArgsSysmemOffset); + CHECK(NVDM_TYPE_COT == 0x14); +} + +/* Build a plan with synthetic bytes and read it back through the NVIDIA types. */ +static void test_decode(void) +{ + enum { CAP = 4u << 20, ELF = 300000 }; + uint8_t *mem = aligned_alloc(4096, CAP), *elf = calloc(1, ELF), *bl = calloc(1, GSP_GB10B_BOOTLOADER_SIZE); + static uint8_t sig[512], fmc[9000], h[48], k[384], s[384], si[GSP_SYSTEM_INFO_SIZE]; + gsp_boot_in in = { .rm_elf = elf, .rm_elf_size = ELF, .rm_sig = sig, .rm_sig_size = 300, + .bootloader = bl, .bootloader_size = GSP_GB10B_BOOTLOADER_SIZE, .bl_code_off = 0xb000, .bl_data_off = 0xa00, + .fmc = fmc, .fmc_size = sizeof fmc, .fmc_hash = h, .fmc_pubkey = k, .fmc_sig = s, + .sysmem_heap_pa = 0x40000000ULL, .sysmem_heap_size = 512u << 20, .system_info = si, .dma_bits = 41 }; + gsp_arena a; gsp_boot_plan p; const char *why = 0; + CHECK(gsp_arena_init(&a, mem, 0x10000000ULL, CAP) == 0 && gsp_boot_build(&a, &in, &p, &why) == 0); +#define AT(pa) (mem + ((pa) - 0x10000000ULL)) + GspFwWprMeta w; memcpy(&w, AT(p.wpr_meta.pa), sizeof w); + CHECK(w.magic == GSP_FW_WPR_META_MAGIC && w.revision == GSP_FW_WPR_META_REVISION); + CHECK(w.sysmemAddrOfRadix3Elf == p.radix3_root_pa && w.sizeOfRadix3Elf == ELF); + CHECK(w.sysmemAddrOfBootloader == p.bootloader.pa && w.sizeOfBootloader == GSP_GB10B_BOOTLOADER_SIZE); + CHECK(w.sysmemAddrOfSignature == p.signature.pa && w.sizeOfSignature == 512 && w.gspFwHeapSize == (133ULL << 20)); + CHECK(w.frtsSize == 0 && w.nonWprHeapSize == 0 && w.vgaWorkspaceSize == 0 && w.pmuReservedSize == 0 && w.verified == 0); + LibosMemoryRegionInitArgument la[8]; memcpy(la, AT(p.libos_args.pa), sizeof la); + CHECK(la[7].pa == p.args_cached.pa && la[7].size == 4096 && la[7].kind == LIBOS_MEMORY_REGION_CONTIGUOUS); + CHECK(la[5].size == 0x1000 && la[0].loc == LIBOS_MEMORY_REGION_LOC_SYSMEM); + GSP_ARGUMENTS_CACHED g; memcpy(&g, AT(p.args_cached.pa), sizeof g); + CHECK(g.messageQueueInitArguments.sharedMemPhysAddr == p.rpc_shared.pa && g.messageQueueInitArguments.pageTableEntryCount == 129); + CHECK(g.messageQueueInitArguments.cmdQueueOffset == 4096 && g.messageQueueInitArguments.statQueueOffset == 4096 + 0x40000); + CHECK(g.bDmemStack == NV_TRUE && g.sysmemHeapArgs.pa == 0x40000000ULL && g.sysmemHeapArgs.size == (512ULL << 20)); + msgqTxHeader tx; memcpy(&tx, AT(p.cmdq_pa), sizeof tx); + CHECK(tx.version == 0 && tx.size == 0x40000 && tx.msgSize == 4096 && tx.msgCount == 63 && tx.writePtr == 1); + CHECK(tx.flags == MSGQ_FLAGS_SWAP_RX && tx.rxHdrOff == 32 && tx.entryOff == 4096); + NV_GSP_MSG_QUEUE_ELEMENT el; memcpy(&el, AT(p.cmdq_pa) + 4096, sizeof el); + CHECK(el.seqNum == 0 && el.elemCount == 1 && el.rpc.function == NV_VGPU_MSG_FUNCTION_GSP_SET_SYSTEM_INFO); + CHECK(el.rpc.length == sizeof(rpc_message_header_v) + GSP_SYSTEM_INFO_SIZE && el.rpc.signature == NV_VGPU_MSG_SIGNATURE_VALID); + GSP_FMC_BOOT_PARAMS f; memcpy(&f, AT(p.fmc_params.pa), sizeof f); + CHECK(f.bootGspRmParams.target == GSP_DMA_TARGET_COHERENT_SYSTEM && f.bootGspRmParams.gspRmDescSize == sizeof(GspFwWprMeta)); + CHECK(f.bootGspRmParams.gspRmDescOffset == p.wpr_meta.pa && f.bootGspRmParams.bIsGspRmBoot == NV_TRUE); + CHECK(f.gspRmParams.target == GSP_DMA_TARGET_NONCOHERENT_SYSTEM && f.gspRmParams.bootArgsOffset == p.libos_args.pa); + NVDM_PAYLOAD_COT c; memcpy(&c, p.cot_packet + 8, sizeof c); + CHECK(c.version == 1 && c.size == sizeof(NVDM_PAYLOAD_COT) && c.gspFmcSysmemOffset == p.fmc.pa); + CHECK(c.frtsSysmemSize == sizeof fmc && c.gspBootArgsSysmemOffset == p.fmc_params.pa); + + gsp_mq q; + CHECK(gsp_mq_attach(&q, &a, &p) == 0); + uint32_t prm[4] = {1, 2, 3, 4}, seq; + CHECK(gsp_rpc_rm_alloc(&q, 0xc1d00001, 0xc1d00001, 0xcaf00010, 0x0080, prm, sizeof prm, &seq, &why) == 0); + uint8_t raw[4096]; memcpy(raw, AT(p.cmdq_pa) + 4096 + 4096, sizeof raw); + NV_GSP_MSG_QUEUE_ELEMENT *e = (NV_GSP_MSG_QUEUE_ELEMENT *)raw; + rpc_gsp_rm_alloc_v03_00 *ra = (rpc_gsp_rm_alloc_v03_00 *)(raw + sizeof *e); + CHECK(e->rpc.function == NV_VGPU_MSG_FUNCTION_GSP_RM_ALLOC && e->rpc.length == sizeof(rpc_message_header_v) + sizeof(rpc_gsp_rm_alloc_v03_00)); + CHECK(ra->hObject == 0xcaf00010 && ra->hClass == 0x0080 && ra->paramsSize == sizeof prm && ra->flags == 0 && + memcmp(ra->params, prm, sizeof prm) == 0); + free(mem); free(elf); free(bl); +} + +int main(void) +{ + test_layouts(); + test_decode(); + return ck_t_verdict("test_gb10_gsp_nvhdr"); +} diff --git a/native/kernel/tests/test_gpu_sim.c b/native/kernel/tests/test_gpu_sim.c new file mode 100644 index 00000000..5d667de4 --- /dev/null +++ b/native/kernel/tests/test_gpu_sim.c @@ -0,0 +1,492 @@ +/* test_gpu_sim.c -- cut D host tests: GB10 GPU page tables, allocator and + * channel over the simulated device in gpu/gpu_sim.c. Proves the logic and + * the encodings against the driver-source layouts, NOT the chip. Run under + * ASan/UBSan and with each CK_GPU_MUTANT_* (make gpu-sim-mutants), where + * every mutant must make this test FAIL. */ +#include +#include +#include +#include "ck_test.h" +#include "gmmu.h" +#include "gpu_mem.h" +#include "gpu_chan.h" +#include "gpu_sim.h" + +#define MEM_BYTES (8u << 20) /* 8 MiB simulated unified memory */ +#define PA_BASE 0x80000000ull +#define POOL_PA PA_BASE /* 64 page-table pages */ +#define DATA_PA (PA_BASE + 64ull * 4096u) /* data pages after the pool */ +#define VA_BASE 0x0000000200000000ull /* 8 GiB, below 2^40 */ + +static uint8_t *mem; +static struct ck_gsim sim; +static struct ck_gpu_regs regs; +static struct ck_gmmu_as as; +static struct ck_gmem gm; + +static void fresh(uint32_t pt_pages) +{ + memset(mem, 0xA5, MEM_BYTES); /* garbage: gmmu must zero what it uses */ + ck_gsim_init(&sim, mem, PA_BASE, MEM_BYTES); + regs = ck_gsim_regs(&sim); + CHECK(ck_gmmu_as_init(&as, &sim.mem, POOL_PA, pt_pages) == CK_GMMU_OK); +} + +static uint32_t gread(uint64_t va, uint32_t *v) { return ck_gsim_gpu_read32(&sim, as.root_pa, va, v); } +static uint32_t gwrite(uint64_t va, uint32_t v) { return ck_gsim_gpu_write32(&sim, as.root_pa, va, v); } + +/* 1. Entry encodings against hand-computed dev_mmu.h bit positions. */ +static void test_encodings(void) +{ + /* PTE: VALID 0, APERTURE 2:1 = SYS_COH(2), PCF 7:3 = 1, KIND 11:8 = 0, ADDR 51:12. */ + CHECK(ck_gmmu_pte(0x123456789000ull, CK_GMMU_PTE_AP_SYS_COH, CK_GMMU_PCF_RW_UNCACHED, 0) == + (0x123456789000ull | (1u << 3) | (2u << 1) | 1u)); + CHECK(ck_gmmu_pte(0xFFF0000000001FFFull, 3, 0x1F, 0xF) == (0x0000000000001000ull | 0xFFFull)); /* masks */ + /* PDE: IS_PTE 0 = 0, APERTURE 2:1, PCF 5:3 = 2 (cached, no ATS), ADDR 51:12. */ + CHECK(ck_gmmu_pde(0xABCDE000ull, CK_GMMU_PDE_AP_SYS_COH) == (0xABCDE000ull | (2u << 3) | (2u << 1))); + CHECK((ck_gmmu_pde(0x1000, CK_GMMU_PDE_AP_SYS_COH) & 1u) == 0); + /* Dual PDE: small half lands in bits 66:65 (aperture), 69:67 (PCF), 115:76 (addr >> 12). */ + uint64_t d[2]; + ck_gmmu_dual_pde(d, 0, CK_GMMU_PDE_AP_INVALID, 0x77777000ull, CK_GMMU_PDE_AP_SYS_COH); + CHECK(d[0] == 0); + CHECK(d[1] == (0x77777000ull | (2u << 3) | (2u << 1))); + ck_gmmu_dual_pde(d, 0x55555500ull, CK_GMMU_PDE_AP_SYS_NC, 0, CK_GMMU_PDE_AP_INVALID); + CHECK(d[0] == (0x55555500ull | (2u << 3) | (3u << 1))); /* ADDRESS_BIG 51:8, shift 8 */ + CHECK(d[1] == 0); + /* Work-submit token: RUNLIST_ID 22:16, VECTOR 11:0. */ + CHECK(ck_gpu_submit_token(3, 0x2A) == 0x0003002Au); + CHECK(ck_gpu_submit_token(0x7E, 0xFFF) == 0x007E0FFFu); + /* Runlist USERD pointer: LO 31:8 of word 0, HI_HW 19:0 of word 1. */ + uint32_t rl[2] = {0, 0}; + CHECK(ck_gpu_rl_userd(rl, 0x000ABCDE12345600ull) == CK_GCHAN_OK); + CHECK(rl[0] == 0x12345600u && rl[1] == 0xABCDEu); + CHECK(ck_gpu_rl_userd(rl, 0x1000000000080ull) == CK_GCHAN_EINVAL); /* not 256-byte aligned */ + CHECK(ck_gpu_rl_userd(rl, 1ull << 52) == CK_GCHAN_EINVAL); /* does not fit 20+32 bits */ + /* Carried encoders, bit-identical to physics nvrm_mthd / nvrm_gp_entry. */ + CHECK(ck_gpu_mthd(1, 0x0100, 1) == ((2u << 28) | (1u << 16) | (1u << 13) | 0x40u)); + CHECK(ck_gpu_gp_entry(0x12345678ull, 10) == (0x12345678ull | (10ull << 42) | (1ull << 41))); + /* clc96f view of the same entry: GET 31:2 / GET_HI 7:0 / LENGTH 30:10 of word 1. */ + uint64_t e = ck_gpu_gp_entry(0xAB12345674ull, 0x1FFFFF); + CHECK((((uint32_t)e) & ~3u) == 0x12345674u); + CHECK(((uint32_t)(e >> 32) & 0xFFu) == 0xABu); + CHECK((((uint32_t)(e >> 32)) >> 10 & 0x1FFFFFu) == 0x1FFFFFu); + /* LEVEL 9:9 of word 1 is set (SUBROUTINE): what physics emits on the chip today. */ + CHECK(((uint32_t)(e >> 32) >> 9 & 1u) == 1u); +} + +/* 2. Map, walk through the simulator, unmap, refusals. */ +static void test_map_unmap(void) +{ + fresh(64); + uint64_t va = 0x0100000000000000ull + 0x5000; /* bit 56 set: PD4 entry 1 */ + uint64_t pa = DATA_PA + 0x3000; + CHECK(ck_gmmu_map(&as, va, pa, 0x2000, CK_GMMU_SZ_4K, CK_GMMU_PTE_AP_SYS_COH, CK_GMMU_PCF_RW_CACHED) == CK_GMMU_OK); + uint64_t wpa = 0, page = 0; + uint32_t lo = 0; + CHECK(ck_gsim_walk(&sim, as.root_pa, va + 0x1234, 0, &wpa, &page, &lo) == 0); + CHECK(wpa == pa + 0x1234 && page == CK_GMMU_SZ_4K); + CHECK(gwrite(va + 0x10, 0xC0FFEE01u) == 0); + CHECK(memcmp(mem + (pa - PA_BASE) + 0x10, "\x01\xEE\xFF\xC0", 4) == 0); /* landed at the PA */ + uint32_t v = 0; + CHECK(gread(va + 0x10, &v) == 0 && v == 0xC0FFEE01u); + /* Unmapped neighbour faults and the access does not touch memory. */ + uint32_t nf = sim.nfaults; + CHECK(gread(va + 0x2000, &v) == CK_GSIM_F_UNMAPPED); + CHECK(sim.nfaults == nf + 1 && sim.faults[nf].va == va + 0x2000); + /* Refusals leave everything unchanged. */ + CHECK(ck_gmmu_map(&as, va + 0x1000, pa, 0x1000, CK_GMMU_SZ_4K, 2, 0) == CK_GMMU_EBUSY); /* overlap */ + CHECK(ck_gmmu_map(&as, va + 0x800, pa, 0x1000, CK_GMMU_SZ_4K, 2, 0) == CK_GMMU_EALIGN); /* VA */ + CHECK(ck_gmmu_map(&as, va + 0x4000, pa + 1, 0x1000, CK_GMMU_SZ_4K, 2, 0) == CK_GMMU_EALIGN); /* PA */ + CHECK(ck_gmmu_map(&as, va + 0x4000, pa, 0x1800, CK_GMMU_SZ_4K, 2, 0) == CK_GMMU_EALIGN); /* size */ + CHECK(ck_gmmu_map(&as, va + 0x4000, pa, 0, CK_GMMU_SZ_4K, 2, 0) == CK_GMMU_EINVAL); /* empty */ + CHECK(ck_gmmu_map(&as, va + 0x4000, pa, 0x1000, 0x2000, 2, 0) == CK_GMMU_EINVAL); /* page size */ + CHECK(ck_gmmu_map(&as, 1ull << 57, pa, 0x1000, CK_GMMU_SZ_4K, 2, 0) == CK_GMMU_ERANGE); /* VA bits */ + CHECK(ck_gmmu_map(&as, (1ull << 57) - 0x1000, pa, 0x2000, CK_GMMU_SZ_4K, 2, 0) == CK_GMMU_ERANGE); /* VA end */ + CHECK(ck_gmmu_map(&as, va + 0x4000, PA_BASE - 0x1000, 0x1000, CK_GMMU_SZ_4K, 2, 0) == CK_GMMU_ERANGE); /* PA below */ + CHECK(ck_gmmu_map(&as, va + 0x4000, PA_BASE + MEM_BYTES, 0x1000, CK_GMMU_SZ_4K, 2, 0) == CK_GMMU_ERANGE); /* PA above */ + CHECK(ck_gmmu_map(&as, va + 0x4000, PA_BASE + MEM_BYTES - 0x1000, 0x2000, CK_GMMU_SZ_4K, 2, 0) == CK_GMMU_ERANGE); /* PA end */ + CHECK(ck_gmmu_map(&as, va + 0x4000, pa, 0x1000, CK_GMMU_SZ_4K, 4, 0) == CK_GMMU_EINVAL); /* aperture */ + CHECK(ck_gmmu_map(&as, va + 0x4000, pa, 0x1000, CK_GMMU_SZ_4K, 2, 0x20) == CK_GMMU_EINVAL); /* PCF */ + /* A 64 KiB page in a 2 MiB region that already has a 4 KiB table: refused. */ + CHECK(ck_gmmu_map(&as, va & ~0xFFFFull, DATA_PA + 0x10000, 0x10000, CK_GMMU_SZ_64K, 2, 0) == CK_GMMU_EBUSY); + /* A 2 MiB page over that region: refused. */ + CHECK(ck_gmmu_map(&as, va & ~0x1FFFFFull, PA_BASE + 0x200000, CK_GMMU_SZ_2M, CK_GMMU_SZ_2M, 2, 0) == CK_GMMU_EBUSY); + CHECK(gread(va + 0x10, &v) == 0 && v == 0xC0FFEE01u); + /* Unmap: partial or wrong-size requests refused with no change. */ + CHECK(ck_gmmu_unmap(&as, va, 0x3000, CK_GMMU_SZ_4K) == CK_GMMU_ENOENT); + CHECK(ck_gmmu_unmap(&as, va & ~0xFFFFull, 0x10000, CK_GMMU_SZ_64K) == CK_GMMU_ENOENT); + CHECK(ck_gsim_walk(&sim, as.root_pa, va + 0x1000, 0, &wpa, &page, &lo) == 0); + CHECK(ck_gmmu_unmap(&as, va, 0x2000, CK_GMMU_SZ_4K) == CK_GMMU_OK); + CHECK(ck_gsim_walk(&sim, as.root_pa, va, 0, &wpa, &page, &lo) == CK_GSIM_F_UNMAPPED); + CHECK(ck_gmmu_unmap(&as, va, 0x1000, CK_GMMU_SZ_4K) == CK_GMMU_ENOENT); /* double unmap */ +} + +/* 3. Page sizes 64 KiB and 2 MiB, and the read-only PCF. */ +static void test_page_sizes(void) +{ + fresh(64); + uint64_t v64 = 0x40000000ull, v2m = 0x80000000ull; + CHECK(ck_gmmu_map(&as, v64, DATA_PA + 0x10000 - (DATA_PA & 0xFFFF), 0x20000, CK_GMMU_SZ_64K, 2, + CK_GMMU_PCF_RO_CACHED) == CK_GMMU_OK); + uint64_t pa2m = (PA_BASE + 0x200000ull); + CHECK(ck_gmmu_map(&as, v2m, pa2m, CK_GMMU_SZ_2M, CK_GMMU_SZ_2M, 2, CK_GMMU_PCF_RW_CACHED) == CK_GMMU_OK); + uint64_t wpa = 0, page = 0; + uint32_t lo = 0, v = 0; + CHECK(ck_gsim_walk(&sim, as.root_pa, v64 + 0x1ABCD, 0, &wpa, &page, &lo) == 0); + CHECK(page == CK_GMMU_SZ_64K && wpa == DATA_PA + 0x10000 - (DATA_PA & 0xFFFF) + 0x1ABCD); + CHECK(ck_gsim_walk(&sim, as.root_pa, v2m + 0x1F0004, 0, &wpa, &page, &lo) == 0); + CHECK(page == CK_GMMU_SZ_2M && wpa == pa2m + 0x1F0004); + CHECK(gwrite(v64 + 8, 1) == CK_GSIM_F_RO_WRITE); /* read-only page */ + CHECK(gread(v64 + 8, &v) == 0); + CHECK(gwrite(v2m + 8, 7) == 0); + /* Small page inside the 2 MiB page: refused. */ + CHECK(ck_gmmu_map(&as, v2m + 0x1000, DATA_PA, 0x1000, CK_GMMU_SZ_4K, 2, 0) == CK_GMMU_EBUSY); + CHECK(ck_gmmu_map(&as, v2m, pa2m, CK_GMMU_SZ_2M, CK_GMMU_SZ_2M, 2, 0) == CK_GMMU_EBUSY); + CHECK(ck_gmmu_unmap(&as, v2m, CK_GMMU_SZ_2M, CK_GMMU_SZ_4K) == CK_GMMU_ENOENT); + CHECK(ck_gmmu_unmap(&as, v2m, CK_GMMU_SZ_2M, CK_GMMU_SZ_2M) == CK_GMMU_OK); + CHECK(ck_gmmu_unmap(&as, v64, 0x20000, CK_GMMU_SZ_64K) == CK_GMMU_OK); +} + +/* 4. Page-table pool exhaustion: the map is refused whole, nothing written. */ +static void test_pool_exhaustion(void) +{ + fresh(5); /* root + 4: exactly one 4K path (PD3, PD2, PD1, PD0) and no PT */ + uint32_t before = 0; + for (uint32_t i = 0; i < as.pt_count; i++) + before += as.pt_used[i]; + CHECK(ck_gmmu_map(&as, 0x1000, DATA_PA, 0x1000, CK_GMMU_SZ_4K, 2, 0) == CK_GMMU_ENOMEM); + uint32_t after = 0; + for (uint32_t i = 0; i < as.pt_count; i++) + after += as.pt_used[i]; + CHECK(before == after); + uint64_t wpa, page; + uint32_t lo; + CHECK(ck_gsim_walk(&sim, as.root_pa, 0x1000, 0, &wpa, &page, &lo) == CK_GSIM_F_UNMAPPED); + /* 2 MiB needs no PT: the same pool is enough. */ + CHECK(ck_gmmu_map(&as, 0x200000, PA_BASE + 0x200000, CK_GMMU_SZ_2M, CK_GMMU_SZ_2M, 2, 0) == CK_GMMU_OK); + /* Exact count across a 2 MiB boundary: two PTs needed, pool has none left. */ + fresh(7); /* root + PD3 + PD2 + PD1 + PD0 + 2 PT */ + CHECK(ck_gmmu_map(&as, 0x1FF000, DATA_PA, 0x2000, CK_GMMU_SZ_4K, 2, 0) == CK_GMMU_OK); + fresh(6); + CHECK(ck_gmmu_map(&as, 0x1FF000, DATA_PA, 0x2000, CK_GMMU_SZ_4K, 2, 0) == CK_GMMU_ENOMEM); + CHECK(ck_gmmu_as_init(&as, &sim.mem, POOL_PA + 1, 8) == CK_GMMU_EINVAL); + CHECK(ck_gmmu_as_init(&as, &sim.mem, PA_BASE + MEM_BYTES - 4096, 2) == CK_GMMU_ERANGE); + CHECK(ck_gmmu_as_init(&as, &sim.mem, POOL_PA, CK_GMMU_MAX_PT + 1) == CK_GMMU_EINVAL); +} + +/* 5. The invalidate sequence, the stale TLB without it, and the timeout latch. */ +static void test_invalidate(void) +{ + fresh(64); + uint64_t va = 0x10000; + CHECK(ck_gmmu_map(&as, va, DATA_PA, 0x1000, CK_GMMU_SZ_4K, 2, 0) == CK_GMMU_OK); + uint32_t v = 0; + CHECK(gwrite(va, 0x11) == 0); /* fills the TLB */ + CHECK(ck_gmmu_unmap(&as, va, 0x1000, CK_GMMU_SZ_4K) == CK_GMMU_OK); + CHECK(gread(va, &v) == 0 && v == 0x11); /* stale: no invalidate yet */ + /* Prove it is the old translation: change the bytes at the old PA from the CPU. */ + *(volatile uint32_t *)(mem + (DATA_PA - PA_BASE)) = 0x5E5E5E5Eu; + CHECK(gread(va, &v) == 0 && v == 0x5E5E5E5Eu); + sim.nlog = 0; + CHECK(ck_gmmu_invalidate(&as, ®s, 10) == CK_GMMU_OK); + /* Register order: PDB, UPPER_PDB, INVALIDATE(ALL_VA|TRIGGER), then polls. */ + CHECK(sim.nlog >= 4); + uint64_t pdb = as.root_pa >> 12; + CHECK(sim.log[0].write && sim.log[0].off == 0x00B830A0u && sim.log[0].val == ((uint32_t)((pdb & 0xFFFFFFF) << 4) | 2u)); + CHECK(sim.log[1].write && sim.log[1].off == 0x00B830A4u && sim.log[1].val == (uint32_t)(pdb >> 28)); + CHECK(sim.log[2].write && sim.log[2].off == 0x00B830B0u && sim.log[2].val == 0x80000001u); + CHECK(!sim.log[3].write && sim.log[3].off == 0x00B830B0u); + CHECK(sim.inval_done == 1); + CHECK(gread(va, &v) == CK_GSIM_F_UNMAPPED); /* translation gone */ + /* Budget smaller than the device latency: timeout, then the AS refuses everything. */ + fresh(64); + sim.inval_latency = 5; + CHECK(ck_gmmu_invalidate(&as, ®s, 3) == CK_GMMU_ETIMEDOUT); + CHECK(as.dead == 1); + CHECK(ck_gmmu_map(&as, va, DATA_PA, 0x1000, CK_GMMU_SZ_4K, 2, 0) == CK_GMMU_EDEAD); + CHECK(ck_gmmu_unmap(&as, va, 0x1000, CK_GMMU_SZ_4K) == CK_GMMU_EDEAD); + CHECK(ck_gmmu_invalidate(&as, ®s, 100) == CK_GMMU_EDEAD); + /* Exact poll budget: latency 3 needs 4 reads (3 with TRIGGER set, then clear). */ + fresh(64); + CHECK(ck_gmmu_invalidate(&as, ®s, 3) == CK_GMMU_ETIMEDOUT); + fresh(64); + CHECK(ck_gmmu_invalidate(&as, ®s, 4) == CK_GMMU_OK); + /* Invalidate-all drops every PDB; one-PDB leaves other PDBs cached. */ + CHECK(ck_gmmu_map(&as, va, DATA_PA, 0x1000, CK_GMMU_SZ_4K, 2, 0) == CK_GMMU_OK); + CHECK(gread(va, &v) == 0); + sim.tlb[0].pdb ^= 0x1000; /* pretend the entry belongs to another address space */ + CHECK(ck_gmmu_invalidate(&as, ®s, 4) == CK_GMMU_OK && sim.tlb[0].valid); + regs.wr(regs.ctx, CK_GPU_REG_INVAL, CK_GPU_INVAL_ALL_PDB | CK_GPU_INVAL_ALL_VA | CK_GPU_INVAL_TRIGGER); + for (int i = 0; i < 4; i++) + (void)regs.rd(regs.ctx, CK_GPU_REG_INVAL); + CHECK(!sim.tlb[0].valid); +} + +/* 6. Allocator: distinct addresses, cache policy, reclaim, bounds, quarantine. */ +static void test_allocator(void) +{ + fresh(64); + CHECK(ck_gmem_init(&gm, &as, ®s, 10, DATA_PA, 16, VA_BASE) == CK_GMEM_OK); + CHECK(ck_gmem_init(&gm, &as, ®s, 10, POOL_PA, 16, VA_BASE) == CK_GMEM_EINVAL); /* overlaps the PT pool */ + CHECK(ck_gmem_init(&gm, &as, ®s, 10, DATA_PA, 16, VA_BASE + 0x1000) == CK_GMEM_EINVAL); /* VA alignment */ + CHECK(ck_gmem_init(&gm, &as, ®s, 10, DATA_PA, 16, VA_BASE) == CK_GMEM_OK); + struct ck_gmem_buf *a = 0, *b = 0, *flag = 0, *x = 0; + CHECK(ck_gmem_alloc(&gm, 5000, CK_GMEM_CACHED, 0, &a) == CK_GMEM_OK); + CHECK(a && a->size == 8192 && a->pa == DATA_PA && a->gpu_va == VA_BASE); + CHECK((uint64_t)(uintptr_t)a->cpu != a->gpu_va && a->cpu == mem + (DATA_PA - PA_BASE)); + /* Host-polled must be uncached: refused when asked cached. */ + CHECK(ck_gmem_alloc(&gm, 4, CK_GMEM_CACHED, CK_GMEM_HOST_POLLED, &flag) == CK_GMEM_EINVAL); + CHECK(ck_gmem_alloc(&gm, 4, CK_GMEM_UNCACHED, CK_GMEM_HOST_POLLED, &flag) == CK_GMEM_OK); + CHECK(ck_gmem_alloc(&gm, 4, 7, 0, &x) == CK_GMEM_EINVAL); + CHECK(ck_gmem_alloc(&gm, 4, CK_GMEM_CACHED, 0x80, &x) == CK_GMEM_EINVAL); + CHECK(ck_gmem_alloc(&gm, 0, CK_GMEM_CACHED, 0, &x) == CK_GMEM_EINVAL); + uint64_t wpa, page; + uint32_t lo = 0; + CHECK(ck_gsim_walk(&sim, as.root_pa, flag->gpu_va, 0, &wpa, &page, &lo) == 0); + CHECK(((lo >> 3) & 0x1F) == CK_GMMU_PCF_RW_UNCACHED && ((lo >> 1) & 3) == CK_GMMU_PTE_AP_SYS_COH); + CHECK(ck_gsim_walk(&sim, as.root_pa, a->gpu_va + 4096, 0, &wpa, &page, &lo) == 0); + CHECK(((lo >> 3) & 0x1F) == CK_GMMU_PCF_RW_CACHED); + /* GPU writes the flag through its VA; the CPU sees it through its own pointer. */ + CHECK(gwrite(flag->gpu_va, 0xD0E) == 0); + CHECK(*(volatile uint32_t *)flag->cpu == 0xD0E); + /* Bounds: 16 pages total, 3 used. 14 more is too many; 13 fits exactly. */ + CHECK(ck_gmem_alloc(&gm, 14 * 4096, CK_GMEM_CACHED, 0, &b) == CK_GMEM_ENOMEM); + CHECK(ck_gmem_alloc(&gm, 13 * 4096, CK_GMEM_CACHED, 0, &b) == CK_GMEM_OK); + CHECK(ck_gmem_count(&gm, CK_GMEM_FREE) == 0); + /* Free reclaims after a completed invalidate; GPU access then faults. */ + uint32_t inv = sim.inval_done; + CHECK(gwrite(a->gpu_va, 1) == 0); + uint64_t a_va = a->gpu_va; + CHECK(ck_gmem_free(&gm, a) == CK_GMEM_OK); + CHECK(sim.inval_done == inv + 1); + CHECK(gwrite(a_va, 2) == CK_GSIM_F_UNMAPPED); + CHECK(ck_gmem_free(&gm, a) == CK_GMEM_ESTATE); /* double free */ + CHECK(ck_gmem_free(&gm, (struct ck_gmem_buf *)((uint8_t *)&gm.buf[0] + 1)) == CK_GMEM_ESTATE); /* not a slot */ + CHECK(ck_gmem_count(&gm, CK_GMEM_FREE) == 2); + CHECK(ck_gmem_alloc(&gm, 8192, CK_GMEM_CACHED, 0, &a) == CK_GMEM_OK && a->pa == DATA_PA); /* reused */ + /* Invalidate that never completes: the buffer is quarantined, not reused. */ + sim.inval_stuck = 1; + CHECK(ck_gmem_free(&gm, b) == CK_GMEM_ETIMEDOUT); + CHECK(ck_gmem_count(&gm, CK_GMEM_QUARANTINED) == 13); + sim.inval_stuck = 0; + CHECK(ck_gmem_alloc(&gm, 4096, CK_GMEM_CACHED, 0, &x) != CK_GMEM_OK); /* AS dead + no free pages */ + CHECK(ck_gmem_count(&gm, CK_GMEM_QUARANTINED) == 13); + /* Slot table bound. */ + fresh(64); + CHECK(ck_gmem_init(&gm, &as, ®s, 10, DATA_PA, 128, VA_BASE) == CK_GMEM_OK); + int ok = 1; + for (uint32_t i = 0; i < CK_GMEM_MAX_BUF; i++) + ok &= ck_gmem_alloc(&gm, 1, CK_GMEM_CACHED, 0, &x) == CK_GMEM_OK; + CHECK(ok); + CHECK(ck_gmem_alloc(&gm, 1, CK_GMEM_CACHED, 0, &x) == CK_GMEM_ENOMEM); +} + +/* 7. Channel: layout, token, submit through the GMMU, refusals, teardown. */ +static void test_channel(void) +{ + fresh(64); + CHECK(ck_gmem_init(&gm, &as, ®s, 10, DATA_PA, 64, VA_BASE) == CK_GMEM_OK); + struct ck_gpu_chan_ops ops = ck_gsim_chan_ops(); + struct ck_gpu_chan ch; + CHECK(ck_gpu_chan_create(&ch, &gm, ®s, &ops, &sim, 0x1000, 0, 8) == CK_GCHAN_EINVAL); /* chid > 11 bits */ + CHECK(ck_gpu_chan_create(&ch, &gm, ®s, &ops, &sim, 1, 0x7F, 8) == CK_GCHAN_EINVAL); /* INVALID_RUNLIST */ + CHECK(ck_gpu_chan_create(&ch, &gm, ®s, &ops, &sim, 1, 0, 6) == CK_GCHAN_EINVAL); /* not a power of 2 */ + CHECK(ck_gpu_chan_create(&ch, &gm, ®s, &ops, &sim, 1, 0, 1) == CK_GCHAN_EINVAL); + CHECK(ck_gmem_count(&gm, CK_GMEM_LIVE) == 0); + CHECK(ck_gpu_chan_create(&ch, &gm, ®s, &ops, &sim, 5, 2, 8) == CK_GCHAN_OK); + if (!ch.open) + return; /* the rest needs a live channel */ + CHECK(ch.d.token == 0x00020005u); + CHECK(ch.d.rl_entry[0] == ((uint32_t)ch.userd->pa & 0xFFFFFF00u) && ch.d.rl_entry[1] == (uint32_t)(ch.userd->pa >> 32)); + CHECK(ch.d.pdb == as.root_pa && ch.d.gpfifo_va == ch.gpfifo->gpu_va); + CHECK(ch.gpfifo->cache == CK_GMEM_UNCACHED && ch.userd->cache == CK_GMEM_UNCACHED); + /* Instance block word 128/129 as the driver writes it: TARGET SYS_COH, BIG_PAGE 64K, NEW_PT_FORMAT 0. */ + const uint32_t *ramin = (const uint32_t *)ch.inst->cpu; + CHECK(ramin[128] == (((uint32_t)as.root_pa & 0xFFFFF000u) | (1u << 11) | 2u)); + CHECK(ramin[129] == (uint32_t)(as.root_pa >> 32)); + struct ck_gpu_chan dup; + CHECK(ck_gpu_chan_create(&dup, &gm, ®s, &ops, &sim, 5, 2, 8) == CK_GCHAN_EBIND); /* same chid live */ + CHECK(ck_gmem_count(&gm, CK_GMEM_LIVE) == 3); /* dup's memory returned */ + + struct ck_gmem_buf *pb = 0, *sem = 0; + CHECK(ck_gmem_alloc(&gm, 4096, CK_GMEM_CACHED, CK_GMEM_GPU_RO, &pb) == CK_GMEM_OK); + CHECK(ck_gmem_alloc(&gm, 16, CK_GMEM_UNCACHED, CK_GMEM_HOST_POLLED, &sem) == CK_GMEM_OK); + uint32_t *w = (uint32_t *)pb->cpu; + w[0] = ck_gpu_mthd(0, 0x5c, 2); + w[1] = (uint32_t)sem->gpu_va; + w[2] = (uint32_t)(sem->gpu_va >> 32); + sim.nlog = 0; + CHECK(ck_gpu_chan_submit(&ch, pb, 0, 3) == CK_GCHAN_OK); + /* Ring entry (CPU view), GPPut in USERD at 0x8c, doorbell write with the token. */ + uint64_t ent = ((uint64_t *)ch.gpfifo->cpu)[0]; + CHECK(ent == ck_gpu_gp_entry(pb->gpu_va, 3)); + CHECK(*(uint32_t *)(ch.userd->cpu + 0x8c) == 1); + CHECK(sim.nlog == 1 && sim.log[0].write && sim.log[0].off == 0x00BB0090u && sim.log[0].val == 0x00020005u); + const struct ck_gsim_chan *sc = ck_gsim_chan(&sim, 5); + CHECK(sc && sc->gp_get == 1 && sc->words_read == 3 && !sc->faulted); + /* Refusals. */ + CHECK(ck_gpu_chan_submit(&ch, pb, 2, 1) == CK_GCHAN_EINVAL); /* misaligned */ + CHECK(ck_gpu_chan_submit(&ch, pb, 0, 0) == CK_GCHAN_EINVAL); /* empty */ + CHECK(ck_gpu_chan_submit(&ch, pb, 4092, 2) == CK_GCHAN_EINVAL); /* past the buffer */ + CHECK(ck_gpu_chan_submit(&ch, pb, 0, 0x200000) == CK_GCHAN_EINVAL); /* LENGTH is 21 bits */ + struct ck_gmem_buf fake = *pb; + CHECK(ck_gpu_chan_submit(&ch, &fake, 0, 1) == CK_GCHAN_EINVAL); /* not an allocator buffer */ + /* Ring full: entries - 1 outstanding at most. */ + int okc = 1; + for (uint32_t i = 1; i < 7; i++) + okc &= ck_gpu_chan_submit(&ch, pb, 0, 1) == CK_GCHAN_OK; + CHECK(okc); + CHECK(ck_gpu_chan_submit(&ch, pb, 0, 1) == CK_GCHAN_EFULL); + ck_gpu_chan_retire(&ch, 100); /* beyond put: ignored */ + CHECK(ch.retired == 0); + ck_gpu_chan_retire(&ch, 7); + CHECK(ck_gpu_chan_submit(&ch, pb, 0, 1) == CK_GCHAN_OK); /* wraps the ring */ + CHECK(sc->gp_get == 0 && !sc->faulted); + /* A pushbuffer that was freed: the GPU faults on it and the channel stops. */ + struct ck_gmem_buf *gone = 0; + CHECK(ck_gmem_alloc(&gm, 4096, CK_GMEM_CACHED, 0, &gone) == CK_GMEM_OK); + ck_gpu_chan_retire(&ch, 8); + uint64_t gone_va = gone->gpu_va; + /* Queue it by hand after freeing (submit itself would refuse a dead buffer). */ + CHECK(ck_gmem_free(&gm, gone) == CK_GMEM_OK); + CHECK(ck_gpu_chan_submit(&ch, gone, 0, 1) == CK_GCHAN_EINVAL); + ((uint64_t *)ch.gpfifo->cpu)[ch.put % 8] = ck_gpu_gp_entry(gone_va, 1); + ch.put++; + *(uint32_t *)(ch.userd->cpu + 0x8c) = ch.put % 8; + uint32_t nf = sim.nfaults; + regs.wr(regs.ctx, CK_GPU_REG_DOORBELL, ch.d.token); + CHECK(sc->faulted && sim.nfaults == nf + 1 && sim.faults[nf].va == gone_va); + /* Unknown token is counted, not acted on. */ + regs.wr(regs.ctx, CK_GPU_REG_DOORBELL, 0x00010001u); + CHECK(sim.doorbell_unknown == 1); + /* Clean teardown: everything returns to FREE except pb/sem (caller's). */ + CHECK(ck_gpu_chan_teardown(&ch, 4, 0, 0) == CK_GCHAN_OK); + CHECK(ck_gmem_count(&gm, CK_GMEM_QUARANTINED) == 0); + CHECK(ck_gmem_count(&gm, CK_GMEM_LIVE) == 2); + CHECK(ck_gpu_chan_submit(&ch, pb, 0, 1) == CK_GCHAN_ESTATE); + CHECK(ck_gpu_chan_teardown(&ch, 4, 0, 0) == CK_GCHAN_ESTATE); + /* The channel id is free again: reopen, then a hung teardown quarantines. */ + CHECK(ck_gpu_chan_create(&ch, &gm, ®s, &ops, &sim, 5, 2, 8) == CK_GCHAN_OK); + sim.hang = 1; + struct ck_gmem_buf *extra[2] = {pb, sem}; + uint64_t pb_pa = pb->pa, sem_pa = sem->pa; /* slots are reused after quarantine; the pages are not */ + uint32_t polls = sim.idle_polls; + CHECK(ck_gpu_chan_teardown(&ch, 6, extra, 2) == CK_GCHAN_ETIMEDOUT); + CHECK(sim.idle_polls == polls + 6); /* bounded wait */ + CHECK(ck_gmem_count(&gm, CK_GMEM_LIVE) == 0); + CHECK(ck_gmem_count(&gm, CK_GMEM_QUARANTINED) == 3 + 1 + 1); /* ring 1 page, USERD 1, inst 1, pb 1, sem 1 */ + uint32_t freep = ck_gmem_count(&gm, CK_GMEM_FREE); + struct ck_gmem_buf *y = 0; + int never = 1; + while (ck_gmem_alloc(&gm, 4096, CK_GMEM_CACHED, 0, &y) == CK_GMEM_OK) + never &= gm.page_state[(y->pa - DATA_PA) / 4096] == CK_GMEM_LIVE && y->pa != pb_pa && y->pa != sem_pa; + CHECK(never); + CHECK(ck_gmem_count(&gm, CK_GMEM_QUARANTINED) == 5 && ck_gmem_count(&gm, CK_GMEM_LIVE) <= freep); +} + +/* 8. Reopen loop: repeated create/submit/teardown leaks nothing. */ +static void test_reopen(void) +{ + fresh(64); + CHECK(ck_gmem_init(&gm, &as, ®s, 10, DATA_PA, 32, VA_BASE) == CK_GMEM_OK); + struct ck_gpu_chan_ops ops = ck_gsim_chan_ops(); + struct ck_gpu_chan ch; + struct ck_gmem_buf *pb = 0; + CHECK(ck_gmem_alloc(&gm, 4096, CK_GMEM_CACHED, CK_GMEM_GPU_RO, &pb) == CK_GMEM_OK); + int ok = 1; + for (uint32_t i = 0; i < 200; i++) { + ok &= ck_gpu_chan_create(&ch, &gm, ®s, &ops, &sim, i & 0xFFF, 1, 4) == CK_GCHAN_OK; + ok &= ck_gpu_chan_submit(&ch, pb, 0, 4) == CK_GCHAN_OK; + ok &= ck_gpu_chan_teardown(&ch, 2, 0, 0) == CK_GCHAN_OK; + } + CHECK(ok); + CHECK(ck_gmem_count(&gm, CK_GMEM_LIVE) == 1 && ck_gmem_count(&gm, CK_GMEM_FREE) == 31); + CHECK(sim.nfaults == 0 && sim.log_dropped > 0); /* the log is bounded too */ +} + +/* 9. Levels with a PTE the mapper never writes: PD1 (512 MiB) and PD2 (256 GiB) + * decode as huge pages (kgmmuFmtInitLevels_GH10X / _GB10X bPageTable), PD3 and + * PD4 have no PTE form (BAD_PDE). Entries are planted by hand. */ +static uint64_t table_at(uint64_t tbl, uint32_t idx) +{ + uint64_t e; + memcpy(&e, mem + (tbl - PA_BASE) + idx * 8u, 8); + return e & 0x000FFFFFFFFFF000ull; +} + +static void plant(uint64_t tbl, uint32_t idx, uint64_t val) +{ + memcpy(mem + (tbl - PA_BASE) + idx * 8u, &val, 8); +} + +static void test_huge_levels(void) +{ + fresh(64); + CHECK(ck_gmmu_map(&as, 0x1000, DATA_PA, 0x1000, CK_GMMU_SZ_4K, 2, 0) == CK_GMMU_OK); + uint64_t pd3 = table_at(as.root_pa, 0), pd2 = table_at(pd3, 0), pd1 = table_at(pd2, 0); + uint64_t wpa = 0, page = 0; + uint32_t lo = 0; + plant(pd1, 1, ck_gmmu_pte(PA_BASE, CK_GMMU_PTE_AP_SYS_COH, 0, 0)); /* VA [512 MiB, 1 GiB) */ + CHECK(ck_gsim_walk(&sim, as.root_pa, (1ull << 29) + 0x4321, 0, &wpa, &page, &lo) == 0); + CHECK(page == (1ull << 29) && wpa == PA_BASE + 0x4321); + plant(pd2, 1, ck_gmmu_pte(0, CK_GMMU_PTE_AP_SYS_COH, 0, 0)); /* VA [256 GiB, 512 GiB) */ + CHECK(ck_gsim_walk(&sim, as.root_pa, (1ull << 38) + PA_BASE + 8, 0, &wpa, &page, &lo) == 0); + CHECK(page == (1ull << 38) && wpa == PA_BASE + 8); + plant(pd3, 1, ck_gmmu_pte(PA_BASE, CK_GMMU_PTE_AP_SYS_COH, 0, 0)); + CHECK(ck_gsim_walk(&sim, as.root_pa, 1ull << 47, 0, &wpa, &page, &lo) == CK_GSIM_F_BAD_PDE); + plant(as.root_pa, 1, ck_gmmu_pte(PA_BASE, CK_GMMU_PTE_AP_SYS_COH, 0, 0)); + CHECK(ck_gsim_walk(&sim, as.root_pa, 1ull << 56, 0, &wpa, &page, &lo) == CK_GSIM_F_BAD_PDE); + /* The mapper refuses to map under a huge PTE instead of overwriting it. */ + CHECK(ck_gmmu_map(&as, 1ull << 29, DATA_PA, 0x1000, CK_GMMU_SZ_4K, 2, 0) == CK_GMMU_EBUSY); + CHECK(ck_gmmu_map(&as, 1ull << 38, PA_BASE + 0x200000, CK_GMMU_SZ_2M, CK_GMMU_SZ_2M, 2, 0) == CK_GMMU_EBUSY); + /* Video and peer apertures do not exist on GB10: fault, never translate. */ + plant(pd1, 2, ck_gmmu_pte(PA_BASE, CK_GMMU_PTE_AP_VIDMEM, 0, 0)); + CHECK(ck_gsim_walk(&sim, as.root_pa, 2ull << 29, 0, &wpa, &page, &lo) == CK_GSIM_F_APERTURE); + plant(pd1, 3, ck_gmmu_pde(PA_BASE, CK_GMMU_PDE_AP_VIDMEM)); + CHECK(ck_gsim_walk(&sim, as.root_pa, 3ull << 29, 0, &wpa, &page, &lo) == CK_GSIM_F_APERTURE); +} + +/* 10. The 40-bit pushbuffer address limit of the GPFIFO entry. */ +static void test_gp_va40(void) +{ + struct ck_gpu_chan_ops ops = ck_gsim_chan_ops(); + struct ck_gpu_chan ch; + struct ck_gmem_buf *big = 0, *pb = 0; + /* Last page ends exactly at 2^40: allowed. */ + fresh(64); + CHECK(ck_gmem_init(&gm, &as, ®s, 10, DATA_PA, 520, (1ull << 40) - 0x200000) == CK_GMEM_OK); + CHECK(ck_gpu_chan_create(&ch, &gm, ®s, &ops, &sim, 9, 0, 4) == CK_GCHAN_OK); + CHECK(ck_gmem_alloc(&gm, 0x200000 - 4u * 4096u, CK_GMEM_CACHED, 0, &big) == CK_GMEM_OK); + CHECK(ck_gmem_alloc(&gm, 4096, CK_GMEM_CACHED, CK_GMEM_GPU_RO, &pb) == CK_GMEM_OK); + CHECK(pb->gpu_va == (1ull << 40) - 4096); + CHECK(ck_gpu_chan_submit(&ch, pb, 0, 1024) == CK_GCHAN_OK); + const struct ck_gsim_chan *sc = ck_gsim_chan(&sim, 9); + CHECK(sc && sc->words_read == 1024 && !sc->faulted); + /* At or beyond 2^40: refused before anything reaches the ring. */ + struct ck_gmem_buf *hi = 0; + CHECK(ck_gmem_alloc(&gm, 4096, CK_GMEM_CACHED, CK_GMEM_GPU_RO, &hi) == CK_GMEM_OK); + CHECK(hi->gpu_va == (1ull << 40)); + uint32_t put = ch.put, bells = sim.doorbells; + CHECK(ck_gpu_chan_submit(&ch, hi, 0, 1) == CK_GCHAN_EINVAL); + CHECK(ch.put == put && sim.doorbells == bells); + CHECK(ck_gpu_chan_teardown(&ch, 2, 0, 0) == CK_GCHAN_OK); +} + +int main(void) +{ + mem = aligned_alloc(4096, MEM_BYTES); + if (!mem) + return 2; + test_encodings(); + test_map_unmap(); + test_page_sizes(); + test_pool_exhaustion(); + test_invalidate(); + test_allocator(); + test_channel(); + test_reopen(); + test_huge_levels(); + test_gp_va40(); + free(mem); + return ck_t_verdict("test_gpu_sim"); +} diff --git a/native/kernel/tests/test_gsp_mmio.c b/native/kernel/tests/test_gsp_mmio.c new file mode 100644 index 00000000..cb435a4d --- /dev/null +++ b/native/kernel/tests/test_gsp_mmio.c @@ -0,0 +1,254 @@ +/* test_gsp_mmio: the GB10B GSP start-up sequence (gpu/gsp_mmio.c) against the simulated SEC2 + GSP falcon + * (gpu/gsp_sim.c). Host only; nothing here has run on the chip. */ +#include "gsp_mmio.h" +#include "gsp_sim.h" +#include "ck_test.h" +#include + +#define ARGS_PA 0x0000000123456000ull +#define APP_VERSION 0x0005f3a1u + +static uint8_t pkt[868]; +static struct ck_gspsim sim; +static struct ck_gpu_regs regs; +static unsigned pauses; + +static void count_pause(void *ctx) +{ + (void)ctx; + pauses++; +} + +/* A well-formed SEC2 boot packet, laid out like L192 gsp_boot_build: MCTP dword, NVDM COT dword, then + * NVDM_PAYLOAD_COT (version 1, size 860, ...). Payload bytes past the header are a pattern. */ +static void make_packet(void) +{ + static const uint32_t hdr[3] = {0x00000001u, 0x1410DE7Eu, 1u | (860u << 16)}; + memcpy(pkt, hdr, sizeof(hdr)); + for (unsigned i = sizeof(hdr); i < sizeof(pkt); i++) + pkt[i] = (uint8_t)(i * 7u + 3u); +} + +static struct ck_gsp_mmio_in base_in(void) +{ + struct ck_gsp_mmio_in in = {pkt, sizeof(pkt), ARGS_PA, APP_VERSION, 100, 100, 100, 100, count_pause, 0}; + return in; +} + +static struct ck_gspsim_cfg base_cfg(void) +{ + struct ck_gspsim_cfg c = {0, 3, 4, 2, 5, 0, 0, 0, ARGS_PA, 0}; + return c; +} + +static int run(const struct ck_gspsim_cfg *c, const struct ck_gsp_mmio_in *in, struct ck_gsp_mmio_out *o) +{ + ck_gspsim_init(&sim, c); + regs = ck_gspsim_regs(&sim); + pauses = 0; + return ck_gsp_mmio_boot(®s, in, o); +} + +static uint32_t writes_to(uint32_t off) +{ + uint32_t n = 0; + for (uint32_t i = 0; i < sim.nlog && i < CK_GSPSIM_LOG_MAX; i++) + n += sim.log[i].write && sim.log[i].off == off; + return n; +} + +static int index_of_write(uint32_t off) +{ + for (uint32_t i = 0; i < sim.nlog && i < CK_GSPSIM_LOG_MAX; i++) + if (sim.log[i].write && sim.log[i].off == off) + return (int)i; + return -1; +} + +static void test_happy(void) +{ + struct ck_gspsim_cfg c = base_cfg(); + struct ck_gsp_mmio_in in = base_in(); + struct ck_gsp_mmio_out o; + CHECK(run(&c, &in, &o) == CK_GSP_OK); + CHECK(o.stage == CK_GSP_OK); + CHECK(sim.violations == 0); + CHECK(memcmp(sim.emem, pkt, sizeof(pkt)) == 0); /* EMEM holds the packet byte for byte */ + CHECK(o.dwords == 217u); + CHECK(o.ememc_after == (CK_GSP_EMEMC_AINCW | 3u << 8 | 25u << 2)); /* 217 = 3 blocks of 64 + 25 */ + CHECK(sim.qtail == 864u); /* padded size minus one dword */ + CHECK(index_of_write(CK_GSP_SEC2_QTAIL0) >= 0); + CHECK(index_of_write(CK_GSP_SEC2_QTAIL0) < index_of_write(CK_GSP_SEC2_QHEAD0)); /* TAIL then HEAD */ + CHECK(writes_to(CK_GSP_SEC2_QHEAD0) == 1 && writes_to(CK_GSP_SEC2_QTAIL0) == 1); + CHECK(writes_to(CK_GSP_SEC2_EMEMC0) == 1 && writes_to(CK_GSP_SEC2_EMEMD0) == 217u); + /* the first accesses, in order: HEAD, TAIL reads, EMEMC config, EMEMC read */ + CHECK(sim.log[0].off == CK_GSP_SEC2_QHEAD0 && !sim.log[0].write); + CHECK(sim.log[1].off == CK_GSP_SEC2_QTAIL0 && !sim.log[1].write); + CHECK(sim.log[2].off == CK_GSP_SEC2_EMEMC0 && sim.log[2].write && sim.log[2].val == CK_GSP_EMEMC_AINCW); + CHECK(sim.log[3].off == CK_GSP_SEC2_EMEMC0 && !sim.log[3].write); + CHECK(sim.os == APP_VERSION && writes_to(CK_GSP_FLCN_OS) == 1); + CHECK(o.cpuctl & CK_GSP_CPUCTL_ACTIVE); + CHECK(o.polls[0] == 0); + CHECK(o.polls[1] == 3); /* cmd_reads busy reads, then handled */ + CHECK(o.polls[2] == 4); /* mask_reads locked reads, then released */ + CHECK(o.polls[3] >= 5); /* args twice, then lockdown_reads */ + CHECK(pauses == o.polls[0] + o.polls[1] + o.polls[2] + o.polls[3]); + CHECK(o.gsp_mb0 == 0 && o.sec2_mb0 == 0); + /* the last two accesses: FALCON_OS write, CPUCTL read */ + uint32_t n = sim.nlog; + CHECK(n >= 2 && sim.log[n - 2].off == CK_GSP_FLCN_OS && sim.log[n - 2].write); + CHECK(sim.log[n - 1].off == CK_GSP_RISCV_CPUCTL && !sim.log[n - 1].write); +} + +static void test_busy(void) +{ + struct ck_gspsim_cfg c = base_cfg(); + struct ck_gsp_mmio_in in = base_in(); + struct ck_gsp_mmio_out o; + c.busy_reads = 3; + CHECK(run(&c, &in, &o) == CK_GSP_OK); + CHECK(o.polls[0] == 3 && sim.violations == 0); + + c.busy_reads = CK_GSPSIM_NO_END; + CHECK(run(&c, &in, &o) == CK_GSP_E_BUSY); + CHECK(o.polls[0] == 100); + CHECK(writes_to(CK_GSP_SEC2_EMEMC0) == 0 && writes_to(CK_GSP_SEC2_EMEMD0) == 0); /* nothing written */ + CHECK(writes_to(CK_GSP_SEC2_QHEAD0) == 0); + + in.polls_can_send = 0; /* budget 0: check once */ + CHECK(run(&c, &in, &o) == CK_GSP_E_BUSY && o.polls[0] == 0 && pauses == 0); +} + +static void test_args(void) +{ + struct ck_gsp_mmio_out o; + struct ck_gsp_mmio_in in = base_in(); + struct ck_gspsim_cfg c = base_cfg(); + in.packet = 0; + CHECK(run(&c, &in, &o) == CK_GSP_E_ARG && sim.nlog == 0); + in = base_in(); + in.len = 0; + CHECK(run(&c, &in, &o) == CK_GSP_E_ARG && sim.nlog == 0); + in.len = CK_GSP_EMEM_CHANNEL_BYTES + 1; + CHECK(run(&c, &in, &o) == CK_GSP_E_ARG && sim.nlog == 0); + CHECK(ck_gsp_mmio_boot(0, &in, &o) == CK_GSP_E_ARG); + CHECK(ck_gsp_mmio_boot(®s, 0, &o) == CK_GSP_E_ARG); + /* 1024 bytes exactly fits the channel */ + static uint8_t big[1024]; + memcpy(big, pkt, sizeof(pkt)); + in = base_in(); + in.packet = big; + in.len = sizeof(big); + c.mask_reads = CK_GSPSIM_NO_END; /* the sim rejects a non-868 packet; we only check the send here */ + in.polls_mask = 2; + CHECK(run(&c, &in, &o) == CK_GSP_E_MASK); + CHECK(o.dwords == 256u && sim.qtail == 1020u && sim.violations == 0); +} + +static void test_odd_length(void) +{ + struct ck_gspsim_cfg c = base_cfg(); + struct ck_gsp_mmio_in in = base_in(); + struct ck_gsp_mmio_out o; + in.len = 7; /* one full dword and a 3-byte tail, zero-padded */ + in.polls_mask = 1; + CHECK(run(&c, &in, &o) == CK_GSP_E_MASK); /* the sim refuses a short packet: mask never released */ + CHECK(o.dwords == 2u && sim.qtail == 4u); + CHECK(sim.emem[0] == 0x00000001u); + CHECK(sim.emem[1] == (0x1410DE7Eu & 0x00FFFFFFu)); /* bytes 4..6, top byte zero */ + CHECK(sim.violations == 0); +} + +static void test_failures(void) +{ + struct ck_gsp_mmio_out o; + struct ck_gsp_mmio_in in = base_in(); + struct ck_gspsim_cfg c; + + c = base_cfg(); c.cmd_reads = CK_GSPSIM_NO_END; + CHECK(run(&c, &in, &o) == CK_GSP_E_SEC2); + CHECK(o.polls[1] == 100 && o.sec2_mb0 == CK_GSP_SEC2_CMD_BUSY); + CHECK(writes_to(CK_GSP_FLCN_OS) == 0); + + c = base_cfg(); c.mask_reads = CK_GSPSIM_NO_END; + CHECK(run(&c, &in, &o) == CK_GSP_E_MASK); + CHECK((o.hwcfg2 & CK_GSP_PRIV_LOCKED_MASK) == CK_GSP_PRIV_LOCKED && writes_to(CK_GSP_FLCN_OS) == 0); + ``` The diff is longer than this page shows; the raw diff has all of it.