From f99758b0336312849c13656c6d486f7a949753c6 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Sun, 4 Oct 2026 10:01:15 -0500 Subject: [PATCH] boot+kernel: load the model from the boot disk through firmware Block I/O (MODEL.MAP, CHANDOF2), kernel-side sha256, QEMU disk gate + negative control (aienos#34 lane 6, L6-B) The fw_cfg channel exists only under QEMU. This cut adds the path that exists on hardware: the UEFI stub opens \EFI\AIENOS\MODEL.MAP on the ESP it booted from, matches the GPT disk GUID at LBA 1 of a whole-disk Block I/O handle, allocates EfiLoaderData and reads the model's absolute-LBA extents in file order before ExitBootServices. The handoff record becomes CHANDOF2 (192 bytes, model base/len/sha256/flags/extents/read time/disk geometry, every offset static-asserted; CHANDOF1 is refused). The kernel reserves the model frames, prefers the disk model over fw_cfg, recomputes SHA-256 over the loaded bytes and refuses to decode on mismatch (infer: sha256 mismatch declared=... -> AIENOS_CK_INFER: FAIL). Host tools: ck_model_map make|show|check (FIEMAP or explicit extents; check reads the extents back by LBA and recomputes the hash: the pre-boot proof on the Spark) and ck_gpt_image ... esp-model (ESP + model in three out-of-order extents). Gate: scripts/qemu_ck_infer_test.sh --disk boots a GPT image on an emulated NVMe controller; --disk-negative-control corrupts the declared sha256 and requires the kernel to refuse. make test adds test_handoff case 7. QEMU evidence at this tree (TCG): fw_cfg gate PASS (regression), disk gate kernel PASS with the golden ids 791 6864 315 9822 374 12366 13 128009 and "The capital of France is Paris." (model read 807694368 bytes in 3 extents), disk negative control PASS (hash mismatch refused, no decode). QEMU qualifies nothing physical; the Spark receipt is the next cut (L6-C). Co-Authored-By: Drake Stapleton Co-Authored-By: Claude Fable 5.1 --- .crumb | 22 +-- docs/.crumb | 8 +- docs/BOOT_HANDOFF_CONTRACT.md | 36 ++-- native/.crumb | 20 +- native/boot/.crumb | 10 +- native/boot/efi.h | 114 +++++++++-- native/boot/efi_main.c | 5 + native/boot/efi_model.c | 224 +++++++++++++++++++++ native/boot/handoff.h | 40 +++- native/boot/model_map.h | 116 +++++++++++ native/kernel/.crumb | 28 +-- native/kernel/Makefile | 10 +- native/kernel/core/.crumb | 8 +- native/kernel/core/ck_internal.h | 1 + native/kernel/core/handoff_check.c | 31 ++- native/kernel/core/infer.c | 93 ++++++--- native/kernel/core/kmain.c | 1 + native/kernel/mm/.crumb | 8 +- native/kernel/mm/mmu.c | 5 + native/kernel/tests/.crumb | 8 +- native/kernel/tests/test_handoff.c | 54 +++++- native/kernel/tools/.crumb | 10 +- native/kernel/tools/ck_gpt_image.c | 71 +++++++ native/kernel/tools/ck_model_map.c | 300 +++++++++++++++++++++++++++++ native/kernel/tools/gpt_write.c | 2 + native/kernel/tools/gpt_write.h | 3 + scripts/.crumb | 8 +- scripts/qemu_ck_infer_test.sh | 77 +++++++- 28 files changed, 1190 insertions(+), 123 deletions(-) create mode 100644 native/boot/efi_model.c create mode 100644 native/boot/model_map.h create mode 100644 native/kernel/tools/ck_model_map.c diff --git a/.crumb b/.crumb index 8bee6353..14d94ebd 100644 --- a/.crumb +++ b/.crumb @@ -22,38 +22,38 @@ "children": [ { "digest": "56d2cf6d9dd340a9df0a880d1fd9879cf3cd31eb1d827302662144b5f2bebe2d", - "last_commit": "4c94ce7", + "last_commit": "733a841", "name": "crates", "purpose": "Directory crates. Purpose not yet described by a human." }, { - "digest": "33fc52a08fa35148a48f29ec7da0c9b39b4d375203bc7515f182767837e728c0", + "digest": "9e7b47432d0ed2b4d3c5c5116b46dd1e6f822461349cdea84b675996e68ec493", "last_commit": "fff3c3b", "name": "docs", "purpose": "Directory docs. Purpose not yet described by a human." }, { - "digest": "80788e797d7ebf8c1d9ca8483ee06039c064856423c7a7d316d13ef006d12ce8", + "digest": "eadafdc74d10684d51194f471a3c027d45e20ab8eaac3432c9ddfc93aed37d6a", "last_commit": "a863d5c", "name": "native", "purpose": "Directory native. Purpose not yet described by a human." }, { - "digest": "e7ab7a937d3d63828c4b3431a5f958217db1c03819f3a7d7532c86d648c85c98", - "last_commit": "91bfd45", + "digest": "f99911001560491e4c719aa841ac33c9cec413ee578fe55da847f4c781e992af", + "last_commit": "733a841", "name": "scripts", "purpose": "Directory scripts. Purpose not yet described by a human." } ], - "children_root": "sha256:0c24eafb4f0e5a4e8c9e938f907e1a1449bed87a892953e9325175b24b48d1a0", - "compiled_at": "2026-10-04T15:04:07Z", + "children_root": "sha256:e38cb0be1d01399240d52132dc5e3c238d9b0526a2f9bb09221071e1464fc4d4", + "compiled_at": "2026-10-04T15:16:40Z", "compiler": "crumb-compile/1", - "digest": "sha256:82262b0cb3a3b4612eb0482fa0baaa7378be761bfd5c1cc44c685f8acb5feead", + "digest": "sha256:d16bcba92a3c8c5d1cd82e2c94705e4fcdfd956f0e5106cfce75719ccddfb07c", "evidence_files": 142, "evidence_root": "sha256:3b8ecf493ee0e4513ffb21827d50f30092f361f8a9a66e5abe4791e94c1cc8ec", - "files": 2829, - "generated_at_commit": "4c94ce75a45f4467f55201581ccd59fdbbd58399", - "source_tree": "sha256:ffa23d565d0fce72aa21b0c287feb10893f6d9a1fb637cc3981fe007fe37d935" + "files": 2832, + "generated_at_commit": "733a8419c1fa44a13dc5e8f525eca33cdea7c5dc", + "source_tree": "sha256:0cba96bd2a00784afe7c8e4b4a85c9ddf409044f032b2b0d7dc9fe63848f67d2" }, "owner_lane": "", "provenance": { diff --git a/docs/.crumb b/docs/.crumb index 1985c81f..09fa8ede 100644 --- a/docs/.crumb +++ b/docs/.crumb @@ -30,14 +30,14 @@ } ], "children_root": "sha256:55d44b8c5361b8f2452ed7fab6a4b51a8bb1f92763f67f1273dd9be45f8cfde0", - "compiled_at": "2026-10-04T13:47:18Z", + "compiled_at": "2026-10-04T15:01:15Z", "compiler": "crumb-compile/1", - "digest": "sha256:33fc52a08fa35148a48f29ec7da0c9b39b4d375203bc7515f182767837e728c0", + "digest": "sha256:9e7b47432d0ed2b4d3c5c5116b46dd1e6f822461349cdea84b675996e68ec493", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 56, - "generated_at_commit": "a863d5c1f5bd89c88c5f6671eecfd27b599ee512", - "source_tree": "sha256:233d804aa521a570e1cce2578ce8cbb8cee70331dc62851ef5c05b2a82989a8e" + "generated_at_commit": "39e611ed040126791acdb667dbbc288a3757858a", + "source_tree": "sha256:be6a02bd78283cef9fec88ec889967fdc517875dc68e939c382ceefbb06dc248" }, "owner_lane": "", "provenance": { diff --git a/docs/BOOT_HANDOFF_CONTRACT.md b/docs/BOOT_HANDOFF_CONTRACT.md index 5e6cdfa8..2cb3ea6a 100644 --- a/docs/BOOT_HANDOFF_CONTRACT.md +++ b/docs/BOOT_HANDOFF_CONTRACT.md @@ -45,7 +45,7 @@ There is **no Rust loader to C kernel handoff in the code**. Three facts: exists anywhere (ADR 0024 Q3). So this contract freezes the record the C kernel already accepts -(`ck_handoff`, magic `CHANDOF1`) as the **one** entry ABI. Any loader (the C +(`ck_handoff`, magic `CHANDOF2`) as the **one** entry ABI. Any loader (the C stub today; the Rust loader only if Q3 is reopened; Atlas later) must produce exactly this record. The Rust loader is not extended by this document. @@ -60,7 +60,7 @@ exactly this record. The Rust loader is not extended by this document. | Record location | inside the loaded image BSS (`static struct ck_handoff handoff`, `efi_main.c:20`); memory map copy in the image BSS too (`efi_main.c:19`) | CODE | | Separate kernel binary entry | **MISSING.** A loader that is not linked into the kernel image has no symbol to call and no load format for the kernel. PROPOSED: not added while Q3 freezes loader expansion. | | -## 3. Record layout (`struct ck_handoff`, `native/boot/handoff.h:11-28`) +## 3. Record layout (`struct ck_handoff`, `native/boot/handoff.h`) Offsets below are derived by hand from AAPCS64 natural alignment (LP64, little endian). **They are not compiler-checked**: the code cut in section @@ -68,7 +68,7 @@ little endian). **They are not compiler-checked**: the code cut in section | Off | Size | Field | Meaning | Producer | Kernel reads it? | | --- | --- | --- | --- | --- | --- | -| 0 | 8 | `magic` | `CK_HANDOFF_MAGIC` = `0x31464f444e414843`, ASCII `CHANDOF1` little endian (`handoff.h:9`) | `efi_main.c:62` | yes, `kmain.c:174` | +| 0 | 8 | `magic` | `CK_HANDOFF_MAGIC` = `0x32464f444e414843`, ASCII `CHANDOF2` little endian (`handoff.h`). `CK_HANDOFF_MAGIC_V1` (`CHANDOF1`, the 112-byte layout) is refused | `efi_main.c` | yes, `kmain.c`, `core/handoff_check.c` | | 8 | 4 | `firmware_el` | `CurrentEL` at UEFI entry | `efi_main.c:61,63` | yes, report only `kmain.c:57` | | 12 | 4 | `desc_version` | UEFI memory descriptor version from `GetMemoryMap` | `efi_main.c:128` | **no** (never checked) | | 16 | 8 | `firmware_ttbr0` | `TTBR0_EL2` (or EL1) of the firmware regime | `efi_main.c:67,70` | yes, report only `kmain.c:53` | @@ -84,20 +84,29 @@ little endian). **They are not compiler-checked**: the code cut in section | 96 | 4 | `exit_attempts` | `ExitBootServices` calls until success (1..8) | `efi_main.c:129` | yes, report only `kmain.c:66` | | 100 | 4 | `reserved0` | zero (BSS) | `efi_main.c:20` (static, zeroed by `efi_entry.S` BSS clear) | **no** (not checked to be zero) | | 104 | 8 | `commit` | pointer to the build commit string | `efi_main.c:75` | **no** (kernel calls `ck_commit()` directly, `core/report.c` `ck_report_header`) | -| 112 | | end | total size 112 bytes (hand derived) | | | +| 112 | 8 | `model_base` | physical base of the model bytes the stub read from the boot disk (EfiLoaderData, 4 KiB aligned); 0 without a model | `efi_model.c` | yes, `core/infer.c` (disk path), reserved `mm/mmu.c` | +| 120 | 8 | `model_len` | model bytes | `efi_model.c` | yes, `core/infer.c`, `core/handoff_check.c` | +| 128 | 32 | `model_sha256` | SHA-256 declared by `MODEL.MAP`; the kernel recomputes it over the loaded bytes and refuses to decode on mismatch | `efi_model.c` | yes, `core/infer.c` | +| 160 | 4 | `model_flags` | bit 0 `CK_HANDOFF_MODEL_PRESENT`, bit 1 `CK_HANDOFF_MODEL_BLOCKIO` (read through the firmware Block I/O before `ExitBootServices`); other bits refused | `efi_model.c` | yes, `core/handoff_check.c`, `core/infer.c` | +| 164 | 4 | `model_extents` | extents listed in `MODEL.MAP` (1..128) | `efi_model.c` | yes (range check), report | +| 168 | 8 | `model_read_us` | wall time of the Block I/O read, microseconds | `efi_model.c` | report only | +| 176 | 8 | `model_disk_last_block` | `EFI_BLOCK_IO_MEDIA.LastBlock` of the matched whole disk | `efi_model.c` | report only | +| 184 | 4 | `model_block_size` | 512 or 4096 | `efi_model.c` | yes, `core/handoff_check.c` | +| 188 | 4 | `reserved1` | zero; refused if nonzero | zero (BSS) | yes, `core/handoff_check.c` | +| 192 | | end | total size 192 bytes (`_Static_assert` in `handoff.h`) | | | ### 3.1 Inputs the task asked about that are not in the record | Input | Status today | Where it comes from instead | | --- | --- | --- | -| Version field | **MISSING** as a field. The version is the trailing `1` inside the magic `CHANDOF1` (`handoff.h:9`). PROPOSED rule: a new layout gets a new magic (`CHANDOF2`, ...); there is no separate version number. | | -| Record size field | **MISSING.** PROPOSED: not added in v1 (adding it changes the frozen layout); the magic fixes the size at 112. | | +| Version field | The version is the trailing digit inside the magic (`CHANDOF2`, `handoff.h`); a new layout gets a new magic, there is no separate version number. `CHANDOF2` (2026-10-04) appended the boot-disk model block (offsets 112..192, section 3). `CHANDOF1` records are refused (`handoff_check.c`, `test_handoff.c` case 2). | | +| Record size field | **MISSING.** The magic fixes the size: `CHANDOF1` = 112 bytes, `CHANDOF2` = 192 bytes (`_Static_assert` in `handoff.h`). | | | DTB pointer | **MISSING.** The C kernel is ACPI only (no `fdt`/`dtb` symbol anywhere in `native/`). Not part of v1. | | | Framebuffer (GOP) | **MISSING** in `ck_handoff`. The Rust loader captures one (`crates/aienos-boot/src/handoff.rs:1170-1178`, type `crates/aienos-kernel/src/display/mod.rs:22-30`), the C stub does not. Not part of v1. | | | Console UART | Not in the record. The stub parses SPCR and configures the console **inside the shared image** (`efi_main.c:91-95`); the kernel inherits that state through static variables, not through the record. A separately linked kernel would get no console. **MISSING** for that case. | | | Entropy | Not in the record. The kernel probes `RNDR` itself and fails closed (`kmain.c:121-132`, `arch/rndr.c`). No loader-supplied seed; PROPOSED: never accept one (a loader seed would be an unverified input). | | | Owner key material (after #215) | Not in the record. Owner **public** keys and machine id are compiled into the hardware staging image at build time (`native/kernel/Makefile:97-125`, `CK_OWNER_PUBKEYS`, `CK_MACHINE_ID`). PROPOSED: the handoff never carries key material. | | -| Boot disk identity | **MISSING.** The kernel binds the first PCI function of class `0x010802` (`native/kernel/dev/nvme_bind.c:141`) and calls it the boot disk (`dev/devices.c:12`). The loader does not tell the kernel which disk it booted from. | | +| Boot disk identity | **Partly.** With a model, `model_disk_last_block` / `model_block_size` describe the whole disk the stub read the model from, and `MODEL.MAP` (`\EFI\AIENOS\MODEL.MAP`, `native/boot/model_map.h`) binds the GPT disk GUID that the stub matched at LBA 1 (`native/boot/efi_model.c`). The GUID itself is not in the record. Without a model the kernel still binds the first PCI function of class `0x010802` (`native/kernel/dev/nvme_bind.c`) and calls it the boot disk. | | | Image / artifact info | Image range only (`image_base`/`image_end`). Artifacts are read by the kernel from the boot disk Store (`kmain.c:141-144`), not passed by the loader. | | | Boot attempt / rollback state | **MISSING**, and PROPOSED to stay out of the record (section 7). | | @@ -180,6 +189,11 @@ panic: | record, map copy or image overlaps `EfiConventionalMemory` | **not checked** (survived by reservation, `mm/mmu.c:118-120`) | PROPOSED `panic: handoff: record region in free memory` | | `rsdp == 0` | **not refused**: boot continues, then panics later `gic: no usable ACPI MADT` (`kmain.c:87-90`) | PROPOSED `panic: handoff: missing rsdp` | | `firmware_el` not 1 or 2 | CODE `kmain.c:186` uses live `CurrentEL`, not the field | PROPOSED `panic: handoff: firmware_el mismatch` when the field disagrees with live `CurrentEL` | +| `model_flags` has bits other than `CK_HANDOFF_MODEL_PRESENT` / `CK_HANDOFF_MODEL_BLOCKIO` | CODE `core/handoff_check.c` | `handoff: bad model flags ` | +| model present with `model_len == 0`, `model_base` not 4 KiB aligned, base+len overflow, `model_block_size` not 512/4096, or `model_extents` 0 or > 128 | CODE `core/handoff_check.c`, `tests/test_handoff.c` case 7 | `handoff: bad model range` / `model base unaligned` / `model range overflow` / `bad model block size` / `bad model extents` | +| no model (`model_flags == 0`) but any model field or `model_sha256` byte nonzero | CODE `core/handoff_check.c` | `handoff: model fields without model` | +| `reserved1 != 0` | CODE `core/handoff_check.c` | `handoff: reserved1 field nonzero` | +| declared `model_sha256` differs from the SHA-256 of the loaded bytes | CODE `core/infer.c` (not a panic: the kernel refuses to decode and reports `AIENOS_CK_INFER: FAIL`) | `infer: sha256 mismatch declared=` | Every PROPOSED check runs **before** `ck_mm_build` (before the first frame is handed out) and after the vectors are installed, so a refusal can print. @@ -259,15 +273,15 @@ QEMU only; Machine 1 is NOT_RUN. ## 8. Frozen forever vs extensible -**Frozen (v1, `CHANDOF1`):** the magic value; the 112-byte layout and every +**Frozen (v2, `CHANDOF2`; v1 `CHANDOF1` is superseded and refused):** the magic value; the 192-byte layout and every offset in section 3; the meaning of every field; `x0` = record address; `ExitBootServices` done before the call; the reserved-range rules in section 5; the `panic: handoff: bad magic` line; "no rollback state and no key material in the record". **Extensible only by a new magic (PROPOSED):** any added field (framebuffer, -boot disk identity, UART, a record size field) means a new struct with a new -magic `CHANDOF2`; the kernel accepts exactly the magics it was built for and +UART, a record size field) means a new struct with a new +magic (`CHANDOF3`, ...); the kernel accepts exactly the magic it was built for and refuses the rest with the `unsupported version` line. No in-place growth of v1, no use of `reserved0` for data (it must stay zero). @@ -277,7 +291,7 @@ Host unit tests (no QEMU) against a PROPOSED pure validator, each with the exact refusal line from section 6: 1. NULL record. -2. Magic off by one bit; magic `CHANDOF2`. +2. Magic off by one bit; the old magic `CHANDOF1` (DONE: `tests/test_handoff.c` case 2). 3. `reserved0 = 1`. 4. `desc_size` 0, 39, 41 (not a multiple of 8). 5. `desc_version` 0 and 2. diff --git a/native/.crumb b/native/.crumb index 894e388a..088dc397 100644 --- a/native/.crumb +++ b/native/.crumb @@ -55,8 +55,8 @@ "purpose": "Directory native/argus. Purpose not yet described by a human." }, { - "digest": "cbaa1c62b54f71216a8991d0e8b9f29330fb3c51eb852cb45eb775ff0b7dbb2c", - "last_commit": "e4f1513", + "digest": "5e920ca9d6fae601ce4e308e7a38fd9cfec409cb532199052942bf55900ebf52", + "last_commit": "39e611e", "name": "boot", "purpose": "Directory native/boot. Purpose not yet described by a human." }, @@ -79,8 +79,8 @@ "purpose": "Directory native/disk. Purpose not yet described by a human." }, { - "digest": "541e7184c7281b549aac9b8dba20fc8c6d648e6135638fc10e00da0ea8c30d33", - "last_commit": "a863d5c", + "digest": "bfdf0a6a28753c18c7c522796188040c7dc94758b3fd5b7a91b221136670f574", + "last_commit": "39e611e", "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:0f46ad82a59b3297c1c8e5457b1786ed0103cdc0a7e91f23ed5f0ec11d9d2493", - "compiled_at": "2026-10-04T13:47:18Z", + "children_root": "sha256:1ee27f503136cb7a2aa9191edf54aca7f21473386b35e344b6c9d01633787556", + "compiled_at": "2026-10-04T15:01:15Z", "compiler": "crumb-compile/1", - "digest": "sha256:80788e797d7ebf8c1d9ca8483ee06039c064856423c7a7d316d13ef006d12ce8", + "digest": "sha256:eadafdc74d10684d51194f471a3c027d45e20ab8eaac3432c9ddfc93aed37d6a", "evidence_files": 4, "evidence_root": "sha256:e410b845507e00568e15b51a5797af32a97e0e4b8ab4e8487bb7c98e7e0cf335", - "files": 291, - "generated_at_commit": "a863d5c1f5bd89c88c5f6671eecfd27b599ee512", - "source_tree": "sha256:f49d4e2642653b0c0ba5c96b7f1cb42b6f13fe2a19d128a20032ea5bb99a7c7d" + "files": 294, + "generated_at_commit": "39e611ed040126791acdb667dbbc288a3757858a", + "source_tree": "sha256:a06f9fcf6abc083df99f9c6cd9257599719df30bb50009745d9bbdad5d01d634" }, "owner_lane": "", "provenance": { diff --git a/native/boot/.crumb b/native/boot/.crumb index 6a503258..ca9ed19d 100644 --- a/native/boot/.crumb +++ b/native/boot/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-04T13:47:18Z", + "compiled_at": "2026-10-04T15:01:15Z", "compiler": "crumb-compile/1", - "digest": "sha256:cbaa1c62b54f71216a8991d0e8b9f29330fb3c51eb852cb45eb775ff0b7dbb2c", + "digest": "sha256:5e920ca9d6fae601ce4e308e7a38fd9cfec409cb532199052942bf55900ebf52", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 6, - "generated_at_commit": "a863d5c1f5bd89c88c5f6671eecfd27b599ee512", - "source_tree": "sha256:58b337eda239dba014d78f8ccddffe32d323e7be7c9b88195cf1bc94360da8cc" + "files": 8, + "generated_at_commit": "39e611ed040126791acdb667dbbc288a3757858a", + "source_tree": "sha256:42b450baaa15f4ff10b97162c6b0ea2ebc9e3fc76f7a768ae88b323e4f673d63" }, "owner_lane": "", "provenance": { diff --git a/native/boot/efi.h b/native/boot/efi.h index 514420be..e4e10896 100644 --- a/native/boot/efi.h +++ b/native/boot/efi.h @@ -1,12 +1,15 @@ -/* efi.h -- the few UEFI definitions the AIENOS boot stub needs, written from - * the UEFI 2.10 specification (sections 4.2, 4.3, 4.4, 7.2, 12.4). Only the - * members we call are typed; the rest are placeholders that keep the layout. - * AArch64 UEFI uses the normal AAPCS64 calling convention. */ -#ifndef AIENOS_EFI_H -#define AIENOS_EFI_H - -#include +/* efi.h -- the slice of UEFI the AIENOS C boot stub uses: system table, + * boot services it calls (GetMemoryMap, ExitBootServices, SetWatchdogTimer, + * AllocatePages, FreePages, FreePool, HandleProtocol, LocateHandleBuffer), + * the Loaded Image, Simple File System and Block I/O protocols (model ingest, + * efi_model.c). Field orders and offsets follow UEFI 2.10 (edk2 + * MdePkg/Include/Uefi/UefiSpec.h, Protocol/BlockIo.h, SimpleFileSystem.h, + * LoadedImage.h); _Static_asserts below pin the offsets this stub relies on. + * Everything not used is a void pointer placeholder of the right size. */ +#ifndef AIENOS_CK_EFI_H +#define AIENOS_CK_EFI_H #include +#include typedef uint16_t CHAR16; typedef uint64_t EFI_STATUS; @@ -16,6 +19,9 @@ typedef void *EFI_HANDLE; #define EFI_ERR(n) (0x8000000000000000ull | (n)) #define EFI_INVALID_PARAMETER EFI_ERR(2) #define EFI_BUFFER_TOO_SMALL EFI_ERR(5) +#define EFI_DEVICE_ERROR EFI_ERR(7) +#define EFI_OUT_OF_RESOURCES EFI_ERR(9) +#define EFI_NOT_FOUND EFI_ERR(14) typedef struct { uint32_t d1; @@ -43,6 +49,10 @@ enum { }; #define EFI_MEMORY_WB 0x8ull +/* EFI_ALLOCATE_TYPE and EFI_LOCATE_SEARCH_TYPE (UefiSpec.h). */ +typedef enum { AllocateAnyPages, AllocateMaxAddress, AllocateAddress, MaxAllocateType } EFI_ALLOCATE_TYPE; +typedef enum { AllHandles, ByRegisterNotify, ByProtocol } EFI_LOCATE_SEARCH_TYPE; + typedef struct { uint32_t Type; uint32_t Pad; @@ -55,14 +65,19 @@ typedef struct { typedef struct { EFI_TABLE_HEADER Hdr; void *RaiseTPL, *RestoreTPL; - void *AllocatePages, *FreePages; + EFI_STATUS (*AllocatePages)(EFI_ALLOCATE_TYPE Type, uint32_t MemoryType, uint64_t Pages, + uint64_t *Memory); + EFI_STATUS (*FreePages)(uint64_t Memory, uint64_t Pages); EFI_STATUS (*GetMemoryMap)(uint64_t *MapSize, EFI_MEMORY_DESCRIPTOR *Map, uint64_t *MapKey, uint64_t *DescriptorSize, uint32_t *DescriptorVersion); - void *AllocatePool, *FreePool; + void *AllocatePool; + EFI_STATUS (*FreePool)(void *Buffer); void *CreateEvent, *SetTimer, *WaitForEvent, *SignalEvent, *CloseEvent, *CheckEvent; void *InstallProtocolInterface, *ReinstallProtocolInterface; - void *UninstallProtocolInterface, *HandleProtocol, *Reserved; + void *UninstallProtocolInterface; + EFI_STATUS (*HandleProtocol)(EFI_HANDLE Handle, const EFI_GUID *Protocol, void **Interface); + void *Reserved; void *RegisterProtocolNotify, *LocateHandle, *LocateDevicePath; void *InstallConfigurationTable; void *LoadImage, *StartImage, *Exit, *UnloadImage; @@ -70,6 +85,11 @@ typedef struct { void *GetNextMonotonicCount, *Stall; EFI_STATUS (*SetWatchdogTimer)(uint64_t Timeout, uint64_t WatchdogCode, uint64_t DataSize, CHAR16 *WatchdogData); + void *ConnectController, *DisconnectController; + void *OpenProtocol, *CloseProtocol, *OpenProtocolInformation, *ProtocolsPerHandle; + EFI_STATUS (*LocateHandleBuffer)(EFI_LOCATE_SEARCH_TYPE SearchType, const EFI_GUID *Protocol, + void *SearchKey, uint64_t *NoHandles, EFI_HANDLE **Buffer); + void *LocateProtocol; } EFI_BOOT_SERVICES; typedef struct { @@ -94,9 +114,13 @@ typedef struct { } EFI_SYSTEM_TABLE; /* Offsets fixed by the specification (LP64). */ +_Static_assert(offsetof(EFI_BOOT_SERVICES, AllocatePages) == 0x28, "AllocatePages"); _Static_assert(offsetof(EFI_BOOT_SERVICES, GetMemoryMap) == 0x38, "GetMemoryMap"); +_Static_assert(offsetof(EFI_BOOT_SERVICES, FreePool) == 0x48, "FreePool"); +_Static_assert(offsetof(EFI_BOOT_SERVICES, HandleProtocol) == 0x98, "HandleProtocol"); _Static_assert(offsetof(EFI_BOOT_SERVICES, ExitBootServices) == 0xe8, "ExitBootServices"); _Static_assert(offsetof(EFI_BOOT_SERVICES, SetWatchdogTimer) == 0x100, "SetWatchdogTimer"); +_Static_assert(offsetof(EFI_BOOT_SERVICES, LocateHandleBuffer) == 0x138, "LocateHandleBuffer"); _Static_assert(offsetof(EFI_SYSTEM_TABLE, ConOut) == 0x40, "ConOut"); _Static_assert(offsetof(EFI_SYSTEM_TABLE, BootServices) == 0x60, "BootServices"); _Static_assert(offsetof(EFI_SYSTEM_TABLE, ConfigurationTable) == 0x70, "ConfigurationTable"); @@ -106,4 +130,72 @@ _Static_assert(sizeof(EFI_MEMORY_DESCRIPTOR) == 40, "descriptor"); #define EFI_ACPI_20_TABLE_GUID_INIT \ { 0x8868e871, 0xe4f1, 0x11d3, { 0xbc, 0x22, 0x00, 0x80, 0xc7, 0x3c, 0x88, 0x81 } } +/* --- Loaded Image (UEFI 2.10 section 9.1) --- */ +#define EFI_LOADED_IMAGE_PROTOCOL_GUID_INIT \ + { 0x5B1B31A1, 0x9562, 0x11d2, { 0x8E, 0x3F, 0x00, 0xA0, 0xC9, 0x69, 0x72, 0x3B } } +typedef struct { + uint32_t Revision; + EFI_HANDLE ParentHandle; + EFI_SYSTEM_TABLE *SystemTable; + EFI_HANDLE DeviceHandle; /* the device handle that the EFI Image was loaded from */ + void *FilePath; + void *Reserved; + uint32_t LoadOptionsSize; + void *LoadOptions; + void *ImageBase; + uint64_t ImageSize; + uint32_t ImageCodeType, ImageDataType; + void *Unload; +} EFI_LOADED_IMAGE_PROTOCOL; +_Static_assert(offsetof(EFI_LOADED_IMAGE_PROTOCOL, DeviceHandle) == 0x18, "DeviceHandle"); + +/* --- Simple File System + File (UEFI 2.10 section 13.4, 13.5) --- */ +#define EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID_INIT \ + { 0x964e5b22, 0x6459, 0x11d2, { 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b } } +#define EFI_FILE_MODE_READ 0x0000000000000001ull +typedef struct EFI_FILE_PROTOCOL { + uint64_t Revision; + EFI_STATUS (*Open)(struct EFI_FILE_PROTOCOL *This, struct EFI_FILE_PROTOCOL **NewHandle, + CHAR16 *FileName, uint64_t OpenMode, uint64_t Attributes); + EFI_STATUS (*Close)(struct EFI_FILE_PROTOCOL *This); + void *Delete; + EFI_STATUS (*Read)(struct EFI_FILE_PROTOCOL *This, uint64_t *BufferSize, void *Buffer); + void *Write, *GetPosition, *SetPosition, *GetInfo, *SetInfo, *Flush; + void *OpenEx, *ReadEx, *WriteEx, *FlushEx; +} EFI_FILE_PROTOCOL; +typedef struct EFI_SIMPLE_FILE_SYSTEM_PROTOCOL { + uint64_t Revision; + EFI_STATUS (*OpenVolume)(struct EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *This, EFI_FILE_PROTOCOL **Root); +} EFI_SIMPLE_FILE_SYSTEM_PROTOCOL; +_Static_assert(offsetof(EFI_FILE_PROTOCOL, Read) == 0x20, "File.Read"); + +/* --- Block I/O (UEFI 2.10 section 13.9) --- */ +#define EFI_BLOCK_IO_PROTOCOL_GUID_INIT \ + { 0x964e5b21, 0x6459, 0x11d2, { 0x8e, 0x39, 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b } } +typedef struct { + uint32_t MediaId; + uint8_t RemovableMedia; + uint8_t MediaPresent; + uint8_t LogicalPartition; /* TRUE if LBA 0 is the first block of a partition */ + uint8_t ReadOnly; + uint8_t WriteCaching; + uint32_t BlockSize; /* ReadBlocks BufferSize must be a multiple of this */ + uint32_t IoAlign; /* alignment requirement for any buffer to read or write */ + uint64_t LastBlock; + uint64_t LowestAlignedLba; /* Revision 2 */ + uint32_t LogicalBlocksPerPhysicalBlock; /* Revision 2 */ + uint32_t OptimalTransferLengthGranularity; /* Revision 3 */ +} EFI_BLOCK_IO_MEDIA; +typedef struct EFI_BLOCK_IO_PROTOCOL { + uint64_t Revision; + EFI_BLOCK_IO_MEDIA *Media; + void *Reset; + EFI_STATUS (*ReadBlocks)(struct EFI_BLOCK_IO_PROTOCOL *This, uint32_t MediaId, uint64_t Lba, + uint64_t BufferSize, void *Buffer); + void *WriteBlocks, *FlushBlocks; +} EFI_BLOCK_IO_PROTOCOL; +_Static_assert(offsetof(EFI_BLOCK_IO_MEDIA, BlockSize) == 12, "Media.BlockSize"); +_Static_assert(offsetof(EFI_BLOCK_IO_MEDIA, LastBlock) == 24, "Media.LastBlock"); +_Static_assert(offsetof(EFI_BLOCK_IO_PROTOCOL, ReadBlocks) == 0x18, "BlockIo.ReadBlocks"); + #endif diff --git a/native/boot/efi_main.c b/native/boot/efi_main.c index 2ff768c7..4a1c799e 100644 --- a/native/boot/efi_main.c +++ b/native/boot/efi_main.c @@ -20,6 +20,8 @@ static uint64_t map_buf[MAP_BYTES / 8]; static struct ck_handoff handoff; static EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *conout; +int ck_boot_model_load(EFI_HANDLE image, EFI_SYSTEM_TABLE *st, struct ck_handoff *h); + static void efi_write(const char *s, size_t n) { CHAR16 buf[130]; @@ -96,6 +98,9 @@ EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *st) ck_puts("\n"); ck_report_header("pre_exit"); + /* The yardstick model from the boot disk, while the firmware drivers are + * still up (efi_model.c). Absent map: boot continues without a model. */ + ck_boot_model_load(image, st, h); ck_puts("kernel_impl: c (native/kernel, Lane 18)\n"); vendor_print(st->FirmwareVendor); ck_printf("firmware_revision: 0x%x\n", st->FirmwareRevision); diff --git a/native/boot/efi_model.c b/native/boot/efi_model.c new file mode 100644 index 00000000..d3941382 --- /dev/null +++ b/native/boot/efi_model.c @@ -0,0 +1,224 @@ +/* efi_model.c -- read the yardstick model from the boot disk before + * ExitBootServices, through the firmware's own Block I/O driver (the one that + * just loaded BOOTAA64.EFI), and hand it to the kernel in CHANDOF2 + * (aienos#34 lane 6: the first model ingest path that exists on hardware). + * + * Why the firmware and not our NVMe driver: our C NVMe driver and its SMMU + * confinement have never run on the DGX Spark (GB10_NATIVE_STATUS: NVMe + * unconfirmed), the inference image is the core-only image without the NVMe + * stage, and one attended boot must not gamble. UEFI Block I/O is the path + * the firmware already proved by loading this image. + * + * Flow (UEFI 2.10; edk2 LoadedImage.h, SimpleFileSystem.h, BlockIo.h): + * 1. HandleProtocol(image, LoadedImage) -> DeviceHandle = the boot volume; + * HandleProtocol(DeviceHandle, SimpleFileSystem) -> OpenVolume -> Open + * \EFI\AIENOS\MODEL.MAP read-only. Absent map: "model_map: absent", + * nothing recorded, boot continues (the kernel then has no disk model). + * 2. ck_model_map_check (native/boot/model_map.h): magic, version, sector + * size, extents, exact coverage. Refused -> "model_map: refused (...)". + * 3. LocateHandleBuffer(ByProtocol, BlockIo): among whole disks + * (LogicalPartition == 0, MediaPresent, BlockSize == map sector size) + * read LBA 1 and match "EFI PART" + disk GUID bytes 56..71 with the map. + * 4. AllocatePages(AllocateAnyPages, EfiLoaderData): the kernel never hands + * LoaderData out (mm/mmu.c) and reserves this range explicitly. + * 5. ReadBlocks per extent in <= 8 MiB pieces, BufferSize a multiple of + * BlockSize, buffers page aligned (>= IoAlign for every driver seen). + * 6. Record base, length, declared SHA-256, flags, timing in the handoff. + * The stub does NOT hash: the kernel recomputes SHA-256 over the bytes it + * received (core/infer.c) and refuses to decode on a mismatch, so a wrong LBA, + * a short read or a stale file can never pass as the model. */ +#include "efi.h" +#include "model_map.h" +#include "handoff.h" +#include "../kernel/arch/arch.h" +#include "../kernel/core/ck_internal.h" + +#define READ_CHUNK (8ull << 20) +#define PAGE 4096ull + +static struct ck_model_map map __attribute__((aligned(4096))); +static uint8_t lba1[4096] __attribute__((aligned(4096))); + + +static void hex(char *out, const uint8_t *b, unsigned n) +{ + static const char d[] = "0123456789abcdef"; + for (unsigned i = 0; i < n; i++) { + out[2 * i] = d[b[i] >> 4]; + out[2 * i + 1] = d[b[i] & 15]; + } + out[2 * n] = 0; +} + +static uint64_t ticks_to_us(uint64_t ticks, uint64_t hz) +{ + return hz ? (ticks / hz) * 1000000ull + ((ticks % hz) * 1000000ull) / hz : 0; +} + +static void clear_model(struct ck_handoff *h) +{ + h->model_base = h->model_len = 0; + memset(h->model_sha256, 0, sizeof h->model_sha256); + h->model_flags = h->model_extents = 0; + h->model_read_us = h->model_disk_last_block = 0; + h->model_block_size = 0; +} + +/* Read MODEL.MAP from the volume this image was loaded from. 1 = absent, + * -1 = present but unreadable/malformed (printed), 0 = in `map`. */ +static int read_map(EFI_HANDLE image, EFI_BOOT_SERVICES *bs) +{ + static const EFI_GUID li_guid = EFI_LOADED_IMAGE_PROTOCOL_GUID_INIT; + static const EFI_GUID fs_guid = EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID_INIT; + static CHAR16 path[] = {'\\', 'E', 'F', 'I', '\\', 'A', 'I', 'E', 'N', 'O', 'S', '\\', + 'M', 'O', 'D', 'E', 'L', '.', 'M', 'A', 'P', 0}; + EFI_LOADED_IMAGE_PROTOCOL *li = 0; + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *fs = 0; + EFI_FILE_PROTOCOL *root = 0, *f = 0; + EFI_STATUS s = bs->HandleProtocol(image, &li_guid, (void **)&li); + if (s != EFI_SUCCESS || !li || !li->DeviceHandle) { + ck_printf("model_map: absent (no LoadedImage device, status=0x%llx)\n", (unsigned long long)s); + return 1; + } + s = bs->HandleProtocol(li->DeviceHandle, &fs_guid, (void **)&fs); + if (s != EFI_SUCCESS || !fs) { + ck_printf("model_map: absent (boot volume has no file system, status=0x%llx)\n", + (unsigned long long)s); + return 1; + } + s = fs->OpenVolume(fs, &root); + if (s != EFI_SUCCESS || !root) { + ck_printf("model_map: absent (OpenVolume status=0x%llx)\n", (unsigned long long)s); + return 1; + } + s = root->Open(root, &f, path, EFI_FILE_MODE_READ, 0); + if (s != EFI_SUCCESS || !f) { + ck_puts("model_map: absent (no " CK_MODEL_MAP_PATH " on the boot volume)\n"); + root->Close(root); + return 1; + } + uint64_t n = sizeof map; + memset(&map, 0, sizeof map); + s = f->Read(f, &n, &map); + f->Close(f); + root->Close(root); + if (s != EFI_SUCCESS || n != sizeof map) { + ck_printf("model_map: refused (read status=0x%llx bytes=%llu, want %u)\n", + (unsigned long long)s, (unsigned long long)n, (unsigned)sizeof map); + return -1; + } + return 0; +} + +/* The whole disk whose GPT disk GUID matches the map; 0 if none. */ +static EFI_BLOCK_IO_PROTOCOL *find_disk(EFI_BOOT_SERVICES *bs, uint64_t *seen) +{ + static const EFI_GUID bio_guid = EFI_BLOCK_IO_PROTOCOL_GUID_INIT; + EFI_HANDLE *handles = 0; + uint64_t n = 0; + EFI_BLOCK_IO_PROTOCOL *found = 0; + *seen = 0; + EFI_STATUS s = bs->LocateHandleBuffer(ByProtocol, &bio_guid, 0, &n, &handles); + if (s != EFI_SUCCESS || !handles) + return 0; + *seen = n; + for (uint64_t i = 0; i < n && !found; i++) { + EFI_BLOCK_IO_PROTOCOL *bio = 0; + if (bs->HandleProtocol(handles[i], &bio_guid, (void **)&bio) != EFI_SUCCESS || !bio || !bio->Media) + continue; + const EFI_BLOCK_IO_MEDIA *m = bio->Media; + if (!m->MediaPresent || m->LogicalPartition || m->BlockSize != map.sector_size || + m->BlockSize > sizeof lba1 || m->LastBlock < 2) + continue; + if (bio->ReadBlocks(bio, m->MediaId, 1, m->BlockSize, lba1) != EFI_SUCCESS) + continue; + if (memcmp(lba1, "EFI PART", 8) == 0 && memcmp(lba1 + 56, map.disk_guid, 16) == 0) + found = bio; + } + bs->FreePool(handles); + return found; +} + +/* 0: model loaded and recorded in h; 1: no MODEL.MAP (not an error); + * -1: map present but refused or the read failed (printed, nothing recorded). */ +int ck_boot_model_load(EFI_HANDLE image, EFI_SYSTEM_TABLE *st, struct ck_handoff *h) +{ + EFI_BOOT_SERVICES *bs = st->BootServices; + char gh[33], sh[65]; + clear_model(h); + int rc = read_map(image, bs); + if (rc) + return rc; + const char *why = 0; + if (ck_model_map_check(&map, 0, 0, &why)) { + ck_printf("model_map: refused (%s)\n", why); + return -1; + } + hex(gh, map.disk_guid, 16); + hex(sh, map.sha256, 32); + ck_printf("model_map: ok len=%llu extents=%u sector=%u disk=%s\n", (unsigned long long)map.model_len, + map.n_extents, map.sector_size, gh); + + uint64_t seen = 0; + EFI_BLOCK_IO_PROTOCOL *bio = find_disk(bs, &seen); + if (!bio) { + ck_printf("model_map: refused (disk %s not found among %llu block devices)\n", gh, + (unsigned long long)seen); + return -1; + } + const EFI_BLOCK_IO_MEDIA *m = bio->Media; + if (ck_model_map_check(&map, m->BlockSize, m->LastBlock, &why)) { + ck_printf("model_map: refused (%s)\n", why); + return -1; + } + if (m->IoAlign > PAGE) { + ck_printf("model_map: refused (IoAlign %u > page)\n", m->IoAlign); + return -1; + } + + uint64_t bs_bytes = m->BlockSize; + uint64_t sectors = (map.model_len + bs_bytes - 1) / bs_bytes; + uint64_t pages = (sectors * bs_bytes + PAGE - 1) / PAGE; + uint64_t base = 0; + EFI_STATUS s = bs->AllocatePages(AllocateAnyPages, EfiLoaderData, pages, &base); + if (s != EFI_SUCCESS || !base) { + ck_printf("model_map: refused (AllocatePages %llu pages status=0x%llx)\n", + (unsigned long long)pages, (unsigned long long)s); + return -1; + } + ck_printf("model: reading %llu bytes in %u extents, block_size=%u last_block=%llu -> 0x%llx\n", + (unsigned long long)map.model_len, map.n_extents, m->BlockSize, + (unsigned long long)m->LastBlock, (unsigned long long)base); + + uint64_t t0 = ck_rd(cntpct_el0), off = 0; + for (uint32_t i = 0; i < map.n_extents; i++) { + uint64_t lba = map.ext[i].lba, left = map.ext[i].count; + while (left) { + uint64_t n = left * bs_bytes > READ_CHUNK ? READ_CHUNK / bs_bytes : left; + s = bio->ReadBlocks(bio, m->MediaId, lba, n * bs_bytes, (void *)(uintptr_t)(base + off)); + if (s != EFI_SUCCESS) { + ck_printf("model: ReadBlocks status=0x%llx at lba=%llu count=%llu (extent %u)\n", + (unsigned long long)s, (unsigned long long)lba, (unsigned long long)n, i); + bs->FreePages(base, pages); + return -1; + } + lba += n; + left -= n; + off += n * bs_bytes; + } + } + uint64_t us = ticks_to_us(ck_rd(cntpct_el0) - t0, h->counter_freq_hz); + + h->model_base = base; + h->model_len = map.model_len; + memcpy(h->model_sha256, map.sha256, 32); + h->model_flags = CK_HANDOFF_MODEL_PRESENT | CK_HANDOFF_MODEL_BLOCKIO; + h->model_extents = map.n_extents; + h->model_read_us = us; + h->model_disk_last_block = m->LastBlock; + h->model_block_size = m->BlockSize; + ck_printf("model: base=0x%llx len=%llu extents=%u read_us=%llu declared_sha256=%s\n", + (unsigned long long)base, (unsigned long long)map.model_len, map.n_extents, + (unsigned long long)us, sh); + return 0; +} diff --git a/native/boot/handoff.h b/native/boot/handoff.h index ad08e381..7ccc36c3 100644 --- a/native/boot/handoff.h +++ b/native/boot/handoff.h @@ -1,13 +1,23 @@ /* handoff.h -- what the AIENOS UEFI boot stub passes to the C kernel core * after ExitBootServices. Everything referenced here lives in memory the - * frame allocator never hands out (the loaded image, LoaderData, ACPI). */ + * frame allocator never hands out (the loaded image, LoaderData, ACPI). + * + * CHANDOF2 (2026-10-04, aienos#34 lane 6): CHANDOF1 plus the yardstick + * model's bytes, read by the stub from the boot disk before ExitBootServices + * (native/boot/efi_model.c, map format native/boot/model_map.h). Per the + * contract (docs/BOOT_HANDOFF_CONTRACT.md section 8) a new layout gets a new + * magic; a kernel built for CHANDOF2 refuses CHANDOF1 as "bad magic". */ #ifndef AIENOS_CK_HANDOFF_H #define AIENOS_CK_HANDOFF_H - #include #include -#define CK_HANDOFF_MAGIC 0x31464f444e414843ull /* "CHANDOF1" */ +#define CK_HANDOFF_MAGIC 0x32464f444e414843ull /* "CHANDOF2" */ +#define CK_HANDOFF_MAGIC_V1 0x31464f444e414843ull /* "CHANDOF1": refused */ + +/* model_flags */ +#define CK_HANDOFF_MODEL_PRESENT 1u /* model_base/model_len hold the model */ +#define CK_HANDOFF_MODEL_BLOCKIO 2u /* read through UEFI Block I/O from MODEL.MAP */ struct ck_handoff { uint64_t magic; @@ -26,11 +36,20 @@ struct ck_handoff { uint32_t exit_attempts; /* ExitBootServices calls until success */ uint32_t reserved0; const char *commit; + /* CHANDOF2: the model (EfiLoaderData pages, 4 KiB aligned), or all zero. */ + uint64_t model_base; + uint64_t model_len; /* bytes */ + uint8_t model_sha256[32]; /* declared by MODEL.MAP; the kernel recomputes */ + uint32_t model_flags; /* CK_HANDOFF_MODEL_* */ + uint32_t model_extents; /* extents read */ + uint64_t model_read_us; /* firmware Block I/O time for the whole model */ + uint64_t model_disk_last_block; /* EFI_BLOCK_IO_MEDIA.LastBlock of the disk */ + uint32_t model_block_size; /* EFI_BLOCK_IO_MEDIA.BlockSize of the disk */ + uint32_t reserved1; /* zero */ }; - -/* Layout pins for the frozen CHANDOF1 v1 record (docs/BOOT_HANDOFF_CONTRACT.md +/* Layout pins for the frozen CHANDOF2 record (docs/BOOT_HANDOFF_CONTRACT.md * section 3, LP64): a reorder, resize or new field fails the build. */ -_Static_assert(sizeof(struct ck_handoff) == 112, "ck_handoff size"); +_Static_assert(sizeof(struct ck_handoff) == 192, "ck_handoff size"); _Static_assert(offsetof(struct ck_handoff, magic) == 0, "ck_handoff.magic offset"); _Static_assert(offsetof(struct ck_handoff, firmware_el) == 8, "ck_handoff.firmware_el offset"); _Static_assert(offsetof(struct ck_handoff, desc_version) == 12, "ck_handoff.desc_version offset"); @@ -47,6 +66,15 @@ _Static_assert(offsetof(struct ck_handoff, uefi_entry_ticks) == 88, "ck_handoff. _Static_assert(offsetof(struct ck_handoff, exit_attempts) == 96, "ck_handoff.exit_attempts offset"); _Static_assert(offsetof(struct ck_handoff, reserved0) == 100, "ck_handoff.reserved0 offset"); _Static_assert(offsetof(struct ck_handoff, commit) == 104, "ck_handoff.commit offset"); +_Static_assert(offsetof(struct ck_handoff, model_base) == 112, "ck_handoff.model_base offset"); +_Static_assert(offsetof(struct ck_handoff, model_len) == 120, "ck_handoff.model_len offset"); +_Static_assert(offsetof(struct ck_handoff, model_sha256) == 128, "ck_handoff.model_sha256 offset"); +_Static_assert(offsetof(struct ck_handoff, model_flags) == 160, "ck_handoff.model_flags offset"); +_Static_assert(offsetof(struct ck_handoff, model_extents) == 164, "ck_handoff.model_extents offset"); +_Static_assert(offsetof(struct ck_handoff, model_read_us) == 168, "ck_handoff.model_read_us offset"); +_Static_assert(offsetof(struct ck_handoff, model_disk_last_block) == 176, "ck_handoff.model_disk_last_block offset"); +_Static_assert(offsetof(struct ck_handoff, model_block_size) == 184, "ck_handoff.model_block_size offset"); +_Static_assert(offsetof(struct ck_handoff, reserved1) == 188, "ck_handoff.reserved1 offset"); /* Kernel core entry, still at the firmware EL with firmware translation. */ __attribute__((noreturn)) void ck_kernel_entry(struct ck_handoff *h); diff --git a/native/boot/model_map.h b/native/boot/model_map.h new file mode 100644 index 00000000..740a78ae --- /dev/null +++ b/native/boot/model_map.h @@ -0,0 +1,116 @@ +/* model_map.h -- MODEL.MAP: where the yardstick model's bytes live on the + * boot disk, so the UEFI boot stub can read them through the firmware's own + * Block I/O driver before ExitBootServices (aienos#34 lane 6, hardware model + * ingest). Shared by the stub (native/boot/efi_model.c), the kernel's + * handoff checks and the hosted map tool (native/kernel/tools/ck_model_map.c). + * + * The file is exactly 4096 bytes, little endian, at \EFI\AIENOS\MODEL.MAP on + * the boot volume (the ESP the stub was loaded from). It names the whole disk + * by its GPT disk GUID (header LBA 1, bytes 56..71, raw on-disk order) and + * lists the model's extents as absolute LBAs of that disk, in FILE order + * (extent 0 holds byte 0 of the model). The model bytes themselves stay where + * they are (an ext4 file, or a raw range in a QEMU image); only this map is + * staged. Integrity: the declared SHA-256 of the model is carried to the kernel + * in the handoff and the kernel recomputes it over the bytes it received; any + * wrong LBA, short read or stale file shows up as a hash mismatch and the + * kernel refuses to decode (never a silent wrong model). + * + * The map has no checksum of its own: every field that could steer a read + * wrong is covered by the SHA-256 check, and a malformed map is refused by + * ck_model_map_check below (the same function in the stub and the tool). */ +#ifndef AIENOS_CK_MODEL_MAP_H +#define AIENOS_CK_MODEL_MAP_H +#include +#include + +#define CK_MODEL_MAP_MAGIC "AIENMDL1" +#define CK_MODEL_MAP_VERSION 1u +#define CK_MODEL_MAP_BYTES 4096u +#define CK_MODEL_MAP_MAX_EXTENTS 128u +#define CK_MODEL_MAP_PATH "\\EFI\\AIENOS\\MODEL.MAP" + +struct ck_model_extent { + uint64_t lba; /* first LBA of this extent on the whole disk */ + uint64_t count; /* sectors in this extent (> 0) */ +}; + +struct ck_model_map { + uint8_t magic[8]; /* "AIENMDL1" */ + uint32_t version; /* 1 */ + uint32_t sector_size; /* 512 or 4096; must equal the disk's BlockSize */ + uint8_t disk_guid[16]; /* GPT header bytes 56..71 of LBA 1, raw */ + uint64_t model_len; /* bytes of the model file */ + uint8_t sha256[32]; /* SHA-256 of the model file */ + uint32_t n_extents; /* 1..CK_MODEL_MAP_MAX_EXTENTS */ + uint32_t flags; /* 0 */ + struct ck_model_extent ext[CK_MODEL_MAP_MAX_EXTENTS]; + uint8_t pad[CK_MODEL_MAP_BYTES - 80u - 16u * CK_MODEL_MAP_MAX_EXTENTS]; +}; +_Static_assert(sizeof(struct ck_model_map) == CK_MODEL_MAP_BYTES, "ck_model_map size"); +_Static_assert(offsetof(struct ck_model_map, ext) == 80, "ck_model_map.ext offset"); + +/* Structural check, no I/O. block_size 0 / last_block 0 skip the disk + * comparisons (the host tool before it knows the disk). 0 = well formed; -1 + * with *why set otherwise. */ +static inline int ck_model_map_check(const struct ck_model_map *m, uint32_t block_size, + uint64_t last_block, const char **why) +{ + static const uint8_t magic[8] = CK_MODEL_MAP_MAGIC; + for (unsigned i = 0; i < 8; i++) + if (m->magic[i] != magic[i]) { + *why = "bad magic"; + return -1; + } + if (m->version != CK_MODEL_MAP_VERSION) { + *why = "unsupported version"; + return -1; + } + if (m->sector_size != 512u && m->sector_size != 4096u) { + *why = "sector size not 512 or 4096"; + return -1; + } + if (block_size && m->sector_size != block_size) { + *why = "sector size differs from the disk block size"; + return -1; + } + if (m->flags != 0) { + *why = "unknown flags"; + return -1; + } + if (m->model_len == 0) { + *why = "zero model length"; + return -1; + } + if (m->n_extents == 0 || m->n_extents > CK_MODEL_MAP_MAX_EXTENTS) { + *why = "extent count out of range"; + return -1; + } + uint64_t sectors = 0; + for (uint32_t i = 0; i < m->n_extents; i++) { + uint64_t lba = m->ext[i].lba, n = m->ext[i].count; + if (n == 0 || lba < 2 /* MBR + GPT header */) { + *why = "extent empty or inside the GPT header"; + return -1; + } + if (lba + n < lba || (last_block && lba + n - 1 > last_block)) { + *why = "extent past the end of the disk"; + return -1; + } + if (sectors + n < sectors) { + *why = "extent total overflows"; + return -1; + } + sectors += n; + } + /* Exact coverage: the extents hold the whole model and less than one + * extra sector (the last sector may be partial). */ + uint64_t need = (m->model_len + m->sector_size - 1) / m->sector_size; + if (sectors != need) { + *why = "extents do not cover exactly the model length"; + return -1; + } + *why = 0; + return 0; +} + +#endif diff --git a/native/kernel/.crumb b/native/kernel/.crumb index 9275f666..a15222f3 100644 --- a/native/kernel/.crumb +++ b/native/kernel/.crumb @@ -57,8 +57,8 @@ "purpose": "Directory native/kernel/artifact. Purpose not yet described by a human." }, { - "digest": "9eeeb7fd4d3f985de10e008c8f80ed12c14cb4d4e19822c60b2960670c723fc5", - "last_commit": "a863d5c", + "digest": "76e09442c61ce7502463145cf8b9540f435ee8fba3cd06fa9f3f09a7e8d6f72d", + "last_commit": "39e611e", "name": "core", "purpose": "Directory native/kernel/core. Purpose not yet described by a human." }, @@ -75,8 +75,8 @@ "purpose": "Directory native/kernel/include. Purpose not yet described by a human." }, { - "digest": "cba1518c92fbce170777d62b2656e6d4609353c3e6a72967500305d35ef1b92f", - "last_commit": "c3878bb", + "digest": "ca0e875c3967ed75fa04e83792468a1ca61755b47c7de27b8e8981e687a341f8", + "last_commit": "39e611e", "name": "mm", "purpose": "Directory native/kernel/mm. Purpose not yet described by a human." }, @@ -87,27 +87,27 @@ "purpose": "Directory native/kernel/svc. Purpose not yet described by a human." }, { - "digest": "e2b639bfcd6cd597a2ab7a6eec99f7654c43006093ede303ad74509dbc6e6f5f", - "last_commit": "4cfc9d3", + "digest": "306b7082c04bacc3a3315c88685b5dd729b25eb31985db569d05541ee0a5204a", + "last_commit": "39e611e", "name": "tests", "purpose": "Directory native/kernel/tests. Purpose not yet described by a human." }, { - "digest": "41b629dd4561303b5383e23b3d5f0348c89d786032fb3076aea03a5da686e0f6", - "last_commit": "31ed9f8", + "digest": "4b271f165e876c5680edfca04f66d3e8399efa5a0aee47ebe59c585cab574d8d", + "last_commit": "39e611e", "name": "tools", "purpose": "Directory native/kernel/tools. Purpose not yet described by a human." } ], - "children_root": "sha256:f6f120f9f913181d64951b5f2eb0487d8b7d7601bec19217410f73a1b878adf0", - "compiled_at": "2026-10-04T13:47:18Z", + "children_root": "sha256:d78a906505b6357d2fd58a337390dd1b4c58889b31aed5b29e33ed627b81eecc", + "compiled_at": "2026-10-04T15:01:15Z", "compiler": "crumb-compile/1", - "digest": "sha256:541e7184c7281b549aac9b8dba20fc8c6d648e6135638fc10e00da0ea8c30d33", + "digest": "sha256:bfdf0a6a28753c18c7c522796188040c7dc94758b3fd5b7a91b221136670f574", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 130, - "generated_at_commit": "a863d5c1f5bd89c88c5f6671eecfd27b599ee512", - "source_tree": "sha256:d9d6f511f6706f6e21343186dd3eb1e1113d75fae3da641378b54d992a9c625b" + "files": 131, + "generated_at_commit": "39e611ed040126791acdb667dbbc288a3757858a", + "source_tree": "sha256:f6569a85ab6a51dbc40e53e42fb87e08c4200ba777956955f46e41ac174bc870" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/Makefile b/native/kernel/Makefile index 61860736..51bfc231 100644 --- a/native/kernel/Makefile +++ b/native/kernel/Makefile @@ -358,7 +358,7 @@ KCFLAGS := -std=gnu11 -O2 -Wall -Wextra -Werror -ffreestanding -nostdlib -fno-bu KLDFLAGS := -nostdlib -pie --no-dynamic-linker -z norelro -z noexecstack -z max-page-size=4096 --no-warn-rwx-segments \ -T $(BOOT)/image.ld -CORE_C := $(BOOT)/efi_main.c \ +CORE_C := $(BOOT)/efi_main.c $(BOOT)/efi_model.c \ $(KDIR)/arch/exception.c $(KDIR)/arch/gic.c $(KDIR)/arch/timer.c \ $(KDIR)/core/acpi.c $(KDIR)/core/console.c $(KDIR)/core/fmt.c \ $(KDIR)/core/kmain.c $(KDIR)/core/handoff_check.c $(KDIR)/core/libc_min.c $(KDIR)/core/report.c \ @@ -890,6 +890,14 @@ $(GPT_IMG_TOOL): $(GPT_IMG_SRCS) $(KDIR)/dev/disk_part.h $(KDIR)/tools/gpt_write $(HOSTCC) -std=gnu11 -O2 -Wall -Wextra -Werror -I$(KDIR)/dev -I$(KDIR)/tools -I$(NATIVE)/disk -o $@ $(GPT_IMG_SRCS) gpt-image: $(GPT_IMG_TOOL) +# MODEL.MAP tool (model ingest gate + the attended-boot staging; hosted, never +# part of an image). SHA-256 is the kernel's own (argus). +MODEL_MAP_TOOL := $(OUT)/host/ck_model_map +$(MODEL_MAP_TOOL): $(KDIR)/tools/ck_model_map.c $(NATIVE)/argus/sha256.c $(BOOT)/model_map.h $(NATIVE)/argus/sha256.h + @mkdir -p $(dir $@) + $(HOSTCC) -std=gnu11 -O2 -Wall -Wextra -Werror -I$(BOOT) -I$(NATIVE)/argus -o $@ $(KDIR)/tools/ck_model_map.c $(NATIVE)/argus/sha256.c +model-map: $(MODEL_MAP_TOOL) + # Owner provisioning generator (hosted; never part of an image) and the # generated header for the hardware staging image. OWNER_GEN := $(OUT)/host/ck_owner_gen diff --git a/native/kernel/core/.crumb b/native/kernel/core/.crumb index 9284aee2..d1cb7f64 100644 --- a/native/kernel/core/.crumb +++ b/native/kernel/core/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-04T13:47:18Z", + "compiled_at": "2026-10-04T15:01:15Z", "compiler": "crumb-compile/1", - "digest": "sha256:9eeeb7fd4d3f985de10e008c8f80ed12c14cb4d4e19822c60b2960670c723fc5", + "digest": "sha256:76e09442c61ce7502463145cf8b9540f435ee8fba3cd06fa9f3f09a7e8d6f72d", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 25, - "generated_at_commit": "a863d5c1f5bd89c88c5f6671eecfd27b599ee512", - "source_tree": "sha256:d843a3f89a17412e74807fb50c62b838f12eb0dc931e28cf491f24361de0091e" + "generated_at_commit": "39e611ed040126791acdb667dbbc288a3757858a", + "source_tree": "sha256:0b49a00bde4e84503ce53a949491eb90e781b5a0f7604a4b59ea30495f4ff267" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/core/ck_internal.h b/native/kernel/core/ck_internal.h index 333ec572..eb5500d4 100644 --- a/native/kernel/core/ck_internal.h +++ b/native/kernel/core/ck_internal.h @@ -49,6 +49,7 @@ struct ck_mm_report { /* EL2/firmware phase: frames from the map, our tables, stack, heap, DMA pool. * Returns the stack top for the EL1 entry. */ uint64_t ck_mm_build(const struct ck_handoff *h); +const struct ck_handoff *ck_handoff_get(void); /* the record the stub passed (kmain.c) */ /* EL1 phase: heap ready after the MMU is on. */ void ck_mm_el1_ready(void); const struct ck_mm_report *ck_mm_report(void); diff --git a/native/kernel/core/handoff_check.c b/native/kernel/core/handoff_check.c index dddd2b5c..9bcdde3b 100644 --- a/native/kernel/core/handoff_check.c +++ b/native/kernel/core/handoff_check.c @@ -1,6 +1,7 @@ /* handoff_check.c -- refuse a malformed loader -> kernel handoff record * before the kernel trusts any field of it (docs/BOOT_HANDOFF_CONTRACT.md - * section 6). Checked here: NULL record, magic, reserved0, descriptor + * section 6). Checked here: NULL record, magic (CHANDOF2 only; CHANDOF1 is + * "bad magic"), reserved0, reserved1, the CHANDOF2 model fields, descriptor * stride and version, memory map size. The other PROPOSED refusals of the * contract (image range, overlaps, rsdp, firmware_el, CHANDOF version * line) are not part of this cut. */ @@ -43,6 +44,34 @@ int ck_handoff_check(const struct ck_handoff *h, const char **why) return -1; } #endif + if (h->reserved1 != 0) { + *why = "reserved1 field nonzero"; + return -1; + } + if (h->model_flags & ~(CK_HANDOFF_MODEL_PRESENT | CK_HANDOFF_MODEL_BLOCKIO)) + return refuse(why, "bad model flags", (unsigned long long)h->model_flags); + if (h->model_flags & CK_HANDOFF_MODEL_PRESENT) { + if (!h->model_base || !h->model_len) + return refuse(why, "bad model range", (unsigned long long)h->model_len); + if (h->model_base % 4096) + return refuse(why, "model base unaligned", (unsigned long long)h->model_base); + if (h->model_base + h->model_len < h->model_base) + return refuse(why, "model range overflow", (unsigned long long)h->model_len); + if (h->model_block_size != 512 && h->model_block_size != 4096) + return refuse(why, "bad model block size", (unsigned long long)h->model_block_size); + if (h->model_extents == 0) + return refuse(why, "bad model extents", 0); + } else { + int zero = h->model_base == 0 && h->model_len == 0 && h->model_flags == 0 && + h->model_extents == 0 && h->model_read_us == 0 && + h->model_disk_last_block == 0 && h->model_block_size == 0; + for (unsigned i = 0; zero && i < 32; i++) + zero = h->model_sha256[i] == 0; + if (!zero) { + *why = "model fields without model"; + return -1; + } + } if (h->desc_size < CK_HANDOFF_DESC_MIN || h->desc_size % 8 != 0) return refuse(why, "bad descriptor size", (unsigned long long)h->desc_size); if (h->desc_version != CK_HANDOFF_DESC_VERSION) diff --git a/native/kernel/core/infer.c b/native/kernel/core/infer.c index fa9e7c82..2809ab44 100644 --- a/native/kernel/core/infer.c +++ b/native/kernel/core/infer.c @@ -6,7 +6,10 @@ * Only compiled into the probe build: Makefile CK_INFER_LIB=<.a> adds * -DCK_INFER_PROBE=1; the default image carries none of this. * - * Ingest path (the smallest that works today): QEMU fw_cfg. The C kernel has + * Ingest paths: (1) the boot disk, read by the UEFI stub through the + * firmware Block I/O driver before ExitBootServices and handed over in + * CHANDOF2 (native/boot/efi_model.c; the hardware path, lane 6); (2) QEMU + * fw_cfg, TEST-ONLY, when the stub found no MODEL.MAP. The C kernel has * no virtio-blk driver (only NVMe store, virtio-net) and the C boot stub reads * no files, but fw_cfg is already used by the TEST-ONLY artifact source * (artifact_loader.c). The traditional byte-at-a-time data register would need @@ -206,9 +209,18 @@ static void hex(char *out, const uint8_t *b, unsigned n) void ck_infer_run(void) { const char *why = 0; - uint64_t base = fwcfg_from_dsdt(&why); + /* Source 1, the boot disk: the UEFI stub read the model through the + * firmware's Block I/O driver before ExitBootServices and recorded it in + * CHANDOF2 (native/boot/efi_model.c, native/boot/model_map.h). The bytes + * live in EfiLoaderData the frame allocator never hands out (mm/mmu.c + * reserves the range). This is the path that exists on hardware. + * Source 2, QEMU fw_cfg: TEST-ONLY, below, when the stub found no map. */ + const struct ck_handoff *h = ck_handoff_get(); + int from_disk = h && (h->model_flags & CK_HANDOFF_MODEL_PRESENT); + uint64_t base = from_disk ? 0 : fwcfg_from_dsdt(&why); uint16_t sel = 0; uint32_t size = 0; + if (!from_disk) { if (base && !ck_mm_mmio_try_map(base, 0x18)) { why = "fw_cfg window not mappable"; base = 0; @@ -237,36 +249,70 @@ void ck_infer_run(void) ck_printf("infer: fw_cfg base=0x%llx dma=yes file=%s size=%u\n", (unsigned long long)base, MODEL_FILE, size); - uint64_t frames_before = ck_mm_free_frames(); - uint64_t mpages = ((uint64_t)size + PAGE - 1) / PAGE, mpa = 0, hpa = 0; - if (ck_mm_frames_alloc(mpages, &mpa) || ck_mm_frames_alloc(HEAP_BYTES / PAGE, &hpa)) { - ck_printf("infer: ingest FAIL (no frames: need %llu + %llu pages, %llu free)\nAIENOS_CK_INFER: FAIL\n", - (unsigned long long)mpages, (unsigned long long)(HEAP_BYTES / PAGE), - (unsigned long long)ck_mm_free_frames()); - return; + } + uint64_t msize = from_disk ? h->model_len : (uint64_t)size; + uint64_t mpa = from_disk ? h->model_base : 0, hpa = 0, mpages = 0; + if (from_disk) { + ck_puts("infer_source_mode: boot-disk model (MODEL.MAP read by the UEFI stub through the firmware's Block I/O before ExitBootServices); the path that exists on hardware\n"); + ck_printf("infer: disk base=0x%llx size=%llu extents=%u read_us=%llu block_size=%u\n", + (unsigned long long)mpa, (unsigned long long)msize, h->model_extents, + (unsigned long long)h->model_read_us, h->model_block_size); + if (!ck_mm_mapped(mpa, msize)) { + ck_puts("infer: ingest FAIL (disk model range not mapped)\nAIENOS_CK_INFER: FAIL\n"); + return; + } } - uint64_t t0 = ck_time_us(); - int rc = 0; - for (uint64_t off = 0; off < size && !rc; off += DMA_CHUNK) { - uint64_t n = size - off < DMA_CHUNK ? size - off : DMA_CHUNK; - rc = fw_dma_read(off == 0 ? (int)sel : -1, mpa + off, (uint32_t)n); + uint64_t frames_before = ck_mm_free_frames(); + if (!from_disk) { + mpages = (msize + PAGE - 1) / PAGE; + if (ck_mm_frames_alloc(mpages, &mpa)) { + ck_printf("infer: ingest FAIL (no frames: need %llu + %llu pages, %llu free)\nAIENOS_CK_INFER: FAIL\n", + (unsigned long long)mpages, (unsigned long long)(HEAP_BYTES / PAGE), + (unsigned long long)ck_mm_free_frames()); + return; + } } - uint64_t t1 = ck_time_us(); - if (rc) { - ck_printf("infer: ingest FAIL (fw_cfg DMA rc=%d)\nAIENOS_CK_INFER: FAIL\n", rc); + if (ck_mm_frames_alloc(HEAP_BYTES / PAGE, &hpa)) { + if (mpages) + ck_mm_frames_free(mpa, mpages); + ck_printf("infer: ingest FAIL (no frames for the %llu-page heap, %llu free)\nAIENOS_CK_INFER: FAIL\n", + (unsigned long long)(HEAP_BYTES / PAGE), (unsigned long long)ck_mm_free_frames()); return; } - ck_printf("infer: ingest bytes=%u dma_us=%llu\n", size, (unsigned long long)(t1 - t0)); + if (!from_disk) { + uint64_t t0 = ck_time_us(); + int rc = 0; + for (uint64_t off = 0; off < msize && !rc; off += DMA_CHUNK) { + uint64_t n = msize - off < DMA_CHUNK ? msize - off : DMA_CHUNK; + rc = fw_dma_read(off == 0 ? (int)sel : -1, mpa + off, (uint32_t)n); + } + if (rc) { + ck_printf("infer: ingest FAIL (fw_cfg DMA rc=%d)\nAIENOS_CK_INFER: FAIL\n", rc); + return; + } + ck_printf("infer: ingest bytes=%llu dma_us=%llu\n", (unsigned long long)msize, + (unsigned long long)(ck_time_us() - t0)); + } + + uint64_t t1 = ck_time_us(); sha256_ctx ctx; uint8_t dg[SHA256_DIGEST_SIZE]; char dh[2 * SHA256_DIGEST_SIZE + 1]; sha256_init(&ctx); - sha256_update(&ctx, (const uint8_t *)(uintptr_t)mpa, size); + sha256_update(&ctx, (const uint8_t *)(uintptr_t)mpa, msize); sha256_final(&ctx, dg); hex(dh, dg, SHA256_DIGEST_SIZE); ck_printf("infer: sha256=%s sha_us=%llu\n", dh, (unsigned long long)(ck_time_us() - t1)); + if (from_disk && memcmp(dg, h->model_sha256, SHA256_DIGEST_SIZE) != 0) { + /* The bytes the firmware read are not the declared model: a wrong + * LBA, a short read or a stale file. Refuse to decode. */ + hex(dh, h->model_sha256, SHA256_DIGEST_SIZE); + ck_printf("infer: sha256 mismatch declared=%s\nAIENOS_CK_INFER: FAIL\n", dh); + ck_mm_frames_free(hpa, HEAP_BYTES / PAGE); + return; + } /* FP/SIMD on, every exception masked for the Rust unit (see core/fpu.c). * The FP registers are left dirty afterwards (nothing else in the kernel @@ -281,7 +327,7 @@ void ck_infer_run(void) uint64_t daif = ck_rd(daif); __asm__ volatile("msr daifset, #0xf" ::: "memory"); uint64_t t2 = ck_time_us(); - int32_t prc = aienos_infer_run((const uint8_t *)(uintptr_t)mpa, size, &res); + int32_t prc = aienos_infer_run((const uint8_t *)(uintptr_t)mpa, msize, &res); uint64_t t3 = ck_time_us(); ck_wr(daif, daif); const uint32_t *out = res.words; @@ -315,10 +361,11 @@ void ck_infer_run(void) ok = ok && res.tokens[i] == expect_gen[i]; /* Unload: the Rust unit kept nothing (its objects died at return); forget - * its heap region, then return every frame of the model and the heap. The - * free-frame count must come back to what it was before the ingest. */ + * its heap region, then return every frame of the heap (and of the model + * when it came over fw_cfg; the disk model stays in LoaderData, never a + * frame). The free-frame count must come back to what it was before. */ aienos_infer_heap_init(0, 0); - int f1 = ck_mm_frames_free(mpa, mpages), f2 = ck_mm_frames_free(hpa, HEAP_BYTES / PAGE); + int f1 = mpages ? ck_mm_frames_free(mpa, mpages) : 0, f2 = ck_mm_frames_free(hpa, HEAP_BYTES / PAGE); uint64_t frames_after = ck_mm_free_frames(); struct ck_mm_usage mu; ck_mm_usage(&mu); diff --git a/native/kernel/core/kmain.c b/native/kernel/core/kmain.c index 7382ac0d..14e31978 100644 --- a/native/kernel/core/kmain.c +++ b/native/kernel/core/kmain.c @@ -16,6 +16,7 @@ #define TTBR_BADDR_MASK 0x0000fffffffffffeull static struct ck_handoff *hand; +const struct ck_handoff *ck_handoff_get(void) { return hand; } const void *ck_acpi_find(const char sig[4]) { diff --git a/native/kernel/mm/.crumb b/native/kernel/mm/.crumb index bcfb2d24..da1c926f 100644 --- a/native/kernel/mm/.crumb +++ b/native/kernel/mm/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-04T13:47:18Z", + "compiled_at": "2026-10-04T15:01:15Z", "compiler": "crumb-compile/1", - "digest": "sha256:cba1518c92fbce170777d62b2656e6d4609353c3e6a72967500305d35ef1b92f", + "digest": "sha256:ca0e875c3967ed75fa04e83792468a1ca61755b47c7de27b8e8981e687a341f8", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 7, - "generated_at_commit": "a863d5c1f5bd89c88c5f6671eecfd27b599ee512", - "source_tree": "sha256:cb6a052401399c17ab68de161a350b855dda7c28267580c478ec312000602754" + "generated_at_commit": "39e611ed040126791acdb667dbbc288a3757858a", + "source_tree": "sha256:1258ccfff89117d426b5d97260118e23c096f5454c319658f15f753df1970f0c" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/mm/mmu.c b/native/kernel/mm/mmu.c index f968bff9..805e47f1 100644 --- a/native/kernel/mm/mmu.c +++ b/native/kernel/mm/mmu.c @@ -118,6 +118,11 @@ uint64_t ck_mm_build(const struct ck_handoff *h) ck_frames_reserve(&frames, h->image_base, h->image_end); ck_frames_reserve(&frames, (uint64_t)(uintptr_t)h, (uint64_t)(uintptr_t)h + sizeof *h); ck_frames_reserve(&frames, h->memory_map, h->memory_map + h->map_size); + /* CHANDOF2: the model the stub read from the boot disk (EfiLoaderData, + * never handed out anyway); whole pages, explicit like the image. */ + if (h->model_flags & CK_HANDOFF_MODEL_PRESENT) + ck_frames_reserve(&frames, h->model_base, + (h->model_base + h->model_len + CK_PAGE - 1) & ~(uint64_t)(CK_PAGE - 1)); /* ACPI: the RSDP, the XSDT/RSDT and every table the root lists, whole * pages, before the first allocation. UEFI keeps them out of * EfiConventionalMemory already; this holds even if a firmware does not. */ diff --git a/native/kernel/tests/.crumb b/native/kernel/tests/.crumb index f76d2ad1..25d121fc 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-04T13:47:18Z", + "compiled_at": "2026-10-04T15:01:15Z", "compiler": "crumb-compile/1", - "digest": "sha256:e2b639bfcd6cd597a2ab7a6eec99f7654c43006093ede303ad74509dbc6e6f5f", + "digest": "sha256:306b7082c04bacc3a3315c88685b5dd729b25eb31985db569d05541ee0a5204a", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 21, - "generated_at_commit": "a863d5c1f5bd89c88c5f6671eecfd27b599ee512", - "source_tree": "sha256:977d1c5b3f7123656eb2c181e383eeb508aa07bdde830a5cefdc96a9e6edf096" + "generated_at_commit": "39e611ed040126791acdb667dbbc288a3757858a", + "source_tree": "sha256:3ac6b3c3391f6ebe6bfb0549ae6dec2e6bfd810f0ed3b3d5819f9c80af98af29" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/tests/test_handoff.c b/native/kernel/tests/test_handoff.c index b3c271c5..9150e371 100755 --- a/native/kernel/tests/test_handoff.c +++ b/native/kernel/tests/test_handoff.c @@ -77,12 +77,12 @@ int main(void) /* 1. NULL record */ expect(0, "handoff: null record"); - /* 2. bad magic: one bit off; CHANDOF2 (refused as bad magic in this cut) */ + /* 2. bad magic: one bit off; CHANDOF1 (the previous layout) and 0 */ h = good(); h.magic ^= 1; expect(&h, "handoff: bad magic"); h = good(); - h.magic = 0x32464f444e414843ull; + h.magic = CK_HANDOFF_MAGIC_V1; expect(&h, "handoff: bad magic"); h = good(); h.magic = 0; @@ -132,6 +132,56 @@ int main(void) h.map_size = 65544; expect(&h, "handoff: bad map size 65544"); + /* 7. CHANDOF2 model fields (docs/BOOT_HANDOFF_CONTRACT.md 3.2): reserved1, + * unknown flags, fields set without the present flag, and the range/ + * geometry checks on a well-formed disk model (the Spark numbers). */ + h = good(); + h.reserved1 = 1; + expect(&h, "handoff: reserved1 field nonzero"); + h = good(); + h.model_flags = 4; + expect(&h, "handoff: bad model flags 4"); + h = good(); + h.model_len = 100; + expect(&h, "handoff: model fields without model"); + h = good(); + h.model_sha256[31] = 1; + expect(&h, "handoff: model fields without model"); + h = good(); + h.model_flags = CK_HANDOFF_MODEL_BLOCKIO; + expect(&h, "handoff: model fields without model"); + struct ck_handoff m = good(); + m.model_flags = CK_HANDOFF_MODEL_PRESENT | CK_HANDOFF_MODEL_BLOCKIO; + m.model_base = 0x140000000ull; + m.model_len = 807694368ull; + m.model_extents = 24; + m.model_block_size = 512; + m.model_disk_last_block = 8001573551ull; + m.model_read_us = 1234567; + m.model_sha256[0] = 0x3f; + expect(&m, ""); + h = m; + h.model_base = 0; + expect(&h, "handoff: bad model range 807694368"); + h = m; + h.model_len = 0; + expect(&h, "handoff: bad model range 0"); + h = m; + h.model_base = 0x140000800ull; + expect(&h, "handoff: model base unaligned 5368711168"); + h = m; + h.model_len = ~0ull; + expect(&h, "handoff: model range overflow 18446744073709551615"); + h = m; + h.model_block_size = 1024; + expect(&h, "handoff: bad model block size 1024"); + h = m; + h.model_extents = 0; + expect(&h, "handoff: bad model extents 0"); + h = m; + h.model_flags = CK_HANDOFF_MODEL_PRESENT; + expect(&h, ""); + /* Check order: the first failing field is reported. */ h = good(); h.magic = 0; diff --git a/native/kernel/tools/.crumb b/native/kernel/tools/.crumb index 915b3d7a..296ce144 100644 --- a/native/kernel/tools/.crumb +++ b/native/kernel/tools/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-04T13:47:18Z", + "compiled_at": "2026-10-04T15:01:15Z", "compiler": "crumb-compile/1", - "digest": "sha256:41b629dd4561303b5383e23b3d5f0348c89d786032fb3076aea03a5da686e0f6", + "digest": "sha256:4b271f165e876c5680edfca04f66d3e8399efa5a0aee47ebe59c585cab574d8d", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 8, - "generated_at_commit": "a863d5c1f5bd89c88c5f6671eecfd27b599ee512", - "source_tree": "sha256:f26b37b43a5b0c2834fde9ed937f754ab8af0e0c7afba58aa7156f40e700eb22" + "files": 9, + "generated_at_commit": "39e611ed040126791acdb667dbbc288a3757858a", + "source_tree": "sha256:992a9662f5f141867fb59e98c6ec0474fbb61cf803fb9164c952711a894155ad" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/tools/ck_gpt_image.c b/native/kernel/tools/ck_gpt_image.c index 098e535f..0180c42d 100644 --- a/native/kernel/tools/ck_gpt_image.c +++ b/native/kernel/tools/ck_gpt_image.c @@ -12,6 +12,8 @@ * aienos-outside sentinel-a, AIENOS [9, M+1): ends past the disk * aienos-overlap sentinel-a [1,9), AIENOS [5,M-7), sentinel-b * no-gpt sentinel fills only: no protective MBR, no GPT + * esp-model ESP_MIB MODEL_FILE ESP + model in 3 out-of-order + * extents (see esp_model below; model ingest gate) * CORRUPTION: bad-primary-crc bad-backup-crc bad-primary-entries * bad-backup-entries no-pmbr * Prints one line: "gpt_image bs=B blocks=N aienos_first_lba=F @@ -21,7 +23,10 @@ * Runs the kernel's own parser (dev/disk_part.c) read-only; prints * "aienos first_lba=F last_lba=L blocks=K" (exit 0) or * "refused: rc=N" (exit 1). */ +#define _GNU_SOURCE #include +#include +#include #include #include #include "disk_file.h" @@ -34,15 +39,81 @@ static int usage(void) return 2; } +/* esp-model (model ingest gate, scripts/qemu_ck_infer_test.sh --disk): + * ck_gpt_image create IMG BS MIB esp-model ESP_MIB MODEL_FILE + * p0 = EFI System Partition [1, 1+ESP_MIB) MiB, left zero (the script formats + * it with mkfs.vfat --offset and fills it with mtools); p1 = Linux type + * [1+ESP_MIB, MIB-1) MiB holding MODEL_FILE in THREE extents written OUT OF + * FILE ORDER with 1 MiB gaps (disk order C, A, B for file thirds A, B, C), so a + * reader that ignores the map order or the gaps cannot produce the right + * bytes. Prints: "gpt_image bs=B blocks=N esp_first_lba=F esp_last_lba=L + * model_len=M model_extents=LBA:COUNT,LBA:COUNT,LBA:COUNT" (file order). */ +static int esp_model(int argc, char **argv, uint32_t bs, uint64_t blocks, uint64_t per, unsigned flags) +{ + if (argc != 8) return usage(); + uint64_t esp_mib = strtoull(argv[6], NULL, 10); + const char *mpath = argv[7]; + uint64_t mib = blocks / per; + if (esp_mib < 16 || esp_mib + 4 >= mib) return usage(); + FILE *mf = fopen(mpath, "rb"); + if (!mf) { fprintf(stderr, "cannot open %s\n", mpath); return 1; } + fseeko(mf, 0, SEEK_END); + uint64_t mlen = (uint64_t)ftello(mf); + fseeko(mf, 0, SEEK_SET); + uint64_t sectors = (mlen + bs - 1) / bs, gap = (1u << 20) / bs; + uint64_t a = sectors / 3, b = sectors / 3, c = sectors - a - b; + uint64_t p1_first = (1 + esp_mib) * per, p1_last = (mib - 1u) * per - 1u; + if (p1_first + 3 * gap + sectors > p1_last + 1) { + fprintf(stderr, "image too small for the model: need %llu more MiB\n", + (unsigned long long)((p1_first + 3 * gap + sectors - p1_last) / per + 1)); + fclose(mf); + return 1; + } + /* disk order: C, A, B */ + uint64_t lba_c = p1_first + gap, lba_a = lba_c + c + gap, lba_b = lba_a + a + gap; + gw_part p[2]; + p[0] = (gw_part){gw_esp_type, 1 * per, (1 + esp_mib) * per - 1u, "ESP", 0}; + p[1] = (gw_part){gw_linux_type, p1_first, p1_last, "model-home", 0}; + if (gw_write(argv[2], bs, blocks, p, 2, flags)) { fclose(mf); return 1; } + int fd = open(argv[2], O_WRONLY); + if (fd < 0) { fclose(mf); fprintf(stderr, "cannot reopen %s\n", argv[2]); return 1; } + struct { uint64_t lba, count; } ext[3] = {{lba_a, a}, {lba_b, b}, {lba_c, c}}; + static uint8_t buf[1u << 20]; + int rc = 0; + for (int i = 0; i < 3 && !rc; i++) { + uint64_t left = ext[i].count * bs, off = ext[i].lba * bs; + while (left && !rc) { + size_t want = left < sizeof buf ? (size_t)left : sizeof buf; + memset(buf, 0, want); + size_t got = fread(buf, 1, want, mf); /* short only on the final partial sector */ + if (got == 0) { rc = 1; break; } + if (pwrite(fd, buf, want, (off_t)off) != (ssize_t)want) rc = 1; + left -= want; + off += want; + } + } + close(fd); + fclose(mf); + if (rc) { fprintf(stderr, "model write failed\n"); return 1; } + printf("gpt_image bs=%u blocks=%llu esp_first_lba=%llu esp_last_lba=%llu model_len=%llu " + "model_extents=%llu:%llu,%llu:%llu,%llu:%llu\n", + bs, (unsigned long long)blocks, (unsigned long long)p[0].first, (unsigned long long)p[0].last, + (unsigned long long)mlen, (unsigned long long)lba_a, (unsigned long long)a, + (unsigned long long)lba_b, (unsigned long long)b, (unsigned long long)lba_c, (unsigned long long)c); + return 0; +} + static int cmd_create(int argc, char **argv) { if (argc < 6) return usage(); + if (argc > 6 && strcmp(argv[5], "esp-model") != 0) return usage(); uint32_t bs = (uint32_t)strtoul(argv[3], NULL, 10); uint64_t mib = strtoull(argv[4], NULL, 10); if ((bs != 512 && bs != 4096) || mib < 16 || mib > 1048576) return usage(); uint64_t per = (1024u * 1024u) / bs, blocks = mib * per; const char *lay = argv[5]; unsigned flags = 0; + if (!strcmp(lay, "esp-model")) return esp_model(argc, argv, bs, blocks, per, flags); for (int i = 6; i < argc; i++) { if (!strcmp(argv[i], "bad-primary-crc")) flags |= GW_BAD_PRIMARY_CRC; else if (!strcmp(argv[i], "bad-backup-crc")) flags |= GW_BAD_BACKUP_CRC; diff --git a/native/kernel/tools/ck_model_map.c b/native/kernel/tools/ck_model_map.c new file mode 100644 index 00000000..9acbebff --- /dev/null +++ b/native/kernel/tools/ck_model_map.c @@ -0,0 +1,300 @@ +/* ck_model_map -- host tool for MODEL.MAP (native/boot/model_map.h): where + * the yardstick model's bytes live on the boot disk, so the UEFI boot stub + * can read them through the firmware's Block I/O driver (aienos#34 lane 6). + * Hosted C, Linux only (FIEMAP), test and staging tooling; never part of an + * image. No Python. + * + * ck_model_map make OUT.MAP --file GGUF --disk DEV|IMG [--sector 512] + * (--fiemap [--part-start LBA|auto] | --extent LBA:COUNT ...) + * [--corrupt-sha] + * Reads GGUF (length + SHA-256), the disk's GPT disk GUID (LBA 1 bytes + * 56..71 of DEV or IMG), and the extents: --extent lists them in file + * order (QEMU images, from ck_gpt_image esp-model); --fiemap asks the + * filesystem where the file's blocks are (FS_IOC_FIEMAP) and converts + * partition-relative byte offsets to whole-disk LBAs with --part-start + * (the partition's first LBA; "auto" reads /sys/dev/block/MAJ:MIN/start + * of the file's own device). Every FIEMAP extent must be plain mapped + * data (no delalloc, unwritten, inline, encoded or unknown extents) and + * the extents must cover the file exactly, else refused. --corrupt-sha + * flips the last SHA-256 byte (the gate's negative control: the stub + * reads fine, the kernel must refuse to decode). + * ck_model_map show MAP + * ck_model_map check MAP --disk DEV|IMG + * Structural check, GUID match against the disk, then reads every extent + * by LBA from DEV|IMG and recomputes the SHA-256: exit 0 only when it + * equals the declared hash. The same bytes the firmware will read, read + * the same way from Linux: the pre-flight for the attended native boot. */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "model_map.h" +#include "sha256.h" + +static int usage(void) +{ + fprintf(stderr, + "usage: ck_model_map make OUT.MAP --file GGUF --disk DEV|IMG [--sector 512]\n" + " (--fiemap [--part-start LBA|auto] | --extent LBA:COUNT ...) [--corrupt-sha]\n" + " ck_model_map show MAP\n" + " ck_model_map check MAP --disk DEV|IMG\n"); + return 2; +} + +static void hex(char *out, const uint8_t *b, unsigned n) +{ + static const char d[] = "0123456789abcdef"; + for (unsigned i = 0; i < n; i++) { + out[2 * i] = d[b[i] >> 4]; + out[2 * i + 1] = d[b[i] & 15]; + } + out[2 * n] = 0; +} + +static int sha_file(FILE *f, uint64_t *len, uint8_t out[32]) +{ + static uint8_t buf[1u << 20]; + sha256_ctx c; + sha256_init(&c); + *len = 0; + size_t n; + while ((n = fread(buf, 1, sizeof buf, f)) > 0) { + sha256_update(&c, buf, n); + *len += n; + } + if (ferror(f)) return -1; + sha256_final(&c, out); + return 0; +} + +/* GPT disk GUID from LBA 1 of DEV|IMG (raw 16 bytes). */ +static int disk_guid(const char *disk, uint32_t sector, uint8_t out[16]) +{ + int fd = open(disk, O_RDONLY); + if (fd < 0) { fprintf(stderr, "cannot open %s: %s\n", disk, strerror(errno)); return -1; } + uint8_t h[4096]; + ssize_t r = pread(fd, h, sector, (off_t)sector); + close(fd); + if (r != (ssize_t)sector) { fprintf(stderr, "cannot read LBA 1 of %s\n", disk); return -1; } + if (memcmp(h, "EFI PART", 8)) { fprintf(stderr, "%s: no GPT header at LBA 1 (sector %u)\n", disk, sector); return -1; } + memcpy(out, h + 56, 16); + return 0; +} + +static int parse_extent(const char *s, struct ck_model_extent *e) +{ + char *end = 0; + e->lba = strtoull(s, &end, 10); + if (!end || *end != ':') return -1; + e->count = strtoull(end + 1, &end, 10); + return (end && *end == 0 && e->count) ? 0 : -1; +} + +/* --part-start auto: the file's device's first 512-byte sector from sysfs. */ +static int part_start_auto(const char *file, uint64_t *start512) +{ + struct stat st; + if (stat(file, &st)) return -1; + char p[128]; + snprintf(p, sizeof p, "/sys/dev/block/%u:%u/start", major(st.st_dev), minor(st.st_dev)); + FILE *f = fopen(p, "r"); + if (!f) { fprintf(stderr, "cannot read %s (is the file on a partition?)\n", p); return -1; } + int ok = fscanf(f, "%llu", (unsigned long long *)start512) == 1; + fclose(f); + return ok ? 0 : -1; +} + +static int fiemap_extents(const char *file, uint64_t len, uint32_t sector, uint64_t part_start_lba, + struct ck_model_map *m) +{ + int fd = open(file, O_RDONLY); + if (fd < 0) { fprintf(stderr, "cannot open %s\n", file); return -1; } + const unsigned cap = 512; + struct fiemap *fm = calloc(1, sizeof *fm + cap * sizeof(struct fiemap_extent)); + if (!fm) { close(fd); return -1; } + fm->fm_start = 0; + fm->fm_length = ~0ull; + fm->fm_flags = FIEMAP_FLAG_SYNC; + fm->fm_extent_count = cap; + if (ioctl(fd, FS_IOC_FIEMAP, fm)) { + fprintf(stderr, "FS_IOC_FIEMAP: %s\n", strerror(errno)); + free(fm); + close(fd); + return -1; + } + close(fd); + const uint32_t bad = FIEMAP_EXTENT_UNKNOWN | FIEMAP_EXTENT_DELALLOC | FIEMAP_EXTENT_ENCODED | + FIEMAP_EXTENT_DATA_ENCRYPTED | FIEMAP_EXTENT_NOT_ALIGNED | + FIEMAP_EXTENT_DATA_INLINE | FIEMAP_EXTENT_DATA_TAIL | FIEMAP_EXTENT_UNWRITTEN; + uint64_t logical = 0; + int last = 0, rc = 0; + for (uint32_t i = 0; i < fm->fm_mapped_extents && !rc; i++) { + const struct fiemap_extent *e = &fm->fm_extents[i]; + if (e->fe_flags & bad) { fprintf(stderr, "extent %u: flags 0x%x not plain mapped data\n", i, e->fe_flags); rc = -1; break; } + if (e->fe_logical != logical) { fprintf(stderr, "extent %u: hole or out of order at %llu\n", i, (unsigned long long)e->fe_logical); rc = -1; break; } + if (e->fe_physical % sector) { fprintf(stderr, "extent %u: physical offset not sector aligned\n", i); rc = -1; break; } + if (m->n_extents >= CK_MODEL_MAP_MAX_EXTENTS) { fprintf(stderr, "more than %u extents\n", CK_MODEL_MAP_MAX_EXTENTS); rc = -1; break; } + uint64_t take = e->fe_length; + if (logical + take > len) take = len - logical; /* the last extent may be block padded */ + m->ext[m->n_extents].lba = part_start_lba + e->fe_physical / sector; + m->ext[m->n_extents].count = (take + sector - 1) / sector; + m->n_extents++; + logical += take; + if (e->fe_flags & FIEMAP_EXTENT_LAST) last = 1; + } + free(fm); + if (rc) return rc; + if (!last || logical != len) { + fprintf(stderr, "FIEMAP did not cover the file (%llu of %llu bytes, last=%d)\n", + (unsigned long long)logical, (unsigned long long)len, last); + return -1; + } + return 0; +} + +static int cmd_make(int argc, char **argv) +{ + const char *out = argv[2], *file = 0, *disk = 0; + uint32_t sector = 512; + int fiemap = 0, corrupt = 0; + uint64_t part_start = 0; + int part_auto = 0; + static struct ck_model_map m; + memset(&m, 0, sizeof m); + for (int i = 3; i < argc; i++) { + if (!strcmp(argv[i], "--file") && i + 1 < argc) file = argv[++i]; + else if (!strcmp(argv[i], "--disk") && i + 1 < argc) disk = argv[++i]; + else if (!strcmp(argv[i], "--sector") && i + 1 < argc) sector = (uint32_t)strtoul(argv[++i], NULL, 10); + else if (!strcmp(argv[i], "--fiemap")) fiemap = 1; + else if (!strcmp(argv[i], "--part-start") && i + 1 < argc) { + if (!strcmp(argv[i + 1], "auto")) part_auto = 1; + else part_start = strtoull(argv[i + 1], NULL, 10); + i++; + } else if (!strcmp(argv[i], "--extent") && i + 1 < argc) { + if (m.n_extents >= CK_MODEL_MAP_MAX_EXTENTS || parse_extent(argv[++i], &m.ext[m.n_extents])) { + fprintf(stderr, "bad --extent %s\n", argv[i]); + return 2; + } + m.n_extents++; + } else if (!strcmp(argv[i], "--corrupt-sha")) corrupt = 1; + else return usage(); + } + if (!file || !disk || (sector != 512 && sector != 4096) || (fiemap == (m.n_extents > 0))) return usage(); + FILE *f = fopen(file, "rb"); + if (!f) { fprintf(stderr, "cannot open %s\n", file); return 1; } + uint64_t len = 0; + if (sha_file(f, &len, m.sha256)) { fclose(f); fprintf(stderr, "read error on %s\n", file); return 1; } + fclose(f); + memcpy(m.magic, CK_MODEL_MAP_MAGIC, 8); + m.version = CK_MODEL_MAP_VERSION; + m.sector_size = sector; + m.model_len = len; + if (disk_guid(disk, sector, m.disk_guid)) return 1; + if (fiemap) { + if (part_auto) { + uint64_t s512 = 0; + if (part_start_auto(file, &s512)) return 1; + part_start = s512 * 512 / sector; + } + if (fiemap_extents(file, len, sector, part_start, &m)) return 1; + } + const char *why = 0; + if (ck_model_map_check(&m, sector, 0, &why)) { fprintf(stderr, "map refused: %s\n", why); return 1; } + if (corrupt) m.sha256[31] ^= 0xff; + FILE *o = fopen(out, "wb"); + if (!o || fwrite(&m, 1, sizeof m, o) != sizeof m || fclose(o)) { fprintf(stderr, "cannot write %s\n", out); return 1; } + char sh[65], gh[33]; + hex(sh, m.sha256, 32); + hex(gh, m.disk_guid, 16); + printf("model_map written=%s len=%llu extents=%u sector=%u disk=%s sha256=%s%s\n", out, + (unsigned long long)len, m.n_extents, sector, gh, sh, corrupt ? " (CORRUPTED on purpose)" : ""); + return 0; +} + +static int load_map(const char *path, struct ck_model_map *m) +{ + FILE *f = fopen(path, "rb"); + if (!f) { fprintf(stderr, "cannot open %s\n", path); return -1; } + size_t n = fread(m, 1, sizeof *m, f); + int extra = fgetc(f) != EOF; + fclose(f); + if (n != sizeof *m || extra) { fprintf(stderr, "%s: not exactly %u bytes\n", path, CK_MODEL_MAP_BYTES); return -1; } + const char *why = 0; + if (ck_model_map_check(m, 0, 0, &why)) { fprintf(stderr, "%s: refused: %s\n", path, why); return -1; } + return 0; +} + +static int cmd_show(int argc, char **argv) +{ + if (argc != 3) return usage(); + static struct ck_model_map m; + if (load_map(argv[2], &m)) return 1; + char sh[65], gh[33]; + hex(sh, m.sha256, 32); + hex(gh, m.disk_guid, 16); + printf("magic=%.8s version=%u sector=%u disk=%s len=%llu sha256=%s extents=%u\n", m.magic, m.version, + m.sector_size, gh, (unsigned long long)m.model_len, sh, m.n_extents); + for (uint32_t i = 0; i < m.n_extents; i++) + printf(" extent %u lba=%llu count=%llu\n", i, (unsigned long long)m.ext[i].lba, + (unsigned long long)m.ext[i].count); + return 0; +} + +static int cmd_check(int argc, char **argv) +{ + if (argc != 5 || strcmp(argv[3], "--disk")) return usage(); + static struct ck_model_map m; + if (load_map(argv[2], &m)) return 1; + uint8_t g[16]; + if (disk_guid(argv[4], m.sector_size, g)) return 1; + if (memcmp(g, m.disk_guid, 16)) { fprintf(stderr, "disk GUID differs from the map\n"); return 1; } + int fd = open(argv[4], O_RDONLY); + if (fd < 0) { fprintf(stderr, "cannot open %s\n", argv[4]); return 1; } + static uint8_t buf[1u << 20]; + sha256_ctx c; + sha256_init(&c); + uint64_t left = m.model_len; + for (uint32_t i = 0; i < m.n_extents && left; i++) { + uint64_t off = m.ext[i].lba * m.sector_size, bytes = m.ext[i].count * m.sector_size; + if (bytes > left) bytes = left; + while (bytes) { + size_t want = bytes < sizeof buf ? (size_t)bytes : sizeof buf; + if (pread(fd, buf, want, (off_t)off) != (ssize_t)want) { close(fd); fprintf(stderr, "read failed at byte %llu\n", (unsigned long long)off); return 1; } + sha256_update(&c, buf, want); + off += want; + bytes -= want; + left -= want; + } + } + close(fd); + uint8_t dg[32]; + sha256_final(&c, dg); + char sh[65]; + hex(sh, dg, 32); + if (left || memcmp(dg, m.sha256, 32)) { + printf("model_map check: FAIL (sha256 of the mapped bytes %s, declared differs, unread=%llu)\n", sh, + (unsigned long long)left); + return 1; + } + printf("model_map check: PASS (sha256 of the mapped bytes = declared %s, %u extents, %llu bytes)\n", sh, + m.n_extents, (unsigned long long)m.model_len); + return 0; +} + +int main(int argc, char **argv) +{ + if (argc < 3) return usage(); + if (!strcmp(argv[1], "make")) return cmd_make(argc, argv); + if (!strcmp(argv[1], "show")) return cmd_show(argc, argv); + if (!strcmp(argv[1], "check")) return cmd_check(argc, argv); + return usage(); +} diff --git a/native/kernel/tools/gpt_write.c b/native/kernel/tools/gpt_write.c index 1f494c00..25869b72 100644 --- a/native/kernel/tools/gpt_write.c +++ b/native/kernel/tools/gpt_write.c @@ -10,6 +10,8 @@ const uint8_t gw_linux_type[16] = {0xaf, 0x3d, 0xc6, 0x0f, 0x83, 0x84, 0x72, 0x47, 0x8e, 0x79, 0x3d, 0x69, 0xd8, 0x47, 0x7d, 0xe4}; +const uint8_t gw_esp_type[16] = {0x28, 0x73, 0x2a, 0xc1, 0x1f, 0xf8, 0xd2, 0x11, + 0xba, 0x4b, 0x00, 0xa0, 0xc9, 0x3e, 0xc9, 0x3b}; static void put32(uint8_t *p, uint32_t v) { diff --git a/native/kernel/tools/gpt_write.h b/native/kernel/tools/gpt_write.h index 0ee70908..7f8396cd 100644 --- a/native/kernel/tools/gpt_write.h +++ b/native/kernel/tools/gpt_write.h @@ -19,6 +19,9 @@ /* Linux filesystem data type GUID 0FC63DAF-8483-4772-8E79-3D69D8477DE4 * (on-disk byte order): used for the sentinel partitions. */ extern const uint8_t gw_linux_type[16]; +/* EFI System Partition type GUID C12A7328-F81F-11D2-BA4B-00A0C93EC93B (on-disk + * byte order): used by the esp-model layout. */ +extern const uint8_t gw_esp_type[16]; typedef struct { const uint8_t *type; /* 16 on-disk bytes */ diff --git a/scripts/.crumb b/scripts/.crumb index d7ae7223..797f63ad 100644 --- a/scripts/.crumb +++ b/scripts/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-04T14:35:29Z", + "compiled_at": "2026-10-04T15:16:40Z", "compiler": "crumb-compile/1", - "digest": "sha256:e7ab7a937d3d63828c4b3431a5f958217db1c03819f3a7d7532c86d648c85c98", + "digest": "sha256:f99911001560491e4c719aa841ac33c9cec413ee578fe55da847f4c781e992af", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 60, - "generated_at_commit": "91bfd45b6201152df26661469f2d984b8b123e1d", - "source_tree": "sha256:e17431f5154acc3d92284d341f75616bbc2c908fb3d0b28544de5223da21fb28" + "generated_at_commit": "733a8419c1fa44a13dc5e8f525eca33cdea7c5dc", + "source_tree": "sha256:11bc11a213a89c83b74db884e14700018aec98cdb8be66d8c1550700473eb8d6" }, "owner_lane": "", "provenance": { diff --git a/scripts/qemu_ck_infer_test.sh b/scripts/qemu_ck_infer_test.sh index a4958ae0..a1a9b8f7 100755 --- a/scripts/qemu_ck_infer_test.sh +++ b/scripts/qemu_ck_infer_test.sh @@ -39,6 +39,11 @@ # bash scripts/qemu_ck_infer_test.sh --negative-control corrupt the GGUF # magic; the gate checks must FAIL (rc=-2) -> prints # AIENOS_CK_INFER_NEGATIVE_CONTROL: PASS when they do +# bash scripts/qemu_ck_infer_test.sh --disk model on a GPT/NVMe +# image via MODEL.MAP + firmware Block I/O (the hardware path) +# bash scripts/qemu_ck_infer_test.sh --disk-negative-control corrupt the +# declared sha256 in MODEL.MAP; the kernel must refuse to decode -> +# AIENOS_CK_INFER_DISK_NEGATIVE_CONTROL: PASS when it does # bash scripts/qemu_ck_infer_test.sh --self-test canned logs, no QEMU/build # Environment: AIENOS_MODEL (the GGUF), AIENOS_QEMU_TIMEOUT (3600 s: TCG runs # the 25 forward passes at roughly 20-30 s each), AIENOS_GATE_LOCK / @@ -49,6 +54,7 @@ set -euo pipefail repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" cd "${repo_root}" verdict_name=AIENOS_CK_INFER +source_mode=fwcfg disk_negctl=0 model="${AIENOS_MODEL:-${HOME}/models/aien-mail/Llama-3.2-1B-Instruct-Q4_K_M.gguf}" ref_file=crates/aienos-infer/tests/fixtures/ref_fr.txt # Pinned model hash: evidence/config_a_reference_bundle.json and @@ -74,6 +80,17 @@ infer_check_log() { local re_txt='^infer: text=(.*)$' local re_un='^infer: unloaded heap_live_kib=([0-9]+) frames_free_before=([0-9]+) frames_free_after=([0-9]+) frames_returned=([0-9]+) rc=(-?[0-9]+),(-?[0-9]+)$' local n sz + if [[ "${source_mode:-fwcfg}" == disk ]]; then + local re_dk='^infer: disk base=0x[0-9a-f]+ size=([0-9]+) extents=([0-9]+) read_us=([0-9]+) block_size=(512|4096)$' + n="$(grep -cE "${re_dk}" "${f}" || true)" + if [[ "${n}" == 1 ]]; then + local dl; dl="$(grep -E "${re_dk}" "${f}")"; [[ "${dl}" =~ ${re_dk} ]]; sz="${BASH_REMATCH[1]}" + [[ "${sz}" == "${want_size}" ]] && ok "boot-disk model size ${sz} = host file size" || bad "boot-disk model size ${sz}, host file is ${want_size}" + grep -qE '^model_map: ok len='"${want_size}"' extents=[0-9]+ sector=(512|4096) disk=[0-9a-f]{32}$' "${f}" && ok "stub accepted MODEL.MAP (len ${want_size})" || bad "no well-formed model_map: ok line from the stub" + grep -qE '^model: base=0x[0-9a-f]+ len='"${want_size}"' extents=[0-9]+ read_us=[0-9]+ declared_sha256=[0-9a-f]{64}$' "${f}" && ok "stub read the model through firmware Block I/O" || bad "no well-formed model: base line from the stub" + else bad "exactly one well-formed infer: disk line (found ${n})"; fi + if grep -qE "${re_fw}|${re_in}|^infer_source_mode: TEST-ONLY" "${f}"; then bad "the TEST-ONLY fw_cfg path ran in disk mode"; else ok "TEST-ONLY fw_cfg path did not run"; fi + else n="$(grep -cE "${re_fw}" "${f}" || true)" if [[ "${n}" == 1 ]]; then sz="$(sed -nE "s|${re_fw}|\\1|p" "${f}")" @@ -84,6 +101,7 @@ infer_check_log() { sz="$(sed -nE "s|${re_in}|\\1|p" "${f}")" [[ "${sz}" == "${want_size}" ]] && ok "kernel ingested ${sz} bytes = host file size" || bad "kernel ingested ${sz} bytes, host file is ${want_size}" else bad "exactly one well-formed ingest line (found ${n})"; fi + fi n="$(grep -cE "${re_sha}" "${f}" || true)" if [[ "${n}" == 1 ]]; then sz="$(sed -nE "s|${re_sha}|\\1|p" "${f}")" @@ -218,7 +236,16 @@ fi negctl=0 [[ "${1:-}" == --negative-control ]] && negctl=1 +# Model source: fwcfg (default, TEST-ONLY QEMU channel) or disk (MODEL.MAP on a +# GPT image, read by the stub through the firmware Block I/O: the hardware +# path, proven here under QEMU). --disk-negative-control corrupts the declared +# SHA-256 in MODEL.MAP: the stub reads fine, the kernel must refuse to decode. +case "${1:-}" in + --disk) source_mode=disk ;; + --disk-negative-control) source_mode=disk disk_negctl=1 ;; +esac if [[ ${negctl} == 1 ]]; then verdict_name=AIENOS_CK_INFER_NEGATIVE_CONTROL; fi +if [[ ${disk_negctl} == 1 ]]; then verdict_name=AIENOS_CK_INFER_DISK_NEGATIVE_CONTROL; fi notrun() { echo "NOT_RUN $*"; echo "${verdict_name}: NOT_RUN ($*)"; exit 2; } [[ -r "${model}" ]] || notrun "model file ${model} not found" @@ -241,6 +268,7 @@ lib="${repo_root}/target/infer-kernel/aarch64-unknown-none/release/libaienos_inf CARGO_TARGET_DIR="${repo_root}/target/infer-kernel" cargo build -q --release --target aarch64-unknown-none \ --manifest-path crates/aienos-infer-kernel/Cargo.toml make -s -C native/kernel CROSS="${cross}" OUT="${out}" AIENOS_COMMIT="${commit}" CK_INFER_LIB="${lib}" >/dev/null +[[ "${source_mode}" != disk ]] || make -s -C native/kernel OUT="${out}" gpt-image model-map >/dev/null # Machine-wide quiet flag: read only, never written here. If someone holds # it, a CPU-heavy TCG run would disturb their measurement: NOT_RUN. @@ -286,6 +314,39 @@ mkdir -p "${work}/esp/EFI/BOOT" "${work}/esp/EFI/AIENOS" touch "${work}/esp/EFI/AIENOS/BOOTREPORT.TXT" cp "${out}/BOOTAA64.EFI" "${work}/esp/EFI/BOOT/BOOTAA64.EFI" cp "${vars_fd}" "${work}/vars.fd" +# Boot media. disk: a GPT image with the ESP (BOOTAA64.EFI + MODEL.MAP) and the +# model in three out-of-order extents, on an NVMe controller; the stub reads +# the model through the firmware Block I/O driver (native/boot/efi_model.c). +# fwcfg: the TEST-ONLY channel, unchanged. +if [[ "${source_mode}" == disk ]]; then + img="${work}/disk.img" + esp_mib=64 + model_bytes="$(stat -c %s "${use_model}")" + total_mib=$(( (model_bytes + 1048575) / 1048576 + esp_mib + 16 )) + gpt_line="$("${out}/host/ck_gpt_image" create "${img}" 512 "${total_mib}" esp-model "${esp_mib}" "${use_model}")" + echo "${gpt_line}" + esp_first="$(sed -nE 's/.* esp_first_lba=([0-9]+).*/\1/p' <<<"${gpt_line}")" + extents="$(sed -nE 's/.* model_extents=([0-9:,]+).*/\1/p' <<<"${gpt_line}")" + [[ -n "${esp_first}" && -n "${extents}" ]] || { echo "FAIL ck_gpt_image esp-model gave no geometry"; echo "${verdict_name}: FAIL"; exit 1; } + mkfs.vfat -F 32 -s 1 -S 512 --offset "${esp_first}" "${img}" $(( esp_mib * 1024 )) >/dev/null 2>&1 + mo="${img}@@$(( esp_first * 512 ))" + mmd -i "${mo}" ::/EFI ::/EFI/BOOT ::/EFI/AIENOS + mcopy -i "${mo}" "${out}/BOOTAA64.EFI" ::/EFI/BOOT/BOOTAA64.EFI + map_args=() + IFS=, read -ra exts <<<"${extents}" + for e in "${exts[@]}"; do map_args+=(--extent "${e}"); done + corrupt=() + [[ "${disk_negctl}" == 1 ]] && corrupt=(--corrupt-sha) + "${out}/host/ck_model_map" make "${work}/MODEL.MAP" --file "${use_model}" --disk "${img}" "${map_args[@]}" "${corrupt[@]}" + if [[ "${disk_negctl}" == 0 ]]; then + "${out}/host/ck_model_map" check "${work}/MODEL.MAP" --disk "${img}" || { echo "FAIL host-side map check"; echo "${verdict_name}: FAIL"; exit 1; } + fi + mcopy -i "${mo}" "${work}/MODEL.MAP" ::/EFI/AIENOS/MODEL.MAP + drive_args=(-drive if=none,id=disk,format=raw,file="${img}" -device nvme,drive=disk,serial=aienos0001) +else + drive_args=(-drive if=none,id=esp,format=raw,file=fat:rw:"${work}/esp" -device virtio-blk-pci,drive=esp + -fw_cfg name=opt/aienos/model,file="${use_model}") +fi log="${work}/serial.log" started=$(date +%s) @@ -294,9 +355,7 @@ timeout "${AIENOS_QEMU_TIMEOUT:-3600}" qemu-system-aarch64 \ -M virt,virtualization=on,gic-version=3 -accel tcg,thread=single -cpu max -smp 2 -m 4096 \ -drive if=pflash,format=raw,readonly=on,file="${code_fd}" \ -drive if=pflash,format=raw,file="${work}/vars.fd" \ - -drive if=none,id=esp,format=raw,file=fat:rw:"${work}/esp" \ - -device virtio-blk-pci,drive=esp \ - -fw_cfg name=opt/aienos/model,file="${use_model}" \ + "${drive_args[@]}" \ -device ramfb -display none -nic none \ -serial file:"${log}" -no-reboot qemu_status=$? @@ -322,6 +381,18 @@ if [[ ${negctl} == 1 ]]; then fi echo "AIENOS_CK_INFER_NEGATIVE_CONTROL: FAIL (corrupt magic was not caught as probe rc=-2)"; exit 1 fi +if [[ ${disk_negctl} == 1 ]]; then + # The control passes only when the corrupted declared SHA-256 is what made + # the gate fail: the stub read the model, the kernel hashed it, refused to + # decode (no probe line), and reported FAIL itself. + s="${work}/serial.txt" + if [[ ${infer_failed} == 1 ]] && grep -q '^infer: sha256 mismatch declared=' "${s}" \ + && ! grep -q '^infer: probe' "${s}" && grep -q '^AIENOS_CK_INFER: FAIL' "${s}" \ + && grep -q '^model: base=0x' "${s}" && grep -q 'kernel: alive' "${s}"; then + echo "AIENOS_CK_INFER_DISK_NEGATIVE_CONTROL: PASS (corrupt MODEL.MAP sha256 -> kernel refused to decode -> gate FAIL)"; exit 0 + fi + echo "AIENOS_CK_INFER_DISK_NEGATIVE_CONTROL: FAIL (corrupt declared sha256 was not refused by the kernel)"; exit 1 +fi # Live control on the same serial log: a mutated expected-id list must FAIL. mut="$(infer_check_log "${work}/serial.txt" "${want_size}" "${want_sha}" "${want_ids}" 1 "$(mutate_gen "${want_gen}")")" || true if grep -q '^FAIL generated ids' <<<"${mut}"; then