Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/patches/a05831955affbba2 # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aienux#418 (code only) closed derived `a05831955affbba2` #418 Imported from GitHub aien-dev/aienux#418 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `9165e0252daa6dc95d6ebc215ad25826dc85715e` · Head `42db55f79ae51d1c49ca58c796e380dcddbac456` github-advanced-security[bot] commented on `native/kernel/dev/tests/fat_boot_test.c` line 64 on 2026-10-31 03:45 UTC ## CodeQL / File created without restricting permissions A file may be created here with mode 0666, which would make it world-writable. Show more details drakestapleton reviewed (COMMENTED) on 2026-10-30 11:18 UTC Triage: blocked (stacked on #415 `feat/imac-keyboard`; merge conflicts) - Trust boundary: the loader→kernel handoff (`struct nb_pass`, `native/boot/netboot_proto.h`). The EfiLoaderData containment and SHA-512 re-check are good; also check for integer overflow in the base+len containment test and that the manifest signature, not just the hash, is re-verified. - Writes the disk (`ck_gpt_add`): needs bounds checks against the GPT size and free-space computation, with a dry-run test. - 14k lines: please split. - Hardware: needs a serial log of booting from the iMac's own disk with no stick or network. - Appears consolidated into #473. github-advanced-security[bot] reviewed (COMMENTED) on 2026-10-31 03:45 UTC ### Fetch it A git bundle of the pull request's head, 221394 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aienux/patches/a05831955affbba2.bundle -o a05831955affbba2.bundle git fetch a05831955affbba2.bundle refs/pull/418/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aienux 418 42db55f79ae51d1c49ca58c796e380dcddbac456 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aienux","number":418,"url":"https://github.com/aien-dev/aienux/pull/418","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:23Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index c2c3920a..81e5c762 100644 --- a/.crumb +++ b/.crumb @@ -22,7 +22,7 @@ "children": [ { "digest": "b7d58d76e7dacaa887051e8c2d64e2eaef683c9ba82c03e073002f6ddd920239", - "last_commit": "45d8f79", + "last_commit": "801b248", "name": "crates", "purpose": "Directory crates. Purpose not yet described by a human." }, @@ -33,14 +33,14 @@ "purpose": "Directory docs. Purpose not yet described by a human." }, { - "digest": "191a912e7f36b80302d1c07a02b8e966094383c68ec594be4dcea46b18948c08", - "last_commit": "792181f", + "digest": "1d869fc8837e95da35cbe14cd535f5c023ab536fead815845eb8d2c4784bcb4a", + "last_commit": "e4bc7aa", "name": "native", "purpose": "Directory native. Purpose not yet described by a human." }, { - "digest": "77ac3f146e84c4b49982d46d81c24d3feb723b1e17bfcf5c5876c9dc29fe0807", - "last_commit": "792181f", + "digest": "5b000b2f77cd62ae8ad2a113a1f77e486e3c974ad5ecc89150e6e54ad714a781", + "last_commit": "e4bc7aa", "name": "scripts", "purpose": "Directory scripts. Purpose not yet described by a human." }, @@ -51,15 +51,15 @@ "purpose": "First-party host artifact preparation tools" } ], - "children_root": "sha256:b6b0ae8664b1e6b59a3f43b25984fac0b7eb4d6c1b0e30afd2061a22f7f0e71c", - "compiled_at": "2026-10-31T03:18:52Z", + "children_root": "sha256:200759cfb94b5906e7a16e2317f48eae785ebf45d27cfabadb93828392c3e8d1", + "compiled_at": "2026-10-31T03:50:47Z", "compiler": "crumb-compile/1", - "digest": "sha256:39eefcc3a6ab400f7a1ab0042fb526de382831c6cf1449d3313ad898586a6d7f", + "digest": "sha256:6be266506bf9feacc5a140eaea5e549940dbdc8c1d81759c9fa963c9e24424d3", "evidence_files": 274, "evidence_root": "sha256:af014a4ed8f6fe759fc5809807fb47578d3410811b522d9f65d749382b029802", - "files": 3724, - "generated_at_commit": "792181fa4d7ded679d92711bb9a8d31e87c42061", - "source_tree": "sha256:c29a72b62a026bcd3c86841857ae3ce0cf9a99a46c20bd1a0832c8f6130d47f1" + "files": 3729, + "generated_at_commit": "b9580267ad8852e8f81391addf20fdd244b91a00", + "source_tree": "sha256:8c6c1135b597a8c2115be3c5b54ad42562d3e56b727e63a91e2ea668c9edc89b" }, "owner_lane": "", "provenance": { diff --git a/native/.crumb b/native/.crumb index c9466339..470ae45c 100644 --- a/native/.crumb +++ b/native/.crumb @@ -50,80 +50,80 @@ "children": [ { "digest": "72ee4e94f3dc99d79ea4eb3bf619ad645c0b76d7009d1883e59adfbfce9c8ac2", - "last_commit": "09e59a8", + "last_commit": "2c9c8b5", "name": "argus", "purpose": "Directory native/argus. Purpose not yet described by a human." }, { - "digest": "5187cf88f03271fb2a89fd18d0a97212ae419491d9bd510732bdbe54a0ccf263", - "last_commit": "52dcb5d", + "digest": "55582525fd80851150b4b8620558bd3d44f516aac70cf20566f33ec98a914c33", + "last_commit": "e4bc7aa", "name": "boot", "purpose": "Directory native/boot. Purpose not yet described by a human." }, { "digest": "1b5414c184e37d4d943e7979db3d82f1441d6004bb9b5c379a4e4e39381fe7fd", - "last_commit": "7db773a", + "last_commit": "f45d00a", "name": "capability", "purpose": "Directory native/capability. Purpose not yet described by a human." }, { "digest": "ec6a4295568339a6dea0df513d23cf7a28a90d07bee2cd8f93a7417b48ff7871", - "last_commit": "7db773a", + "last_commit": "2c9c8b5", "name": "crypto", "purpose": "Directory native/crypto. Purpose not yet described by a human." }, { "digest": "43e1cf9e246a9cdfca6b1147381ad071e1cffaf408bb58d3e09b7001e7b0eb5c", - "last_commit": "7db773a", + "last_commit": "b5e7268", "name": "disk", "purpose": "Directory native/disk. Purpose not yet described by a human." }, { - "digest": "4b16282d4d64d2a986a079db5c29a238106dea5f9cd8611d5b4faf22f1c1248e", - "last_commit": "52dcb5d", + "digest": "1b9b958d2f033dcf14a2b22e6166a3d2f44d03d8af9ee5ab3a93751523cc845b", + "last_commit": "e4bc7aa", "name": "kernel", "purpose": "Directory native/kernel. Purpose not yet described by a human." }, { "digest": "b9588f7026aaa3fbf7777f5c10d90a1c915cc301be98be5081d3d66106cf77c8", - "last_commit": "7db773a", + "last_commit": "2c9c8b5", "name": "m5", "purpose": "Directory native/m5. Purpose not yet described by a human." }, { "digest": "b0c2410bb450a0bf6156e064185b024b622fd844e87d7acd476df10c7af63cf6", - "last_commit": "7db773a", + "last_commit": "dc9a996", "name": "net", "purpose": "Directory native/net. Purpose not yet described by a human." }, { "digest": "f3c7ee4f18f768fa9964c123e07f076c544c58c0966a8a5e9571b0397bf57b06", - "last_commit": "", + "last_commit": "c93a5f5", "name": "omega", "purpose": "Seeded Omega native modules" }, { "digest": "6f0bf10c76df492d27ae642792476c1138bc73f0d897b3ddca04605ac07b4268", - "last_commit": "7db773a", + "last_commit": "2c9c8b5", "name": "sig", "purpose": "Directory native/sig. Purpose not yet described by a human." }, { "digest": "e125172a18437b662edf303f4b9615bb791f5e7d2ed94192033823185e7d40e1", - "last_commit": "e5e8f08", + "last_commit": "2c9c8b5", "name": "store", "purpose": "Directory native/store. Purpose not yet described by a human." } ], - "children_root": "sha256:c202ba995d4bfa215379bc98ef74e867e8293fc07e1a876dcf7b0f3320f120b4", - "compiled_at": "2026-10-31T02:42:46Z", + "children_root": "sha256:bb2fa8f7899f1249c331015e30b462056dab1e9dc7df60eafaa715999f613321", + "compiled_at": "2026-10-31T03:50:47Z", "compiler": "crumb-compile/1", - "digest": "sha256:191a912e7f36b80302d1c07a02b8e966094383c68ec594be4dcea46b18948c08", + "digest": "sha256:1d869fc8837e95da35cbe14cd535f5c023ab536fead815845eb8d2c4784bcb4a", "evidence_files": 24, "evidence_root": "sha256:ecc7ccf2e924c221a5bac1d91e23b13d8f3c8d78c2a893a882ed7ca5e88d855d", - "files": 767, - "generated_at_commit": "47faeddadfb49c9e84f9d1058547f7bb0ef45d1d", - "source_tree": "sha256:aaf8d32c5e9316d18e1b95c725c4352e3b82cb467a2f8eb74c473cd9148ecd5b" + "files": 770, + "generated_at_commit": "b9580267ad8852e8f81391addf20fdd244b91a00", + "source_tree": "sha256:eb1fc62f665224ab3fcdcaa8e25ad1ae711503507d3fa500b8e64527dbf84ee9" }, "owner_lane": "", "provenance": { diff --git a/native/boot/.crumb b/native/boot/.crumb index 8fb910a1..8eebc35d 100644 --- a/native/boot/.crumb +++ b/native/boot/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-30T11:54:31Z", + "compiled_at": "2026-10-31T02:43:29Z", "compiler": "crumb-compile/1", - "digest": "sha256:5187cf88f03271fb2a89fd18d0a97212ae419491d9bd510732bdbe54a0ccf263", + "digest": "sha256:55582525fd80851150b4b8620558bd3d44f516aac70cf20566f33ec98a914c33", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 29, - "generated_at_commit": "fd4ac5b5bdf13645e310e506c997ca18c39b7fe2", - "source_tree": "sha256:de39e3167409e052cbdff629906e54fb87071aa5fa3593ea0bd8facaf84124f6" + "generated_at_commit": "00e555f6296726b12cbcb226b4de58838540c2be", + "source_tree": "sha256:0ea7bd755899bd60137f0ce6d3bfa8e2c92f3610486eaf68a3855d58d2679bc5" }, "owner_lane": "", "provenance": { diff --git a/native/boot/net_loader.c b/native/boot/net_loader.c index fa285745..3c8087ef 100644 --- a/native/boot/net_loader.c +++ b/native/boot/net_loader.c @@ -19,7 +19,9 @@ * the reason, nothing runs, back to step 2. * 4. Verified: DONE status 0, SNP Shutdown + Stop + CloseProtocol (no * firmware DMA into memory the kernel will own), LoadImage from the - * verified buffer, StartImage. + * verified buffer, StartImage, with LoadOptions = struct nb_pass + * (netboot_proto.h): the loader's clock stamps and where the verified + * object lies, so the kernel can install it on its own disk. * No answer at all for CK_NETLDR_FALLBACK_S seconds: start the kernel on the * stick itself (\EFI\AIENOS\IMACKERN.EFI on this loader's volume), so the * iMac still runs AIENOS with the Spark disconnected. That file is trusted @@ -387,11 +389,16 @@ static int net_recv(const uint8_t nonce[16], uint64_t deadline, struct nb_msg *o } /* ---- starting a kernel ------------------------------------------------------ */ -static void start_image(const char *what, void *buf, uint64_t len) +static struct nb_pass pass; /* the kernel copies it before it leaves boot services */ + +/* obj: the verified object (manifest + image) for a network kernel, 0 for the local one */ +static void start_image(const char *what, void *buf, uint64_t len, const uint8_t *obj, uint64_t obj_len) { static const EFI_GUID lidp_guid = LOADED_IMAGE_DEVICE_PATH_GUID_INIT; + static const EFI_GUID li_guid = EFI_LOADED_IMAGE_PROTOCOL_GUID_INIT; void *dp = 0; EFI_HANDLE child = 0; + EFI_LOADED_IMAGE_PROTOCOL *li = 0; bs->HandleProtocol(self, &lidp_guid, &dp); EFI_STATUS s = ((load_image_fn)bs->LoadImage)(0, self, dp, buf, len, &child); if (s != EFI_SUCCESS) { @@ -400,6 +407,14 @@ static void start_image(const char *what, void *buf, uint64_t len) } say("netldr: starting the %s kernel (%llu bytes)\n", what, (unsigned long long)len); watchdog(300); + memcpy(pass.magic, NB_PASS_MAGIC, 8); + pass.object = (uint64_t)(uintptr_t)obj; + pass.object_len = obj ? obj_len : 0; + if (bs->HandleProtocol(child, &li_guid, (void **)&li) == EFI_SUCCESS && li) { + li->LoadOptions = &pass; + li->LoadOptionsSize = sizeof pass; + } + pass.start_tsc = rdtsc(); s = ((start_image_fn)bs->StartImage)(child, 0, 0); say("netldr: the %s kernel returned status=0x%llx\n", what, (unsigned long long)s); } @@ -437,7 +452,7 @@ static void start_local(void) f->Close(f); root->Close(root); if (pa && got > 0 && got < LOCAL_MAX) - start_image("local", (void *)(uintptr_t)pa, got); + start_image("local", (void *)(uintptr_t)pa, got, 0, 0); else if (pa) say("netldr: local kernel unreadable or larger than %llu bytes\n", (unsigned long long)LOCAL_MAX); if (pa) @@ -578,13 +593,14 @@ static int exchange(void) done(nonce, 0, "verified, starting"); bs->Stall(200000); /* let the last frames leave before the NIC is stopped */ net_close(); - start_image("network", obj + CK_SLOT_UNIT, m->image_len); + start_image("network", obj + CK_SLOT_UNIT, m->image_len, obj, total); bs->FreePages(pa, pages); return R_BOOT; } EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *st) { + pass.loader_tsc = rdtsc(); conout = st->ConOut; bs = st->BootServices; self = image; diff --git a/native/boot/netboot_proto.h b/native/boot/netboot_proto.h index 62830bff..e604f24e 100644 --- a/native/boot/netboot_proto.h +++ b/native/boot/netboot_proto.h @@ -82,4 +82,20 @@ static inline size_t nb_text_len(const char *text) return n; } +/* What the loader hands the kernel it starts, as that image's LoadOptions + * (EFI_LOADED_IMAGE_PROTOCOL, UEFI 2.10 section 9.1): the processor clock + * (TSC, counting since power-on) when the loader began and when it started + * the kernel, and, for a network kernel, where the verified object (4096-byte + * signed manifest + image) lies, in the loader's EfiLoaderData pages, which + * the kernel's frame allocator never hands out. The kernel installs that + * object on its disk's boot section (kernel/dev/fat_boot.h). */ +#define NB_PASS_MAGIC "AIENNLP1" +struct nb_pass { + uint8_t magic[8]; + uint64_t loader_tsc; /* the loader's first instruction */ + uint64_t start_tsc; /* just before StartImage */ + uint64_t object; /* physical address of the verified object; 0: none (a local kernel) */ + uint64_t object_len; /* manifest + image bytes */ +}; + #endif /* AIENOS_NETBOOT_PROTO_H */ diff --git a/native/kernel/.crumb b/native/kernel/.crumb index d9129819..1c1f2b19 100644 --- a/native/kernel/.crumb +++ b/native/kernel/.crumb @@ -46,68 +46,68 @@ "children": [ { "digest": "aa16ee3dab6c71bf912686eef4e763743d26883addadc7ca4371eb8545b513aa", - "last_commit": "2529bc0", + "last_commit": "9e48cf8", "name": "arch", "purpose": "Directory native/kernel/arch. Purpose not yet described by a human." }, { "digest": "de009659b554bfb75b093c0b62567ed58238731e3ce4c457008fcc2be1488b89", - "last_commit": "6ad9190", + "last_commit": "f45d00a", "name": "artifact", "purpose": "Directory native/kernel/artifact. Purpose not yet described by a human." }, { "digest": "ed58fce3de8581101263e4241f336cc14ea58cd50263fd4bbb5e9ca9bb6639eb", - "last_commit": "0f6ef82", + "last_commit": "792181f", "name": "core", "purpose": "Directory native/kernel/core. Purpose not yet described by a human." }, { - "digest": "f4d9f6e374a17bdc6bca5564d5e01d32fc4cfb0bcfd33bc1876c26184d74cf06", - "last_commit": "4eb74bf", + "digest": "eb03419b33745642bf04e2ba6a0a9451910c3d7b7e15c5cb516863fbe41121f3", + "last_commit": "e4bc7aa", "name": "dev", "purpose": "Directory native/kernel/dev. Purpose not yet described by a human." }, { "digest": "54cee35b405dc1c90f62d4d227ed172142abfd4917e720708ba0b83b94b9376e", - "last_commit": "0735543", + "last_commit": "f45d00a", "name": "include", "purpose": "Directory native/kernel/include. Purpose not yet described by a human." }, { "digest": "c7dc6acbe30f21ef0d3983d31b212f89ff23ae6e56862a2718d98fd28c76649a", - "last_commit": "2bc7146", + "last_commit": "f45d00a", "name": "mm", "purpose": "Directory native/kernel/mm. Purpose not yet described by a human." }, { "digest": "ef3844c1228b5fc5b740f944b4a3d2539fc4a816bf5402fa47fce6b50850d543", - "last_commit": "4eb74bf", + "last_commit": "792181f", "name": "svc", "purpose": "Directory native/kernel/svc. Purpose not yet described by a human." }, { "digest": "2ca38317e04e90ee53c0a97be152b07b62e80b4b32db8bbe6b8aa3cb60aa3900", - "last_commit": "7ef5916", + "last_commit": "792181f", "name": "tests", "purpose": "Directory native/kernel/tests. Purpose not yet described by a human." }, { "digest": "1dd8ed2150cfa3709d98eed188288b25edc8d94711ea36b4b846fe66b9ab224b", - "last_commit": "52dcb5d", + "last_commit": "792181f", "name": "tools", "purpose": "Hosted (Linux-built) checkers for the native kernel, run by `make -C native/kernel test`; nothin" } ], - "children_root": "sha256:121c5932c956df51a50824f36ee65f951f60dc742546f740c546dffe17db1dcc", - "compiled_at": "2026-10-31T02:42:46Z", + "children_root": "sha256:272980ba0ceda75ccf3e1724c6ef1ba325163cb86c34af6b021c7a2dba7dd0a3", + "compiled_at": "2026-10-31T03:50:47Z", "compiler": "crumb-compile/1", - "digest": "sha256:4b16282d4d64d2a986a079db5c29a238106dea5f9cd8611d5b4faf22f1c1248e", + "digest": "sha256:1b9b958d2f033dcf14a2b22e6166a3d2f44d03d8af9ee5ab3a93751523cc845b", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 512, - "generated_at_commit": "47faeddadfb49c9e84f9d1058547f7bb0ef45d1d", - "source_tree": "sha256:e0a7fb7d6be67f260d4fd9b646d5f7cdf9e8f12f0a5408f22b05797bee043c40" + "files": 515, + "generated_at_commit": "b9580267ad8852e8f81391addf20fdd244b91a00", + "source_tree": "sha256:d43e0abbd73a52f5c53ae318bb488b978439cc2eb9f75254723b838cdec00e93" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/Makefile b/native/kernel/Makefile index 7c9cc971..82da5a29 100644 --- a/native/kernel/Makefile +++ b/native/kernel/Makefile @@ -2593,7 +2593,7 @@ $(error CK_X86_REPORT must be 0 (default) or 1 (lab-only network report)) endif IMACKERN_ELF := $(IMACKERN_DIR)/imackern.elf IMACKERN_CFLAGS := $(X86CFLAGS) -I$(KDIR)/include -I$(KDIR)/mm -I$(KDIR)/dev -I$(NATIVE)/disk -I$(NATIVE)/net \ - -I$(NATIVE)/argus + -I$(NATIVE)/argus -I$(NATIVE)/sig IMACKERN_OBJS := $(IMACKERN_DIR)/efi_entry_x86_64.o $(IMACKERN_DIR)/efi_x86.o $(IMACKERN_DIR)/efi_gop.o \ $(IMACKERN_DIR)/kmain_x86.o $(IMACKERN_DIR)/console_x86.o $(IMACKERN_DIR)/trap.o \ $(IMACKERN_DIR)/fbcon.o $(IMACKERN_DIR)/fmt.o $(IMACKERN_DIR)/acpi.o $(IMACKERN_DIR)/handoff_check.o \ @@ -2603,7 +2603,8 @@ IMACKERN_OBJS := $(IMACKERN_DIR)/efi_entry_x86_64.o $(IMACKERN_DIR)/efi_x86.o $( $(IMACKERN_DIR)/tg3_x86.o $(IMACKERN_DIR)/xhci_x86.o $(IMACKERN_DIR)/hda_x86.o $(IMACKERN_DIR)/usb_hid.o $(IMACKERN_DIR)/sha256.o \ $(IMACKERN_DIR)/allen_ui.o $(IMACKERN_DIR)/allen_font.o $(IMACKERN_DIR)/allen_reply.o \ $(IMACKERN_DIR)/paint.o $(IMACKERN_DIR)/night.o $(IMACKERN_DIR)/mind.o $(IMACKERN_DIR)/chirp.o \ - $(IMACKERN_DIR)/allen_memory.o $(IMACKERN_DIR)/allen_notes.o $(IMACKERN_DIR)/gpt_add.o $(IMACKERN_DIR)/memory_x86.o + $(IMACKERN_DIR)/allen_memory.o $(IMACKERN_DIR)/allen_notes.o $(IMACKERN_DIR)/gpt_add.o $(IMACKERN_DIR)/memory_x86.o \ + $(IMACKERN_DIR)/fat_boot.o $(IMACKERN_DIR)/sha512.o $(IMACKERN_DIR)/ct.o IMACKERN_REPORT_OBJS := $(IMACKERN_DIR)/report_x86.o $(IMACKERN_DIR)/aienos_net.o # Symbols only the lab image may contain; the default image is checked for them after linking. IMACKERN_REPORT_SYMS := ck_x86_report_hold|ck_x86_report_frame|ck_x86_report_filter|ck_x86_report_parts|ck_x86_tg3_send|ck_x86_tg3_drain|net_udp_build @@ -2613,7 +2614,7 @@ IMACKERN_CFLAGS += -DCK_X86_REPORT=1 endif IMACKERN_HDRS := $(X86K)/x86.h $(BOOT)/handoff.h $(BOOT)/efi.h $(KDIR)/core/ck_internal.h $(KDIR)/include/ck.h $(IMACKERN_DIR)/efi_entry_x86_64.o: $(BOOT)/efi_entry_x86_64.S -$(IMACKERN_DIR)/efi_x86.o: $(X86K)/efi_x86.c $(IMACKERN_HDRS) +$(IMACKERN_DIR)/efi_x86.o: $(X86K)/efi_x86.c $(IMACKERN_HDRS) $(BOOT)/netboot_proto.h $(IMACKERN_DIR)/efi_gop.o: $(BOOT)/efi_gop.c $(IMACKERN_HDRS) $(IMACKERN_DIR)/kmain_x86.o: $(X86K)/kmain_x86.c $(IMACKERN_HDRS) $(KDIR)/core/handoff_check.h $(KDIR)/mm/frames.h $(KDIR)/mm/heap.h $(KDIR)/ui/allen_ui.h $(KDIR)/svc/allen_reply.h $(OUT)/commit.stamp $(IMACKERN_DIR)/console_x86.o: $(X86K)/console_x86.c $(IMACKERN_HDRS) $(KDIR)/core/fbcon.h @@ -2646,7 +2647,11 @@ $(IMACKERN_DIR)/allen_reply.o: $(KDIR)/svc/allen_reply.c $(KDIR)/svc/allen_reply $(IMACKERN_DIR)/allen_notes.o: $(KDIR)/svc/allen_notes.c $(KDIR)/svc/allen_notes.h $(IMACKERN_DIR)/allen_memory.o: $(KDIR)/svc/allen_memory.c $(KDIR)/svc/allen_memory.h $(KDIR)/svc/allen_reply.h $(KDIR)/svc/allen_notes.h $(NATIVE)/disk/disk.h $(NATIVE)/argus/sha256.h $(IMACKERN_DIR)/gpt_add.o: $(KDIR)/dev/gpt_add.c $(KDIR)/dev/gpt_add.h $(KDIR)/dev/disk_part.h $(NATIVE)/disk/disk.h $(NATIVE)/argus/sha256.h -$(IMACKERN_DIR)/memory_x86.o: $(X86K)/memory_x86.c $(IMACKERN_HDRS) $(KDIR)/svc/allen_memory.h $(KDIR)/svc/allen_notes.h $(KDIR)/dev/gpt_add.h $(KDIR)/dev/disk_part.h +$(IMACKERN_DIR)/memory_x86.o: $(X86K)/memory_x86.c $(IMACKERN_HDRS) $(KDIR)/svc/allen_memory.h $(KDIR)/svc/allen_notes.h $(KDIR)/dev/gpt_add.h $(KDIR)/dev/disk_part.h \ + $(KDIR)/dev/fat_boot.h $(BOOT)/netboot_proto.h $(BOOT)/slot_format.h $(NATIVE)/sig/aienos_sig.h +$(IMACKERN_DIR)/fat_boot.o: $(KDIR)/dev/fat_boot.c $(KDIR)/dev/fat_boot.h $(NATIVE)/disk/disk.h +$(IMACKERN_DIR)/sha512.o: $(NATIVE)/sig/sha512.c $(NATIVE)/sig/aienos_sig.h +$(IMACKERN_DIR)/ct.o: $(NATIVE)/sig/ct.c $(NATIVE)/sig/aienos_sig.h $(IMACKERN_DIR)/report_x86.o: $(X86K)/report_x86.c $(X86K)/report_x86.h $(IMACKERN_HDRS) $(NATIVE)/net/aienos_net.h $(IMACKERN_DIR)/aienos_net.o: $(NATIVE)/net/aienos_net.c $(NATIVE)/net/aienos_net.h $(sort $(IMACKERN_OBJS) $(IMACKERN_REPORT_OBJS)): diff --git a/native/kernel/README.md b/native/kernel/README.md index 8957e84d..68c92d9b 100644 --- a/native/kernel/README.md +++ b/native/kernel/README.md @@ -300,6 +300,26 @@ screenshot as `target/native-kernel-imac-keyboard/allen-qemu.png`). What Allen learns and the notes it keeps are saved in its section of the disk (`svc/allen_memory.c`, `x86/memory_x86.c`) and come back after a restart. +**Starting from its own disk.** When the network loader (`../boot/net_loader.c`) +starts a kernel it hands it a `struct nb_pass` (`../boot/netboot_proto.h`) as +LoadOptions: the processor clock when the loader began, and where the verified +object (signed manifest + image) lies in the loader's memory. The kernel checks +the image's SHA-512 against the manifest again and installs it on the disk that +holds Allen's section, in a 256 MiB EFI System Partition it adds in unused +space (`dev/gpt_add.c` `ck_gpt_add`; never on a disk that already has another +system's), as `\EFI\BOOT\BOOTX64.EFI` on a FAT32 volume it writes itself +(`dev/fat_boot.c`, Microsoft FAT32 specification 1.03). Two slots: the new +kernel goes into the one the firmware does not start, then a single directory +sector switches over, so a power cut leaves the old kernel or the new one, +never a mix; the same kernel again writes nothing. After that the firmware +starts AIENOS from the disk with no stick and no network. Every start prints +`boot_time:` (milliseconds since power on: firmware, loader, kernel, Allen's +window) and `boot_disk:` (what the boot section holds). Tests: +`scripts/ck_fat_boot_test.sh` (host: power cuts at every sampled block, +`fsck.fat` and mtools as outside readers) and +`scripts/qemu_ck_imac_bootdisk_test.sh` (QEMU: install over the network, then +start from the disk alone, then a second kernel into the other slot). + Output: the GOP framebuffer (`core/fbcon.c`, lines from before ExitBootServices replayed onto it) and COM1 when a 16550 answers there (QEMU; the iMac has none). Shared, unchanged: @@ -308,7 +328,7 @@ when a 16550 answers there (QEMU; the iMac has none). Shared, unchanged: cores and attaches a SATA data disk and an NVMe disk, each with a GPT from `ck_gpt_image`, and fails unless three cores check in, the kernel finds each AIENOS partition where the tool wrote it and both disks are byte-identical -afterwards. Not yet: work scheduled on the other cores, x2APIC, disk writes, +afterwards. Not yet: work scheduled on the other cores, x2APIC, VT-d, receiving on the network, a store. QEMU (no BCM57766 there) qualifies nothing physical; copy the image to a FAT stick as `EFI/BOOT/BOOTX64.EFI` and start it from the Option-key boot picker. diff --git a/native/kernel/dev/.crumb b/native/kernel/dev/.crumb index 3a019b48..f1ff0656 100644 --- a/native/kernel/dev/.crumb +++ b/native/kernel/dev/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-31T02:24:33Z", + "compiled_at": "2026-10-31T03:50:47Z", "compiler": "crumb-compile/1", - "digest": "sha256:f4d9f6e374a17bdc6bca5564d5e01d32fc4cfb0bcfd33bc1876c26184d74cf06", + "digest": "sha256:eb03419b33745642bf04e2ba6a0a9451910c3d7b7e15c5cb516863fbe41121f3", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 52, - "generated_at_commit": "47faeddadfb49c9e84f9d1058547f7bb0ef45d1d", - "source_tree": "sha256:6c5f03446d854e6d5ffc35d960f5b065246ba4c418e4692798c066b9590547fb" + "files": 55, + "generated_at_commit": "b9580267ad8852e8f81391addf20fdd244b91a00", + "source_tree": "sha256:b8bcc276caab72a375ef513d15b69115b767c83e6ea273ac50e12e9d4a16cf1f" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/dev/fat_boot.c b/native/kernel/dev/fat_boot.c new file mode 100644 index 00000000..9b7c737c --- /dev/null +++ b/native/kernel/dev/fat_boot.c @@ -0,0 +1,493 @@ +/* fat_boot.c -- the AIENOS boot section (FAT32); see fat_boot.h. Field names + * and offsets are those of the Microsoft FAT32 File System Specification + * 1.03 ("Boot Sector and BPB Structure", "FAT32 FSInfo Sector Structure", + * "FAT 32 Byte Directory Entry Structure"). */ +#include "fat_boot.h" + +const uint8_t ck_esp_part_type[16] = {0x28, 0x73, 0x2a, 0xc1, 0x1f, 0xf8, 0xd2, 0x11, + 0xba, 0x4b, 0x00, 0xa0, 0xc9, 0x3e, 0xc9, 0x3b}; + +#define SEC 512u +#define CHUNK 128u /* sectors per buffered transfer */ +#define PER_FAT_SEC (SEC / 4u) /* FAT32 entries in one FAT sector */ +#define EOC 0x0FFFFFFFu +#define MAN_CLUS (CK_FATB_MAN_BYTES / SEC) +#define ROOT 2u +#define EFI_DIR 3u +#define BOOT_DIR 4u +#define FMT_DATE 0x0021u /* 1980-01-01, the directories' stamp */ + +static uint8_t g_buf[CHUNK * SEC]; +static uint8_t g_sec[SEC], g_want[SEC]; + +typedef struct { + uint32_t total, rsv, fatsz, data0, clusters, slotc; +} geo; + +static void put16(uint8_t *p, uint32_t v) +{ + p[0] = (uint8_t)v; + p[1] = (uint8_t)(v >> 8); +} +static void put32(uint8_t *p, uint32_t v) +{ + put16(p, v); + put16(p + 2, v >> 16); +} +static uint32_t get16(const uint8_t *p) { return (uint32_t)p[0] | (uint32_t)p[1] << 8; } +static uint32_t get32(const uint8_t *p) { return get16(p) | get16(p + 2) << 16; } +static void fill(uint8_t *p, uint8_t v, uint32_t n) +{ + for (uint32_t i = 0; i < n; i++) + p[i] = v; +} +static void copy(uint8_t *d, const uint8_t *s, uint32_t n) +{ + for (uint32_t i = 0; i < n; i++) + d[i] = s[i]; +} +static int same(const uint8_t *a, const uint8_t *b, uint32_t n) +{ + uint8_t x = 0; + for (uint32_t i = 0; i < n; i++) + x |= a[i] ^ b[i]; + return x == 0; +} + +/* The spec's FAT32 sizing ("FAT Type Determination", BPB_FATSz32 formula + * with TmpVal2 = (256 * BPB_SecPerClus + BPB_NumFATs) / 2), one sector per + * cluster as its table gives up to 260 MB and fine above; the reserved + * region padded to a 4 KiB boundary for the data region. */ +static int geometry(const disk_dev *p, geo *g) +{ + if (p->block_size != SEC || p->block_count > 0xffffffffull || + p->block_count < (uint64_t)CK_FATB_MIN_MIB * (1024u * 1024u / SEC)) + return CK_FATB_EGEOM; + g->total = (uint32_t)p->block_count; + uint32_t t1 = g->total - 32u, t2 = (256u * 1u + 2u) / 2u; + g->fatsz = (t1 + t2 - 1u) / t2; + g->rsv = 32u + (8u - (32u + 2u * g->fatsz) % 8u) % 8u; + g->data0 = g->rsv + 2u * g->fatsz; + g->clusters = g->total - g->data0; + if (g->clusters < 65525u || (uint64_t)g->fatsz * PER_FAT_SEC < (uint64_t)g->clusters + 2u) + return CK_FATB_EGEOM; + g->slotc = ((g->clusters + 2u - 128u) / 2u) & ~127u; + return g->slotc >= 256u ? CK_FATB_OK : CK_FATB_EGEOM; +} + +static uint32_t slot_base(const geo *g, int k) { return 128u + (uint32_t)k * g->slotc; } +static uint32_t clus_sec(const geo *g, uint32_t c) { return g->data0 + (c - 2u); } +static uint32_t slot_max(const geo *g) { return (g->slotc - 128u) * SEC; } + +static int rd(const disk_dev *p, uint32_t lba, uint32_t n, uint8_t *b) +{ + return disk_read(p, lba, n, b) == DISK_OK ? CK_FATB_OK : CK_FATB_EIO; +} +static int wr(const disk_dev *p, uint32_t lba, uint32_t n, const uint8_t *b, uint32_t *count) +{ + if (disk_write(p, lba, n, b) != DISK_OK) + return CK_FATB_EIO; + if (count) + *count += n; + return CK_FATB_OK; +} +static int flush(const disk_dev *p) { return disk_flush(p) == DISK_OK ? CK_FATB_OK : CK_FATB_EIO; } + +/* ---- the fixed sectors ---------------------------------------------------- */ +static void boot_sector(const geo *g, uint32_t serial, uint8_t *b) +{ + fill(b, 0, SEC); + b[0] = 0xeb, b[1] = 0x58, b[2] = 0x90; + copy(b + 3, (const uint8_t *)"AIENOS ", 8); + put16(b + 11, SEC); + b[13] = 1; /* BPB_SecPerClus */ + put16(b + 14, g->rsv); /* BPB_RsvdSecCnt */ + b[16] = 2; /* BPB_NumFATs; RootEntCnt, TotSec16, FATSz16 stay 0 */ + b[21] = 0xf8; /* BPB_Media: fixed */ + put16(b + 24, 63); + put16(b + 26, 255); + put32(b + 32, g->total); + put32(b + 36, g->fatsz); + put32(b + 44, ROOT); /* BPB_RootClus; ExtFlags 0 = mirrored, FSVer 0:0 */ + put16(b + 48, 1); /* BPB_FSInfo */ + put16(b + 50, 6); /* BPB_BkBootSec */ + b[64] = 0x80; + b[66] = 0x29; + put32(b + 67, serial); + copy(b + 71, (const uint8_t *)"AIENOS ", 11); + copy(b + 82, (const uint8_t *)"FAT32 ", 8); + b[90] = 0xcd, b[91] = 0x18; /* not a BIOS boot disk: int 18h */ + b[510] = 0x55, b[511] = 0xaa; +} + +static void fsinfo(uint8_t *b) +{ + fill(b, 0, SEC); + put32(b, 0x41615252u); + put32(b + 484, 0x61417272u); + put32(b + 488, 0xffffffffu); /* free count unknown */ + put32(b + 492, 0xffffffffu); /* no hint */ + put32(b + 508, 0xaa550000u); +} + +static void dirent(uint8_t *e, const char *name11, uint8_t attr, uint32_t clus, uint32_t size, uint16_t date, + uint16_t time) +{ + fill(e, 0, 32); + copy(e, (const uint8_t *)name11, 11); + e[11] = attr; + put16(e + 14, time); + put16(e + 16, date); + put16(e + 18, date); + put16(e + 20, clus >> 16); + put16(e + 22, time); + put16(e + 24, date); + put16(e + 26, clus & 0xffffu); + put32(e + 28, size); +} + +/* Directory sector for cluster 2, 3 or 4 as ck_fatb_format writes it. */ +static void dir_sector(uint32_t c, uint8_t *b) +{ + fill(b, 0, SEC); + if (c == ROOT) { + dirent(b, "AIENOS ", 0x08, 0, 0, FMT_DATE, 0); + dirent(b + 32, "EFI ", 0x10, EFI_DIR, 0, FMT_DATE, 0); + } else if (c == EFI_DIR) { + dirent(b, ". ", 0x10, EFI_DIR, 0, FMT_DATE, 0); + dirent(b + 32, ".. ", 0x10, 0, 0, FMT_DATE, 0); /* parent is the root: 0 */ + dirent(b + 64, "BOOT ", 0x10, BOOT_DIR, 0, FMT_DATE, 0); + } else { + dirent(b, ". ", 0x10, BOOT_DIR, 0, FMT_DATE, 0); + dirent(b + 32, ".. ", 0x10, EFI_DIR, 0, FMT_DATE, 0); + } +} + +/* FAT sector 0: FAT[0] media, FAT[1] end of chain (clean, no error), and + * the three one-cluster directories. */ +static void fat_sector0(uint8_t *b) +{ + fill(b, 0, SEC); + put32(b, 0x0FFFFFF8u); + for (uint32_t c = 1; c <= BOOT_DIR; c++) + put32(b + 4 * c, EOC); +} + +/* ---- format --------------------------------------------------------------- */ +int ck_fatb_format(const disk_dev *p, uint32_t serial) +{ + geo g; + int rc = geometry(p, &g); + if (rc) + return rc; + /* the old boot sector goes first, so a cut format is never taken for ours */ + fill(g_sec, 0, SEC); + if ((rc = wr(p, 0, 1, g_sec, 0)) || (rc = flush(p))) + return rc; + fill(g_buf, 0, sizeof g_buf); + for (uint32_t s = g.rsv; s < g.data0; s += CHUNK) { + uint32_t n = g.data0 - s < CHUNK ? g.data0 - s : CHUNK; + if ((rc = wr(p, s, n, g_buf, 0))) + return rc; + } + fat_sector0(g_sec); + if ((rc = wr(p, g.rsv, 1, g_sec, 0)) || (rc = wr(p, g.rsv + g.fatsz, 1, g_sec, 0))) + return rc; + for (uint32_t c = ROOT; c <= BOOT_DIR; c++) { + dir_sector(c, g_sec); + if ((rc = wr(p, clus_sec(&g, c), 1, g_sec, 0))) + return rc; + } + if ((rc = flush(p))) + return rc; + for (uint32_t s = 1; s < g.rsv; s++) { + if (s == 1 || s == 7) + fsinfo(g_sec); + else if (s == 6) + boot_sector(&g, serial, g_sec); + else + fill(g_sec, 0, SEC); + if ((rc = wr(p, s, 1, g_sec, 0))) + return rc; + } + if ((rc = flush(p))) + return rc; + boot_sector(&g, serial, g_sec); + if ((rc = wr(p, 0, 1, g_sec, 0))) + return rc; + return flush(p); +} + +/* ---- reading -------------------------------------------------------------- */ +/* 1 when FAT `fat` (0 or 1) holds the chain first, first+1, .., first+n-1, + * end of chain; 0 when not; or CK_FATB_EIO. */ +static int chain_ok(const disk_dev *p, const geo *g, int fat, uint32_t first, uint32_t n) +{ + uint32_t loaded = 0xffffffffu, base = g->rsv + (uint32_t)fat * g->fatsz; + for (uint32_t c = first; c < first + n; c++) { + uint32_t s = c / PER_FAT_SEC; + if (s != loaded) { + if (rd(p, base + s, 1, g_sec)) + return CK_FATB_EIO; + loaded = s; + } + uint32_t v = get32(g_sec + 4u * (c % PER_FAT_SEC)) & 0x0FFFFFFFu; + if (c + 1u < first + n ? v != c + 1u : v < 0x0FFFFFF8u) + return 0; + } + return 1; +} + +static int find(const uint8_t *dir, const char *name11, uint32_t *clus, uint32_t *size) +{ + for (uint32_t i = 2; i < SEC / 32u; i++) { + const uint8_t *e = dir + 32u * i; + if (e[0] == 0) + break; + if (same(e, (const uint8_t *)name11, 11) && !(e[11] & 0x18)) { + *clus = get16(e + 20) << 16 | get16(e + 26); + *size = get32(e + 28); + return 1; + } + } + return 0; +} + +/* Compares n bytes read (got) with what ck_fatb_format wrote (want), after + * taking over from want the fields FAT drivers change in normal use (see + * fat_boot.h). Records the first difference in st; 1 when none. */ +enum { BOOT_SEC, FAT_SEC, DIR_SEC }; +static int as_written(uint8_t *got, const uint8_t *want, uint32_t n, int kind, const char *where, ck_fatb_state *st) +{ + if (kind == BOOT_SEC) { + got[65] = want[65]; /* BS_Reserved1 */ + } else if (kind == FAT_SEC) { + got[7] = (uint8_t)((got[7] & ~0x0cu) | (want[7] & 0x0cu)); /* FAT[1] bits 27, 26 */ + } else { + for (uint32_t e = 0; e + 32u <= n; e += 32u) { + got[e + 18] = want[e + 18], got[e + 19] = want[e + 19]; /* DIR_LstAccDate */ + /* Firmware may mark an existing directory for backup and stamp + * it as written (Apple's does both to \EFI when it starts the + * kernel). Only normalize ARCHIVE, DIR_WrtTime and DIR_WrtDate + * on expected directories, never their type, volume labels, or + * unused entries (FAT32 spec DIR_Attr). */ + if (want[e] && (want[e + 11] & 0x10)) { + got[e + 11] = (uint8_t)((got[e + 11] & ~0x20u) | (want[e + 11] & 0x20u)); + copy(got + e + 22, want + e + 22, 4); + } + } + } + for (uint32_t i = 0; i < n; i++) + if (got[i] != want[i]) { + st->where = where, st->at = i, st->got = got[i], st->want = want[i]; + return 0; + } + return 1; +} + +int ck_fatb_state_read(const disk_dev *p, uint32_t serial, ck_fatb_state *st) +{ + static const char *const dir_name[] = {"root", "EFI", "BOOT"}; + geo g; + int rc = geometry(p, &g); + st->ours = 0; + st->slot = -1; + st->image_len = 0; + st->slot_max = 0; + st->where = 0; + if (rc) + return rc; + st->slot_max = slot_max(&g); + boot_sector(&g, serial, g_want); + if (rd(p, 0, 1, g_sec)) + return CK_FATB_EIO; + if (!as_written(g_sec, g_want, SEC, BOOT_SEC, "boot sector", st)) + return CK_FATB_OK; + fat_sector0(g_want); + for (int f = 0; f < 2; f++) { + if (rd(p, g.rsv + (uint32_t)f * g.fatsz, 1, g_sec)) + return CK_FATB_EIO; + if (!as_written(g_sec, g_want, 4u * (BOOT_DIR + 1u), FAT_SEC, f ? "FAT 2" : "FAT 1", st)) + return CK_FATB_OK; + } + for (uint32_t c = ROOT; c <= BOOT_DIR; c++) { + dir_sector(c, g_want); + if (rd(p, clus_sec(&g, c), 1, g_sec)) + return CK_FATB_EIO; + if (!as_written(g_sec, g_want, c == BOOT_DIR ? 64u : SEC, DIR_SEC, dir_name[c - ROOT], st)) + return CK_FATB_OK; + } + st->ours = 1; + uint32_t ic, is, mc, ms; + if (!find(g_sec, "BOOTX64 EFI", &ic, &is) || !find(g_sec, "BOOTX64 MAN", &mc, &ms)) + return CK_FATB_OK; + for (int k = 0; k < 2; k++) { + uint32_t base = slot_base(&g, k); + if (mc != base || ms != CK_FATB_MAN_BYTES || ic != base + 128u || is == 0 || is > st->slot_max) + continue; + for (int f = 0; f < 2; f++) { + int a = chain_ok(p, &g, f, mc, MAN_CLUS), b = a == 1 ? chain_ok(p, &g, f, ic, (is + SEC - 1u) / SEC) : a; + if (a < 0 || b < 0) + return CK_FATB_EIO; + if (!a || !b) + return CK_FATB_OK; + } + st->slot = k; + st->image_len = is; + } + return CK_FATB_OK; +} + +/* 1 when the n bytes at sector lba equal want; 0 when not; or CK_FATB_EIO. */ +static int same_on_disk(const disk_dev *p, uint32_t lba, const uint8_t *want, uint32_t n) +{ + for (uint32_t done = 0; done < n;) { + uint32_t secs = (n - done + SEC - 1u) / SEC; + if (secs > CHUNK) + secs = CHUNK; + if (rd(p, lba + done / SEC, secs, g_buf)) + return CK_FATB_EIO; + uint32_t m = secs * SEC < n - done ? secs * SEC : n - done; + if (!same(g_buf, want + done, m)) + return 0; + for (uint32_t i = m; i < secs * SEC; i++) /* the tail of the last sector: zero */ + if (g_buf[i]) + return 0; + done += m; + } + return 1; +} + +static int slot_holds(const disk_dev *p, const geo *g, int k, const uint8_t *man, const uint8_t *img, uint32_t len) +{ + uint32_t base = slot_base(g, k); + int a = same_on_disk(p, clus_sec(g, base), man, CK_FATB_MAN_BYTES); + return a == 1 ? same_on_disk(p, clus_sec(g, base + 128u), img, len) : a; +} + +/* Writes slot k's FAT sectors in both FATs: the manifest and image chains + * when len > 0, all free when len == 0. */ +static int slot_fat(const disk_dev *p, const geo *g, int k, uint32_t len, uint32_t *count) +{ + uint32_t base = slot_base(g, k), img0 = base + 128u, n = (len + SEC - 1u) / SEC; + uint32_t s0 = base / PER_FAT_SEC, s1 = (base + g->slotc) / PER_FAT_SEC; + for (uint32_t s = s0; s < s1; s += CHUNK) { + uint32_t secs = s1 - s < CHUNK ? s1 - s : CHUNK; + for (uint32_t i = 0; i < secs * PER_FAT_SEC; i++) { + uint32_t c = s * PER_FAT_SEC + i, v = 0; + if (len && c >= base && c < base + MAN_CLUS) + v = c + 1u < base + MAN_CLUS ? c + 1u : EOC; + else if (len && c >= img0 && c < img0 + n) + v = c + 1u < img0 + n ? c + 1u : EOC; + put32(g_buf + 4u * i, v); + } + int rc; + if ((rc = wr(p, g->rsv + s, secs, g_buf, count)) || (rc = wr(p, g->rsv + g->fatsz + s, secs, g_buf, count))) + return rc; + } + return CK_FATB_OK; +} + +static int write_bytes(const disk_dev *p, uint32_t lba, const uint8_t *b, uint32_t n, uint32_t *count) +{ + int rc; + if (n / SEC && (rc = wr(p, lba, n / SEC, b, count))) + return rc; + if (n % SEC) { + fill(g_sec, 0, SEC); + copy(g_sec, b + n / SEC * SEC, n % SEC); + if ((rc = wr(p, lba + n / SEC, 1, g_sec, count))) + return rc; + } + return CK_FATB_OK; +} + +int ck_fatb_install(const disk_dev *p, uint32_t serial, int format_ok, const uint8_t *man, const uint8_t *img, + uint32_t img_len, uint16_t dos_date, uint16_t dos_time, ck_fatb_result *out) +{ + geo g; + ck_fatb_state st; + out->formatted = out->written = 0; + out->slot = -1; + out->sectors_written = 0; + int rc = geometry(p, &g); + if (rc) + return rc; + if (!man || !img || img_len == 0 || img_len > slot_max(&g)) + return CK_FATB_EBIG; + if ((rc = ck_fatb_state_read(p, serial, &st))) + return rc; + if (!st.ours) { + if (!format_ok) + return CK_FATB_ENOTOURS; + if ((rc = ck_fatb_format(p, serial)) || (rc = ck_fatb_state_read(p, serial, &st))) + return rc; + if (!st.ours) + return CK_FATB_EVERIFY; + out->formatted = 1; + out->sectors_written = g.data0 + 4u; + } + if (st.slot >= 0 && st.image_len == img_len) { + int h = slot_holds(p, &g, st.slot, man, img, img_len); + if (h < 0) + return h; + if (h) { + out->slot = st.slot; + return CK_FATB_OK; + } + } + int k = st.slot == 0 ? 1 : 0; + uint32_t base = slot_base(&g, k); + if ((rc = slot_fat(p, &g, k, img_len, &out->sectors_written)) || + (rc = write_bytes(p, clus_sec(&g, base), man, CK_FATB_MAN_BYTES, &out->sectors_written)) || + (rc = write_bytes(p, clus_sec(&g, base + 128u), img, img_len, &out->sectors_written)) || (rc = flush(p))) + return rc; + dir_sector(BOOT_DIR, g_sec); + dirent(g_sec + 64, "BOOTX64 EFI", 0x20, base + 128u, img_len, dos_date, dos_time); + dirent(g_sec + 96, "BOOTX64 MAN", 0x20, base, CK_FATB_MAN_BYTES, dos_date, dos_time); + if ((rc = wr(p, clus_sec(&g, BOOT_DIR), 1, g_sec, &out->sectors_written)) || (rc = flush(p))) + return rc; + if (st.slot >= 0 && ((rc = slot_fat(p, &g, st.slot, 0, &out->sectors_written)) || (rc = flush(p)))) + return rc; + if ((rc = ck_fatb_state_read(p, serial, &st))) + return rc; + int h = st.slot == k && st.image_len == img_len ? slot_holds(p, &g, k, man, img, img_len) : 0; + if (h < 0) + return h; + if (!h) + return CK_FATB_EVERIFY; + out->written = 1; + out->slot = k; + return CK_FATB_OK; +} + +void ck_fatb_dos_time(uint64_t unix_s, uint16_t *date, uint16_t *time) +{ + *date = FMT_DATE; + *time = 0; + if (unix_s < 315532800ull) /* 1980-01-01 */ + return; + uint64_t days = unix_s / 86400u, rem = unix_s % 86400u; + /* civil from days (proleptic Gregorian), era-based */ + uint64_t z = days + 719468u, era = z / 146097u, doe = z - era * 146097u; + uint64_t yoe = (doe - doe / 1460u + doe / 36524u - doe / 146096u) / 365u; + uint64_t doy = doe - (365u * yoe + yoe / 4u - yoe / 100u), mp = (5u * doy + 2u) / 153u; + uint64_t d = doy - (153u * mp + 2u) / 5u + 1u, m = mp < 10u ? mp + 3u : mp - 9u, y = yoe + era * 400u + (m <= 2u); + if (y > 2107u) + return; + *date = (uint16_t)((y - 1980u) << 9 | m << 5 | d); + *time = (uint16_t)((rem / 3600u) << 11 | (rem / 60u % 60u) << 5 | (rem % 60u) / 2u); +} + +const char *ck_fatb_strerror(int rc) +{ + switch (rc) { + case CK_FATB_OK: return "ok"; + case CK_FATB_EGEOM: return "the section is not 512-byte sectors or too small"; + case CK_FATB_EIO: return "a read, write or flush failed"; + case CK_FATB_ENOTOURS: return "the section holds a volume AIENOS did not write"; + case CK_FATB_EBIG: return "the image is larger than a slot"; + case CK_FATB_EVERIFY: return "read back, the files are not what was written"; + default: return "unknown"; + } +} diff --git a/native/kernel/dev/fat_boot.h b/native/kernel/dev/fat_boot.h new file mode 100644 index 00000000..8f2f76e2 --- /dev/null +++ b/native/kernel/dev/fat_boot.h @@ -0,0 +1,104 @@ +/* fat_boot.h -- the AIENOS boot section: a FAT32 volume (Microsoft FAT32 + * File System Specification 1.03; UEFI 2.10 section 13.3: FAT32 for a system + * partition) on an EFI System Partition that AIENOS added itself, holding + * + * \EFI\BOOT\BOOTX64.EFI the kernel image, started by the firmware + * \EFI\BOOT\BOOTX64.MAN its signed slot manifest (boot/slot_format.h) + * + * so a machine starts AIENOS from its own disk with no stick and no network. + * + * Layout, all fixed by the partition size (512-byte sectors only): + * sector 0 boot sector, 1 FSInfo, 6 and 7 their backups; the reserved + * region is padded so the data region starts on a 4 KiB boundary + * (UEFI: "aligned to the physical block boundary"); two FATs; one sector + * per cluster. Cluster 2 is the root (volume label AIENOS, directory EFI), + * 3 is \EFI, 4 is \EFI\BOOT. The rest holds two image slots, A and B, each + * starting on a 128-cluster boundary so their FAT sectors never overlap: + * the manifest at the slot's first cluster, the image 128 clusters later, + * each one contiguous chain. + * + * Installing a new image never touches the files the firmware starts now: + * the new manifest and image go into the other slot (its FAT sectors, then + * its data), flush; then the one sector of \EFI\BOOT is rewritten to name + * the new slot, flush; then the old slot's FAT sectors are freed, flush; + * then everything is read back. A power cut leaves the old kernel or the new + * one, never a mix (at worst the old slot stays allocated with no name, + * "lost clusters", freed by the next install). + * + * A volume is "ours" only when its boot sector is byte for byte the one + * ck_fatb_format writes for that size and volume serial; anything else is + * formatted only if the caller says so (the partition itself must already + * be AIENOS's, gpt_add.h ck_gpt_is_ours). Freestanding: no libc, no heap, + * I/O through disk_read/disk_write/disk_flush on the partition view only. + * Host tested in dev/tests/fat_boot_test.c (with fsck.fat and mtools as + * outside readers). */ +#ifndef AIENOS_CK_FAT_BOOT_H +#define AIENOS_CK_FAT_BOOT_H +#include +#include "disk.h" + +/* EFI System Partition type C12A7328-F81F-11D2-BA4B-00A0C93EC93B (UEFI 2.10 + * table 5-7), on-disk byte order. */ +extern const uint8_t ck_esp_part_type[16]; + +#define CK_FATB_MAN_BYTES 4096u /* a slot manifest */ +#define CK_FATB_MIN_MIB 64u /* smallest partition handled */ + +enum { + CK_FATB_OK = 0, + CK_FATB_EGEOM = -440, /* not 512-byte sectors, or too small for FAT32 with two slots */ + CK_FATB_EIO = -441, /* a read, write or flush failed */ + CK_FATB_ENOTOURS = -442, /* the volume is not one ck_fatb_format wrote */ + CK_FATB_EBIG = -443, /* the image is larger than a slot */ + CK_FATB_EVERIFY = -444, /* read back, the files are not what was written */ +}; + +typedef struct { + int ours; /* the boot sector is ck_fatb_format's */ + int slot; /* 0 or 1: the slot \EFI\BOOT names; -1: none (or not valid) */ + uint32_t image_len; /* BOOTX64.EFI's size when slot >= 0 */ + uint32_t slot_max; /* the largest image a slot holds, in bytes */ + /* when not ours: the first byte that differs from what ck_fatb_format + * wrote (where = "boot sector", "FAT 1", "FAT 2", "root", "EFI" or + * "BOOT"; 0 when the geometry or a read failed) */ + const char *where; + uint32_t at; + uint8_t got, want; +} ck_fatb_state; + +/* Reads the volume: is it ours, and which slot holds a complete, valid pair + * of files (directory entries, contiguous FAT chains ending in the + * end-of-chain mark). Reads only. Fields that FAT drivers change in normal use + * are not compared: the boot sector's BS_Reserved1 (the NT dirty flag), + * FAT[1]'s ClnShutBitMask and HrdErrBitMask, each directory entry's + * DIR_LstAccDate, and ATTR_ARCHIVE, DIR_WrtTime and DIR_WrtDate on the + * expected directory entries (Apple's firmware sets them on the EFI directory + * when it starts the kernel). + * CK_FATB_OK (also for "not ours") or CK_FATB_EGEOM / CK_FATB_EIO. */ +int ck_fatb_state_read(const disk_dev *p, uint32_t serial, ck_fatb_state *st); + +/* Writes an empty AIENOS boot volume over the whole partition view p: both + * FATs, the three directories, then (last, after a flush) the FSInfo and + * boot sectors and their backups. */ +int ck_fatb_format(const disk_dev *p, uint32_t serial); + +typedef struct { + int formatted; /* 1: the volume was not ours and was formatted first */ + int written; /* 1: a new image was installed; 0: the same one was already there */ + int slot; /* the slot the firmware now starts */ + uint32_t sectors_written; +} ck_fatb_result; + +/* Makes BOOTX64.EFI = img and BOOTX64.MAN = man (CK_FATB_MAN_BYTES bytes), + * formatting first when the volume is not ours and format_ok is set. When + * the current slot already holds exactly these bytes nothing is written. + * `dos_date`/`dos_time`: the FAT time stamps for the new entries. */ +int ck_fatb_install(const disk_dev *p, uint32_t serial, int format_ok, const uint8_t *man, const uint8_t *img, + uint32_t img_len, uint16_t dos_date, uint16_t dos_time, ck_fatb_result *out); + +/* FAT date and time (spec "Date and Time Formats") of a Unix time, UTC; + * times before 1980 give 1980-01-01 00:00. */ +void ck_fatb_dos_time(uint64_t unix_s, uint16_t *date, uint16_t *time); + +const char *ck_fatb_strerror(int rc); +#endif diff --git a/native/kernel/dev/gpt_add.c b/native/kernel/dev/gpt_add.c index 681eb037..949abcd4 100644 --- a/native/kernel/dev/gpt_add.c +++ b/native/kernel/dev/gpt_add.c @@ -12,7 +12,7 @@ static uint64_t g_f[CK_GPT_MAX_USED], g_l[CK_GPT_MAX_USED]; /* UEFI 2.10 table 5-5 offsets, as in disk_part.c */ enum { H_CRC = 16, H_SIZE = 12, H_GUID = 56, H_ENT_LBA = 72, H_ECRC = 88 }; -static const char part_name[] = "AIENOS Allen memory"; +static const ck_gpt_new allen_memory = {ck_aienos_part_type, "AIENOS Allen memory", "aienos.allen.memory.v1"}; static uint32_t get32(const uint8_t *p) { @@ -67,8 +67,10 @@ int ck_gpt_list(const disk_dev *d, void (*fn)(void *ctx, const ck_gpt_entry *e), continue; ck_gpt_entry out; out.index = i; - for (int k = 0; k < 16; k++) + for (int k = 0; k < 16; k++) { out.type[k] = e[k]; + out.uguid[k] = e[16 + k]; + } out.first = get64(e + 32); out.last = get64(e + 40); unsigned n = 0; @@ -93,14 +95,72 @@ static void header_crc(uint8_t *h, uint32_t ecrc) put32(h + H_CRC, ck_crc32(0, h, get32(h + H_SIZE))); } +/* The unique GUID of a partition this file adds: SHA-256 over the label + * (with its terminator), the disk GUID and the first LBA, cut to 16 bytes and + * marked version 4 / variant 1. */ +static void unique_guid(const char *label, const uint8_t *disk_guid, uint64_t first, uint8_t out[16]) +{ + uint8_t dig[32], lba8[8]; + size_t n = 0; + while (label[n]) + n++; + put64(lba8, first); + sha256_ctx h; + sha256_init(&h); + sha256_update(&h, (const uint8_t *)label, n + 1u); + sha256_update(&h, disk_guid, 16); + sha256_update(&h, lba8, 8); + sha256_final(&h, dig); + for (int i = 0; i < 16; i++) + out[i] = dig[i]; + out[7] = (uint8_t)((out[7] & 0x0f) | 0x40); + out[8] = (uint8_t)((out[8] & 0x3f) | 0x80); +} + +int ck_gpt_is_ours(const disk_dev *d, const ck_gpt_new *spec, uint32_t index) +{ + ck_part p; + ck_gpt_info gi; + int rc = ck_gpt_find_type(d, spec->type, &p, &gi); + if (rc != CK_GPT_OK) + return rc; + uint32_t bytes, blocks; + if (index != gi.part_index || (rc = load(d, &gi, &bytes, &blocks))) + return rc ? rc : 0; + const uint8_t *e = g_ent + (uint64_t)index * gi.entry_size; + uint8_t want[16]; + unique_guid(spec->label, g_ph + H_GUID, get64(e + 32), want); + for (int i = 0; i < 16; i++) + if (e[16 + i] != want[i]) + return 0; + for (unsigned i = 0; i < 36; i++) { + uint16_t c = (uint16_t)(e[56 + 2 * i] | e[57 + 2 * i] << 8); + if (c != (uint8_t)spec->name[i]) + return 0; + if (!c) + break; + } + return 1; +} + int ck_gpt_add_aienos(const disk_dev *d, uint64_t blocks, uint64_t align, ck_gpt_added *out) +{ + return ck_gpt_add(d, &allen_memory, blocks, align, out); +} + +int ck_gpt_add(const disk_dev *d, const ck_gpt_new *spec, uint64_t blocks, uint64_t align, ck_gpt_added *out) { ck_part p; ck_gpt_info gi; - if (!out || !blocks || !align) + if (!out || !blocks || !align || !spec || !spec->type || !spec->name || !spec->label) + return CK_GPT_EGEOM; + size_t name_len = 0; + while (spec->name[name_len]) + name_len++; + if (name_len > 36) return CK_GPT_EGEOM; *out = (ck_gpt_added){0, 0, 0, 0}; - int rc = ck_gpt_find_aienos(d, &p, &gi); + int rc = ck_gpt_find_type(d, spec->type, &p, &gi); if (rc == CK_GPT_OK) { out->first = p.first_lba; out->last = p.first_lba + p.blocks - 1u; @@ -151,30 +211,17 @@ int ck_gpt_add_aienos(const disk_dev *d, uint64_t blocks, uint64_t align, ck_gpt if (!found) return CK_GPT_ENOSPACE; - /* The new entry. Its unique GUID: SHA-256 over a label, the disk GUID - * and the first LBA, cut to 16 bytes and marked version 4 / variant 1. */ + /* The new entry, its unique GUID from unique_guid. */ uint8_t *e = g_ent + (uint64_t)slot * gi.entry_size; for (uint32_t i = 0; i < gi.entry_size; i++) e[i] = 0; for (int i = 0; i < 16; i++) - e[i] = ck_aienos_part_type[i]; - uint8_t dig[32], lba8[8]; - static const char label[] = "aienos.allen.memory.v1"; - put64(lba8, at); - sha256_ctx h; - sha256_init(&h); - sha256_update(&h, (const uint8_t *)label, sizeof label); - sha256_update(&h, g_ph + H_GUID, 16); - sha256_update(&h, lba8, 8); - sha256_final(&h, dig); - for (int i = 0; i < 16; i++) - e[16 + i] = dig[i]; - e[16 + 7] = (uint8_t)((e[16 + 7] & 0x0f) | 0x40); - e[16 + 8] = (uint8_t)((e[16 + 8] & 0x3f) | 0x80); + e[i] = spec->type[i]; + unique_guid(spec->label, g_ph + H_GUID, at, e + 16); put64(e + 32, at); put64(e + 40, at + blocks - 1u); - for (unsigned i = 0; part_name[i]; i++) - e[56 + 2 * i] = (uint8_t)part_name[i]; + for (unsigned i = 0; i < name_len; i++) + e[56 + 2 * i] = (uint8_t)spec->name[i]; uint32_t ecrc = ck_crc32(0, g_ent, bytes); header_crc(g_ph, ecrc); @@ -185,7 +232,7 @@ int ck_gpt_add_aienos(const disk_dev *d, uint64_t blocks, uint64_t align, ck_gpt disk_write(d, 1, 1, g_ph) != DISK_OK || disk_flush(d) != DISK_OK) return CK_GPT_EWRITE; - rc = ck_gpt_find_aienos(d, &p, &gi); + rc = ck_gpt_find_type(d, spec->type, &p, &gi); if (rc != CK_GPT_OK || p.first_lba != at || p.blocks != blocks || gi.part_index != slot) return CK_GPT_EVERIFY; out->first = at; diff --git a/native/kernel/dev/gpt_add.h b/native/kernel/dev/gpt_add.h index c2070242..968f9c2c 100644 --- a/native/kernel/dev/gpt_add.h +++ b/native/kernel/dev/gpt_add.h @@ -1,7 +1,8 @@ -/* gpt_add.h -- the one GPT change the AIENOS kernel may make: add an AIENOS - * partition (disk_part.h type GUID) in space no partition uses, on a disk - * whose GPT already passes ck_gpt_find_aienos's strict check with "no AIENOS - * partition". Existing entries are never moved, resized or rewritten; the +/* gpt_add.h -- the one GPT change the AIENOS kernel may make: add a partition + * (Allen's AIENOS-type memory section, disk_part.h, or the boot section, + * dev/fat_boot.h) in space no partition uses, on a disk whose GPT already + * passes the strict check of disk_part.h with "no partition of that type". + * Existing entries are never moved, resized or rewritten; the * protective MBR (LBA 0) is never written. Writes, in this order: the backup * entry array and backup header, flush, then the primary entry array and * primary header, flush; then the whole GPT is checked again and must show @@ -10,7 +11,7 @@ * nothing further is written (the firmware keeps reading the primary). * * Also ck_gpt_list: every used entry, read only, for the boot report. - * Freestanding: no libc, no heap. Host tested in dev/tests/gpt_add_test.c. */ + * Freestanding: no libc, no heap. Host tested in svc/tests/allen_memory_test.c and dev/tests/fat_boot_test.c. */ #ifndef AIENOS_CK_GPT_ADD_H #define AIENOS_CK_GPT_ADD_H #include @@ -27,6 +28,7 @@ enum { typedef struct { uint32_t index; uint8_t type[16]; /* on-disk byte order */ + uint8_t uguid[16]; /* unique partition GUID, on-disk byte order */ uint64_t first, last; /* inclusive LBAs */ char name[37]; /* the UTF-16 name as ASCII, '?' for anything else */ } ck_gpt_entry; @@ -42,6 +44,28 @@ typedef struct { int created; /* 1: added now; 0: it was already there */ } ck_gpt_added; +/* What ck_gpt_add writes: the partition type, its name and the label that + * seeds its unique GUID (with the disk GUID and the first LBA), so the same + * partition can later be recognised as one this file added. */ +typedef struct { + const uint8_t *type; /* on-disk byte order */ + const char *name; /* ASCII, at most 36 characters */ + const char *label; +} ck_gpt_new; + +/* Makes sure the disk has exactly one partition of spec->type: an existing + * one is reported (nothing written, whoever made it); otherwise one of + * `blocks` blocks is added at the start of the first unused gap that holds + * it, its first LBA rounded up to a multiple of `align` blocks. CK_GPT_OK or + * the refusal (CK_GPT_EMULTI: two of that type; nothing written unless the + * code is CK_GPT_EWRITE or CK_GPT_EVERIFY). */ +int ck_gpt_add(const disk_dev *d, const ck_gpt_new *spec, uint64_t blocks, uint64_t align, ck_gpt_added *out); + +/* 1 when entry `index` is the only partition of spec->type and carries the + * unique GUID and name ck_gpt_add would have given it (this file added it); + * 0 when it is someone else's; or the CK_GPT_* refusal. Reads only. */ +int ck_gpt_is_ours(const disk_dev *d, const ck_gpt_new *spec, uint32_t index); + /* Makes sure the disk has an AIENOS partition: an existing one is reported * (nothing written); otherwise one of `blocks` blocks is added at the start * of the first unused gap that holds it, its first LBA rounded up to a diff --git a/native/kernel/dev/tests/fat_boot_test.c b/native/kernel/dev/tests/fat_boot_test.c new file mode 100644 index 00000000..0a18bef8 --- /dev/null +++ b/native/kernel/dev/tests/fat_boot_test.c @@ -0,0 +1,309 @@ +/* fat_boot_test.c -- host tests for the AIENOS boot section: + * 1. the EFI System Partition added in unused space next to an existing + * partition full of sentinel bytes (dev/gpt_add.c ck_gpt_add), known as + * ours afterwards; a foreign one is not; + * 2. a volume that is not ours is refused unless formatting is allowed; + * installed: only blocks inside the partition change; the same image + * again writes nothing; a new image goes to the other slot; + * 3. a power cut after every possible number of written blocks (sampled, + * plus the exact switch point) leaves exactly the old or the new + * kernel, old before one point and new after it, and the next install + * completes; + * 4. FAT time stamps. + * Writes part1.img/img1.bin, part2.img/img2.bin and part3.img into the + * folder given, for scripts/ck_fat_boot_test.sh to check with fsck.fat and + * mtools (outside readers). Hosted test code only (libc). */ +#include +#include +#include +#include +#include +#include "disk_file.h" +#include "disk_part.h" +#include "fat_boot.h" +#include "gpt_add.h" +#include "gpt_write.h" + +static int checks, failures; +#define CHECK(c) \ + do { \ + checks++; \ + if (!(c)) { \ + failures++; \ + printf(" FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); \ + } \ + } while (0) + +#define BS 512u +#define MIB (1024u * 1024u / BS) +static const ck_gpt_new esp = {ck_esp_part_type, "AIENOS boot", "aienos.boot.v1"}; +static const uint32_t serial = 0x1234abcdu; +static char g_dir[400], g_path[512]; + +static uint8_t *slurp(const char *path, size_t *len) +{ + FILE *fp = fopen(path, "rb"); + if (!fp) + return NULL; + fseek(fp, 0, SEEK_END); + long n = ftell(fp); + fseek(fp, 0, SEEK_SET); + uint8_t *b = malloc((size_t)n); + if (b && fread(b, 1, (size_t)n, fp) != (size_t)n) { + free(b); + b = NULL; + } + fclose(fp); + *len = (size_t)n; + return b; +} + +static int spill(const char *name, const uint8_t *b, size_t n) +{ + char path[512]; + snprintf(path, sizeof path, "%s/%s", g_dir, name); + /* 0644, not fopen's 0666 & ~umask: the images must not be world-writable. */ + int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); + FILE *fp = fd < 0 ? NULL : fdopen(fd, "wb"); + if (fd >= 0 && !fp) + close(fd); + if (!fp) + return -1; + size_t w = fwrite(b, 1, n, fp); + return fclose(fp) == 0 && w == n ? 0 : -1; +} + +static void pattern(uint8_t *b, size_t n, uint32_t seed) +{ + for (size_t i = 0; i < n; i++) { + seed = seed * 1103515245u + 12345u; + b[i] = (uint8_t)(seed >> 16); + } +} + +/* the partition's bytes from the image file, written to name */ +static int export_part(const ck_part *p, const char *name) +{ + size_t n = 0; + uint8_t *all = slurp(g_path, &n); + int rc = all ? spill(name, all + p->first_lba * BS, p->blocks * BS) : -1; + free(all); + return rc; +} + +/* xors byte at of the partition's sector lba with x, through the disk itself */ +static int poke(const ck_part *p, uint32_t lba, uint32_t at, uint8_t x) +{ + uint8_t s[BS]; + if (disk_read(&p->dev, lba, 1, s) != DISK_OK) + return -1; + s[at] ^= x; + return disk_write(&p->dev, lba, 1, s) == DISK_OK ? 0 : -1; +} + +/* the changes FAT drivers make in normal use: BS_Reserved1, FAT[1]'s two + * flags in both FATs, DIR_LstAccDate in the root and in BOOT */ +static int driver_marks(const ck_part *p, uint32_t rsv, uint32_t fatsz) +{ + uint32_t root = rsv + 2u * fatsz; + return poke(p, 0, 65, 0x01) || poke(p, rsv, 7, 0x0c) || poke(p, rsv + fatsz, 7, 0x08) || + poke(p, root, 32 + 18, 0x5a) || poke(p, root + 2, 19, 0x01); +} + +static int install(disk_file *f, const ck_part *p, int fmt, const uint8_t *man, const uint8_t *img, uint32_t len, + ck_fatb_result *r, uint64_t *blocks) +{ + uint64_t b0 = f->blocks_written; + int rc = ck_fatb_install(&p->dev, serial, fmt, man, img, len, 23890, 12149, r); + if (blocks) + *blocks = f->blocks_written - b0; + return rc; +} + +int main(int argc, char **argv) +{ + if (argc < 2) + return 2; + snprintf(g_dir, sizeof g_dir, "%s", argv[1]); + snprintf(g_path, sizeof g_path, "%s/disk.img", g_dir); + const uint64_t disk = 96 * MIB; + + /* 1. the partition */ + gw_part sentinel[1] = {{gw_linux_type, 1 * MIB, 9 * MIB - 1u, "old system", 0xa5}}; + CHECK(gw_write(g_path, BS, disk, sentinel, 1, 0) == 0); + disk_file f; + disk_dev d; + CHECK(disk_file_open(&f, &d, g_path, BS, 0, 0) == 0); + ck_gpt_added a; + CHECK(ck_gpt_add(&d, &esp, 64 * MIB, MIB, &a) == CK_GPT_OK); + CHECK(a.created == 1 && a.first == 9 * MIB && a.last == 73 * MIB - 1u && a.index == 1); + CHECK(ck_gpt_is_ours(&d, &esp, a.index) == 1); + CHECK(ck_gpt_add(&d, &esp, 64 * MIB, MIB, &a) == CK_GPT_OK && a.created == 0 && a.first == 9 * MIB); + ck_part p, q; + ck_gpt_info gi; + CHECK(ck_gpt_find_type(&d, ck_esp_part_type, &p, &gi) == CK_GPT_OK && p.first_lba == 9 * MIB && + p.blocks == 64 * MIB); + CHECK(ck_gpt_find_aienos(&d, &q, &gi) == CK_GPT_ENOPART); /* GPT still valid; no Allen section yet */ + /* Allen's section can still be added beside it */ + CHECK(ck_gpt_add_aienos(&d, 8 * MIB, MIB, &a) == CK_GPT_OK && a.created == 1 && a.first == 73 * MIB); + CHECK(ck_gpt_find_type(&d, ck_esp_part_type, &p, &gi) == CK_GPT_OK && ck_gpt_is_ours(&d, &esp, gi.part_index) == 1); + + /* 2. install */ + ck_fatb_state st; + CHECK(ck_fatb_state_read(&p.dev, serial, &st) == CK_FATB_OK && st.ours == 0 && st.slot == -1); + static uint8_t man1[CK_FATB_MAN_BYTES], man2[CK_FATB_MAN_BYTES]; + const uint32_t len1 = 300001, len2 = 123457; + uint8_t *img1 = malloc(len1), *img2 = malloc(len2); + if (!img1 || !img2) + return 2; + pattern(man1, sizeof man1, 1); + pattern(man2, sizeof man2, 2); + pattern(img1, len1, 3); + pattern(img2, len2, 4); + ck_fatb_result r; + uint64_t wrote = 0; + size_t n0, n1; + uint8_t *before = slurp(g_path, &n0), *after; + CHECK(install(&f, &p, 0, man1, img1, len1, &r, &wrote) == CK_FATB_ENOTOURS && wrote == 0); + CHECK(install(&f, &p, 1, man1, img1, len1, &r, &wrote) == CK_FATB_OK && r.formatted && r.written && r.slot == 0); + after = slurp(g_path, &n1); + CHECK(before && after && n0 == n1); + if (before && after && n0 == n1) { + CHECK(!memcmp(before, after, p.first_lba * BS)); /* MBR, GPT, the sentinel partition */ + size_t end = (p.first_lba + p.blocks) * BS; + CHECK(!memcmp(before + end, after + end, n0 - end)); /* Allen's section, the backup GPT */ + } + free(before); + free(after); + CHECK(ck_fatb_state_read(&p.dev, serial, &st) == CK_FATB_OK && st.ours && st.slot == 0 && st.image_len == len1); + CHECK(ck_fatb_state_read(&p.dev, serial + 1u, &st) == CK_FATB_OK && st.ours == 0); /* another serial: not ours */ + { + /* what FAT drivers change in normal use leaves it ours; any other change is named */ + uint8_t s0[BS]; + CHECK(disk_read(&p.dev, 0, 1, s0) == DISK_OK); + uint32_t rsv = (uint32_t)s0[14] | (uint32_t)s0[15] << 8, fatsz; + memcpy(&fatsz, s0 + 36, 4); + uint32_t efi = rsv + 2u * fatsz + 1u, boot_entry = 64u + 13u; /* EFI dir, BOOT's DIR_CrtTimeTenth */ + CHECK(driver_marks(&p, rsv, fatsz) == 0); + CHECK(ck_fatb_state_read(&p.dev, serial, &st) == CK_FATB_OK && st.ours && st.slot == 0 && st.image_len == len1); + CHECK(poke(&p, efi, boot_entry, 0x01) == 0); + CHECK(ck_fatb_state_read(&p.dev, serial, &st) == CK_FATB_OK && !st.ours && st.where && + !strcmp(st.where, "EFI") && st.at == boot_entry && st.got == 1 && st.want == 0); + CHECK(poke(&p, efi, boot_entry, 0x01) == 0 && driver_marks(&p, rsv, fatsz) == 0); /* back as written */ + CHECK(ck_fatb_state_read(&p.dev, serial, &st) == CK_FATB_OK && st.ours && st.slot == 0); + /* Apple sets ATTR_ARCHIVE on the root's EFI directory during boot. */ + CHECK(poke(&p, efi - 1u, 32u + 11u, 0x20) == 0); + CHECK(ck_fatb_state_read(&p.dev, serial, &st) == CK_FATB_OK && st.ours && st.slot == 0); + /* ... and stamps it written (real machine: root byte 54 = 0x82); a + * file entry's stamp is not taken over */ + CHECK(poke(&p, efi - 1u, 32u + 22u, 0x82) == 0 && poke(&p, efi - 1u, 32u + 25u, 0x5a) == 0); + CHECK(ck_fatb_state_read(&p.dev, serial, &st) == CK_FATB_OK && st.ours && st.slot == 0); + CHECK(poke(&p, efi - 1u, 32u + 22u, 0x82) == 0 && poke(&p, efi - 1u, 32u + 25u, 0x5a) == 0); + CHECK(poke(&p, efi - 1u, 22u, 0x01) == 0); /* the volume label entry: strict */ + CHECK(ck_fatb_state_read(&p.dev, serial, &st) == CK_FATB_OK && !st.ours && st.at == 22u); + CHECK(poke(&p, efi - 1u, 22u, 0x01) == 0); + /* The directory type is still structural, even with ARCHIVE set. */ + CHECK(poke(&p, efi - 1u, 32u + 11u, 0x10) == 0); + CHECK(ck_fatb_state_read(&p.dev, serial, &st) == CK_FATB_OK && !st.ours && st.where && + !strcmp(st.where, "root") && st.at == 43u); + CHECK(poke(&p, efi - 1u, 32u + 11u, 0x10) == 0); + /* Do not ignore archive bits in the volume label or unused entries. */ + CHECK(poke(&p, efi - 1u, 11u, 0x20) == 0); + CHECK(ck_fatb_state_read(&p.dev, serial, &st) == CK_FATB_OK && !st.ours); + CHECK(poke(&p, efi - 1u, 11u, 0x20) == 0); + CHECK(poke(&p, efi - 1u, 64u + 11u, 0x20) == 0); + CHECK(ck_fatb_state_read(&p.dev, serial, &st) == CK_FATB_OK && !st.ours); + CHECK(poke(&p, efi - 1u, 64u + 11u, 0x20) == 0); + CHECK(ck_fatb_state_read(&p.dev, serial, &st) == CK_FATB_OK && st.ours && st.slot == 0); + } + CHECK(export_part(&p, "part1.img") == 0 && spill("img1.bin", img1, len1) == 0); + CHECK(install(&f, &p, 0, man1, img1, len1, &r, &wrote) == CK_FATB_OK && !r.written && r.slot == 0 && wrote == 0); + static uint8_t big[1]; + CHECK(install(&f, &p, 0, man1, big, st.slot_max + 1u, &r, &wrote) == CK_FATB_EBIG && wrote == 0); + + /* 3. power cuts while img2 replaces img1 */ + uint8_t *base = malloc(p.blocks * BS); + if (!base) + return 2; + CHECK(pread(f.fd, base, p.blocks * BS, (off_t)(p.first_lba * BS)) == (ssize_t)(p.blocks * BS)); + uint64_t total = 0; + CHECK(install(&f, &p, 0, man2, img2, len2, &r, &total) == CK_FATB_OK && r.written && r.slot == 1); + int last = 0, bad = 0, switches = 0; + uint64_t first_new = 0; + for (uint64_t cut = 0; cut <= total; cut += cut < 16 || total - cut < 16 ? 1 : total / 97 + 1) { + if (pwrite(f.fd, base, p.blocks * BS, (off_t)(p.first_lba * BS)) != (ssize_t)(p.blocks * BS)) + bad++; + disk_file_arm_cut(&f, cut); + int rc = install(&f, &p, 0, man2, img2, len2, &r, 0); + disk_file_disarm(&f); + if (rc == CK_FATB_OK && cut < total) /* a cut is always reported (at the very end only the flush is lost) */ + bad++; + int now = -1; + if (ck_fatb_state_read(&p.dev, serial, &st) == CK_FATB_OK && st.ours) { + uint64_t w; + if (st.slot == 0 && install(&f, &p, 0, man1, img1, len1, &r, &w) == CK_FATB_OK && !r.written && !w) + now = 0; + else if (st.slot == 1 && install(&f, &p, 0, man2, img2, len2, &r, &w) == CK_FATB_OK && !r.written && !w) + now = 1; + } + if (now < 0 || now < last) { + printf(" cut after %llu of %llu blocks: %s\n", (unsigned long long)cut, (unsigned long long)total, + now < 0 ? "neither kernel whole" : "back to the old kernel"); + bad++; + } + if (now == 1 && last == 0) { + switches++; + first_new = cut; + } + last = now < 0 ? last : now; + if (install(&f, &p, 0, man2, img2, len2, &r, 0) != CK_FATB_OK) + bad++; /* the next start installs it whole */ + } + /* the exact switch: one block before it the old kernel, at it the new */ + uint64_t lo = 0, hi = first_new; + while (lo + 1 < hi) { + uint64_t mid = (lo + hi) / 2; + if (pwrite(f.fd, base, p.blocks * BS, (off_t)(p.first_lba * BS)) != (ssize_t)(p.blocks * BS)) + bad++; + disk_file_arm_cut(&f, mid); + install(&f, &p, 0, man2, img2, len2, &r, 0); + disk_file_disarm(&f); + if (ck_fatb_state_read(&p.dev, serial, &st) == CK_FATB_OK && st.slot == 1) + hi = mid; + else + lo = mid; + } + printf("note: replacing the kernel writes %llu blocks; the firmware's view switches after block %llu " + "(one directory sector); cut points tried with neither kernel whole: %d\n", + (unsigned long long)total, (unsigned long long)hi, bad); + CHECK(bad == 0 && switches == 1 && hi > 0); + CHECK(pwrite(f.fd, base, p.blocks * BS, (off_t)(p.first_lba * BS)) == (ssize_t)(p.blocks * BS)); + CHECK(install(&f, &p, 0, man2, img2, len2, &r, 0) == CK_FATB_OK && r.written && r.slot == 1); + CHECK(export_part(&p, "part2.img") == 0 && spill("img2.bin", img2, len2) == 0); + CHECK(install(&f, &p, 0, man1, img1, len1, &r, 0) == CK_FATB_OK && r.written && r.slot == 0); + CHECK(export_part(&p, "part3.img") == 0); + free(base); + disk_file_close(&f); + + /* someone else's EFI System Partition is not ours */ + gw_part foreign[1] = {{gw_esp_type, 1 * MIB, 65 * MIB - 1u, "AIENOS boot", 0}}; + CHECK(gw_write(g_path, BS, disk, foreign, 1, 0) == 0); + CHECK(disk_file_open(&f, &d, g_path, BS, 0, 0) == 0); + CHECK(ck_gpt_find_type(&d, ck_esp_part_type, &p, &gi) == CK_GPT_OK && ck_gpt_is_ours(&d, &esp, gi.part_index) == 0); + CHECK(ck_gpt_add(&d, &esp, 64 * MIB, MIB, &a) == CK_GPT_OK && a.created == 0); /* reported, never a second */ + disk_file_close(&f); + + /* 4. time stamps */ + uint16_t dd, tt; + ck_fatb_dos_time(1792303183u, &dd, &tt); /* 2026-10-18 05:59:43 UTC */ + CHECK(dd == 23890 && tt == 12149); + ck_fatb_dos_time(1709251199u, &dd, &tt); /* 2024-02-29 23:59:59 UTC */ + CHECK(dd == 22621 && tt == 49021); + ck_fatb_dos_time(0, &dd, &tt); + CHECK(dd == 0x21 && tt == 0); + + free(img1); + free(img2); + printf("fat boot: %d checks, %d failures\n", checks, failures); + return failures ? 1 : 0; +} diff --git a/native/kernel/x86/efi_x86.c b/native/kernel/x86/efi_x86.c index 3a994d93..3b062799 100644 --- a/native/kernel/x86/efi_x86.c +++ b/native/kernel/x86/efi_x86.c @@ -21,10 +21,14 @@ * It finds the ACPI 2.0 RSDP and the GOP framebuffer (boot/efi_gop.c), takes * the final memory map, leaves boot services (retrying when the map key goes * stale) and jumps to ck_x86_kernel_entry. It never calls a runtime service. + * When the network loader started it, it keeps the loader's struct nb_pass + * (boot/netboot_proto.h, from LoadOptions) and drops its object unless that + * lies wholly in EfiLoaderData of the final memory map. * x86 meaning of the AArch64-named fields: firmware_el = CPL (0), * firmware_ttbr0 = CR3, firmware_sctlr = CR0, uefi_entry_ticks = TSC, * counter_freq_hz = 0 (the kernel measures the TSC itself). */ #include "../../boot/efi.h" +#include "../../boot/netboot_proto.h" #include "../core/ck_internal.h" #include "x86.h" @@ -37,12 +41,54 @@ void ck_boot_gop_find(EFI_SYSTEM_TABLE *st, struct ck_handoff *h); static uint64_t map_buf[MAP_BYTES / 8]; static struct ck_handoff handoff; +static struct nb_pass pass; /* from the network loader, when it started this kernel */ +static int pass_state; /* 0 none, 1 taken, 2 taken but its object was not in loader memory (dropped) */ + +const struct nb_pass *ck_x86_netldr_pass(int *object_dropped) +{ + if (object_dropped) + *object_dropped = pass_state == 2; + return pass_state ? &pass : 0; +} + +/* The loader's object must lie wholly inside one EfiLoaderData range of the + * final memory map (pages nothing in this kernel allocates from). */ +static int in_loader_data(const struct ck_handoff *h, uint64_t a, uint64_t n) +{ + for (uint64_t off = 0; off + h->desc_size <= h->map_size; off += h->desc_size) { + const EFI_MEMORY_DESCRIPTOR *m = (const void *)((const uint8_t *)map_buf + off); + uint64_t bytes = m->NumberOfPages * 4096u; + if (m->Type == 2 && a >= m->PhysicalStart && n <= bytes && a - m->PhysicalStart <= bytes - n) + return 1; + } + return 0; +} static int guid_eq(const EFI_GUID *a, const EFI_GUID *b) { return memcmp(a, b, sizeof *a) == 0; } +/* The night's empty sky (ui/night.c, no stars yet: about 2, 2, 6) over the + * whole screen, before ExitBootServices: the firmware's own shutdown takes + * about 1.2 s on the real machine, and the firmware's picture should not be + * what is seen meanwhile. Eight bytes at a time, two pixels per store. */ +static void night_ground(const struct ck_handoff *h) +{ + if (h->fb_status != CK_HANDOFF_FB_PRESENT || !h->fb_base || h->fb_pitch < h->fb_width || + (uint64_t)h->fb_pitch * h->fb_height * 4u > h->fb_size) + return; + uint64_t px = h->fb_format == CK_HANDOFF_FB_BGRX ? 0x00020206u : 0x00060202u; + px |= px << 32; + for (uint32_t y = 0; y < h->fb_height; y++) { + volatile uint64_t *row = (volatile uint64_t *)(uintptr_t)(h->fb_base + (uint64_t)y * h->fb_pitch * 4u); + for (uint32_t x = 0; x + 1u < h->fb_width; x += 2u) + row[x / 2u] = px; + if (h->fb_width & 1u) + ((volatile uint32_t *)row)[h->fb_width - 1u] = (uint32_t)px; + } +} + EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *st) { struct ck_handoff *h = &handoff; @@ -61,10 +107,18 @@ EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *st) ck_x86_com1_probe(); if (st->BootServices->SetWatchdogTimer) st->BootServices->SetWatchdogTimer(0, 0, 0, 0); + static const EFI_GUID li_guid = EFI_LOADED_IMAGE_PROTOCOL_GUID_INIT; + EFI_LOADED_IMAGE_PROTOCOL *li = 0; + if (st->BootServices->HandleProtocol(image, &li_guid, (void **)&li) == EFI_SUCCESS && li && li->LoadOptions && + li->LoadOptionsSize == sizeof pass && !memcmp(li->LoadOptions, NB_PASS_MAGIC, 8)) { + memcpy(&pass, li->LoadOptions, sizeof pass); + pass_state = 1; + } static const EFI_GUID acpi20 = EFI_ACPI_20_TABLE_GUID_INIT; for (uint64_t i = 0; i < st->NumberOfTableEntries; i++) if (guid_eq(&st->ConfigurationTable[i].VendorGuid, &acpi20)) h->rsdp = (uint64_t)(uintptr_t)st->ConfigurationTable[i].VendorTable; + ck_x86_step("start"); ck_puts("AIENOS-KERNEL-0\n"); ck_printf("report_kind: pre_exit\naienos_commit: %s\n", ck_commit()); @@ -77,6 +131,9 @@ EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *st) ck_printf("firmware_vendor: %s\nfirmware_revision: 0x%x\n", v, st->FirmwareRevision); ck_printf("firmware_cpl: %u\n", h->firmware_el); ck_boot_gop_find(st, h); + ck_x86_step("gop"); + night_ground(h); + ck_x86_step("paint"); ck_printf("acpi_rsdp: 0x%llx\n", (unsigned long long)h->rsdp); ck_printf("image: 0x%llx-0x%llx\n", (unsigned long long)h->image_base, (unsigned long long)h->image_end); ck_puts("exiting firmware boot services\n"); @@ -105,5 +162,10 @@ EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *st) EXIT_TRIES); return s; } + ck_x86_step("exit"); + if (pass_state && pass.object && !in_loader_data(h, pass.object, pass.object_len)) { + pass.object = pass.object_len = 0; + pass_state = 2; + } ck_x86_kernel_entry(h); } diff --git a/native/kernel/x86/kmain_x86.c b/native/kernel/x86/kmain_x86.c index 0a8b96e8..79f301dd 100644 --- a/native/kernel/x86/kmain_x86.c +++ b/native/kernel/x86/kmain_x86.c @@ -49,6 +49,7 @@ #include "../svc/allen_reply.h" #include "../ui/allen_ui.h" #include "x86.h" +#include "../../boot/netboot_proto.h" #ifndef AIENOS_COMMIT #define AIENOS_COMMIT "unknown" @@ -291,6 +292,19 @@ static void acpi_reset(void) static int allen_on; static uint64_t allen_bye; /* TSC when Allen said goodbye; 0 = still talking */ static uint64_t allen_woke; /* TSC when Allen's window took the screen */ + +#define STEP_MAX 16 +static struct { + const char *name; + uint64_t tsc; +} steps[STEP_MAX]; +static unsigned nsteps; + +void ck_x86_step(const char *name) +{ + if (nsteps < STEP_MAX) + steps[nsteps].name = name, steps[nsteps++].tsc = ck_rdtsc(); +} static void night_stats(const char *when); static ck_allen_facts allen_facts; /* filled at the summary line */ static ck_allen_mind allen_mind; @@ -437,12 +451,45 @@ static void night_stats(const char *when) draw_on ? "a secondary core" : "the boot core"); } +/* Time since the power button for each step. The TSC counts from power-on + * (and from every reset), so its value at a step is the time since then: + * firmware until the loader (or this kernel) starts, the loader, this kernel + * until Allen's window takes the screen and the keyboard. */ +static void boot_times(void) +{ + const struct nb_pass *np = ck_x86_netldr_pass(0); + uint64_t per_ms = tsc_hz / 1000u, entry = hand->uefi_entry_ticks; + if (!per_ms) + return; + if (np) + ck_printf("boot_time: since power on: firmware until the loader %llu ms, loader %llu ms, kernel %llu ms; " + "Allen's window at %llu ms\n", (unsigned long long)(np->loader_tsc / per_ms), + (unsigned long long)((entry - np->loader_tsc) / per_ms), + (unsigned long long)((allen_woke - entry) / per_ms), (unsigned long long)(allen_woke / per_ms)); + else + ck_printf("boot_time: since power on: firmware until this kernel %llu ms (no loader), kernel %llu ms; " + "Allen's window at %llu ms\n", (unsigned long long)(entry / per_ms), + (unsigned long long)((allen_woke - entry) / per_ms), (unsigned long long)(allen_woke / per_ms)); + /* each step of this kernel, and when the night reached the screen */ + static char line[240]; /* the report keeps lines up to 240 characters */ + uint64_t prev = entry; + int n = ck_snprintf(line, sizeof line, "boot_time: steps in ms:"); + for (unsigned k = 0; k < nsteps && n > 0 && (size_t)n < sizeof line; k++) { + n += ck_snprintf(line + n, sizeof line - (size_t)n, " %s %llu", steps[k].name, + (unsigned long long)((steps[k].tsc - prev) / per_ms)); + prev = steps[k].tsc; + } + ck_printf("%s window %llu; the night on screen at %llu ms\n", line, (unsigned long long)((allen_woke - prev) / per_ms), + night_t0 ? (unsigned long long)(night_t0 / per_ms + night_ms) : 0ull); +} + static void allen_window(void) { static char footer[64]; volatile uint32_t *px; uint32_t w, h, pitch, format; uint64_t pa; + ck_x86_step("keyboard"); ck_allen_mind_init(&allen_mind, &allen_facts); allen_mind.notes = &allen_notes; if (ck_x86_memory_open(&allen_mind.mem, &allen_notes, tsc_hz)) { @@ -454,6 +501,7 @@ static void allen_window(void) allen_notes.n = 0; /* nothing half-loaded is kept */ allen_mind.mem.nnotes = 0; } + ck_x86_step("memory"); ck_x86_kbd_sink(0, allen_line); if (ck_x86_console_fb_get(&px, &w, &h, &pitch, &format)) { ck_puts("screen: text only (no framebuffer for Allen's window)\n"); @@ -485,6 +533,7 @@ static void allen_window(void) ck_x86_kbd_sink(allen_edit, allen_line); allen_on = 1; allen_woke = ck_rdtsc(); + boot_times(); night_stats("before Allen woke"); allen_map(); /* the notes loaded from disk, before the first word */ const char *hello = ck_allen_welcome(&allen_mind); @@ -1321,7 +1370,9 @@ static __attribute__((noreturn)) void kernel_main(void *arg) (void)arg; const struct ck_handoff *h = hand; tsc_measure(); /* first: the night runs on this clock */ + ck_x86_step("clock"); night_start(h); + ck_x86_step("night"); if (h->fb_status == CK_HANDOFF_FB_PRESENT && mm.fb_ok) { uint32_t scale, cols, rows; if (ck_x86_console_fb_on((volatile void *)(uintptr_t)h->fb_base, h->fb_width, h->fb_height, @@ -1399,6 +1450,7 @@ static __attribute__((noreturn)) void kernel_main(void *arg) struct apic_report ar = {0}; madt_walk(&ar); apic_start(&ar); + ck_x86_step("timer"); ck_printf("apic: mode=%s id=%u version=0x%x timer_hz=%u\n", "xapic", ar.id, ar.version, ar.lapic_hz); ck_printf("madt: cpus=%u ioapics=%u ioapic_lines_masked=%u\n", ar.cpus, ar.ioapics, ar.ioapic_lines); @@ -1411,6 +1463,7 @@ static __attribute__((noreturn)) void kernel_main(void *arg) struct smp_report sr = {0}; smp_start(&ar, &sr); + ck_x86_step("cores"); if (sr.why) { ck_printf("smp: cpus=%u started=0 (%s)\n", sr.listed, sr.why); } else { @@ -1426,7 +1479,9 @@ static __attribute__((noreturn)) void kernel_main(void *arg) const struct ck_x86_storage_result *st = ck_x86_storage(h->rsdp, &frames, tsc_hz, mm.top); ck_x86_sound(&frames, tsc_hz, night_t0); /* before the keyboard: the chirp is already under way */ + ck_x86_step("sound"); ck_x86_usb(&frames, tsc_hz); + ck_x86_step("usb"); allen_facts.cores = sr.started + 1; allen_facts.sata_disks = st->ahci_disks; allen_facts.nvme_disks = st->nvme_disks; @@ -1438,6 +1493,7 @@ static __attribute__((noreturn)) void kernel_main(void *arg) : st->net_driver == 2 ? "driver-failed" : st->net_link == 1 ? "link-up" : st->net_link == 2 ? "link-down" + : st->net_link == 3 ? "link-pending" : "seen"); ck_puts("AIENOS-KERNEL-0 DONE\n"); ck_puts("note: QEMU qualifies nothing physical\n"); @@ -1461,5 +1517,6 @@ void ck_x86_kernel_entry(struct ck_handoff *h) ck_panic("handoff: %s", why); ck_puts("handoff: CHANDOF3 ok\n"); mm_build(); + ck_x86_step("paging"); ck_x86_call_on_stack(kernel_main, 0, (uint64_t)(uintptr_t)(kstack + sizeof kstack)); } diff --git a/native/kernel/x86/memory_x86.c b/native/kernel/x86/memory_x86.c index 156e2061..c2ea398c 100644 --- a/native/kernel/x86/memory_x86.c +++ b/native/kernel/x86/memory_x86.c @@ -15,7 +15,10 @@ * installer instead, on the disk its owner picks there; * 3. every partition of the chosen disk is listed ("ahci_part:"), a record * of the layout as found; - * 4. the write range is set to the units of the section Allen uses (the two + * 4. the boot section beside it (boot_section below): the network loader's + * verified kernel installed as \EFI\BOOT\BOOTX64.EFI so the disk starts + * AIENOS by itself; + * 5. the write range is set to the units of the section Allen uses (the two * memory copies and the note units, svc/allen_memory.h) and nothing * else; the newest valid copy is loaded, then the notes it counts. * NVMe disks are never written (no write path exists). With no usable disk @@ -26,9 +29,16 @@ #include "../svc/allen_memory.h" #include "disk_part.h" #include "gpt_add.h" +#include "fat_boot.h" +#include "aienos_sig.h" +#include "../../boot/netboot_proto.h" +#include "../../boot/slot_format.h" #include "x86.h" #define ALLEN_PART_MIB 1024u +#define BOOT_PART_MIB 256u + +static const ck_gpt_new boot_spec = {ck_esp_part_type, "AIENOS boot", "aienos.boot.v1"}; /* Disks whose owner approved adding Allen's section to them. */ static const char *const approved_disks[] = {"APPLE HDD ST1000DM003", 0}; @@ -95,6 +105,118 @@ static int add_section(const disk_dev *d, const ck_gpt_info *gi) return 1; } +/* The boot section beside Allen's (dev/fat_boot.h), on the same disk: when the + * network loader handed over a verified kernel, that kernel is installed as + * \EFI\BOOT\BOOTX64.EFI, so the next start needs no stick and no network + * (Drake approved a small boot section in free space on this disk, + * 2026-10-17). Its SHA-512 is checked again here against the signed + * manifest. A disk that already has another system's EFI System Partition is + * never touched. Without a handed-over kernel only what is there is reported. + * Writes happen only inside the windows opened here and closed right after: + * the GPT blocks while the partition is added, then the partition itself. */ +static uint32_t boot_serial(const ck_part *bp) +{ + return (uint32_t)(bp->first_lba ^ bp->first_lba >> 32) * 2654435761u ^ 0x41494e42u; +} + +static void boot_section(const disk_dev *d) +{ + int dropped = 0; + const struct nb_pass *np = ck_x86_netldr_pass(&dropped); + const uint8_t *obj = np && np->object ? (const uint8_t *)(uintptr_t)np->object : 0; + ck_part bp; + ck_gpt_info gi; + ck_fatb_state st; + if (dropped) + ck_puts("boot_disk: the loader named a kernel outside its own memory; ignored\n"); + int rc = ck_gpt_find_type(d, ck_esp_part_type, &bp, &gi); + if (rc == CK_GPT_OK && ck_gpt_is_ours(d, &boot_spec, gi.part_index) != 1) { + ck_puts("boot_disk: this disk already has another system's boot section; not touched\n"); + return; + } + if (rc != CK_GPT_OK && rc != CK_GPT_ENOPART) { + ck_printf("boot_disk: %s; not touched\n", ck_gpt_add_strerror(rc)); + return; + } + if (!obj) { + if (rc == CK_GPT_ENOPART) + ck_puts("boot_disk: no boot section yet (made when the network loader starts a kernel)\n"); + else if ((rc = ck_fatb_state_read(&bp.dev, boot_serial(&bp), &st)) != CK_FATB_OK) + ck_printf("boot_disk: the boot section could not be read (%s)\n", ck_fatb_strerror(rc)); + else if (!st.ours) + ck_printf("boot_disk: the boot section is not as AIENOS wrote it: %s byte %u is 0x%02x, not 0x%02x\n", + st.where, st.at, st.got, st.want); + else if (st.slot >= 0) + ck_printf("boot_disk: \\EFI\\BOOT\\BOOTX64.EFI on disk %u: %u bytes (slot %c)\n", disk_index, + st.image_len, 'A' + st.slot); + else + ck_puts("boot_disk: the boot section holds no complete kernel\n"); + return; + } + const struct ck_slot_manifest *m = (const void *)obj; + if (np->object_len <= CK_SLOT_UNIT || memcmp(m->magic, CK_SLOT_MANIFEST_MAGIC, 8) || + m->image_len != np->object_len - CK_SLOT_UNIT) { + ck_puts("boot_disk: the loader's object is not a manifest and its image; nothing installed\n"); + return; + } + uint64_t t0 = ck_rdtsc(); + uint8_t dig[AIENOS_SHA512_DIGEST_LEN]; + aienos_sha512(obj + CK_SLOT_UNIT, (size_t)m->image_len, dig); + if (memcmp(dig, m->image_sha512, sizeof dig)) { + ck_puts("boot_disk: the kernel's SHA-512 differs from its signed manifest; nothing installed\n"); + return; + } + if (rc == CK_GPT_ENOPART && d->block_size != 512u) { + ck_printf("boot_disk: %u-byte sectors: the boot section handles 512 only; nothing added\n", d->block_size); + return; + } + if (rc == CK_GPT_ENOPART) { + uint64_t per_mib = (1024u * 1024u) / d->block_size; + ck_gpt_added a; + if (ck_x86_ahci_allow(disk_index, 1, gi.first_usable - 1u) || + ck_x86_ahci_allow(disk_index, gi.last_usable + 1u, gi.last_lba)) + rc = CK_GPT_EWRITE; + else + rc = ck_gpt_add(d, &boot_spec, (uint64_t)BOOT_PART_MIB * per_mib, per_mib, &a); + ck_x86_ahci_allow_none(disk_index); + if (rc) { + ck_printf("boot_disk: boot section not added: %s%s\n", ck_gpt_add_strerror(rc), + rc == CK_GPT_EWRITE || rc == CK_GPT_EVERIFY ? " (the GPT may need a look)" : "; nothing was written"); + return; + } + ck_printf("boot_disk: boot section added, entry %u, first_lba=%llu last_lba=%llu (%u MiB, EFI System " + "Partition); the existing partitions were not touched\n", a.index, (unsigned long long)a.first, + (unsigned long long)a.last, BOOT_PART_MIB); + if ((rc = ck_gpt_find_type(d, ck_esp_part_type, &bp, &gi))) { + ck_printf("boot_disk: %s after adding it\n", ck_gpt_add_strerror(rc)); + return; + } + } + uint16_t dd, tt; + ck_fatb_dos_time(m->timestamp, &dd, &tt); + ck_fatb_result r; + if (ck_x86_ahci_allow(disk_index, bp.first_lba, bp.first_lba + bp.blocks - 1u)) + rc = CK_FATB_EIO; + else + rc = ck_fatb_install(&bp.dev, boot_serial(&bp), 1, obj, obj + CK_SLOT_UNIT, (uint32_t)m->image_len, dd, tt, + &r); + ck_x86_ahci_allow_none(disk_index); + char commit[13]; + memcpy(commit, m->commit, 12); + commit[12] = 0; + uint64_t ms = hz ? (ck_rdtsc() - t0) * 1000 / hz : 0; + if (rc) + ck_printf("boot_disk: install FAILED: %s; the computer still starts from the stick\n", ck_fatb_strerror(rc)); + else if (!r.written) + ck_printf("boot_disk: this kernel (commit %s, generation %llu) is already \\EFI\\BOOT\\BOOTX64.EFI (slot %c); " + "nothing written\n", commit, (unsigned long long)m->generation, 'A' + r.slot); + else + ck_printf("boot_disk: installed this kernel (commit %s, generation %llu, %llu bytes) as \\EFI\\BOOT\\BOOTX64.EFI, " + "slot %c%s, %u blocks in %llu ms, read back exact; the computer can now start without the stick\n", + commit, (unsigned long long)m->generation, (unsigned long long)m->image_len, 'A' + r.slot, + r.formatted ? ", new FAT32 volume" : "", r.sectors_written, (unsigned long long)ms); +} + int ck_x86_memory_open(ck_allen_memory *mem, ck_allen_notes *notes, uint64_t tsc_hz) { hz = tsc_hz; @@ -141,6 +263,8 @@ int ck_x86_memory_open(ck_allen_memory *mem, ck_allen_notes *notes, uint64_t tsc ck_printf("allen_memory: AIENOS partition found, entry %u, first_lba=%llu last_lba=%llu\n", gi.part_index, (unsigned long long)part.first_lba, (unsigned long long)(part.first_lba + part.blocks - 1u)); + boot_section(d); + uint64_t units = (uint64_t)CK_ALLEN_DISK_UNITS * CK_ALLEN_MEM_UNIT / d->block_size; if (part.blocks < units || ck_x86_ahci_allow(disk_index, part.first_lba, part.first_lba + units - 1u)) return no_memory("could not open Allen's section for writing"); diff --git a/native/kernel/x86/pci_x86.c b/native/kernel/x86/pci_x86.c index acd260e9..f4377f0c 100644 --- a/native/kernel/x86/pci_x86.c +++ b/native/kernel/x86/pci_x86.c @@ -223,8 +223,9 @@ static void net_look(const struct pfn *f) bmsr & 0x20 ? 1u : 0u); } -/* Drives the BCM57766 (tg3_x86.c) and waits up to 8 s for the link, so the - * summary and the report can say whether the network is up. */ +/* Drives the BCM57766 (tg3_x86.c) and looks at the link once. Nothing at + * start-up waits for it (autonegotiation takes seconds); the report, the only + * user of the network, polls the link itself during the hold. */ static void net_drive(const struct pfn *f, struct ck_frames *fr) { uint32_t lo = cr32(f->cfg, 0x10), hi = (lo & 6) == 4 ? cr32(f->cfg, 0x14) : 0; @@ -236,15 +237,9 @@ static void net_drive(const struct pfn *f, struct ck_frames *fr) return; } res.net_driver = 1; - uint64_t t0 = ck_rdtsc(); - while (!ck_x86_tg3_link() && ck_rdtsc() - t0 < 8 * g_tsc_hz) { - uint64_t t1 = ck_rdtsc(); - while (ck_rdtsc() - t1 < g_tsc_hz / 4) - ck_pause(); - } - res.net_link = ck_x86_tg3_link() ? 1 : 2; + res.net_link = ck_x86_tg3_link() ? 1 : 3; if (res.net_link != 1) - ck_puts("net_tg3: no link after 8 s (cable unplugged?); the report is sent if it comes up during the hold\n"); + ck_puts("net_tg3: link not up yet (autonegotiation under way, or no cable); the report goes out once it is\n"); } /* Brings a function to D0 through its power management capability, if it has @@ -414,15 +409,18 @@ const struct ck_x86_storage_result *ck_x86_storage(uint64_t rsdp, struct ck_fram res.ahci_ctrls++; } res.ahci_disks = ck_x86_ahci_disks(); + ck_x86_step("disk"); for (unsigned i = 0; i < nfound; i++) if (found[i].cls == 0x010802 && (found[i].ht & 0x7f) == 0) nvme_start(&found[i], fr); + ck_x86_step("nvme"); for (unsigned i = 0; i < nfound; i++) if ((found[i].cls >> 8) == 0x0200 && (found[i].ht & 0x7f) == 0) net_look(&found[i]); for (unsigned i = 0; i < nfound; i++) if ((found[i].cls >> 8) == 0x0200 && (found[i].ht & 0x7f) == 0 && !res.net_driver) net_drive(&found[i], fr); + ck_x86_step("network"); if (!res.net_found) ck_puts("net: no Ethernet controller\n"); ck_printf("storage: pci_functions=%u ahci_controllers=%u disks=%u nvme_controllers=%u nvme_disks=%u " diff --git a/native/kernel/x86/report_x86.c b/native/kernel/x86/report_x86.c index cbacdb5f..d0d2e3af 100644 --- a/native/kernel/x86/report_x86.c +++ b/native/kernel/x86/report_x86.c @@ -56,18 +56,19 @@ /* The allowlist: every key the iMac kernel prints (the x86 sources, efi_gop.c, * the disk report's ahci_/nvme_ _read and _gpt lines, and Allen's memory - * status "allen_memory:", which carries only counts and the disk layout), + * status "allen_memory:", which carries only counts and the disk layout, + * and "boot_disk:" / "boot_time:", only sizes, commit ids and milliseconds), * minus "memory:", which describes the kernel's own memory layout, and * minus what is said to Allen ("keyboard_line:" and "allen:"): the conversation never leaves the * iMac; "screen: Allen answered" carries only lengths. A new key stays off the * report until it is added here. */ static const char *const allowed_keys[] = { "acpi_rsdp", "ahci", "ahci_disk", "ahci_gpt", "ahci_part", "ahci_port", "ahci_read", "ahci_write", - "aienos_commit", "allen_memory", "apic", "cpu", "descriptors", "exit_boot_services", "firmware_cpl", - "firmware_revision", "firmware_vendor", "gop", "guard_page", "handoff", "image", "kernel", "kernel_impl", - "keyboard", "madt", "net", "net_tg3", "note", "nvme", "nvme_disk", "nvme_gpt", "nvme_read", "paging", "panic", - "pci", "power", "ram", "report", "report_kind", "screen", "smp", "sound", "stack", "storage", "summary", "timebase", - "timer_irq", "timer_stats", "usb", "xhci", + "aienos_commit", "allen_memory", "apic", "boot_disk", "boot_time", "cpu", "descriptors", "exit_boot_services", + "firmware_cpl", "firmware_revision", "firmware_vendor", "gop", "guard_page", "handoff", "image", "kernel", + "kernel_impl", "keyboard", "madt", "net", "net_tg3", "note", "nvme", "nvme_disk", "nvme_gpt", "nvme_read", "paging", + "panic", "pci", "power", "ram", "report", "report_kind", "screen", "smp", "sound", "stack", "storage", "summary", + "timebase", "timer_irq", "timer_stats", "usb", "xhci", }; static const char *const allowed_lines[] = { "AIENOS-KERNEL-0", diff --git a/native/kernel/x86/x86.h b/native/kernel/x86/x86.h index 46014304..21a6aede 100644 --- a/native/kernel/x86/x86.h +++ b/native/kernel/x86/x86.h @@ -124,7 +124,7 @@ void ck_x86_console_fb_show(void); struct ck_frames; struct ck_x86_storage_result { unsigned pci_functions, ahci_ctrls, ahci_disks, nvme_ctrls, nvme_disks, gpt_valid; - unsigned net_found, net_link; /* net_link: 0 not read, 1 up, 2 down */ + unsigned net_found, net_link; /* net_link: 0 not read, 1 up, 2 down, 3 not up yet (driver running) */ unsigned net_driver; /* 0 not tried, 1 running, 2 failed */ }; const struct ck_x86_storage_result *ck_x86_storage(uint64_t rsdp, struct ck_frames *fr, uint64_t tsc_hz, @@ -142,9 +142,21 @@ int ck_x86_ahci_allow(unsigned index, uint64_t first, uint64_t last); /* Closes every write range of the disk. */ void ck_x86_ahci_allow_none(unsigned index); +/* efi_x86.c: what the network loader handed this kernel (boot/netboot_proto.h), + * or 0 when it was not started by the loader (the firmware started it from a + * disk, or another loader). *object_dropped: the loader named an object that + * was not in its own memory, so it was ignored. */ +struct nb_pass; +const struct nb_pass *ck_x86_netldr_pass(int *object_dropped); + +/* kmain_x86.c: marks the end of a start-up step (TSC now) for boot_time's + * breakdown; name is a short static string. */ +void ck_x86_step(const char *name); + /* memory_x86.c: Allen's memory and notes on a hard disk (svc/allen_memory.h). * open: finds the disk holding Allen's section (or adds one on an approved - * disk, in unused space), lists its partitions, loads the newest copy into + * disk, in unused space), lists its partitions, installs the network loader's + * verified kernel on the boot section beside it (fat_boot.h), loads the newest copy into * *mem and the notes it counts into *notes. 1 when saves will reach the disk, * 0 when Allen remembers only until power off. save, notes_write (note index, * written before the save that counts it): 0 or -1 (then nothing more is diff --git a/scripts/.crumb b/scripts/.crumb index ec87502b..e1ec69d4 100644 --- a/scripts/.crumb +++ b/scripts/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-31T02:42:46Z", + "compiled_at": "2026-10-31T02:43:29Z", "compiler": "crumb-compile/1", - "digest": "sha256:77ac3f146e84c4b49982d46d81c24d3feb723b1e17bfcf5c5876c9dc29fe0807", + "digest": "sha256:5b000b2f77cd62ae8ad2a113a1f77e486e3c974ad5ecc89150e6e54ad714a781", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 131, - "generated_at_commit": "47faeddadfb49c9e84f9d1058547f7bb0ef45d1d", - "source_tree": "sha256:a64bdf787f95b790030cec694daeb9d19f3dfa3b334c36436b80ab787cc688d0" + "files": 133, + "generated_at_commit": "00e555f6296726b12cbcb226b4de58838540c2be", + "source_tree": "sha256:faa99151e464c03feaef7f07143105e27823030748f91212f4ec2c36bfccb0a3" }, "owner_lane": "", "provenance": { diff --git a/scripts/ck_fat_boot_test.sh b/scripts/ck_fat_boot_test.sh new file mode 100755 index 00000000..c9a924c2 --- /dev/null +++ b/scripts/ck_fat_boot_test.sh @@ -0,0 +1,36 @@ +#!/bin/sh +# ck_fat_boot_test.sh -- host test of the AIENOS boot section: the EFI System +# Partition added in unused space (native/kernel/dev/gpt_add.c) and the FAT32 +# volume holding \EFI\BOOT\BOOTX64.EFI (native/kernel/dev/fat_boot.c), with +# power cuts. See native/kernel/dev/tests/fat_boot_test.c. The volumes it +# writes are then read by outside tools as judges: fsck.fat must find nothing +# to repair and mtools must read back BOOTX64.EFI byte for byte. Hosted only. +# Ends with "AIENOS_FAT_BOOT: PASS" or "AIENOS_FAT_BOOT: FAIL ". +set -u +cd "$(dirname "$0")/.." +K=native/kernel +N=native +W=$(mktemp -d "${TMPDIR:-/tmp}/ck_fat_boot.XXXXXX") +trap 'rm -rf "$W"' EXIT +fail() { echo "AIENOS_FAT_BOOT: FAIL $*"; exit 1; } +CC=${HOSTCC:-cc} +$CC -std=c11 -D_DEFAULT_SOURCE -O2 -Wall -Wextra -Werror -I$K/dev -I$K/tools -I$N/disk -I$N/argus \ + -o "$W/test" $K/dev/tests/fat_boot_test.c $K/dev/fat_boot.c $K/dev/gpt_add.c $K/dev/disk_part.c \ + $K/tools/gpt_write.c $N/disk/disk.c $N/disk/disk_file.c $N/argus/sha256.c || fail "test does not build" +"$W/test" "$W" || fail "boot section checks" +FSCK=$(command -v fsck.fat || echo /usr/sbin/fsck.fat) +for v in part1 part2 part3; do + "$FSCK" -n "$W/$v.img" >"$W/$v.fsck" 2>&1 || { cat "$W/$v.fsck"; fail "fsck.fat finds faults in $v"; } +done +"$FSCK" -n -v "$W/part1.img" | grep -q "2 FATs, 32 bit entries" || fail "fsck.fat does not see FAT32" +export MTOOLS_SKIP_CHECK=1 +mtype -i "$W/part1.img" ::/EFI/BOOT/BOOTX64.EFI >"$W/got1" || fail "mtools cannot read BOOTX64.EFI (part1)" +cmp -s "$W/got1" "$W/img1.bin" || fail "BOOTX64.EFI read by mtools differs from the image (part1)" +mtype -i "$W/part2.img" ::/EFI/BOOT/BOOTX64.EFI >"$W/got2" || fail "mtools cannot read BOOTX64.EFI (part2)" +cmp -s "$W/got2" "$W/img2.bin" || fail "BOOTX64.EFI read by mtools differs from the image (part2)" +mtype -i "$W/part3.img" ::/EFI/BOOT/BOOTX64.EFI >"$W/got3" || fail "mtools cannot read BOOTX64.EFI (part3)" +cmp -s "$W/got3" "$W/img1.bin" || fail "BOOTX64.EFI read by mtools differs from the image (part3)" +mdir -i "$W/part2.img" -b ::/EFI/BOOT | grep -qx "::/EFI/BOOT/BOOTX64.MAN" || fail "no BOOTX64.MAN" +[ "$(mdir -i "$W/part2.img" -b ::/EFI/BOOT | wc -l)" = 2 ] || fail "\\EFI\\BOOT holds more than the two files" +echo "note: fsck.fat clean on all three volumes; mtools reads BOOTX64.EFI exactly" +echo "AIENOS_FAT_BOOT: PASS" diff --git a/scripts/qemu_ck_imac_bootdisk_test.sh b/scripts/qemu_ck_imac_bootdisk_test.sh new file mode 100755 index 00000000..9cc4bf4e --- /dev/null +++ b/scripts/qemu_ck_imac_bootdisk_test.sh @@ -0,0 +1,212 @@ +#!/usr/bin/env bash +# qemu_ck_imac_bootdisk_test.sh -- QEMU test of the boot section: the network +# loader's verified kernel installs itself on the computer's own hard disk +# (native/kernel/x86/memory_x86.c boot_section, dev/fat_boot.c, dev/gpt_add.c, +# boot/net_loader.c struct nb_pass), and the firmware then starts it from that +# disk with no stick and no network. QEMU is an emulator: a PASS here +# qualifies nothing about any real machine or its firmware. +# +# One q35 + OVMF machine; a fresh firmware variable store for every start (no +# boot entries remembered). The hard disk is ck_gpt_image "one-old" (one +# partition full of a pattern, the rest unused) under the approved model +# "APPLE HDD ST1000DM003". +# start 1 stick (NETLDR.EFI) + network: the server offers the signed +# default kernel; it adds Allen's section and the boot section +# (EFI System Partition, 256 MiB) in unused space, installs itself +# as \EFI\BOOT\BOOTX64.EFI (slot A), reports boot_time; goodbye. +# Host: fsck.fat finds nothing to repair, mtools reads BOOTX64.EFI +# equal to the kernel image, the old partition and the stick are +# byte-identical. +# start 2 the hard disk alone, no network: the firmware starts the kernel +# from it; boot_time says no loader; Allen's memory loads (start 2). +# start 3 stick + network, a second kernel (another commit stamp): it goes +# to slot B. +# start 4 the hard disk alone: the second kernel is the one that runs. +# Final line: AIENOS_IMAC_BOOTDISK: PASS|FAIL|NOT_RUN exit 0 / 1 / 2 (tools) / 3 +set -euo pipefail +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "${repo_root}" +tag="AIENOS_IMAC_BOOTDISK" +code_fd="${OVMF_CODE:-/usr/share/OVMF/OVMF_CODE_4M.fd}" +vars_fd="${OVMF_VARS:-/usr/share/OVMF/OVMF_VARS_4M.fd}" +cross="" +if [ "$(uname -m)" != "x86_64" ]; then cross="x86_64-linux-gnu-"; fi +for t in qemu-system-x86_64 mformat mmd mcopy mtype cmp sha256sum "${cross}gcc" "${cross}ld"; do + command -v "${t}" >/dev/null || { echo "${tag}: NOT_RUN (${t} missing)"; exit 2; } +done +fsck_fat="$(command -v fsck.fat || echo /usr/sbin/fsck.fat)" +[[ -x "${fsck_fat}" ]] || { echo "${tag}: NOT_RUN (fsck.fat missing)"; exit 2; } +[[ -r "${code_fd}" && -r "${vars_fd}" ]] || { echo "${tag}: NOT_RUN (no OVMF)"; exit 2; } + +. "${repo_root}/scripts/lib_gate_hold.sh" +if ! gh_quiet_check || ! gh_lock_take qemu_ck_imac_bootdisk_test "${AIENOS_GATE_MINUTES:-30}"; then + echo "${tag}: NOT_RUN (${gh_why})" + exit 3 +fi +work="$(mktemp -d)" +pids=() +cleanup() { + local p + for p in "${pids[@]}"; do kill "${p}" 2>/dev/null || true; done + rm -rf "${work}" + gh_lock_release +} +trap cleanup EXIT + +out="${work}/out" +out2="${work}/out2" +commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)" +second="0000000000000000000000000000000000000b0b" +mk() { make -s -C native/kernel X86_CROSS="${cross}" OUT="${out}" AIENOS_COMMIT="${commit}" "$@" >/dev/null; } +mk slot-tool imac-netboot-tool gpt-image +nb="${out}/host/ck_imac_netboot" +gpt="${out}/host/ck_gpt_image" +"${nb}" keygen "${work}/test.key" "${work}/test.pub" >/dev/null +mk CK_NETLDR_KEYS="${work}/test.pub" CK_NETLDR_FALLBACK_S=8 imac-netldr +mk imac-kernel +make -s -C native/kernel X86_CROSS="${cross}" OUT="${out2}" AIENOS_COMMIT="${second}" imac-kernel >/dev/null +push() { NETBOOT_TOOL_OUT="${out}" bash scripts/ck_imac_netboot_push.sh "$1" "${work}/test.key" "${work}/spool" >/dev/null; } + +stick="${work}/stick.img" +truncate -s 64M "${stick}" +mformat -i "${stick}" -F :: +mmd -i "${stick}" ::/EFI ::/EFI/BOOT +mcopy -i "${stick}" "${out}/NETLDR.EFI" ::/EFI/BOOT/BOOTX64.EFI +"${gpt}" create "${work}/hdd.img" 512 2048 one-old >/dev/null +cp --sparse=always "${work}/hdd.img" "${work}/hdd.before" +stick_sum="$(sha256sum <"${stick}")" + +fails=0 +pass() { echo "PASS $1"; } +fail() { echo "FAIL $1"; fails=$((fails + 1)); } +chk() { # description, file, pattern + if grep -aqE -- "$3" "$2"; then pass "$1"; else fail "$1 (no match for: $3)"; fi +} +nochk() { + if grep -aqE -- "$3" "$2"; then fail "$1 (unexpected: $3)"; else pass "$1"; fi +} +txt() { tr -d '\r' <"${work}/$1.log" 2>/dev/null || true; } +has() { txt "$1" | grep -aqE -- "$2"; } +wait_for() { # name seconds pattern + local i + for ((i = 0; i < $2 * 5; i++)); do + has "$1" "$3" && return 0 + sleep 0.2 + done + return 1 +} +lp=$((40000 + RANDOM % 10000)) +rp=$((lp + 1)) +start() { # name with-stick(0/1) + local name="$1" net=() + cp "${vars_fd}" "${work}/${name}.vars" + mkfifo "${work}/${name}.mon.in" "${work}/${name}.mon.out" + : >"${work}/${name}.log" + local disks=(-drive if=none,id=hdd,format=raw,file="${work}/hdd.img" + -device ide-hd,drive=hdd,bus=ide.1,model="APPLE HDD ST1000DM003",bootindex=2) + if [[ "$2" == 1 ]]; then + disks+=(-drive if=none,id=stick,format=raw,file="${stick}" -device ide-hd,drive=stick,bus=ide.0,bootindex=1) + net=(-netdev dgram,id=n0,local.type=inet,local.host=127.0.0.1,local.port="${lp}",remote.type=inet,remote.host=127.0.0.1,remote.port="${rp}" + -device virtio-net-pci,netdev=n0,mac=52:54:00:12:34:56) + else + net=(-nic none) + fi + qemu-system-x86_64 -M q35 -accel tcg -cpu max -smp 2 -m 1024 \ + -drive if=pflash,format=raw,readonly=on,file="${code_fd}" \ + -drive if=pflash,format=raw,file="${work}/${name}.vars" \ + "${disks[@]}" "${net[@]}" \ + -device qemu-xhci,id=xhci -device usb-kbd,bus=xhci.0,port=1 \ + -chardev pipe,id=mon,path="${work}/${name}.mon" -mon chardev=mon,mode=readline \ + -display none -serial file:"${work}/${name}.log" -no-reboot 2>"${work}/${name}.err" & + pids+=($!) + eval "pid_${name}=$!" + cat "${work}/${name}.mon.out" >/dev/null & + pids+=($!) +} +running() { local v="pid_$1"; kill -0 "${!v}" 2>/dev/null; } +stop() { local v="pid_$1"; kill "${!v}" 2>/dev/null || true; } +say() { # name "lower-case words": typed through the QEMU monitor, then Enter + local name="$1" text="$2" c k i + exec 3>"${work}/${name}.mon.in" + for ((i = 0; i < ${#text}; i++)); do + c="${text:i:1}" + case "${c}" in " ") k=spc ;; [a-z0-9]) k="${c}" ;; *) echo "say: no key for '${c}'" >&2; exit 2 ;; esac + echo "sendkey ${k}" >&3 + sleep 0.15 + done + echo "sendkey ret" >&3 + exec 3>&- +} +off() { local i; for i in $(seq 1 300); do running "$1" || return 0; sleep 1; done; stop "$1"; return 1; } +ready='^keyboard: type a line and press Enter' +run() { # name with-stick: start, wait for Allen, goodbye, power off; result in name.txt + start "$1" "$2" + if wait_for "$1" 400 "${ready}"; then + say "$1" "goodbye" + off "$1" || true + fi + stop "$1" + txt "$1" >"${work}/$1.txt" +} + +mkdir -p "${work}/spool" +"${nb}" serve "${work}/spool" --qemu-dgram "${rp}:${lp}" >"${work}/serve.log" 2>&1 & +pids+=($!) + +echo "== start 1: stick + network, install ==" +push "${out}/IMACKERN.EFI" +run one 1 +chk "1: the network kernel started" "${work}/one.txt" '^netldr: starting the network kernel \([0-9]+ bytes\)$' +chk "1: Allen's section added" "${work}/one.txt" '^allen_memory: AIENOS partition added, entry [0-9]+, ' +chk "1: boot section added in unused space" "${work}/one.txt" '^boot_disk: boot section added, entry [0-9]+, first_lba=[0-9]+ last_lba=[0-9]+ \(256 MiB, EFI System Partition\); the existing partitions were not touched$' +chk "1: installed in slot A, read back" "${work}/one.txt" "^boot_disk: installed this kernel \\(commit ${commit:0:12}, generation [0-9]+, [0-9]+ bytes\\) as .EFI.BOOT.BOOTX64\\.EFI, slot A, new FAT32 volume, [0-9]+ blocks in [0-9]+ ms, read back exact; " +chk "1: boot times reported with the loader" "${work}/one.txt" '^boot_time: since power on: firmware until the loader [0-9]+ ms, loader [0-9]+ ms, kernel [0-9]+ ms; Allen.s window at [0-9]+ ms$' +chk "1: powered off after goodbye" "${work}/one.txt" '^power: off via ACPI S5 ' +nochk "1: no write refused by the fence" "${work}/one.txt" 'ahci_write: .*refused' +first="$(grep -aoE '^boot_disk: boot section added, entry [0-9]+, first_lba=[0-9]+' "${work}/one.txt" | grep -oE '[0-9]+$' || echo 0)" +if [[ "${first}" -gt 0 ]]; then + dd if="${work}/hdd.img" of="${work}/esp1.img" bs=512 skip="${first}" count=$((256 * 2048)) status=none + if "${fsck_fat}" -n "${work}/esp1.img" >"${work}/fsck1" 2>&1; then pass "1: fsck.fat finds nothing to repair" + else cat "${work}/fsck1"; fail "1: fsck.fat finds faults"; fi + if MTOOLS_SKIP_CHECK=1 mtype -i "${work}/esp1.img" ::/EFI/BOOT/BOOTX64.EFI >"${work}/got1" && + cmp -s "${work}/got1" "${out}/IMACKERN.EFI"; then pass "1: mtools reads BOOTX64.EFI equal to the kernel image" + else fail "1: BOOTX64.EFI differs from the kernel image"; fi +else + fail "1: no boot section first LBA" +fi +if cmp -s -i $((2048 * 512)) -n $((16384 * 512)) "${work}/hdd.before" "${work}/hdd.img"; then + pass "1: the old partition is byte-identical" +else fail "1: the old partition changed"; fi +[[ "$(sha256sum <"${stick}")" == "${stick_sum}" ]] && pass "1: the stick was not written" || fail "1: the stick changed" + +echo "== start 2: the hard disk alone ==" +run two 0 +nochk "2: no network loader" "${work}/two.txt" '^netldr: ' +chk "2: the kernel ran from the hard disk" "${work}/two.txt" "^aienos_commit: ${commit}\$" +chk "2: boot times without a loader" "${work}/two.txt" '^boot_time: since power on: firmware until this kernel [0-9]+ ms \(no loader\), kernel [0-9]+ ms; Allen.s window at [0-9]+ ms$' +chk "2: the boot section reported, slot A" "${work}/two.txt" '^boot_disk: .EFI.BOOT.BOOTX64\.EFI on disk [0-9]+: [0-9]+ bytes \(slot A\)$' +chk "2: Allen's memory loaded (second start)" "${work}/two.txt" '^allen_memory: loaded generation [0-9]+ \(2 of 2 copies valid\): .*1 earlier start$' +nochk "2: nothing added" "${work}/two.txt" 'partition added|boot section added' + +echo "== start 3: stick + network, a second kernel ==" +push "${out2}/IMACKERN.EFI" +run three 1 +chk "3: the second kernel ran" "${work}/three.txt" "^aienos_commit: ${second}\$" +chk "3: installed in slot B" "${work}/three.txt" '^boot_disk: installed this kernel \(commit [0-9a-f]{12}, generation [0-9]+, [0-9]+ bytes\) as .EFI.BOOT.BOOTX64\.EFI, slot B, [0-9]+ blocks in [0-9]+ ms, read back exact; ' +nochk "3: no new partition" "${work}/three.txt" 'partition added|boot section added' + +echo "== start 4: the hard disk alone ==" +run four 0 +chk "4: the second kernel runs from the hard disk" "${work}/four.txt" "^aienos_commit: ${second}\$" +chk "4: slot B reported" "${work}/four.txt" '^boot_disk: .EFI.BOOT.BOOTX64\.EFI on disk [0-9]+: [0-9]+ bytes \(slot B\)$' +dd if="${work}/hdd.img" of="${work}/esp4.img" bs=512 skip="${first:-0}" count=$((256 * 2048)) status=none +if "${fsck_fat}" -n "${work}/esp4.img" >"${work}/fsck4" 2>&1; then pass "4: fsck.fat finds nothing to repair" +else cat "${work}/fsck4"; fail "4: fsck.fat finds faults"; fi + +grep -ahE '^boot_time:|^boot_disk:' "${work}"/one.txt "${work}"/two.txt "${work}"/three.txt "${work}"/four.txt | sed 's/^/note: /' +if [[ "${fails}" -ne 0 ]]; then + for n in one two three four; do echo "---- ${n} (last 30 lines) ----"; tail -30 "${work}/${n}.txt"; done + echo "${tag}: FAIL (${fails} checks)" + exit 1 +fi +echo "${tag}: PASS" ```