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/018f6d0fc711e93f # 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#420 (code only) closed derived `018f6d0fc711e93f` #420 Imported from GitHub aien-dev/aienux#420 (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 `17ad0167eac91edc280472020679a11969a78609` · Head `dced92c687245614f3813c6745f9b0b4973493d7` ### Fetch it A git bundle of the pull request's head, 360234 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aienux/patches/018f6d0fc711e93f.bundle -o 018f6d0fc711e93f.bundle git fetch 018f6d0fc711e93f.bundle refs/pull/420/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 420 dced92c687245614f3813c6745f9b0b4973493d7 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aienux","number":420,"url":"https://github.com/aien-dev/aienux/pull/420","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:24Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index fced4e5e..3aa17681 100644 --- a/.crumb +++ b/.crumb @@ -22,7 +22,7 @@ "children": [ { "digest": "b5ced6fea583b485206b73ec08b91de68a5cfd2672ac448191831754c9e0907d", - "last_commit": "4bd49ca", + "last_commit": "7db773a", "name": "crates", "purpose": "Directory crates. Purpose not yet described by a human." }, @@ -33,27 +33,27 @@ "purpose": "Directory docs. Purpose not yet described by a human." }, { - "digest": "64cc87f8507bb580e1788d335c5a76039f3e3a016552595526718448ab5aa098", - "last_commit": "3037967", + "digest": "bfe709b81e776dc71dbd68b895ae1d0f667acd6452a4ae6c4cf2e765ce804f5b", + "last_commit": "1055448", "name": "native", "purpose": "Directory native. Purpose not yet described by a human." }, { - "digest": "9adb69cc749bc97fa48e268f0397b900da83c84191ab6a9373358e8b9ab57922", - "last_commit": "44cf2dd", + "digest": "8b9338bc51b3920c364cfe7ccf7c6cf82d42c4145dada9f79453e69ef17c7daf", + "last_commit": "1055448", "name": "scripts", "purpose": "Directory scripts. Purpose not yet described by a human." } ], - "children_root": "sha256:19cc8f21ac13e49018f60836bdaf7c4c23477cf558624048754f1e83c6d88cac", - "compiled_at": "2026-10-17T01:49:45Z", + "children_root": "sha256:269b75f3e018da8bb23859accd915b3b409c5dd1138568226fd69721f7f9f128", + "compiled_at": "2026-10-18T12:23:39Z", "compiler": "crumb-compile/1", - "digest": "sha256:1b7f96caef28425fc1a0751dd671452aa26ef3561f79f663480e083341950199", - "evidence_files": 211, - "evidence_root": "sha256:3a8f56415109a697e4beb6048c85805c50c9c6c4089629057f4e8b3e76863981", - "files": 3501, - "generated_at_commit": "30379678add587e388db4e11713d6bca8d159b08", - "source_tree": "sha256:4fa99ea1d4144da8067bb5d01898dc38984898b2c5d5fb06b0e19033c824b265" + "digest": "sha256:24c7189a5f18da20c381f8824519600407477eca54583f2eb789da333f9adf55", + "evidence_files": 212, + "evidence_root": "sha256:d6222b90f848855d10762564c13fc9ab7d759928bb77251ff68047a84f5d808f", + "files": 3554, + "generated_at_commit": "105544890f780085f64bee754d4a92c1a2f17ecf", + "source_tree": "sha256:a57f2bf969169f80bbc7e8b07c29fd81593d5f12e44d77134bb65ecf4695e470" }, "owner_lane": "", "provenance": { diff --git a/README.md b/README.md index 18c62798..4385efa4 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # AIENOS -> **Status: experimental / pre-alpha. Nothing here is physically qualified.** The first native boot on the NVIDIA DGX Spark passed on 2026-09-24 ([evidence](evidence/m2_first_boot_2026-09-24.md)). Since then most of the work has run in an emulator (QEMU); the C kernel has also run on a Raspberry Pi 5 (see Current state). No support, stability or compatibility promises. Expect breaking changes. +> **Status: experimental / pre-alpha. Nothing here is physically qualified.** The first native boot on the NVIDIA DGX Spark passed on 2026-09-24 ([evidence](evidence/m2_first_boot_2026-09-24.md)). Since then most of the work has run in an emulator (QEMU); the C kernel has also run on a Raspberry Pi 5 and on an x86 desktop test computer, where Allen now lives (see Current state). No support, stability or compatibility promises. Expect breaking changes. AIENOS is our own operating system kernel, built to replace Linux on the DGX Spark. It is agent-native: the agent is the control plane, and the model is never the kernel. The kernel stays small, deterministic and non-intelligent, and the agent is never the root of trust. @@ -10,7 +10,7 @@ Firmware -> AIEN Boot -> AIEN Kernel -> AIEN Runtime -> AIEN Agent -> You ## Current state -The kernel is being rewritten in C (the `native/` directory) and is IMPLEMENTED / NOT QUALIFIED: all 24 emulator gates pass in the [newest receipt](evidence/ck_gates_29ed03c97454354a18676f768273dd7f7a8e15462c4be1939d9994d277d0d639.json) (run at 7f0de7e on 2026-10-09, QEMU only), and `scripts/ck_gates.sh` now lists 26 gates, so a newer receipt is owed. It has not been booted on the DGX Spark. Its first runs on real hardware were on a Raspberry Pi 5 on 2026-10-13: a bring-up run that reached interrupts, four cores, user-mode tasks, scheduling and message passing and wrote its log to the SD card, then two runs that wrote and re-read a test region on the card's AIENOS partition (pull requests [#345](https://github.com/aien-spark/aienos/pull/345) and [#346](https://github.com/aien-spark/aienos/pull/346); the run logs are not stored in this repository). The earlier Rust kernel in `crates/` is legacy and is being replaced; it is not extended. Trust-chain and encrypted-storage work (TRUST-1 and M5) is NOT_QUALIFIED, with hardware and operator steps outstanding. Do not trust any number in this file over the live documents: +The kernel is being rewritten in C (the `native/` directory) and is IMPLEMENTED / NOT QUALIFIED: all 24 emulator gates pass in the [newest receipt](evidence/ck_gates_29ed03c97454354a18676f768273dd7f7a8e15462c4be1939d9994d277d0d639.json) (run at 7f0de7e on 2026-10-09, QEMU only), and `scripts/ck_gates.sh` now lists 26 gates, so a newer receipt is owed. It has not been booted on the DGX Spark. Its first runs on real hardware were on a Raspberry Pi 5 on 2026-10-13: a bring-up run that reached interrupts, four cores, user-mode tasks, scheduling and message passing and wrote its log to the SD card, then two runs that wrote and re-read a test region on the card's AIENOS partition (pull requests [#345](https://github.com/aien-spark/aienos/pull/345) and [#346](https://github.com/aien-spark/aienos/pull/346); the run logs are not stored in this repository). An x86_64 build of the same kernel runs on a desktop test computer (2026-10-17, pull requests [#414](https://github.com/aien-dev/aienos-mv/pull/414) and [#415](https://github.com/aien-dev/aienos-mv/pull/415); details in [native/kernel/README.md](native/kernel/README.md)): it loads over the local network as a signed image, reads a wired USB keyboard, and hosts **Allen**, the resident agent, full screen. On that machine Allen answered "Hello Allen" with "Hello Humanity." from its own local rules (no model, no network), added its own memory section to the owner-approved internal disk without touching the existing partition, and saved its memory to both copies. Remembering a taught note across a restart passes in the emulator and is not yet shown on the real machine. The startup now opens on a night sky where two black holes merge and Allen forms from the light; that build has not run on the real machine yet. DMA confinement (IOMMU) is not in place, so this is not qualified for sensitive use. The earlier Rust kernel in `crates/` is legacy and is being replaced; it is not extended. Trust-chain and encrypted-storage work (TRUST-1 and M5) is NOT_QUALIFIED, with hardware and operator steps outstanding. Do not trust any number in this file over the live documents: - [ROADMAP.md](ROADMAP.md): component status (its newest status block is dated 2026-10-01) - [native/kernel/GATES.md](native/kernel/GATES.md): what each emulator gate checks diff --git a/evidence/spark_region_probe_2026-10-18.md b/evidence/spark_region_probe_2026-10-18.md new file mode 100644 index 00000000..ddc0b745 --- /dev/null +++ b/evidence/spark_region_probe_2026-10-18.md @@ -0,0 +1,8 @@ +# Spark AIENOS region: map + raw-disk proof (2026-10-18) +Region: /var/lib/aienos-region/region.img, 214748364800 B, immutable, zero filled; host partition nvme0n1p2 starts at LBA 612352. +REGION.MAP (ck_region_map, FIEMAP): pieces=12045 bytes=214748364800 base=612352 window=612352..8001573518 size=289152. +Probe (ck_region_probe, same dev/disk_extent.c as the kernel, raw /dev/nvme0n1 read only): 62 logical blocks (46 seeded random + first/last block of pieces 1, 100, 5000, 12044) written via the filesystem with distinct patterns, read raw through the map: REGION_PROBE: PASS checked=62 mismatches=0. +Negative control: same map against /dev/nvme0n1p2 (wrong parent) -> REGION_PROBE: FAIL parse region piece outside its window. +Map re-made after the probe writes and after blanking: byte identical. Probe spots re-zeroed (0 nonzero). +Incident: a first spot list mixed physical offsets in; 4 writes landed past EOF and grew the file sparse (filesystem writes only, nothing outside the file). Truncated back to 214748364800; map byte identical to the original afterwards. +Host test: make disk-extent-test -> DISK_EXTENT_HOST: PASS (30 checks, ASan+UBSan) and 6/6 guard mutants caught. diff --git a/native/.crumb b/native/.crumb index dbbce44e..25d79498 100644 --- a/native/.crumb +++ b/native/.crumb @@ -50,74 +50,74 @@ "children": [ { "digest": "50aa2fbd6ca356b7703517bc7ecf439f7b6e0a6b935d0ca6ca4c6f7caf23ce34", - "last_commit": "4bd49ca", + "last_commit": "09e59a8", "name": "argus", "purpose": "Directory native/argus. Purpose not yet described by a human." }, { - "digest": "7bd231b92b38492fbb936e28caa803047edd9250800eac92fe56e09d38bf98cd", - "last_commit": "bfea771", + "digest": "e98806cbea0fcd38d29760c3e6ddf8ddfcedcd29bcf68a4675cb74dce68963a8", + "last_commit": "2eef482", "name": "boot", "purpose": "Directory native/boot. Purpose not yet described by a human." }, { "digest": "750c519c466783ed6330a6a2c8fcb2153efdaadb9d65b38a6a85e8463d78b68d", - "last_commit": "4bd49ca", + "last_commit": "7db773a", "name": "capability", "purpose": "Directory native/capability. Purpose not yet described by a human." }, { "digest": "0a3e98a5f36f528eb7ae6e1611d466343068780b9029621286b292ec1c796950", - "last_commit": "4bd49ca", + "last_commit": "7db773a", "name": "crypto", "purpose": "Directory native/crypto. Purpose not yet described by a human." }, { "digest": "99bc55e79695290b65ae08a38e5731e3ed976d79cdb3b6c9bc21c706b1ddab22", - "last_commit": "4bd49ca", + "last_commit": "7db773a", "name": "disk", "purpose": "Directory native/disk. Purpose not yet described by a human." }, { - "digest": "7a81b1b4b47154e15b9682b72d7fa49f309454f093aeb019061b8148550920ae", - "last_commit": "3037967", + "digest": "10db4a03aa159fb128309af8992c878eded5f0164b837eaf29b2acb47e560c59", + "last_commit": "1055448", "name": "kernel", "purpose": "Directory native/kernel. Purpose not yet described by a human." }, { "digest": "a805df7e3af4b8a2ef345223523b54e7e47565204ec8f8e598f6dcaf53b07419", - "last_commit": "4bd49ca", + "last_commit": "7db773a", "name": "m5", "purpose": "Directory native/m5. Purpose not yet described by a human." }, { "digest": "ff5c88f5e9bf86e7ff836d24c048dd2d4efc94f6f19a21a0caf72ae9c402deaf", - "last_commit": "4bd49ca", + "last_commit": "7db773a", "name": "net", "purpose": "Directory native/net. Purpose not yet described by a human." }, { "digest": "135fd1edbe2388764de7dc755611b483b0c61adab858718c390b7745d141635c", - "last_commit": "4bd49ca", + "last_commit": "7db773a", "name": "sig", "purpose": "Directory native/sig. Purpose not yet described by a human." }, { "digest": "f75197d76b7daaeee8223cf25353251824cd4497400a439724a3a424e014a229", - "last_commit": "4bd49ca", + "last_commit": "e5e8f08", "name": "store", "purpose": "Directory native/store. Purpose not yet described by a human." } ], - "children_root": "sha256:cec690f1b64aaba9f5f7ea41048a25c5b3cdf4834f672e977dc7eb47d34e4be2", - "compiled_at": "2026-10-17T01:49:45Z", + "children_root": "sha256:3abdfb0d211ede49dc3d4911d27a1de91c57d2b05c5f8e384610635ac074cbcb", + "compiled_at": "2026-10-18T12:23:39Z", "compiler": "crumb-compile/1", - "digest": "sha256:64cc87f8507bb580e1788d335c5a76039f3e3a016552595526718448ab5aa098", + "digest": "sha256:bfe709b81e776dc71dbd68b895ae1d0f667acd6452a4ae6c4cf2e765ce804f5b", "evidence_files": 4, "evidence_root": "sha256:e410b845507e00568e15b51a5797af32a97e0e4b8ab4e8487bb7c98e7e0cf335", - "files": 606, - "generated_at_commit": "30379678add587e388db4e11713d6bca8d159b08", - "source_tree": "sha256:1d9fe182bcaa94de3564ee02f9e8c63bddcea00fcea22feed112ffe6e01a1b78" + "files": 646, + "generated_at_commit": "105544890f780085f64bee754d4a92c1a2f17ecf", + "source_tree": "sha256:d43d03bdc487c683a08c59bb0f82365e88e8e91e129fe5595adfa30c405cb0e0" }, "owner_lane": "", "provenance": { diff --git a/native/boot/.crumb b/native/boot/.crumb index cc53e7fd..4462d379 100644 --- a/native/boot/.crumb +++ b/native/boot/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-16T23:33:50Z", + "compiled_at": "2026-10-18T06:34:48Z", "compiler": "crumb-compile/1", - "digest": "sha256:7bd231b92b38492fbb936e28caa803047edd9250800eac92fe56e09d38bf98cd", + "digest": "sha256:e98806cbea0fcd38d29760c3e6ddf8ddfcedcd29bcf68a4675cb74dce68963a8", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 26, - "generated_at_commit": "4bd49ca164761fe66c6eb339acabdbcc84e8a33c", - "source_tree": "sha256:57b9a2e0d628acd6b2c2d1dab4fc1a4eafec507bc2601b54d92f96fc46393666" + "files": 29, + "generated_at_commit": "2eef482f83ebc4ccc67fb3f88a5151c347f0497f", + "source_tree": "sha256:c82a45075c953c9172976ece034ca1703ab92ad4d210e00510bba3b8dc8ab8ba" }, "owner_lane": "", "provenance": { diff --git a/native/boot/net_loader.c b/native/boot/net_loader.c new file mode 100644 index 00000000..6446bc46 --- /dev/null +++ b/native/boot/net_loader.c @@ -0,0 +1,657 @@ +/* net_loader.c -- NETLDR.EFI: the AIENOS lab network loader for the 2017 iMac + * (x86_64 UEFI application; wire format netboot_proto.h). + * + * Lives on the USB stick as EFI/BOOT/BOOTX64.EFI so the stick never has to + * move again. At every power-on it asks the LAN for a kernel, verifies it and + * starts it: + * 1. Network: the firmware's Simple Network Protocol (UEFI 2.10 section + * 24.1), opened EXCLUSIVE so the firmware's own network stack lets go of + * the receive queue. No SNP handle: ConnectController on every handle + * once, then look again. Every handle is tried (the iMac also has a Wi-Fi + * SNP that looks like Ethernet): the first with its cable link up wins; + * with none reporting a link, each gets a 10 s turn before the fallback. + * 2. HELLO every second. WAIT: the server is there with nothing queued; ask + * again after the seconds it names. OFFER: fetch the object (signed slot + * manifest + image) in NB_WINDOW-chunk windows, re-asking for gaps. + * 3. ck_slot_verify (slot_select.c, the SLOTLDR verifier): Ed25519 manifest + * signature by a key baked in at build time (CK_NETLDR_KEYS), SHA-512 of + * the image, image_len == the bytes received. Refused: DONE status 1 with + * 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, 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 + * as the stick is: whoever can write the stick can replace this loader too. + * + * The UEFI watchdog is re-armed to NETLDR_WATCHDOG_S on every server answer + * and before StartImage, so a hung loader or kernel (before ExitBootServices) + * resets the machine instead of waiting for a hand on the power button. + * Never: UEFI variables, runtime services, ExitBootServices, disk writes. + * Freestanding C with the x86 kernel's flags; no kernel objects are linked. */ +#include +#include "efi.h" +#include "slot_format.h" +#include "netboot_proto.h" +#include "aienos_net.h" +#include "../kernel/core/fmt.h" + +#ifndef AIENOS_COMMIT +#define AIENOS_COMMIT "unknown" +#endif +#ifndef CK_NETLDR_FALLBACK_S +#define CK_NETLDR_FALLBACK_S 30u +#endif +#define NETLDR_WATCHDOG_S 600u +#define LOCAL_KERNEL u"\\EFI\\AIENOS\\IMACKERN.EFI" +#define LOCAL_MAX (16ull << 20) +#define PAGE 4096ull + +void *memcpy(void *dst, const void *src, size_t n); +void *memset(void *dst, int c, size_t n); +int memcmp(const void *a, const void *b, size_t n); + +/* Generated at build time (native/kernel/Makefile, ck_slot_tool keys-c). */ +extern const uint8_t ck_slot_loader_keys[][32]; +extern const unsigned ck_slot_loader_nkeys; + +#define EFI_LOAD_ERROR EFI_ERR(1) +#define EFI_NOT_READY EFI_ERR(6) +#define EFI_ALREADY_STARTED EFI_ERR(20) + +/* ---- Simple Network Protocol (UEFI 2.10 section 24.1; r-efi 6.0.0 + * protocols/simple_network.rs) ---- */ +#define SNP_GUID_INIT { 0xa19832b9, 0xac25, 0x11d3, { 0x9a, 0x2d, 0x00, 0x90, 0x27, 0x3f, 0xc1, 0x4d } } +#define LOADED_IMAGE_DEVICE_PATH_GUID_INIT \ + { 0xbc62157e, 0x3e33, 0x4fec, { 0x99, 0x20, 0x2d, 0x3b, 0x36, 0xd7, 0x50, 0xdf } } +enum { SNP_STOPPED, SNP_STARTED, SNP_INITIALIZED }; +#define SNP_RX_UNICAST 1u +#define SNP_RX_BROADCAST 4u +#define OPEN_BY_HANDLE 0x1u +#define OPEN_EXCLUSIVE 0x20u + +typedef struct { uint8_t addr[32]; } EFI_MAC_ADDRESS; +typedef struct { + uint32_t State, HwAddressSize, MediaHeaderSize, MaxPacketSize, NvRamSize, NvRamAccessSize; + uint32_t ReceiveFilterMask, ReceiveFilterSetting, MaxMCastFilterCount, MCastFilterCount; + EFI_MAC_ADDRESS MCastFilter[16]; + EFI_MAC_ADDRESS CurrentAddress, BroadcastAddress, PermanentAddress; + uint8_t IfType, MacAddressChangeable, MultipleTxSupported, MediaPresentSupported, MediaPresent; +} SNP_MODE; +_Static_assert(offsetof(SNP_MODE, CurrentAddress) == 552, "SNP_MODE CurrentAddress"); +_Static_assert(offsetof(SNP_MODE, MediaPresent) == 652, "SNP_MODE MediaPresent"); + +typedef struct SNP { + uint64_t Revision; + EFI_STATUS (*Start)(struct SNP *); + EFI_STATUS (*Stop)(struct SNP *); + EFI_STATUS (*Initialize)(struct SNP *, uint64_t extra_rx, uint64_t extra_tx); + EFI_STATUS (*Reset)(struct SNP *, uint8_t extended); + EFI_STATUS (*Shutdown)(struct SNP *); + EFI_STATUS (*ReceiveFilters)(struct SNP *, uint32_t enable, uint32_t disable, uint8_t reset_mcast, + uint64_t mcast_count, EFI_MAC_ADDRESS *mcast); + void *StationAddress, *Statistics, *MCastIpToMac, *NvData; + EFI_STATUS (*GetStatus)(struct SNP *, uint32_t *irq, void **tx_buf); + EFI_STATUS (*Transmit)(struct SNP *, uint64_t header_size, uint64_t size, void *buf, EFI_MAC_ADDRESS *src, + EFI_MAC_ADDRESS *dst, uint16_t *proto); + EFI_STATUS (*Receive)(struct SNP *, uint64_t *header_size, uint64_t *size, void *buf, EFI_MAC_ADDRESS *src, + EFI_MAC_ADDRESS *dst, uint16_t *proto); + void *WaitForPacket; + SNP_MODE *Mode; +} SNP; +_Static_assert(offsetof(SNP, GetStatus) == 0x58, "SNP GetStatus"); +_Static_assert(offsetof(SNP, Receive) == 0x68, "SNP Receive"); +_Static_assert(offsetof(SNP, Mode) == 0x78, "SNP Mode"); + +/* Boot-services members efi.h keeps as placeholders (UEFI 2.10 section 7). */ +typedef EFI_STATUS (*load_image_fn)(uint8_t boot_policy, EFI_HANDLE parent, void *device_path, void *source, + uint64_t source_size, EFI_HANDLE *out); +typedef EFI_STATUS (*start_image_fn)(EFI_HANDLE image, uint64_t *exit_data_size, CHAR16 **exit_data); +typedef EFI_STATUS (*connect_fn)(EFI_HANDLE controller, EFI_HANDLE *driver, void *remaining, uint8_t recursive); +typedef EFI_STATUS (*open_protocol_fn)(EFI_HANDLE handle, const EFI_GUID *protocol, void **iface, EFI_HANDLE agent, + EFI_HANDLE controller, uint32_t attributes); +typedef EFI_STATUS (*close_protocol_fn)(EFI_HANDLE handle, const EFI_GUID *protocol, EFI_HANDLE agent, + EFI_HANDLE controller); +_Static_assert(offsetof(EFI_BOOT_SERVICES, LoadImage) == 0xc8, "LoadImage"); +_Static_assert(offsetof(EFI_BOOT_SERVICES, ConnectController) == 0x108, "ConnectController"); +_Static_assert(offsetof(EFI_BOOT_SERVICES, OpenProtocol) == 0x118, "OpenProtocol"); + +static const EFI_GUID snp_guid = SNP_GUID_INIT; +static EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *conout; +static EFI_BOOT_SERVICES *bs; +static EFI_HANDLE self; +static SNP *snp; +static EFI_HANDLE snp_handle; +static int snp_exclusive; +static uint8_t mac[6]; +static uint8_t tx[1600], rx[2048]; +static uint8_t have[NB_OBJECT_MAX / NB_CHUNK / 8]; +static uint64_t tsc_per_ms; + +/* ---- console -------------------------------------------------------------- */ +struct line { + char b[256]; + size_t n; +}; + +static void line_emit(void *ctx, char c) +{ + struct line *l = ctx; + if (l->n < sizeof l->b - 1) + l->b[l->n++] = c; +} + +static void say(const char *fmt, ...) __attribute__((format(printf, 1, 2))); +static void say(const char *fmt, ...) +{ + struct line l; + CHAR16 w[2 * sizeof l.b + 1]; + size_t k = 0; + va_list ap; + l.n = 0; + va_start(ap, fmt); + ck_vformat(line_emit, &l, fmt, ap); + va_end(ap); + for (size_t i = 0; i < l.n; i++) { + if (l.b[i] == '\n') + w[k++] = '\r'; + w[k++] = (uint8_t)l.b[i]; + } + w[k] = 0; + if (conout) + conout->OutputString(conout, w); +} + +/* ---- time ------------------------------------------------------------------- */ +static uint64_t rdtsc(void) +{ + uint32_t lo, hi; + __asm__ volatile("rdtsc" : "=a"(lo), "=d"(hi)); + return (uint64_t)hi << 32 | lo; +} + +static uint64_t now_ms(void) { return rdtsc() / tsc_per_ms; } + +static void watchdog(uint64_t seconds) { bs->SetWatchdogTimer(seconds, 0x10000, 0, 0); } + +/* ---- network ---------------------------------------------------------------- */ +static void net_close(void) +{ + if (!snp) + return; + snp->Shutdown(snp); + snp->Stop(snp); + if (snp_exclusive) + ((close_protocol_fn)bs->CloseProtocol)(snp_handle, &snp_guid, self, 0); + snp = 0; +} + +/* Every SNP handle, in firmware order. The iMac firmware carries a Wi-Fi driver (Internet + * Recovery) beside the wired one, and an 802.11 SNP reports IfType 1 like Ethernet, so the + * first handle is not necessarily the cable. */ +#define NIC_MAX 8 +static EFI_HANDLE nics[NIC_MAX]; +static unsigned n_nics, nic_tries = 1; + +static int find_nics(void) +{ + EFI_HANDLE *h = 0; + uint64_t n = 0; + if (bs->LocateHandleBuffer(ByProtocol, &snp_guid, 0, &n, &h) != EFI_SUCCESS || n == 0) { + EFI_HANDLE *all = 0; + uint64_t na = 0; + say("netldr: no network interface yet; connecting firmware drivers\n"); + if (bs->LocateHandleBuffer(AllHandles, 0, 0, &na, &all) == EFI_SUCCESS) { + for (uint64_t i = 0; i < na; i++) + ((connect_fn)bs->ConnectController)(all[i], 0, 0, 1); + bs->FreePool(all); + } + if (bs->LocateHandleBuffer(ByProtocol, &snp_guid, 0, &n, &h) != EFI_SUCCESS || n == 0) { + say("netldr: no network interface (Simple Network Protocol) in this firmware\n"); + return -1; + } + } + n_nics = n < NIC_MAX ? (unsigned)n : NIC_MAX; + for (unsigned i = 0; i < n_nics; i++) + nics[i] = h[i]; + bs->FreePool(h); + return 0; +} + +enum { LINK_UNUSABLE = -1, LINK_DOWN, LINK_UNKNOWN, LINK_UP }; + +/* Open nics[i] (exclusive if the firmware lets go), bring it to Initialized with unicast + + * broadcast receive, wait up to 10 s for the cable link. Leaves it open as snp unless + * LINK_UNUSABLE; the caller closes the ones it does not keep. */ +static int use_nic(unsigned i, int quiet) +{ + EFI_STATUS s; + SNP *p = 0; + int ex = 1; + if (((open_protocol_fn)bs->OpenProtocol)(nics[i], &snp_guid, (void **)&p, self, 0, OPEN_EXCLUSIVE) != + EFI_SUCCESS) { + ex = 0; + if (bs->HandleProtocol(nics[i], &snp_guid, (void **)&p) != EFI_SUCCESS) + p = 0; + } + if (!p || !p->Mode) { + say("netldr: nic %u unusable (no protocol)\n", i); + return LINK_UNUSABLE; + } + SNP_MODE *m = p->Mode; + if (!quiet) + say("netldr: nic %u of %u mac=%02x:%02x:%02x:%02x:%02x:%02x type=%u state=%u open=%s\n", i, n_nics, + m->CurrentAddress.addr[0], m->CurrentAddress.addr[1], m->CurrentAddress.addr[2], m->CurrentAddress.addr[3], + m->CurrentAddress.addr[4], m->CurrentAddress.addr[5], m->IfType, m->State, ex ? "exclusive" : "shared"); + snp = p; + snp_handle = nics[i]; + snp_exclusive = ex; + if (m->IfType != 1 || m->HwAddressSize != 6) { + net_close(); + return LINK_UNUSABLE; + } + memcpy(mac, m->CurrentAddress.addr, 6); + if (m->State == SNP_STOPPED && (s = p->Start(p)) != EFI_SUCCESS && s != EFI_ALREADY_STARTED) { + say("netldr: nic %u Start status=0x%llx\n", i, (unsigned long long)s); + net_close(); + return LINK_UNUSABLE; + } + if (m->State == SNP_STARTED && (s = p->Initialize(p, 0, 0)) != EFI_SUCCESS) { + say("netldr: nic %u Initialize status=0x%llx\n", i, (unsigned long long)s); + net_close(); + return LINK_UNUSABLE; + } + uint32_t want = (SNP_RX_UNICAST | SNP_RX_BROADCAST) & m->ReceiveFilterMask; + if (!(want & SNP_RX_BROADCAST) || (s = p->ReceiveFilters(p, want, 0, 0, 0, 0)) != EFI_SUCCESS) { + say("netldr: nic %u cannot receive broadcasts (mask=0x%x status=0x%llx)\n", i, m->ReceiveFilterMask, + (unsigned long long)(want & SNP_RX_BROADCAST ? s : EFI_ERR(3))); + net_close(); + return LINK_UNUSABLE; + } + if (!m->MediaPresentSupported) { + if (!quiet) + say("netldr: nic %u link: not reported\n", i); + return LINK_UNKNOWN; + } + for (uint64_t t = now_ms() + 10000; !m->MediaPresent && now_ms() < t;) { + uint32_t irq; + p->GetStatus(p, &irq, 0); + bs->Stall(100000); + } + if (!quiet) + say("netldr: nic %u link %s\n", i, m->MediaPresent ? "up" : "down"); + return m->MediaPresent ? LINK_UP : LINK_DOWN; +} + +/* Keep the first interface with its cable link up. With none up, round number `round` picks + * among the rest (link not reported first, then link down), so a caller that moves to the + * next round after a silent window tries each in turn; nic_tries says how many there are. */ +static int net_open(unsigned round) +{ + unsigned cand[2 * NIC_MAX], nc = 0, down[NIC_MAX], nd = 0; + if (find_nics() != 0) + return -1; + for (unsigned i = 0; i < n_nics; i++) { + int r = use_nic(i, round != 0); + if (r == LINK_UP) { + nic_tries = 1; + return 0; + } + if (r == LINK_UNUSABLE) + continue; + net_close(); + if (r == LINK_UNKNOWN) + cand[nc++] = i; + else + down[nd++] = i; + } + for (unsigned k = 0; k < nd; k++) + cand[nc++] = down[k]; + if (nc == 0) { + say("netldr: no usable network interface\n"); + return -1; + } + nic_tries = nc; + unsigned pick = cand[round % nc]; + say("netldr: no interface reports a cable link; trying nic %u (%u of %u)\n", pick, round % nc + 1, nc); + return use_nic(pick, 1) == LINK_UNUSABLE ? -1 : 0; +} + +/* Why the last net_send failed (for the DONE report). */ +static const char *tx_why; +static EFI_STATUS tx_status; + +static int net_send(const struct nb_msg *m) +{ + static uint8_t msg[NB_MSG_MAX], udp[8 + NB_MSG_MAX], ip[20 + sizeof udp]; + const net_ipv4 any = {{0, 0, 0, 0}}, bcast = {{255, 255, 255, 255}}; + net_udp_header uh = {NB_PORT_LOADER, NB_PORT_SERVER}; + net_ipv4_header ih = {0, 0, 1, NET_IPPROTO_UDP, any, bcast}; + net_eth_frame e; + size_t n = nb_build(m, msg, sizeof msg), uw = 0, iw = 0, ew = 0; + tx_why = "frame build"; + if (!n || net_udp_build(&uh, msg, n, any, bcast, udp, sizeof udp, &uw) != NET_OK || + net_ipv4_build(&ih, udp, uw, ip, sizeof ip, &iw) != NET_OK) + return -1; + memset(e.destination.b, 0xff, 6); + memcpy(e.source.b, mac, 6); + e.ethertype = NET_ETHERTYPE_IPV4; + e.payload = ip; + e.payload_len = iw; + if (net_eth_build(&e, tx, sizeof tx, &ew) != NET_OK) + return -1; + tx_why = "Transmit"; + if ((tx_status = snp->Transmit(snp, 0, ew, tx, 0, 0, 0)) != EFI_SUCCESS) + return -1; + /* The frame buffer is the firmware's until GetStatus hands it back. A driver that never + * reports the completion still sent the frame: go on and listen (the next frame is built + * a second or more later), and say so if nothing ever answers. */ + for (uint64_t t = now_ms() + 100; now_ms() < t;) { + uint32_t irq; + void *done = 0; + if (snp->GetStatus(snp, &irq, &done) == EFI_SUCCESS && done) { + tx_why = "frames sent, nothing came back"; + return 0; + } + } + tx_why = "frames handed to the card, completion never reported"; + return 0; +} + +/* Next netboot message with our nonce before deadline (ms). 0 or -1. */ +static int net_recv(const uint8_t nonce[16], uint64_t deadline, struct nb_msg *out) +{ + do { + uint64_t size = sizeof rx; + EFI_STATUS s = snp->Receive(snp, 0, &size, rx, 0, 0, 0); + if (s == EFI_NOT_READY) + continue; + if (s != EFI_SUCCESS || size > sizeof rx) + continue; + net_eth_frame e; + net_ipv4_header ih; + net_udp_header uh; + const uint8_t *ipp, *up; + size_t ipn, un; + if (net_eth_parse(rx, size, &e) != NET_OK || e.ethertype != NET_ETHERTYPE_IPV4 || + net_ipv4_parse(e.payload, e.payload_len, &ih, &ipp, &ipn) != NET_OK || ih.protocol != NET_IPPROTO_UDP || + net_udp_parse(ipp, ipn, ih.source, ih.destination, &uh, &up, &un) != NET_OK || + uh.destination_port != NB_PORT_LOADER || uh.source_port != NB_PORT_SERVER) + continue; + if (nb_parse(up, un, out) != 0 || memcmp(out->nonce, nonce, 16) != 0) + continue; + return 0; + } while (now_ms() < deadline); + return -1; +} + +/* ---- starting a kernel ------------------------------------------------------ */ +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) { + say("netldr: LoadImage of the %s kernel status=0x%llx: not started\n", what, (unsigned long long)s); + return; + } + 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); +} + +/* The kernel on the stick itself, for when no server answers. */ +static void start_local(void) +{ + static const EFI_GUID li_guid = EFI_LOADED_IMAGE_PROTOCOL_GUID_INIT; + static const EFI_GUID sfs_guid = EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID_INIT; + EFI_LOADED_IMAGE_PROTOCOL *li = 0; + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *fs = 0; + EFI_FILE_PROTOCOL *root = 0, *f = 0; + uint64_t pa = 0, got = 0; + if (bs->HandleProtocol(self, &li_guid, (void **)&li) != EFI_SUCCESS || !li || + bs->HandleProtocol(li->DeviceHandle, &sfs_guid, (void **)&fs) != EFI_SUCCESS || !fs || + fs->OpenVolume(fs, &root) != EFI_SUCCESS) { + say("netldr: cannot open this stick's volume: no local kernel\n"); + return; + } + if (root->Open(root, &f, (CHAR16 *)LOCAL_KERNEL, 1 /* read */, 0) != EFI_SUCCESS) { + say("netldr: no \\EFI\\AIENOS\\IMACKERN.EFI on this stick\n"); + root->Close(root); + return; + } + if (bs->AllocatePages(AllocateAnyPages, EfiLoaderData, LOCAL_MAX / PAGE, &pa) != EFI_SUCCESS) { + say("netldr: no memory for the local kernel\n"); + } else { + for (;;) { + uint64_t n = LOCAL_MAX - got; + if (n == 0 || f->Read(f, &n, (uint8_t *)(uintptr_t)pa + got) != EFI_SUCCESS || n == 0) + break; + got += n; + } + } + f->Close(f); + root->Close(root); + if (pa && got > 0 && got < LOCAL_MAX) + 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) + bs->FreePages(pa, LOCAL_MAX / PAGE); +} + +/* ---- one netboot exchange --------------------------------------------------- */ +enum { R_SILENT, R_ANSWERED, R_BOOT }; + +static void new_nonce(uint8_t nonce[16]) +{ + static uint64_t ctr; + uint64_t a = rdtsc() ^ (++ctr << 48), b = a * 0x9e3779b97f4a7c15ull ^ ((uint64_t)mac[5] << 8 | mac[4]); + memcpy(nonce, &a, 8); + memcpy(nonce + 8, &b, 8); +} + +static void done(const uint8_t nonce[16], uint8_t status, const char *text) +{ + struct nb_msg m = {0}; + size_t n = 0; + while (n < NB_TEXT_MAX && text[n]) + n++; + m.type = NB_DONE; + memcpy(m.nonce, nonce, 16); + m.status = status; + m.len = (uint16_t)n; + m.data = (const uint8_t *)text; + int sent = 0; + for (int i = 0; i < 3; i++) + sent += net_send(&m) == 0; + if (sent) + say("netldr: told the Spark: %s (%d/3 sent)\n", text, sent); + else + say("netldr: could not tell the Spark (%s, status 0x%llx)\n", tx_why, (unsigned long long)tx_status); +} + +/* Fetch total bytes into obj. 0 complete, -1 gave up. */ +static int fetch(const uint8_t nonce[16], uint8_t *obj, uint32_t total) +{ + uint32_t chunks = nb_chunks(total), got = 0, next = 0, strikes = 0, shown = 0; + memset(have, 0, (chunks + 7) / 8); + while (got < chunks) { + while (have[next / 8] & (1u << (next % 8))) + next++; + struct nb_msg g = {0}, d; + g.type = NB_GET; + memcpy(g.nonce, nonce, 16); + g.offset = next * NB_CHUNK; + g.count = (uint16_t)(chunks - next < NB_WINDOW ? chunks - next : NB_WINDOW); + uint32_t before = got; + if (net_send(&g) == 0) { + uint64_t deadline = now_ms() + 300; + while (net_recv(nonce, deadline, &d) == 0) { + if (d.type != NB_DATA) + continue; + uint32_t c = d.offset / NB_CHUNK; + uint32_t want = total - d.offset < NB_CHUNK ? total - d.offset : NB_CHUNK; + if (d.offset >= total || d.len != want || (have[c / 8] & (1u << (c % 8)))) + continue; + memcpy(obj + d.offset, d.data, d.len); + have[c / 8] |= (uint8_t)(1u << (c % 8)); + got++; + deadline = now_ms() + 300; + if (got == chunks || c == next + g.count - 1u) + break; + } + } + if (got == before) { + if (++strikes >= 20) { + say("netldr: transfer stalled at %u of %u pieces; starting over\n", got, chunks); + return -1; + } + } else { + strikes = 0; + watchdog(NETLDR_WATCHDOG_S); + } + if (got * 10 / chunks > shown) { + shown = got * 10 / chunks; + say("netldr: received %u%%\n", shown * 10); + } + } + return 0; +} + +static int exchange(void) +{ + static unsigned last_wait; + uint8_t nonce[16]; + struct nb_msg h = {0}, r; + new_nonce(nonce); + h.type = NB_HELLO; + memcpy(h.nonce, nonce, 16); + memcpy(h.mac, mac, 6); + if (net_send(&h) != 0 || net_recv(nonce, now_ms() + 1000, &r) != 0) + return R_SILENT; + if (r.type != NB_WAIT && r.type != NB_OFFER) + return R_SILENT; + watchdog(NETLDR_WATCHDOG_S); + if (r.type == NB_WAIT) { + if (last_wait != r.seconds) + say("netldr: the Spark answered: nothing queued; asking again every %u s\n", r.seconds); + last_wait = r.seconds; + bs->Stall((uint64_t)r.seconds * 1000000u); + return R_ANSWERED; + } + last_wait = 0; + uint32_t total = r.total; + uint64_t pages = (total + PAGE - 1) / PAGE, pa = 0; + say("netldr: the Spark offers a kernel: %u bytes\n", total); + if (bs->AllocatePages(AllocateAnyPages, EfiLoaderData, pages, &pa) != EFI_SUCCESS) { + say("netldr: no memory for %u bytes\n", total); + done(nonce, 1, "loader out of memory"); + return R_ANSWERED; + } + uint8_t *obj = (uint8_t *)(uintptr_t)pa; + if (fetch(nonce, obj, total) != 0) { + bs->FreePages(pa, pages); + return R_ANSWERED; + } + const struct ck_slot_manifest *m = (const struct ck_slot_manifest *)obj; + struct ck_slot_eval ev; + ck_slot_verify(m, obj + CK_SLOT_UNIT, total - CK_SLOT_UNIT, ck_slot_loader_keys, ck_slot_loader_nkeys, &ev); + if (ev.valid && m->image_len != total - CK_SLOT_UNIT) { + ev.valid = 0; + ev.why = "image_len differs from the bytes received"; + } + if (!ev.valid) { + say("netldr: REFUSED the network kernel (%s): nothing was started\n", ev.why ? ev.why : "invalid"); + done(nonce, 1, ev.why ? ev.why : "invalid"); + bs->FreePages(pa, pages); + bs->Stall(5000000); + return R_ANSWERED; + } + char commit[13]; + memcpy(commit, m->commit, 12); + commit[12] = 0; + say("netldr: signature and SHA-512 verified: gen=%llu commit=%s len=%llu\n", + (unsigned long long)m->generation, commit, (unsigned long long)m->image_len); + 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, 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; + say("netldr: AIENOS NETLDR v1 commit=%s keys=%u fallback=%us\n", AIENOS_COMMIT, ck_slot_loader_nkeys, + (unsigned)CK_NETLDR_FALLBACK_S); + uint64_t t0 = rdtsc(); + bs->Stall(20000); + tsc_per_ms = (rdtsc() - t0) / 20; + if (!tsc_per_ms) + tsc_per_ms = 1; + watchdog(NETLDR_WATCHDOG_S); + unsigned round = 0; + for (;;) { + if (ck_slot_loader_nkeys == 0 || net_open(round) != 0) { + say("netldr: %s; starting the kernel on this stick in 10 s\n", + ck_slot_loader_nkeys == 0 ? "no trusted keys built in" : "no usable network"); + bs->Stall(10000000); /* time to read (or photograph) the lines above */ + start_local(); + say("netldr: nothing started; trying again in 10 s\n"); + bs->Stall(10000000); + continue; + } + /* With several candidate interfaces and no cable link reported, each gets a share. */ + uint64_t window = (uint64_t)(nic_tries > 1 ? 10u : CK_NETLDR_FALLBACK_S) * 1000u; + say("netldr: asking the Spark for a kernel from %02x:%02x:%02x:%02x:%02x:%02x (ports %u/%u)\n", mac[0], + mac[1], mac[2], mac[3], mac[4], mac[5], NB_PORT_SERVER, NB_PORT_LOADER); + uint64_t last = now_ms(); + int r = R_SILENT; + while (snp && now_ms() - last < window) { + r = exchange(); + if (r == R_BOOT) + break; + if (r == R_ANSWERED) + last = now_ms(); + } + if (r == R_BOOT) { /* the network kernel returned: open the network again */ + round = 0; + continue; + } + net_close(); + if (++round < nic_tries) { + say("netldr: no answer on this interface; trying the next one\n"); + continue; + } + round = 0; + say("netldr: no answer from the Spark (%s); starting the kernel on this stick in 10 s\n", + tx_why ? tx_why : "frames sent"); + bs->Stall(10000000); /* time to read (or photograph) the lines above */ + start_local(); + say("netldr: back from the local kernel; asking the network again\n"); + } +} diff --git a/native/boot/netboot_proto.c b/native/boot/netboot_proto.c new file mode 100644 index 00000000..b0f010e7 --- /dev/null +++ b/native/boot/netboot_proto.c @@ -0,0 +1,161 @@ +/* netboot_proto.c -- encode and check AIENOS lab netboot messages + * (netboot_proto.h is the wire spec). Freestanding: no heap, no I/O. */ +#include "netboot_proto.h" + +static void put16(uint8_t *p, uint16_t v) +{ + p[0] = (uint8_t)(v >> 8); + p[1] = (uint8_t)v; +} + +static void put32(uint8_t *p, uint32_t v) +{ + p[0] = (uint8_t)(v >> 24); + p[1] = (uint8_t)(v >> 16); + p[2] = (uint8_t)(v >> 8); + p[3] = (uint8_t)v; +} + +static uint16_t get16(const uint8_t *p) { return (uint16_t)(p[0] << 8 | p[1]); } + +static uint32_t get32(const uint8_t *p) +{ + return (uint32_t)p[0] << 24 | (uint32_t)p[1] << 16 | (uint32_t)p[2] << 8 | p[3]; +} + +static int zero(const uint8_t *p, size_t n) +{ + uint8_t a = 0; + for (size_t i = 0; i < n; i++) + a |= p[i]; + return a == 0; +} + +static int printable(const uint8_t *p, size_t n) +{ + for (size_t i = 0; i < n; i++) + if (p[i] < 0x20 || p[i] > 0x7e) + return 0; + return 1; +} + +/* The field rules shared by build and parse. */ +static int fields_ok(const struct nb_msg *m) +{ + switch (m->type) { + case NB_HELLO: + return 1; + case NB_OFFER: + return m->total >= NB_OBJECT_MIN && m->total <= NB_OBJECT_MAX; + case NB_WAIT: + return m->seconds >= 1 && m->seconds <= NB_WAIT_MAX; + case NB_GET: + return m->count >= 1 && m->count <= NB_WINDOW && m->offset % NB_CHUNK == 0 && m->offset < NB_OBJECT_MAX; + case NB_DATA: + return m->len >= 1 && m->len <= NB_CHUNK && m->offset % NB_CHUNK == 0 && m->offset < NB_OBJECT_MAX && + (m->data != 0); + case NB_DONE: + return m->status <= 1 && m->len <= NB_TEXT_MAX && (m->len == 0 || (m->data && printable(m->data, m->len))); + default: + return 0; + } +} + +size_t nb_build(const struct nb_msg *m, uint8_t *out, size_t cap) +{ + size_t n = NB_MIN + (m && (m->type == NB_DATA || m->type == NB_DONE) ? m->len : 0); + if (!m || !out || !fields_ok(m) || cap < n) + return 0; + for (size_t i = 0; i < NB_MIN; i++) + out[i] = 0; + for (size_t i = 0; i < 4; i++) + out[i] = (uint8_t)NB_MAGIC[i]; + out[4] = m->type; + for (size_t i = 0; i < 16; i++) + out[8 + i] = m->nonce[i]; + switch (m->type) { + case NB_HELLO: + for (size_t i = 0; i < 6; i++) + out[24 + i] = m->mac[i]; + break; + case NB_OFFER: + put32(out + 24, m->total); + put16(out + 28, NB_CHUNK); + break; + case NB_WAIT: + put16(out + 24, m->seconds); + break; + case NB_GET: + put32(out + 24, m->offset); + put16(out + 28, m->count); + break; + case NB_DATA: + put32(out + 24, m->offset); + put16(out + 28, m->len); + break; + case NB_DONE: + out[24] = m->status; + break; + } + for (size_t i = 0; i < n - NB_MIN; i++) + out[NB_MIN + i] = m->data[i]; + return n; +} + +int nb_parse(const uint8_t *b, size_t len, struct nb_msg *m) +{ + if (!b || !m || len < NB_MIN || len > NB_MSG_MAX) + return -1; + for (size_t i = 0; i < 4; i++) + if (b[i] != (uint8_t)NB_MAGIC[i]) + return -1; + if (!zero(b + 5, 3)) + return -1; + *m = (struct nb_msg){0}; + m->type = b[4]; + for (size_t i = 0; i < 16; i++) + m->nonce[i] = b[8 + i]; + switch (m->type) { + case NB_HELLO: + if (len != NB_MIN || !zero(b + 30, 2)) + return -1; + for (size_t i = 0; i < 6; i++) + m->mac[i] = b[24 + i]; + break; + case NB_OFFER: + if (len != NB_MIN || get16(b + 28) != NB_CHUNK || !zero(b + 30, 2)) + return -1; + m->total = get32(b + 24); + break; + case NB_WAIT: + if (len != NB_MIN || !zero(b + 26, 6)) + return -1; + m->seconds = get16(b + 24); + break; + case NB_GET: + if (len != NB_MIN || !zero(b + 30, 2)) + return -1; + m->offset = get32(b + 24); + m->count = get16(b + 28); + break; + case NB_DATA: + if (!zero(b + 30, 2)) + return -1; + m->offset = get32(b + 24); + m->len = get16(b + 28); + if (len != NB_MIN + (size_t)m->len) + return -1; + m->data = b + NB_MIN; + break; + case NB_DONE: + if (!zero(b + 25, 7)) + return -1; + m->status = b[24]; + m->len = (uint16_t)(len - NB_MIN); + m->data = b + NB_MIN; + break; + default: + return -1; + } + return fields_ok(m) ? 0 : -1; +} diff --git a/native/boot/netboot_proto.h b/native/boot/netboot_proto.h new file mode 100644 index 00000000..1e923fbd --- /dev/null +++ b/native/boot/netboot_proto.h @@ -0,0 +1,91 @@ +/* netboot_proto.h -- the AIENOS lab netboot wire format (NETLDR.EFI <-> host + * tools/ck_imac_netboot.c). Freestanding C, no heap, no I/O; the same object + * is linked into the UEFI loader and the host server. + * + * Purpose: put a new test kernel on the iMac without touching the USB stick. + * NETLDR.EFI stays on the stick as EFI/BOOT/BOOTX64.EFI, asks the LAN for a + * kernel, verifies it (ck_slot_verify: Ed25519 manifest signature by a key + * baked in at build time, SHA-512 of the image) and only then starts it. + * Nothing in these messages is trusted: the transfer only moves bytes, the + * signature decides. Anyone on the LAN can read the transfer (the kernels are + * open source) or disturb it (a denial of service, never a takeover). + * + * Transport: UDP over IPv4, Ethernet broadcast both ways, so neither side + * needs an address, ARP or DHCP. The loader sends from 0.0.0.0:NB_PORT_LOADER + * to 255.255.255.255:NB_PORT_SERVER; the server answers to the subnet + * broadcast address, port NB_PORT_LOADER. TTL 1: this network only. + * + * Message (all integers big-endian), NB_HDR + 8 fixed body bytes minimum: + * 0 magic "ANB1" 4 type u8 5 reserved[3] = 0 8 nonce[16] + * HELLO 1 L->S 24 mac[6] 30 reserved[2] (32 bytes) + * OFFER 2 S->L 24 total u32 28 chunk u16 = NB_CHUNK 30 rsvd u16 (32) + * WAIT 3 S->L 24 seconds u16 (1..NB_WAIT_MAX) 26 reserved[6] (32) + * GET 4 L->S 24 offset u32 28 count u16 (1..NB_WINDOW) 30 rsvd (32) + * DATA 5 S->L 24 offset u32 28 len u16 30 rsvd u16 32 data[len] (32 + len) + * DONE 6 L->S 24 status u8 (0 verified, booting; 1 refused) 25 rsvd[7] + * 32 text[n], n <= NB_TEXT_MAX printable ASCII (32 + n) + * The nonce is chosen by the loader for each attempt and echoed by the server; + * it pairs replies with requests and is not a secret. + * The object served is a signed slot manifest (CK_SLOT_UNIT bytes, + * slot_format.h) followed by the image: total = CK_SLOT_UNIT + image_len. + * DATA offsets are multiples of NB_CHUNK; every chunk but the last is full. */ +#ifndef AIENOS_NETBOOT_PROTO_H +#define AIENOS_NETBOOT_PROTO_H +#include +#include + +#define NB_MAGIC "ANB1" +#define NB_PORT_SERVER 47032u +#define NB_PORT_LOADER 47033u +#define NB_HDR 24u +#define NB_MIN 32u +#define NB_CHUNK 1024u +#define NB_WINDOW 16u +#define NB_WAIT_MAX 60u +#define NB_TEXT_MAX 96u +#define NB_OBJECT_MIN (4096u + 1u) +#define NB_OBJECT_MAX (64u << 20) +#define NB_MSG_MAX (NB_MIN + NB_CHUNK) + +enum nb_type { NB_HELLO = 1, NB_OFFER, NB_WAIT, NB_GET, NB_DATA, NB_DONE }; + +struct nb_msg { + uint8_t type; + uint8_t nonce[16]; + uint8_t mac[6]; /* HELLO */ + uint32_t total; /* OFFER */ + uint16_t seconds; /* WAIT */ + uint32_t offset; /* GET, DATA */ + uint16_t count; /* GET */ + uint16_t len; /* DATA bytes, DONE text bytes */ + uint8_t status; /* DONE */ + const uint8_t *data; /* DATA payload or DONE text: a view into the parsed buffer, or the bytes to send */ +}; + +/* Encode m into out. Returns the message length, or 0 if m breaks a rule + * above or cap is too small. */ +size_t nb_build(const struct nb_msg *m, uint8_t *out, size_t cap); +/* Decode and check one message. Returns 0 and fills *m, or -1 for anything + * malformed (wrong magic, nonzero reserved bytes, unknown type, wrong length, + * out-of-range field, unprintable text). */ +int nb_parse(const uint8_t *b, size_t len, struct nb_msg *m); +/* Number of NB_CHUNK pieces in an object of total bytes. */ +static inline uint32_t nb_chunks(uint32_t total) { return (total + NB_CHUNK - 1u) / NB_CHUNK; } + +/* 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 57d1b019..12c6cb8e 100644 --- a/native/kernel/.crumb +++ b/native/kernel/.crumb @@ -46,68 +46,68 @@ "children": [ { "digest": "8f63182b423b274a3fa6dcf0a17811343f93bd1539e33479102ffa87935da1ca", - "last_commit": "4bd49ca", + "last_commit": "2529bc0", "name": "arch", "purpose": "Directory native/kernel/arch. Purpose not yet described by a human." }, { "digest": "cd3be26829bc7f947521b1e5df144df2504ef25a3763ec0356861b7d17d5d901", - "last_commit": "4bd49ca", + "last_commit": "6ad9190", "name": "artifact", "purpose": "Directory native/kernel/artifact. Purpose not yet described by a human." }, { - "digest": "c9035b8f32a9539fe8d1f93ed968b3b56dd3ba4c2630b32b6c286b1dbd19d908", - "last_commit": "4bd49ca", + "digest": "c7fcac4a7a3ed7e973c4178fc4a24bbc22518043ff6159223d4426351ec15b12", + "last_commit": "9329896", "name": "core", "purpose": "Directory native/kernel/core. Purpose not yet described by a human." }, { - "digest": "ebdd66c0966fba664f36dc167836b98d26ffae97f9502b4409e9c22da687b473", - "last_commit": "4bd49ca", + "digest": "61a3ab174dcd2486d62ede45aeeef387b1dbbcebcd56bf9cb88a82a4661db367", + "last_commit": "ad395ea", "name": "dev", "purpose": "Directory native/kernel/dev. Purpose not yet described by a human." }, { "digest": "8198bb9a0fbd634281a251b012eca8874c97e469a45eec8b5a6bf06a7e828f9a", - "last_commit": "4bd49ca", + "last_commit": "0735543", "name": "include", "purpose": "Directory native/kernel/include. Purpose not yet described by a human." }, { "digest": "8252fab960e4a3bb686f2e864b0d9a0571f43381d5006de2ff6c134c132ef092", - "last_commit": "4bd49ca", + "last_commit": "2bc7146", "name": "mm", "purpose": "Directory native/kernel/mm. Purpose not yet described by a human." }, { - "digest": "2a98333d826d94a7131119aaeb5a15d8bc543baa5531fa930e6f0afc1fccb83d", - "last_commit": "4bd49ca", + "digest": "1c3f76b94e58577b472903cbdcf85ec62012e84d9393c0c6a9eb6975cab22754", + "last_commit": "6cdd8bd", "name": "svc", "purpose": "Directory native/kernel/svc. Purpose not yet described by a human." }, { - "digest": "0f3d28a645346382567a7a279a3e02a095c8e7f298967db175944c0a58ca9c5d", - "last_commit": "3037967", + "digest": "3897aca9c8eeaa11c18f07ca90a4831041213be12a49c209378787705064351b", + "last_commit": "0175c6c", "name": "tests", "purpose": "Directory native/kernel/tests. Purpose not yet described by a human." }, { - "digest": "412f0a290f187935193ec94f1817c46dbe0edc07a5eb427e39977b65c1d00f9f", - "last_commit": "3037967", + "digest": "5eb33301e44ab4e5e4459aae9086102f41774e3809855028f9b9211e3edff7a3", + "last_commit": "c9065b1", "name": "tools", "purpose": "Hosted (Linux-built) checkers for the native kernel, run by `make -C native/kernel test`; nothin" } ], - "children_root": "sha256:658a040f493b6ff9dc4a775b2b73a0c89ded592a235231016dd8594094530e0f", - "compiled_at": "2026-10-17T01:49:45Z", + "children_root": "sha256:b8569318c0fb4a3dfb9f84bb85fec09c6faa6c0fdcbeacec4fe7b230a243f195", + "compiled_at": "2026-10-18T12:23:39Z", "compiler": "crumb-compile/1", - "digest": "sha256:7a81b1b4b47154e15b9682b72d7fa49f309454f093aeb019061b8148550920ae", + "digest": "sha256:10db4a03aa159fb128309af8992c878eded5f0164b837eaf29b2acb47e560c59", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 421, - "generated_at_commit": "30379678add587e388db4e11713d6bca8d159b08", - "source_tree": "sha256:cfa9d56bd0bae125be856e13a57758e007e620d1fc9501643728e676f53eaabe" + "files": 458, + "generated_at_commit": "105544890f780085f64bee754d4a92c1a2f17ecf", + "source_tree": "sha256:40791b3f30885e79a97382478de71f1f6ffe80c83fc1c6d8b8c2e8ce2ec57014" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/Makefile b/native/kernel/Makefile index 20a92ad3..07941e6a 100644 --- a/native/kernel/Makefile +++ b/native/kernel/Makefile @@ -604,9 +604,17 @@ ifneq ($(strip $(CK_CONSOLE_SESSION)),) ifneq ($(strip $(CK_CONSOLE_SESSION)),1) $(error CK_CONSOLE_SESSION must be empty or 1) endif +# CK_ALLEN=1 is the one session allowed on hardware: its lines go only to +# Allen's conversation (svc/allen_session.c), the shell is never called, so +# the session adds no command authority; the xHCI DMA fence is unchanged. ifneq ($(strip $(CK_HARDWARE_STAGING)),) +ifneq ($(strip $(CK_ALLEN)),1) $(error CK_CONSOLE_SESSION (QEMU test console session) cannot be combined with CK_HARDWARE_STAGING) endif +ifneq ($(strip $(CK_TEST_CONSOLE_MUTATION)),) +$(error CK_TEST_CONSOLE_MUTATION is QEMU only and cannot be combined with CK_HARDWARE_STAGING) +endif +endif ifneq ($(strip $(CK_QEMU_UNSAFE_DMA)),) $(error CK_CONSOLE_SESSION cannot be combined with CK_QEMU_UNSAFE_DMA) endif @@ -858,6 +866,11 @@ endif # GOP framebuffer console keeps the last report on screen before the PSCI # reset, so an operator can read or photograph it. 0 (default) in every QEMU # gate; scripts/stage_one_time_boot_ck.sh builds the hardware image with 120. +# The Allen hardware image holds its last screen 120 s (the owner reads or +# photographs it before the reset) unless the build line sets CK_FB_HOLD_S. +ifeq ($(strip $(CK_ALLEN))$(if $(strip $(CK_HARDWARE_STAGING)),hw),1hw) +CK_FB_HOLD_S ?= 120 +endif CK_FB_HOLD_S ?= 0 ifeq ($(shell echo '$(CK_FB_HOLD_S)' | grep -Ex '[0-9]{1,4}'),) $(error CK_FB_HOLD_S must be 0..9999 seconds) @@ -942,10 +955,25 @@ FULL_NAME := full-test-console-mutation STAGE_DMA_FLAGS += -DCK_TEST_CONSOLE_MUTATION=1 endif endif +# CK_ALLEN=1 (with CK_CONSOLE_SESSION=1): the console session hands each line +# to Allen (svc/allen_session.c) instead of the shell; own OUT full-allen/. +ifneq ($(strip $(CK_ALLEN)),) +ifneq ($(strip $(CK_CONSOLE_SESSION)),1) +$(error CK_ALLEN needs CK_CONSOLE_SESSION=1) +endif +FULL_NAME := full-allen +STAGE_DMA_FLAGS += -DCK_ALLEN=1 +STAGE_SRCS += $(KDIR)/svc/allen_reply.c $(KDIR)/svc/allen_notes.c $(KDIR)/svc/allen_memory.c \ + $(KDIR)/svc/allen_session.c $(KDIR)/dev/disk_extent.c +endif ifneq ($(strip $(CK_HARDWARE_STAGING)),) # Own OUT subdirectory: stage objects built with these flags never mix with # the default full image's objects. +ifeq ($(strip $(CK_ALLEN)),1) +FULL_NAME := full-allen-hardware +else FULL_NAME := full-hardware-staging +endif OWNER_HDR := $(OUT)/gen-$(FULL_NAME)/ck_owner_prov.h STAGE_DMA_FLAGS += -DCK_HARDWARE_STAGING=1 -I$(dir $(OWNER_HDR)) else @@ -1061,11 +1089,19 @@ $(OUT)/commit.stamp: FORCE @mkdir -p $(OUT) @echo '$(AIENOS_COMMIT)' | cmp -s - $@ || echo '$(AIENOS_COMMIT)' > $@ -$(KOBJ)/%.o: $(NATIVE)/%.c $(HDRS) +# Shared kernel objects are rebuilt whenever the compile flags change (e.g. +# CK_FB_HOLD_S differs between the QEMU and the hardware Allen image), so one +# image never links another image's objects. +$(OUT)/kcflags.stamp: FORCE + @mkdir -p $(OUT) + $(file >$@.new,$(KCC) $(KCFLAGS)) + @cmp -s $@.new $@ && rm -f $@.new || mv -f $@.new $@ + +$(KOBJ)/%.o: $(NATIVE)/%.c $(HDRS) $(OUT)/kcflags.stamp @mkdir -p $(dir $@) $(KCC) $(KCFLAGS) -c -o $@ $< -$(KOBJ)/kernel/core/report.o: $(KDIR)/core/report.c $(HDRS) $(OUT)/commit.stamp +$(KOBJ)/kernel/core/report.o: $(KDIR)/core/report.c $(HDRS) $(OUT)/commit.stamp $(OUT)/kcflags.stamp @mkdir -p $(dir $@) $(KCC) $(KCFLAGS) -DAIENOS_COMMIT='"$(AIENOS_COMMIT)"' -c -o $@ $< @@ -1107,7 +1143,7 @@ $(KOBJ)/kernel/core/osh_test.o: $(KDIR)/core/osh_test.c $(HDRS) $(ART_HDRS) $(OU @mkdir -p $(dir $@) $(KCC) $(KCFLAGS) $(ART_TRUST_FLAGS) -c -o $@ $< -$(KOBJ)/%.o: $(NATIVE)/%.S +$(KOBJ)/%.o: $(NATIVE)/%.S $(OUT)/kcflags.stamp @mkdir -p $(dir $@) $(KCC) $(KCFLAGS) -c -o $@ $< @@ -2236,35 +2272,65 @@ $(IMACDIAG_EFI): $(IMACDIAG_ELF) @echo "built $@ (commit $(AIENOS_COMMIT))" imac-diag: $(IMACDIAG_EFI) -# ---- IMACKERN.EFI: AIENOS-IMAC-KERNEL-0, the C kernel core on x86_64 (2017 iMac) ---- +# ---- IMACKERN.EFI: AIENOS-KERNEL-0, the C kernel core on x86_64 (2017 iMac) ---- # x86/efi_x86.c (stub: GOP, RSDP, memory map, ExitBootServices, CHANDOF3) + x86/kmain_x86.c # (GDT/TSS/IDT, own page tables, guard page, HPET-timed TSC, local APIC timer, ACPI S5) # + x86/pci_x86.c (PCI walk; AHCI via x86/ahci_x86.c and NVMe via ../disk/disk_nvme.c, both # read-only, GPT checked by dev/disk_part.c; a look at the Ethernet chip) + x86/smp_x86.S -# (secondary cores started and parked) + x86/tg3_x86.c (BCM57766 Ethernet, transmit only) and -# x86/report_x86.c with ../../net/aienos_net.c (the screen sent as UDP broadcasts during the hold; -# host test scripts/ck_imac_report_test.sh, receiver tools/ck_imac_report_listen.c) +# (secondary cores started and parked) + x86/xhci_x86.c (USB boot keyboard, polled, hubs; key +# decode and line editor from dev/usb_hid.c) + x86/tg3_x86.c (BCM57766 Ethernet: link detection; no +# transmit in the default image) + ui/allen_ui.c, ui/allen_font.c (Allen's window on the screen, drawn +# with its own stroke typeface; ui/night.c, the night sky of the startup, and ui/mind.c, Allen's presence, on ui/paint.c; +# drawn by the secondary cores) + svc/allen_reply.c (Allen's first local answers) # + x86/trap.S + x86/console_x86.c (COM1 when present, GOP framebuffer), on the # arch-neutral core: fbcon, fmt, acpi, handoff_check, frames, heap. Same toolchain and PE # header as IMACDIAG. Copy to a FAT stick as EFI/BOOT/BOOTX64.EFI. # make imac-kernel -> $(OUT)/IMACKERN.EFI QEMU test: scripts/qemu_ck_imac_kernel_test.sh +# The network report is a LAB-ONLY diagnostic, opt-in and default off: +# make imac-kernel CK_X86_REPORT=1 -> $(OUT)/IMACKERN-LAB.EFI (own object dir) +# adds x86/report_x86.c + ../../net/aienos_net.c and tg3 transmit (-DCK_X86_REPORT=1): during the +# hold it broadcasts only allowlisted console lines (ck_x86_report_filter, never the raw console) +# as UDP to port 47031, header "AIENOS-REPORT v=2 auth=none": UNAUTHENTICATED, never a +# receipt, evidence or a command. Host test scripts/ck_imac_report_test.sh, receiver +# tools/ck_imac_report_listen.c. The default image, and any resident or service (ALLEN) build, +# must not contain it: the link step below fails a default image that has a report symbol. +CK_X86_REPORT ?= 0 X86K := $(KDIR)/x86 +ifeq ($(CK_X86_REPORT),1) +IMACKERN_DIR := $(OUT)/imackern-lab +IMACKERN_EFI := $(OUT)/IMACKERN-LAB.EFI +else ifeq ($(CK_X86_REPORT),0) IMACKERN_DIR := $(OUT)/imackern -IMACKERN_ELF := $(IMACKERN_DIR)/imackern.elf IMACKERN_EFI := $(OUT)/IMACKERN.EFI -IMACKERN_CFLAGS := $(X86CFLAGS) -I$(KDIR)/include -I$(KDIR)/mm -I$(KDIR)/dev -I$(NATIVE)/disk -I$(NATIVE)/net +else +$(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)/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 \ $(IMACKERN_DIR)/frames.o $(IMACKERN_DIR)/heap.o $(IMACKERN_DIR)/libc_min.o \ $(IMACKERN_DIR)/ahci_x86.o $(IMACKERN_DIR)/disk_part.o $(IMACKERN_DIR)/disk.o \ $(IMACKERN_DIR)/pci_x86.o $(IMACKERN_DIR)/smp_x86.o $(IMACKERN_DIR)/disk_nvme.o \ - $(IMACKERN_DIR)/tg3_x86.o $(IMACKERN_DIR)/report_x86.o $(IMACKERN_DIR)/aienos_net.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)/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 +ifeq ($(CK_X86_REPORT),1) +IMACKERN_OBJS += $(IMACKERN_REPORT_OBJS) +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 $(OUT)/commit.stamp +$(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 $(IMACKERN_DIR)/trap.o: $(X86K)/trap.S $(IMACKERN_DIR)/fbcon.o: $(KDIR)/core/fbcon.c $(KDIR)/core/fbcon.h $(KDIR)/core/font8x8.h @@ -2281,16 +2347,37 @@ $(IMACKERN_DIR)/pci_x86.o: $(X86K)/pci_x86.c $(IMACKERN_HDRS) $(KDIR)/mm/frames. $(IMACKERN_DIR)/smp_x86.o: $(X86K)/smp_x86.S $(IMACKERN_DIR)/disk_nvme.o: $(NATIVE)/disk/disk_nvme.c $(NATIVE)/disk/disk_nvme.h $(NATIVE)/disk/disk.h $(IMACKERN_DIR)/tg3_x86.o: $(X86K)/tg3_x86.c $(IMACKERN_HDRS) $(KDIR)/mm/frames.h +$(IMACKERN_DIR)/xhci_x86.o: $(X86K)/xhci_x86.c $(IMACKERN_HDRS) $(KDIR)/mm/frames.h $(KDIR)/dev/usb_hid.h +$(IMACKERN_DIR)/hda_x86.o: $(X86K)/hda_x86.c $(IMACKERN_HDRS) $(KDIR)/mm/frames.h $(KDIR)/ui/chirp.h $(KDIR)/ui/night.h +$(IMACKERN_DIR)/usb_hid.o: $(KDIR)/dev/usb_hid.c $(KDIR)/dev/usb_hid.h $(NATIVE)/argus/sha256.h +$(IMACKERN_DIR)/sha256.o: $(NATIVE)/argus/sha256.c $(NATIVE)/argus/sha256.h +$(IMACKERN_DIR)/allen_ui.o: $(KDIR)/ui/allen_ui.c $(KDIR)/ui/allen_ui.h $(KDIR)/ui/allen_font.h $(KDIR)/ui/night.h $(KDIR)/ui/mind.h $(KDIR)/ui/paint.h +$(IMACKERN_DIR)/allen_font.o: $(KDIR)/ui/allen_font.c $(KDIR)/ui/allen_font.h +$(IMACKERN_DIR)/paint.o: $(KDIR)/ui/paint.c $(KDIR)/ui/paint.h $(KDIR)/ui/allen_font.h +$(IMACKERN_DIR)/night.o: $(KDIR)/ui/night.c $(KDIR)/ui/night.h $(KDIR)/ui/paint.h +$(IMACKERN_DIR)/chirp.o: $(KDIR)/ui/chirp.c $(KDIR)/ui/chirp.h $(KDIR)/ui/night.h +$(IMACKERN_DIR)/mind.o: $(KDIR)/ui/mind.c $(KDIR)/ui/mind.h $(KDIR)/ui/paint.h +$(IMACKERN_DIR)/allen_reply.o: $(KDIR)/svc/allen_reply.c $(KDIR)/svc/allen_reply.h $(KDIR)/svc/allen_notes.h +$(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 \ + $(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 -$(IMACKERN_OBJS): +$(sort $(IMACKERN_OBJS) $(IMACKERN_REPORT_OBJS)): @mkdir -p $(dir $@) $(X86CC) $(IMACKERN_CFLAGS) -DAIENOS_COMMIT='"$(AIENOS_COMMIT)"' -c -o $@ $< $(IMACKERN_ELF): $(IMACKERN_OBJS) $(BOOT)/image_x86_64.ld @if grep -nE -- 'rt->|RuntimeServices' $(X86K)/*.c; then \ echo "the x86 kernel calls a UEFI runtime service; it must never call one"; exit 1; fi - @if grep -nE "define ATA_" $(X86K)/ahci_x86.c | grep -vE "ATA_(IDENTIFY 0xec|READ_DMA_EXT 0x25)$$"; then \ - echo "ahci_x86.c defines an ATA command other than IDENTIFY and READ DMA EXT; the driver is read-only"; exit 1; fi + @if grep -nE "define ATA_" $(X86K)/ahci_x86.c | grep -vE "ATA_(IDENTIFY 0xec|READ_DMA_EXT 0x25|WRITE_DMA_EXT 0x35|FLUSH_CACHE_EXT 0xea)$$"; then \ + echo "ahci_x86.c defines an ATA command other than IDENTIFY, READ/WRITE DMA EXT and FLUSH CACHE EXT"; exit 1; fi + @if grep -nE "ck_x86_ahci_allow\(" $(X86K)/*.c | grep -vE "^$(X86K)/(memory_x86\.c|ahci_x86\.c:[0-9]+:int ck_x86_ahci_allow\()"; then \ + echo "only memory_x86.c may open a write range on an AHCI disk"; exit 1; fi @if grep -nE "nvme_(write|flush)\(" $(X86K)/*.c; then \ echo "the x86 kernel calls nvme_write or nvme_flush; its disks are read-only"; exit 1; fi @mkdir -p $(dir $@) @@ -2302,6 +2389,15 @@ $(IMACKERN_ELF): $(IMACKERN_OBJS) $(BOOT)/image_x86_64.ld @n=$$($(X86NM) $@ | grep -c ' t isr_common$$' || true); s=$$($(X86NM) $@ | grep ' T ck_x86_isr_stubs$$' | cut -c1-16); \ e=$$($(X86NM) $@ | grep ' t isr_common$$' | cut -c1-16); \ if [ "$$n" != 1 ] || [ $$((0x$$e - 0x$$s)) != 4096 ]; then echo "interrupt stubs are not 256 x 16 bytes"; rm -f $@; exit 1; fi + @r=$$($(X86NM) $@ | grep -E ' [TtDdBbRr] ($(IMACKERN_REPORT_SYMS))$$' || true); \ + if [ "$(CK_X86_REPORT)" = 1 ]; then \ + for s in ck_x86_report_hold ck_x86_report_filter ck_x86_report_frame; do \ + echo "$$r" | grep -q " $$s$$" || { echo "lab image lacks $$s"; rm -f $@; exit 1; }; done; \ + elif [ -n "$$r" ]; then \ + echo "default iMac image links the lab-only network report (build it with CK_X86_REPORT=1 only):"; \ + echo "$$r"; rm -f $@; exit 1; fi + @if [ "$(CK_X86_REPORT)" != 1 ] && grep -aq "AIENOS-REPORT" $@; then \ + echo "default iMac image carries the report header string"; rm -f $@; exit 1; fi $(IMACKERN_EFI): $(IMACKERN_ELF) $(X86OBJCOPY) -O binary $< $@ @sz=$$(stat -c %s $@); pad=$$(( (4096 - sz % 4096) % 4096 )); \ @@ -2310,6 +2406,93 @@ $(IMACKERN_EFI): $(IMACKERN_ELF) @[ "$$(od -An -tx1 -j68 -N2 $@ | tr -d ' ')" = "6486" ] || { echo "PE Machine is not x86_64 (0x8664)"; rm -f $@; exit 1; } @echo "built $@ (commit $(AIENOS_COMMIT))" imac-kernel: $(IMACKERN_EFI) +# Negative test builds for W^X (#409), QEMU only and never deployed: CK_X86_WX_MUTATE=1 leaves RAM +# executable, =2 leaves the kernel's code writable, and the kernel's W^X probes must then panic +# (scripts/qemu_ck_imac_kernel_test.sh). Build them into their own OUT directory. +CK_X86_WX_MUTATE ?= 0 +ifneq ($(CK_X86_WX_MUTATE),0) +IMACKERN_CFLAGS += -DCK_X86_WX_MUTATE=$(CK_X86_WX_MUTATE) +endif + +# ---- NETLDR.EFI: the lab network loader for the 2017 iMac (x86_64) ---- +# native/boot/net_loader.c + netboot_proto.c (wire spec netboot_proto.h). Stays on the stick as +# EFI/BOOT/BOOTX64.EFI; at every power-on it fetches a kernel from tools/ck_imac_netboot.c over +# the LAN, verifies it with the SLOTLDR verifier (ck_slot_verify: Ed25519 manifest signature, +# SHA-512 of the image) against the public keys baked in from CK_NETLDR_KEYS ("owner_root_ed25519 +# <64 hex>" lines; ck_imac_netboot keygen writes one) and only then starts it. No answer for +# CK_NETLDR_FALLBACK_S seconds: it starts \EFI\AIENOS\IMACKERN.EFI from the stick instead. +# make imac-netldr CK_NETLDR_KEYS= -> $(OUT)/NETLDR.EFI +# make imac-netboot-tool -> $(OUT)/host/ck_imac_netboot (keygen, sign, serve) +# QEMU test: scripts/qemu_ck_imac_netboot_test.sh (AIENOS_IMAC_NETBOOT). +CK_NETLDR_KEYS ?= +CK_NETLDR_FALLBACK_S ?= 30 +ifeq ($(shell echo '$(CK_NETLDR_FALLBACK_S)' | grep -xE '[1-9][0-9]{0,3}'),) +$(error CK_NETLDR_FALLBACK_S must be a whole number of seconds, 1..9999) +endif +NETLDR_DIR := $(OUT)/netldr +NETLDR_ELF := $(NETLDR_DIR)/netldr.elf +NETLDR_EFI := $(OUT)/NETLDR.EFI +NETLDR_KEYS_C := $(NETLDR_DIR)/netldr_keys.c +NETLDR_C := $(BOOT)/net_loader.c $(BOOT)/netboot_proto.c $(BOOT)/slot_select.c $(NATIVE)/net/aienos_net.c \ + $(NATIVE)/sig/sha512.c $(NATIVE)/sig/ed25519.c $(NATIVE)/sig/ct.c $(NATIVE)/argus/sha256.c \ + $(KDIR)/core/libc_min.c $(KDIR)/core/fmt.c +NETLDR_OBJS := $(patsubst $(NATIVE)/%.c,$(NETLDR_DIR)/obj/%.o,$(NETLDR_C)) \ + $(NETLDR_DIR)/obj/efi_entry_x86_64.o $(NETLDR_DIR)/obj/netldr_keys.o +NETLDR_CFLAGS := $(X86CFLAGS) $(ART_INC) -I$(NATIVE)/net -I$(NATIVE)/store +NETLDR_HDRS := $(BOOT)/netboot_proto.h $(BOOT)/slot_format.h $(BOOT)/efi.h $(NATIVE)/net/aienos_net.h \ + $(KDIR)/core/fmt.h $(ART_HDRS) +$(NETLDR_DIR)/obj/%.o: $(NATIVE)/%.c $(NETLDR_HDRS) + @mkdir -p $(dir $@) + $(X86CC) $(NETLDR_CFLAGS) -c -o $@ $< +# The fallback delay is compiled in; the stamp rebuilds the loader when it changes. +$(NETLDR_DIR)/fallback.stamp: FORCE + @mkdir -p $(dir $@) + @[ "$$(cat $@ 2>/dev/null)" = "$(CK_NETLDR_FALLBACK_S)" ] || echo "$(CK_NETLDR_FALLBACK_S)" > $@ +$(NETLDR_DIR)/obj/boot/net_loader.o: $(BOOT)/net_loader.c $(NETLDR_HDRS) $(OUT)/commit.stamp $(NETLDR_DIR)/fallback.stamp + @mkdir -p $(dir $@) + $(X86CC) $(NETLDR_CFLAGS) -DAIENOS_COMMIT='"$(AIENOS_COMMIT)"' -DCK_NETLDR_FALLBACK_S=$(CK_NETLDR_FALLBACK_S)u -c -o $@ $< +$(NETLDR_DIR)/obj/efi_entry_x86_64.o: $(BOOT)/efi_entry_x86_64.S + @mkdir -p $(dir $@) + $(X86CC) $(X86CFLAGS) -c -o $@ $< +$(NETLDR_KEYS_C): $(SLOT_TOOL) FORCE + @[ -n "$(strip $(CK_NETLDR_KEYS))" ] || { echo "imac-netldr: give CK_NETLDR_KEYS= (ck_imac_netboot keygen writes one)"; exit 1; } + @mkdir -p $(dir $@) + @$(SLOT_TOOL) keys-c --keys $(abspath $(CK_NETLDR_KEYS)) --out $@ +$(NETLDR_DIR)/obj/netldr_keys.o: $(NETLDR_KEYS_C) + @mkdir -p $(dir $@) + $(X86CC) $(NETLDR_CFLAGS) -c -o $@ $< +$(NETLDR_ELF): $(NETLDR_OBJS) $(BOOT)/image_x86_64.ld + @if grep -nE -- '->(RuntimeServices|ExitBootServices|SetVariable|GetVariable)|RuntimeServices' $(BOOT)/net_loader.c; then \ + echo "net_loader.c calls a service the network loader must never call"; exit 1; fi + @mkdir -p $(dir $@) + $(X86LD) $(X86LDFLAGS) -o $@ $(NETLDR_OBJS) + @u=$$($(X86NM) -u $@ | grep -v ' w ' || true); \ + if [ -n "$$u" ]; then echo "image has undefined symbols: $$u"; rm -f $@; exit 1; fi + @bad=$$($(X86READELF) -rW $@ | grep -E '^[0-9a-f]+ ' | grep -v R_X86_64_RELATIVE || true); \ + if [ -n "$$bad" ]; then echo "image has non-RELATIVE relocations:"; echo "$$bad"; rm -f $@; exit 1; fi + @k=$$($(X86NM) $@ | grep -E ' [TtDdBbRr] (ck_x86_kernel_entry|kernel_main|ck_printf)$$' || true); \ + if [ -n "$$k" ]; then echo "NETLDR links kernel objects: $$k"; rm -f $@; exit 1; fi + @if grep -aqF "TEST-ONLY" $@; then echo "NETLDR carries a TEST-ONLY key note"; rm -f $@; exit 1; fi +$(NETLDR_EFI): $(NETLDR_ELF) + $(X86OBJCOPY) -O binary $< $@ + @sz=$$(stat -c %s $@); pad=$$(( (4096 - sz % 4096) % 4096 )); \ + if [ $$pad -gt 0 ]; then head -c $$pad /dev/zero >> $@; fi + @[ "$$(head -c 2 $@)" = "MZ" ] || { echo "not a PE image"; rm -f $@; exit 1; } + @[ "$$(od -An -tx1 -j68 -N2 $@ | tr -d ' ')" = "6486" ] || { echo "PE Machine is not x86_64 (0x8664)"; rm -f $@; exit 1; } + @echo "built $@ (commit $(AIENOS_COMMIT), fallback $(CK_NETLDR_FALLBACK_S) s)" +imac-netldr: $(NETLDR_EFI) +NETBOOT_TOOL := $(OUT)/host/ck_imac_netboot +NETBOOT_TOOL_SRCS := $(KDIR)/tools/ck_imac_netboot.c $(BOOT)/netboot_proto.c $(NATIVE)/net/aienos_net.c \ + $(NATIVE)/sig/sha512.c $(NATIVE)/sig/ed25519.c $(NATIVE)/sig/ct.c +$(NETBOOT_TOOL): $(NETBOOT_TOOL_SRCS) $(BOOT)/netboot_proto.h $(NATIVE)/net/aienos_net.h $(NATIVE)/sig/aienos_sig.h + @mkdir -p $(dir $@) + $(HOSTCC) -std=gnu11 -O2 -Wall -Wextra -Werror -I$(BOOT) -I$(NATIVE)/net -I$(NATIVE)/sig -o $@ $(NETBOOT_TOOL_SRCS) +# Apple NetBoot answerer (BSDP + one-file TFTP): the iMac starts NETLDR.EFI from the Spark with N held. +BSDP_TOOL := $(OUT)/host/ck_imac_bsdp +$(BSDP_TOOL): $(KDIR)/tools/ck_imac_bsdp.c + @mkdir -p $(dir $@) + $(HOSTCC) -std=gnu11 -O2 -Wall -Wextra -Werror -o $@ $< +imac-netboot-tool: $(NETBOOT_TOOL) $(BSDP_TOOL) # Raspberry Pi 5 board image (see CK_PI5 above): target/native-kernel-pi5/BOOTAA64.EFI pi5-store: @@ -2398,7 +2581,7 @@ $(OUT)/host-san/test_pi5_rng: $(KDIR)/tests/test_pi5_rng.c $(PI5_RNG_SRCS) $(KDI $(HOSTCC) $(HCFLAGS) $(SANFLAGS) -DCK_RNG200_SPINS=1000 -I$(KDIR)/dev -o $@ $< $(PI5_RNG_SRCS) FORCE: -.PHONY: uefi-vars slot-loader slot-loader-check pi5-diag imac-diag imac-kernel +.PHONY: uefi-vars slot-loader slot-loader-check pi5-diag imac-diag imac-kernel imac-netldr imac-netboot-tool .PHONY: artifact-tier-pi5 artifact-tier-mutant .PHONY: osc-receipt-mutants osc-receipt-release all full pi5 pi5-store pi5-infer pi5-unlock pi5-unlock-card pi5-fact pi5-agent pi5-lifecycle pi5-artifact artifact-card-mutant test sanitize context-mutant agent-cmd-mutant cortex-image handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants acpi-scan clean print-kcflags udp-echo tool store-image gpt-image cont-tool owner-gen fb-check continuity-mutants continuity-resolve-mutants FORCE diff --git a/native/kernel/README.md b/native/kernel/README.md index 9b30cc2f..34b468f4 100644 --- a/native/kernel/README.md +++ b/native/kernel/README.md @@ -14,7 +14,7 @@ QEMU qualifies nothing physical: a PASS here says nothing about real hardware. | `core/` | Console, printf, ACPI, reports/panic/PSCI reset, M3 (threads, scheduler, EL0, capabilities, IPC), `kmain.c`. | | `tests/` | Host unit tests. | | `third_party/omega/` | The canonical Omega Cortex store, byte for byte from the omega commit in `omega.lock` (checked by `scripts/omega_lock_check.sh`); built freestanding by `svc/cortex_store.c` over the sealed Store through `svc/cortex_journal.c` (native v1 plan P06). | -| `x86/` | x86_64 port, first cut (AIENOS-IMAC-KERNEL-0, 2017 iMac): UEFI stub, descriptor tables and interrupt stubs, page tables, local APIC timer, ACPI power off, console, secondary-core start, PCI walk, read-only AHCI and NVMe disks, transmit-only BCM57766 Ethernet report. | +| `x86/` | x86_64 port, first cut (AIENOS-KERNEL-0, 2017 iMac): UEFI stub, descriptor tables and interrupt stubs, page tables, local APIC timer, ACPI power off, console, secondary-core start, PCI walk, read-only AHCI and NVMe disks, BCM57766 Ethernet link detection; a lab-only, opt-in network report (`CK_X86_REPORT=1`). | | `../boot/` | Minimal UEFI entry stub (one image with the kernel). | ## Build and test @@ -143,7 +143,7 @@ of them: host tools) are still present as data in every image, including hardware staging; the ordinary loader trusts no anchor. -## 2017 iMac image (AIENOS-IMAC-KERNEL-0, x86_64) +## 2017 iMac image (AIENOS-KERNEL-0, x86_64) make -C native/kernel imac-kernel # target/native-kernel/IMACKERN.EFI scripts/qemu_ck_imac_kernel_test.sh # QEMU q35 + OVMF, two CPU models, ends AIENOS_IMAC_KERNEL @@ -168,19 +168,137 @@ build refuses any other ATA command); NVMe through the shared `x86/`). Both disk_dev write hooks always refuse, serial numbers and MAC addresses are never printed, and each disk's GPT is checked by the shared `dev/disk_part.c` (both copies, CRCs, the AIENOS partition located if present). -The Broadcom BCM57766 Ethernet chip (14e4:1686) gets a transmit-only, polled -driver (`x86/tg3_x86.c`: core reset, bootcode handshake, rings in one DMA block -below 4 GiB, PHY autonegotiation; it never receives and the MAC address is -never printed). The last line before the hold is a one-line `summary:`. It -prints `kernel: alive`, holds the screen 60 s and powers off through ACPI S5. -During the hold `x86/report_x86.c` sends the RAM copy of the console (first -16 KiB) every 2 s while the link is up, as UDP broadcast from 0.0.0.0 to -255.255.255.255 port 47031 (TTL 1), in 1 KiB parts that each start with -`AIENOS-IMAC-REPORT v=1 run= part=/ bytes=`. -`tools/ck_imac_report_listen.c` (`make -C native/kernel imac-report-listen`, -run as `ck_imac_report_listen 47031 OUTDIR SECONDS`) rebuilds each run into -`OUTDIR/imac-.txt`; `scripts/ck_imac_report_test.sh` checks frames and -reassembly on the host, so a wired iMac no longer needs a photo of its screen. Output: the GOP framebuffer +The Broadcom BCM57766 Ethernet chip (14e4:1686) gets a polled driver +(`x86/tg3_x86.c`: core reset, bootcode handshake, rings in one DMA block below +4 GiB, PHY autonegotiation; it never reads received frames and the MAC address +is never printed). In the default image it only detects the link: frame +transmit is not compiled in. The last line before the hold is a one-line +`summary:`. It prints `kernel: alive`, holds the screen 60 s and powers off +through ACPI S5. + +**Network report: lab-only, opt-in, unauthenticated.** `make -C native/kernel +imac-kernel CK_X86_REPORT=1` builds a separate lab image, +`IMACKERN-LAB.EFI`, that adds `x86/report_x86.c`, `../net/aienos_net.c` and +tg3 transmit. The default `IMACKERN.EFI`, and any resident or service (ALLEN) +build, contain none of it; the link step fails a default image that has a +report symbol. During the hold the lab image sends, every 2 s while the link +is up, an allowlisted copy of the console (`ck_x86_report_filter`: only +complete, printable lines of at most 240 bytes whose key is on a fixed list of +kernel diagnostic keys; everything else, including `memory:`, is dropped +whole, so chat, keys, tokens and credentials cannot enter it), as UDP +broadcast from 0.0.0.0 to 255.255.255.255 port 47031 (TTL 1), in 1 KiB parts +that each start with +`AIENOS-REPORT v=2 auth=none run= part=/ bytes=`. +Anyone on the LAN can read or forge these datagrams; the run id and checksum +are not authenticity, so a report is never a receipt, evidence or a command. +Future service diagnostics belong on the authenticated transport with an +explicitly authorized peer. `tools/ck_imac_report_listen.c` (`make -C +native/kernel imac-report-listen`, run as `ck_imac_report_listen 47031 OUTDIR +SECONDS`) says so when it starts, refuses the retired v=1 raw-console format +and rebuilds each run into `OUTDIR/imac-.unauthenticated.txt`; +`scripts/ck_imac_report_test.sh` checks the default and lab builds' symbols, +the allowlist (sentinel lines never leave), the frames and reassembly on the +host. + +**Startup: the night sky.** The moment the clock is measured, before anything +is printed, `ui/allen_ui.c` takes the screen and starts the night +(`ui/night.c`): a dark sky fades in over about seven seconds, the brightest +stars first, with the Milky Way, its dust and six galaxies; two black holes +appear, bending the starlight round them, circle and spiral in on the +inspiral law (separation as t^(1/4), angle as t^(5/8), t the time left), +merge at 12 s in a flash, and a ripple runs out across the sky. From the light +of the merger Allen gathers (`ui/mind.c`): no face and no body, a mind drawn as +light, about a hundred points on and inside a sphere joined by fine threads, +turning slowly round a warm heart, with sparks running along the threads. +The startup text stays off the screen (`ck_x86_console_fb_hold`) until +Allen's window takes over; a panic, or no window, stops the drawing and +brings the text back. Every pixel is worked out from its position and the +time, so a frame redraws only the parts that change, in strips: once the +secondary cores are up, the first draws the frames and the next two draw +strips of them (`smp: ... state=drawing helpers=2`); before that the boot core +draws a frame between console writes. Kernel lines: `screen: night: the sky +made in ...` and `screen: night: N frames ..., average ... ms, slowest ... +ms` (when Allen wakes, 20 s later, and at goodbye). +`ui/chirp.c` is the matching sound: a quick "blirp", the last 0.6 s of the +gravitational-wave chirp of the same inspiral, raised into hearing (200 Hz +sweeping to 1000 Hz, loudness as pitch^(2/3)), peaking at the merger and +ringing out within 0.3 s: under a second in all, worked out from the formula. `x86/hda_x86.c` plays +it: on each HD Audio controller it stops any DMA the firmware left running, resets the link with +the settle times Linux uses, talks to the codecs through the command rings +(CORB/RIRB, polled), maps every widget of each codec onto the report +(`sound: codec=N w=0x.. ...`), opens every speaker, line-out and headphone +path back to a converter (power, routing, 0 dB, pin drive, EAPD; on Apple +boards the codec GPIOs), and on the first controller with a path runs one +output stream: the chirp from the moment the night has reached, then 8 s of +silence; the stream is stopped once the chirp is over. Intel controllers get +Linux's PCI settings first (`pci_x86.c`). In QEMU the recording of what the +guest played matches the chirp sample for sample, starting at the night's +moment. A Cirrus CS8409 bridge on an Apple board (the desktop test +computer's codec) gets its own set-up instead: its four speaker amplifiers +sit behind it on its own I2C bus, so the driver sets the bridge's defaults, +resets the amplifiers into shutdown, sets the TDM slots and clocks, configures +and switches on each amplifier and synchronises the two converters, following +the sequence davidjo/snd_hda_macbookpro replays from macOS. That sequence only +plays 44.1 kHz 24-bit, so behind a CS8409 the chirp is resampled to that +(`ck_chirp_fill_441`, host tested against the 48 kHz sound). The amplifiers +run 24 dB under the level macOS uses. **Heard on the test computer +(2026-10-18):** all four amplifiers answered (no I2C transfer unconfirmed) +and the chirp played; at 12 dB under it was very loud and the old ten-second +chirp too long, hence the quieter level and the short blirp. QEMU has no +CS8409, so this path is checked only on that machine. +Tests: `scripts/ck_allen_ui_test.sh` (host; pictures in +`target/native-kernel-allen-ui/`), `scripts/ck_chirp_test.sh` (the sound as +`target/native-kernel-chirp/chirp.wav`); the QEMU kernel test requires the +night line, the drawing cores, the codec mapped through the command rings, +the chirp stream running and its stop. `AIENOS_IMAC_KERNEL_KEEP_DIR=` +keeps each run's serial log and a `.wav` recording of its sound. + +**Keyboard and Allen's window.** `x86/xhci_x86.c` drives a wired USB boot +keyboard (polled xHCI, through USB 2.0 hubs). When one is ready, Allen wakes: +the person is his guest. A quiet glass bar comes up at the bottom for what +they type; on Enter the line rises from the bar into him, he thinks (he draws +in, turns faster, sparks cascade), then answers under him word by word while +the galaxies shimmer with his voice, all in Allen's own stroke typeface +(`ui/allen_font.c`, every printable ASCII character as pen strokes, +rasterized with integer math). Nothing else is on the screen unless it is in +use: the bar fades when the conversation rests (a key brings it back), his +words fade once read, and the notes map (a small constellation) shows only +when a note is saved or handed back. Each Enter gets a local answer from +`svc/allen_reply.c`: "Hello Allen" gives "Hello Humanity."; it also knows small +talk, your name for the session, facts about the machine, how long it has been +awake and sums said in words ("what is 12 times 4"); anything else gives "I +don't know that yet." Answers print as `allen: ` on the console. The +window has no idle countdown: it stays up until "goodbye" (then ACPI S5, or a +restart in the lab image) or the power button. The conversation stays on the computer: `keyboard_line:` and `allen:` +are off the lab report's allowlist, which carries only `screen: Allen +answered (N characters in, M out)`. Without a keyboard or the memory the text +screen and its 60 s hold stay. Tests: `scripts/ck_allen_ui_test.sh` (host) and +`scripts/qemu_ck_imac_keyboard_test.sh` (QEMU, types "Hello Allen", keeps a +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: `core/fbcon.c`, `fmt.c`, `acpi.c`, `handoff_check.c`, `mm/frames.c`, `heap.c`, @@ -188,7 +306,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, NX, disk writes, +afterwards. Not yet: work scheduled on the other cores, x2APIC, NX, 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. @@ -280,9 +398,13 @@ What is implemented (NEXT-PHASE-3 cut 1): `dev/usb_kbd.c` resets the controller, finds the first connected port with a USB HID boot keyboard, addresses it, configures its interrupt IN endpoint and polls it. Polled only: no interrupts, no scheduler, no Store. -- **Key decode** to one small fixed US keymap (`dev/usb_hid.c`): a-z (with - Shift: A-Z), 0-9, space, `-`, `.`, `/`, Enter, Backspace, Escape. Every - other key is ignored. A held key produces one event, not a repeat. +- **Key decode** to one fixed US keymap (`dev/usb_hid.c`): every printable + character a US keyboard types, with and without Shift (letters, digits and + `!@#$%^&*()`, space, and the symbol keys with their shifted pairs, `?` + included), plus Enter, Backspace, Escape. Function keys, arrows, Tab and the + non-US key are ignored. A held key produces one event, not a repeat. The + console's commands match whole words only, so symbols can only make an + unknown command; Allen's facts keep letters, digits and spaces. - **Line input** with echo and a bound of 64 characters. One key past the bound makes the whole line fail closed: at Enter it is refused (`keyboard_line: overflow (line refused: N keys typed, limit 64)`) and never @@ -621,3 +743,8 @@ low-water free bytes. (no FP/SIMD; EL0 FP/SIMD traps). Placement is computed from the MADT; no secondary core is started (same as Rust). See GATES.md rows 16-20. - MAIR adds a Normal Non-cacheable attribute (index 2) for the DMA pool. + +## Allen on AArch64 and the many-piece region (2026-10-18) + +- `make full CK_CONSOLE_SESSION=1 CK_ALLEN=1` builds the Allen image: the console session hands every typed line to Allen (`svc/allen_session.c`), never to the shell. Add `CK_HARDWARE_STAGING=1` with the owner files for the hardware image (`full-allen-hardware/`); it is the only console session allowed on hardware. Without a keyboard it says so and the boot ends. Test: `scripts/qemu_ck_allen_arm64_test.sh` (A1-A6; `AIENOS_NO_KBD=1` for B1-B3; `AIENOS_ALLEN_EFI=` to test a prebuilt image). +- `dev/disk_extent.c` turns a locked host file's pieces (`REGION.MAP`) into one linear disk with fail-closed checks; `tools/ck_region_map.c` makes the map from FIEMAP and `tools/ck_region_probe.c` proves it against the raw disk. `make disk-extent-test` runs the host test and one mutant per guard. Evidence: `evidence/spark_region_probe_2026-10-18.md`. diff --git a/native/kernel/core/.crumb b/native/kernel/core/.crumb index 11410454..2889eca7 100644 --- a/native/kernel/core/.crumb +++ b/native/kernel/core/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-15T02:48:19Z", + "compiled_at": "2026-10-18T03:12:05Z", "compiler": "crumb-compile/1", - "digest": "sha256:c9035b8f32a9539fe8d1f93ed968b3b56dd3ba4c2630b32b6c286b1dbd19d908", + "digest": "sha256:c7fcac4a7a3ed7e973c4178fc4a24bbc22518043ff6159223d4426351ec15b12", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 69, - "generated_at_commit": "edd175183f30a31f4c7683e194dd6479dc8c7a6e", - "source_tree": "sha256:928d92ef1abd9076c57a25fb07becf22b43f0a46a7edd1998383f3dd6296e083" + "generated_at_commit": "9329896a390876ec99cff3405532effe8af4c166", + "source_tree": "sha256:49fe251937305771536a416424f536af104eadaccf764a9b0ce8658595b800d3" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/core/fbcon.c b/native/kernel/core/fbcon.c index 4e95f08c..fd4b6255 100644 --- a/native/kernel/core/fbcon.c +++ b/native/kernel/core/fbcon.c @@ -14,8 +14,8 @@ uint32_t ck_fbcon_scale_for(uint32_t width, uint32_t height) return s; } -int ck_fbcon_setup(struct ck_fbcon *c, volatile uint32_t *px, uint32_t width, uint32_t height, - uint32_t pitch, uint32_t format) +int ck_fbcon_attach(struct ck_fbcon *c, volatile uint32_t *px, uint32_t width, uint32_t height, + uint32_t pitch, uint32_t format) { if (!px || format > 1 || pitch < width) return -1; @@ -42,6 +42,14 @@ int ck_fbcon_setup(struct ck_fbcon *c, volatile uint32_t *px, uint32_t width, ui for (uint32_t r = 0; r < CK_FBCON_MAX_ROWS; r++) for (uint32_t k = 0; k < CK_FBCON_MAX_COLS; k++) c->text[r][k] = 0; + return 0; +} + +int ck_fbcon_setup(struct ck_fbcon *c, volatile uint32_t *px, uint32_t width, uint32_t height, + uint32_t pitch, uint32_t format) +{ + if (ck_fbcon_attach(c, px, width, height, pitch, format) != 0) + return -1; ck_fbcon_clear(c); return 0; } @@ -118,6 +126,11 @@ void ck_fbcon_write(struct ck_fbcon *c, const char *s, size_t n) c->col = 0; continue; } + if (ch == '\b') { /* cursor one cell left, within the line; the caller overwrites */ + if (!c->pending_nl && c->col) + c->col--; + continue; + } if (c->pending_nl) { advance(c); c->pending_nl = 0; diff --git a/native/kernel/core/fbcon.h b/native/kernel/core/fbcon.h index 73e5c75e..064a9fc4 100644 --- a/native/kernel/core/fbcon.h +++ b/native/kernel/core/fbcon.h @@ -48,6 +48,10 @@ uint32_t ck_fbcon_scale_for(uint32_t width, uint32_t height); * format is not 0/1. */ int ck_fbcon_setup(struct ck_fbcon *c, volatile uint32_t *px, uint32_t width, uint32_t height, uint32_t pitch, uint32_t format); +/* The same without touching a pixel: the screen keeps what is on it until + * the first clear or write. */ +int ck_fbcon_attach(struct ck_fbcon *c, volatile uint32_t *px, uint32_t width, uint32_t height, + uint32_t pitch, uint32_t format); void ck_fbcon_clear(struct ck_fbcon *c); void ck_fbcon_write(struct ck_fbcon *c, const char *s, size_t n); diff --git a/native/kernel/dev/.crumb b/native/kernel/dev/.crumb index 722e1a6b..3979e850 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-13T23:37:04Z", + "compiled_at": "2026-10-18T12:23:39Z", "compiler": "crumb-compile/1", - "digest": "sha256:ebdd66c0966fba664f36dc167836b98d26ffae97f9502b4409e9c22da687b473", + "digest": "sha256:61a3ab174dcd2486d62ede45aeeef387b1dbbcebcd56bf9cb88a82a4661db367", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 43, - "generated_at_commit": "23c8bcd5490dd2ec9ded661ffefd5ecb5533dcec", - "source_tree": "sha256:802face91e606e3063e35e7499217980f488aa11797961decc4c17e21bf4c22f" + "files": 51, + "generated_at_commit": "105544890f780085f64bee754d4a92c1a2f17ecf", + "source_tree": "sha256:b42c0757719aab2ec9bc8b84468c504bac1ff760234523a246a67eced15bccf0" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/dev/devices.c b/native/kernel/dev/devices.c index 9a9fdf39..2a8d5b36 100644 --- a/native/kernel/dev/devices.c +++ b/native/kernel/dev/devices.c @@ -160,6 +160,10 @@ void ck_stage_quiesce(void) if (xhci_live) ck_printf("devices: quiesce before reset xhci=released-now\n"); } +#if defined(CK_ALLEN) && CK_ALLEN +#include "../svc/allen_reply.h" +void ck_allen_session_begin(const ck_allen_facts *facts); +#endif #if defined(CK_CONSOLE_SESSION) && CK_CONSOLE_SESSION /* Final boot stage "console" (C3-1a, TEST-ONLY QEMU image built with * CK_CONSOLE_SESSION=1): runs after every other boot step. Serial (PL011) and @@ -173,10 +177,28 @@ int ck_stage_console_session(void) ck_printf("WARNING: TEST-ONLY console session MUTATION BUILD (CK_TEST_CONSOLE_MUTATION=bm-left-on-after-exit, " "QEMU gate self-test only, never a PASS)\n"); #endif +#if defined(CK_ALLEN) && CK_ALLEN && defined(CK_HARDWARE_STAGING) + ck_printf("console_session: begin (Allen hardware image: lines go to Allen only, no shell)\n"); +#else ck_printf("console_session: begin (TEST-ONLY QEMU image, CK_CONSOLE_SESSION=1; QEMU only, hardware NOT_RUN)\n"); +#endif +#if defined(CK_ALLEN) && CK_ALLEN + { + ck_allen_facts facts = {0, 0, g_nvme.pf ? 1u : 0u, 0, 0}; + ck_allen_session_begin(&facts); + } +#endif int xrc = ck_xhci_session(&g_pci); ck_printf("console_session: xhci fence returned rc=%d state=%s\n", xrc, ck_xhci_state()); +#if defined(CK_ALLEN) && CK_ALLEN && defined(CK_HARDWARE_STAGING) + /* Hardware Allen: no serial operator is assumed. Without the keyboard the + * session ends here and the boot goes on to its report and reset, so the + * machine returns to its default system instead of waiting forever. */ + if (!ck_console_session_ended()) + ck_printf("allen: I can't hear the keyboard on this computer yet, so I'll stop here for now. (keyboard: %s)\n", ck_xhci_state()); +#else ck_console_session_serial_only(); /* no-op once the exit came inside the fence */ +#endif ck_printf("console_session: end (exit) xhci=%s\n", ck_xhci_live() ? "LIVE" : "released"); return 0; } diff --git a/native/kernel/dev/disk_extent.c b/native/kernel/dev/disk_extent.c new file mode 100644 index 00000000..057674bc --- /dev/null +++ b/native/kernel/dev/disk_extent.c @@ -0,0 +1,209 @@ +/* disk_extent.c -- see disk_extent.h. Every check runs before the region is + * marked valid; a refused map leaves r->valid == 0 and no disk_dev. */ +#include "disk_extent.h" +#include "../../argus/sha256.h" + +static const uint8_t map_magic[8] = {'A', 'X', 'M', 'A', 'P', '1', 0, 0}; +static const uint8_t seal_magic[8] = {'A', 'I', 'E', 'N', 'R', 'G', 'N', '1'}; + +static uint64_t le64(const uint8_t *p) +{ + uint64_t v = 0; + for (int i = 7; i >= 0; i--) v = (v << 8) | p[i]; + return v; +} +static uint32_t le32(const uint8_t *p) { return (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24; } +static void put64(uint8_t *p, uint64_t v) +{ + for (int i = 0; i < 8; i++) p[i] = (uint8_t)(v >> (8 * i)); +} + +/* Heap sort of order[0..n) by piece[].abs (no allocation, n log n). */ +static void sift(const ck_ext_piece *pc, uint32_t *o, uint32_t i, uint32_t n) +{ + for (;;) { + uint32_t big = i, l = 2 * i + 1, r = l + 1; + if (l < n && pc[o[l]].abs > pc[o[big]].abs) big = l; + if (r < n && pc[o[r]].abs > pc[o[big]].abs) big = r; + if (big == i) return; + uint32_t t = o[i]; o[i] = o[big]; o[big] = t; + i = big; + } +} +static void sort_abs(const ck_ext_piece *pc, uint32_t *o, uint32_t n) +{ + for (uint32_t i = 0; i < n; i++) o[i] = i; + for (uint32_t i = n / 2; i-- > 0;) sift(pc, o, i, n); + for (uint32_t end = n; end-- > 1;) { + uint32_t t = o[0]; o[0] = o[end]; o[end] = t; + sift(pc, o, 0, end); + } +} + +static int ext_read(void *ctx, uint64_t lba, uint32_t count, uint8_t *buf); +static int ext_write(void *ctx, uint64_t lba, uint32_t count, const uint8_t *buf); +static int ext_flush(void *ctx); + +int ck_ext_parse(ck_ext_region *r, const disk_dev *parent, const uint8_t *map, size_t len, + ck_ext_piece *piece, uint32_t *order, uint32_t cap) +{ + if (!r || !parent || !map || !piece || !order) return DISK_EARG; + r->valid = 0; + r->parent = parent; + r->piece = piece; + r->count = 0; + r->blocks = 0; + if (parent->block_size != DISK_SECTOR_BYTES) return CK_EXT_EGEOM; + if (len < CK_EXT_HDR_BYTES) return CK_EXT_ECOUNT; + for (int i = 0; i < 8; i++) + if (map[i] != map_magic[i]) return CK_EXT_EMAGIC; + if (le32(map + 8) != 1u) return CK_EXT_EMAGIC; + uint32_t n = le32(map + 12); + if (n == 0 || n > CK_EXT_MAX || n > cap) return CK_EXT_ECOUNT; + if ((size_t)n * CK_EXT_PIECE_BYTES != len - CK_EXT_HDR_BYTES) return CK_EXT_ECOUNT; + uint64_t base = le64(map + 16), wfirst = le64(map + 24), wlast = le64(map + 32); + if (wfirst > wlast || wlast >= parent->block_count) return CK_EXT_EWINDOW; /* GUARD:ext-window */ + + const uint8_t *arr = map + CK_EXT_HDR_BYTES; + { + sha256_ctx h; + sha256_init(&h); + sha256_update(&h, map, 40); + sha256_update(&h, arr, (size_t)n * CK_EXT_PIECE_BYTES); + sha256_final(&h, r->digest); + } + uint8_t diff = 0; + for (int i = 0; i < 32; i++) diff |= (uint8_t)(r->digest[i] ^ map[40 + i]); + if (diff) return CK_EXT_EDIGEST; + + uint64_t next = 0; + for (uint32_t i = 0; i < n; i++) { + const uint8_t *e = arr + (size_t)i * CK_EXT_PIECE_BYTES; + uint64_t lg = le64(e), ph = le64(e + 8), ln = le64(e + 16); + if (ln == 0 || lg != next) return CK_EXT_EORDER; /* GUARD:ext-gapfree */ + if (lg + ln < lg) return CK_EXT_EORDER; + uint64_t a = base + ph; + if (a < base || a < wfirst || a > wlast || ln - 1 > wlast - a) return CK_EXT_EWINDOW; /* GUARD:ext-piece */ + piece[i].logical = lg; + piece[i].abs = a; + piece[i].length = ln; + next = lg + ln; + } + sort_abs(piece, order, n); + for (uint32_t i = 1; i < n; i++) { + const ck_ext_piece *lo = &piece[order[i - 1]], *hi = &piece[order[i]]; + if (lo->abs + lo->length > hi->abs) return CK_EXT_EOVERLAP; /* GUARD:ext-disjoint */ + } + r->count = n; + r->blocks = next; + r->dev.ctx = r; + r->dev.block_size = DISK_SECTOR_BYTES; + r->dev.block_count = next; + r->dev.read = ext_read; + r->dev.write = ext_write; + r->dev.flush = ext_flush; + r->dev.max_blocks_per_io = parent->max_blocks_per_io; + return CK_EXT_OK; +} + +int ck_ext_xlate(const ck_ext_region *r, uint64_t lba, uint64_t *abs, uint64_t *left) +{ + if (!r || !r->piece || r->count == 0 || !abs || !left) return DISK_ESTATE; + if (lba >= r->blocks) return DISK_ERANGE; + uint32_t lo = 0, hi = r->count; /* last piece with logical <= lba */ + while (hi - lo > 1) { + uint32_t mid = lo + (hi - lo) / 2; + if (r->piece[mid].logical <= lba) lo = mid; else hi = mid; + } + const ck_ext_piece *p = &r->piece[lo]; + uint64_t off = lba - p->logical; + if (off >= p->length) return DISK_ERANGE; + *abs = p->abs + off; + *left = p->length - off; + return DISK_OK; +} + +/* Split a request at piece boundaries; each part goes to the parent. */ +static int ext_io(ck_ext_region *r, uint64_t lba, uint32_t count, uint8_t *rd, const uint8_t *wr) +{ + if (!r || !r->parent || r->count == 0) return DISK_ESTATE; + if (count == 0) return DISK_EARG; + if (lba >= r->blocks || (uint64_t)count > r->blocks - lba) return DISK_ERANGE; /* second line: disk_read/disk_write check block_count first */ + while (count) { + uint64_t abs = 0, left = 0; + int rc = ck_ext_xlate(r, lba, &abs, &left); + if (rc) return rc; + uint32_t n = left < count ? (uint32_t)left : count; + rc = rd ? disk_read(r->parent, abs, n, rd) : disk_write(r->parent, abs, n, wr); + if (rc) return rc; + lba += n; + count -= n; + if (rd) rd += (size_t)n * DISK_SECTOR_BYTES; else wr += (size_t)n * DISK_SECTOR_BYTES; + } + return DISK_OK; +} +static int ext_read(void *ctx, uint64_t lba, uint32_t count, uint8_t *buf) +{ + ck_ext_region *r = ctx; + if (!r || !r->valid) return DISK_ESTATE; + return ext_io(r, lba, count, buf, 0); +} +static int ext_write(void *ctx, uint64_t lba, uint32_t count, const uint8_t *buf) +{ + ck_ext_region *r = ctx; + if (!r || !r->valid) return DISK_ESTATE; + if (lba == 0) return DISK_ERANGE; /* GUARD:ext-seal: block 0 is the seal, written only by open */ + return ext_io(r, lba, count, 0, buf); +} +static int ext_flush(void *ctx) +{ + ck_ext_region *r = ctx; + if (!r || !r->valid || !r->parent) return DISK_ESTATE; + return disk_flush(r->parent); +} + +static void make_seal(const ck_ext_region *r, uint8_t s[512]) +{ + for (int i = 0; i < 512; i++) s[i] = 0; + for (int i = 0; i < 8; i++) s[i] = seal_magic[i]; + for (int i = 0; i < 32; i++) s[8 + i] = r->digest[i]; + put64(s + 40, r->blocks); +} + +int ck_ext_open(ck_ext_region *r, uint8_t scratch[512]) +{ + if (!r || !scratch || r->count == 0 || r->valid) return DISK_ESTATE; + int rc = ext_io(r, 0, 1, scratch, 0); + if (rc) return rc; + uint8_t any = 0; + for (int i = 0; i < 512; i++) any |= scratch[i]; + uint8_t want[512]; + make_seal(r, want); + if (!any) { + rc = ext_io(r, 0, 1, 0, want); + if (!rc) rc = disk_flush(r->parent); + if (!rc) rc = ext_io(r, 0, 1, scratch, 0); + if (rc) return rc; + } + uint8_t diff = 0; + for (int i = 0; i < 512; i++) diff |= (uint8_t)(scratch[i] ^ want[i]); + if (diff) return CK_EXT_ESEAL; /* GUARD:ext-sealmatch */ + r->valid = 1; + return CK_EXT_OK; +} + +const char *ck_ext_strerror(int rc) +{ + switch (rc) { + case CK_EXT_OK: return "ok"; + case CK_EXT_EMAGIC: return "region map magic or version"; + case CK_EXT_ECOUNT: return "region map piece count"; + case CK_EXT_EDIGEST: return "region map digest mismatch"; + case CK_EXT_EORDER: return "region map gap or overlap"; + case CK_EXT_EWINDOW: return "region piece outside its window"; + case CK_EXT_EOVERLAP: return "region pieces overlap on disk"; + case CK_EXT_ESEAL: return "region seal does not match this map"; + case CK_EXT_EGEOM: return "region parent block size"; + default: return "disk error"; + } +} diff --git a/native/kernel/dev/disk_extent.h b/native/kernel/dev/disk_extent.h new file mode 100644 index 00000000..33bfb250 --- /dev/null +++ b/native/kernel/dev/disk_extent.h @@ -0,0 +1,75 @@ +/* disk_extent.h -- an AIENOS region made of many pieces of a shared disk. + * + * On a disk whose partition table belongs to another system, the owner can + * reserve a region as one locked, preallocated file of that system; the + * file's pieces (extents) are scattered over the disk. This layer turns the + * piece list into one linear disk_dev: logical block 0 .. blocks-1 maps, + * piece by piece, to absolute LBAs of the parent namespace. Nothing outside + * the listed pieces is ever read or written; a request that crosses a piece + * boundary is split; a list with a gap, an overlap, a piece outside the + * declared window or outside the parent is refused whole (fail closed). + * + * Map (on the boot disk as \EFI\AIENOS\REGION.MAP, little endian): + * 0 magic "AXMAP1\0\0" + * 8 u32 version (1) + * 12 u32 count of pieces (1 .. CK_EXT_MAX) + * 16 u64 base: absolute LBA the piece offsets are relative to + * (start of the host partition holding the file) + * 24 u64 window_first, 32 u64 window_last: absolute LBAs every piece + * must stay inside (the host partition) + * 40 u8[32] SHA-256 of bytes 0..39 then the piece array (header bound too) + * 72 pieces: count x { u64 logical, u64 physical (relative to base), u64 length } + * all in 512-byte units, sorted by logical, logical coverage gap free from 0. + * + * Seal (logical block 0 of the region, 512 bytes): "AIENRGN1", the map's + * piece SHA-256, the region length. A zero block 0 is a fresh region and + * is sealed on first open; any other content that is not this map's seal + * refuses the region (the pieces moved or a different map was supplied). */ +#ifndef AIENOS_CK_DISK_EXTENT_H +#define AIENOS_CK_DISK_EXTENT_H + +#include +#include +#include "disk.h" + +#define CK_EXT_MAX 16384u +#define CK_EXT_HDR_BYTES 72u +#define CK_EXT_PIECE_BYTES 24u + +enum { + CK_EXT_OK = 0, + CK_EXT_EMAGIC = -501, /* map magic / version */ + CK_EXT_ECOUNT = -502, /* zero or too many pieces, or short map */ + CK_EXT_EDIGEST = -503, /* piece array SHA-256 mismatch */ + CK_EXT_EORDER = -504, /* gap or overlap in logical coverage */ + CK_EXT_EWINDOW = -505, /* a piece outside the window or the parent */ + CK_EXT_EOVERLAP = -506, /* two pieces share physical blocks */ + CK_EXT_ESEAL = -507, /* block 0 holds something that is not our seal */ + CK_EXT_EGEOM = -508, /* parent block size is not 512 */ +}; + +typedef struct { + uint64_t logical, abs, length; /* abs = base + physical, checked */ +} ck_ext_piece; + +typedef struct { + const disk_dev *parent; + ck_ext_piece *piece; /* caller storage, count entries */ + uint32_t count; + uint64_t blocks; /* region length */ + uint8_t digest[32]; + int valid; + disk_dev dev; /* the linear region; use only when valid */ +} ck_ext_region; + +/* Parse and check a map (bytes, len) against the parent, filling piece[] + * (room for cap entries; order[] is scratch of the same size) and r. Does not touch the disk. */ +int ck_ext_parse(ck_ext_region *r, const disk_dev *parent, const uint8_t *map, size_t len, + ck_ext_piece *piece, uint32_t *order, uint32_t cap); +/* Read block 0: seal a zero block, accept our seal, refuse anything else. */ +int ck_ext_open(ck_ext_region *r, uint8_t scratch[512]); +/* One logical run -> absolute LBA and the blocks left in that piece. */ +int ck_ext_xlate(const ck_ext_region *r, uint64_t lba, uint64_t *abs, uint64_t *left); +const char *ck_ext_strerror(int rc); + +#endif diff --git a/native/kernel/dev/disk_part.c b/native/kernel/dev/disk_part.c index cf8a2d21..e4b02aba 100644 --- a/native/kernel/dev/disk_part.c +++ b/native/kernel/dev/disk_part.c @@ -214,15 +214,15 @@ int ck_gpt_find_type(const disk_dev *d, const uint8_t type[16], ck_part *p, ck_g if (rc) return rc; if (bcrc != get32(g_hdr + H_ECRC)) return CK_GPT_EBACKUP; + info->first_usable = first_u; + info->last_usable = last_u; + info->entries = g.num; + info->entry_size = g.esize; if (sem) { p->first_lba = 0; p->blocks = 0; return sem; } - info->first_usable = first_u; - info->last_usable = last_u; - info->entries = g.num; - info->entry_size = g.esize; p->valid = 1; p->dev.block_count = p->blocks; return CK_GPT_OK; diff --git a/native/kernel/dev/disk_part.h b/native/kernel/dev/disk_part.h index 7a4f8176..115eb505 100644 --- a/native/kernel/dev/disk_part.h +++ b/native/kernel/dev/disk_part.h @@ -70,6 +70,8 @@ typedef struct { uint32_t entries, entry_size; uint32_t used; /* used entries */ uint32_t part_index; /* index of the AIENOS entry */ + /* first_usable .. entry_size are filled whenever both GPT copies are + * valid, also when the answer is CK_GPT_ENOPART / EMULTI / EOVERLAP. */ } ck_gpt_info; typedef struct { 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 new file mode 100644 index 00000000..949abcd4 --- /dev/null +++ b/native/kernel/dev/gpt_add.c @@ -0,0 +1,255 @@ +/* gpt_add.c -- add the AIENOS partition in unused space; see gpt_add.h. */ +#include "gpt_add.h" + +#include "disk_part.h" +#include "sha256.h" + +#define ENT_MAX (64u << 10) +static uint8_t g_ent[ENT_MAX]; +static uint8_t g_ph[4096]; /* primary header block */ +static uint8_t g_bh[4096]; /* backup header block */ +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 ck_gpt_new allen_memory = {ck_aienos_part_type, "AIENOS Allen memory", "aienos.allen.memory.v1"}; + +static uint32_t get32(const uint8_t *p) +{ + return (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24; +} +static uint64_t get64(const uint8_t *p) { return (uint64_t)get32(p) | (uint64_t)get32(p + 4) << 32; } +static void put32(uint8_t *p, uint32_t v) +{ + for (int i = 0; i < 4; i++) + p[i] = (uint8_t)(v >> (8 * i)); +} +static void put64(uint8_t *p, uint64_t v) +{ + put32(p, (uint32_t)v); + put32(p + 4, (uint32_t)(v >> 32)); +} +static int zero16(const uint8_t *p) +{ + uint8_t d = 0; + for (int i = 0; i < 16; i++) + d |= p[i]; + return d == 0; +} + +/* Reads both header blocks and the primary entry array (after the strict + * check passed far enough to fill info). */ +static int load(const disk_dev *d, const ck_gpt_info *gi, uint32_t *bytes, uint32_t *blocks) +{ + *bytes = gi->entries * gi->entry_size; + if (*bytes == 0 || *bytes > ENT_MAX || d->block_size > sizeof g_ph) + return CK_GPT_EBIG; + *blocks = (*bytes + d->block_size - 1u) / d->block_size; + if (disk_read(d, 1, 1, g_ph) != DISK_OK || disk_read(d, gi->last_lba, 1, g_bh) != DISK_OK || + disk_read(d, get64(g_ph + H_ENT_LBA), *blocks, g_ent) != DISK_OK) + return CK_GPT_EIO; + return CK_GPT_OK; +} + +int ck_gpt_list(const disk_dev *d, void (*fn)(void *ctx, const ck_gpt_entry *e), void *ctx) +{ + ck_part p; + ck_gpt_info gi; + int rc = ck_gpt_find_aienos(d, &p, &gi); + if (rc != CK_GPT_OK && gi.entries == 0) + return rc; + uint32_t bytes, blocks, used = 0; + if ((rc = load(d, &gi, &bytes, &blocks))) + return rc; + for (uint32_t i = 0; i < gi.entries; i++) { + const uint8_t *e = g_ent + (uint64_t)i * gi.entry_size; + if (zero16(e)) + continue; + ck_gpt_entry out; + out.index = i; + 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; + for (; n < 36; n++) { + uint16_t c = (uint16_t)(e[56 + 2 * n] | e[57 + 2 * n] << 8); + if (!c) + break; + out.name[n] = c >= 0x20 && c < 0x7f && c != '"' ? (char)c : '?'; + } + out.name[n] = 0; + used++; + if (fn) + fn(ctx, &out); + } + return (int)used; +} + +static void header_crc(uint8_t *h, uint32_t ecrc) +{ + put32(h + H_ECRC, ecrc); + put32(h + H_CRC, 0); + 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 || !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_type(d, spec->type, &p, &gi); + if (rc == CK_GPT_OK) { + out->first = p.first_lba; + out->last = p.first_lba + p.blocks - 1u; + out->index = gi.part_index; + return CK_GPT_OK; + } + if (rc != CK_GPT_ENOPART) + return rc; + uint32_t bytes, eblocks; + if ((rc = load(d, &gi, &bytes, &eblocks))) + return rc; + + /* Used ranges, sorted by first LBA (the strict check proved they lie in + * the usable range and do not overlap). */ + uint32_t n = 0, slot = gi.entries; + for (uint32_t i = 0; i < gi.entries; i++) { + const uint8_t *e = g_ent + (uint64_t)i * gi.entry_size; + if (zero16(e)) { + if (slot == gi.entries) + slot = i; + continue; + } + if (n == CK_GPT_MAX_USED) + return CK_GPT_ETOOMANY; + uint64_t f = get64(e + 32), l = get64(e + 40); + uint32_t k = n++; + for (; k && g_f[k - 1] > f; k--) { + g_f[k] = g_f[k - 1]; + g_l[k] = g_l[k - 1]; + } + g_f[k] = f; + g_l[k] = l; + } + if (slot == gi.entries) + return CK_GPT_ENOSLOT; + uint64_t at = 0, cursor = gi.first_usable; + int found = 0; + for (uint32_t k = 0; k <= n && !found; k++) { + uint64_t gap_end = k < n ? g_f[k] - 1u : gi.last_usable; /* g_f[k] >= first_usable >= 34 */ + uint64_t start = (cursor + align - 1u) / align * align; + if (cursor <= gap_end && start >= cursor && start <= gap_end && gap_end - start >= blocks - 1u) { + at = start; + found = 1; + } + if (k < n && g_l[k] + 1u > cursor) + cursor = g_l[k] + 1u; + } + if (!found) + return CK_GPT_ENOSPACE; + + /* 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] = 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; 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); + header_crc(g_bh, ecrc); + uint64_t bent = get64(g_bh + H_ENT_LBA), pent = get64(g_ph + H_ENT_LBA); + if (disk_write(d, bent, eblocks, g_ent) != DISK_OK || disk_write(d, gi.last_lba, 1, g_bh) != DISK_OK || + disk_flush(d) != DISK_OK || disk_write(d, pent, eblocks, g_ent) != DISK_OK || + disk_write(d, 1, 1, g_ph) != DISK_OK || disk_flush(d) != DISK_OK) + return CK_GPT_EWRITE; + + 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; + out->last = at + blocks - 1u; + out->index = slot; + out->created = 1; + return CK_GPT_OK; +} + +const char *ck_gpt_add_strerror(int rc) +{ + switch (rc) { + case CK_GPT_ENOSPACE: return "no unused space large enough"; + case CK_GPT_ENOSLOT: return "no free partition entry"; + case CK_GPT_EBIG: return "partition entry array too large"; + case CK_GPT_EWRITE: return "write failed"; + case CK_GPT_EVERIFY: return "partition not as written after the check"; + default: return ck_gpt_strerror(rc); + } +} diff --git a/native/kernel/dev/gpt_add.h b/native/kernel/dev/gpt_add.h new file mode 100644 index 00000000..968f9c2c --- /dev/null +++ b/native/kernel/dev/gpt_add.h @@ -0,0 +1,78 @@ +/* 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 + * the new partition exactly. A power cut part way leaves one copy old and + * one new; the strict check then refuses both until a person looks, so + * 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 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 +#include "disk.h" + +enum { + CK_GPT_ENOSPACE = -420, /* no unused gap holds the partition */ + CK_GPT_ENOSLOT = -421, /* no free entry in the array */ + CK_GPT_EBIG = -422, /* entry array larger than this file handles (64 KiB) */ + CK_GPT_EWRITE = -423, /* a write or flush failed */ + CK_GPT_EVERIFY = -424, /* after writing, the GPT does not show the partition exactly */ +}; + +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; + +/* Calls fn for every used entry when both GPT copies are valid (any + * ck_gpt_find_aienos answer that got that far). The number of used entries, + * or the CK_GPT_* refusal. */ +int ck_gpt_list(const disk_dev *d, void (*fn)(void *ctx, const ck_gpt_entry *e), void *ctx); + +typedef struct { + uint64_t first, last; /* the AIENOS partition, inclusive */ + uint32_t index; /* its entry */ + 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 + * multiple of `align` blocks. CK_GPT_OK or the refusal (nothing written + * unless the code is CK_GPT_EWRITE or CK_GPT_EVERIFY). */ +int ck_gpt_add_aienos(const disk_dev *d, uint64_t blocks, uint64_t align, ck_gpt_added *out); + +/* Text for the codes here and those of disk_part.h. */ +const char *ck_gpt_add_strerror(int rc); +#endif diff --git a/native/kernel/dev/tests/disk_extent_test.c b/native/kernel/dev/tests/disk_extent_test.c new file mode 100644 index 00000000..ea6eea3f --- /dev/null +++ b/native/kernel/dev/tests/disk_extent_test.c @@ -0,0 +1,159 @@ +/* disk_extent_test.c -- host tests for the many-piece region (dev/disk_extent.c). + * An in-memory parent disk whose every block outside the pieces carries a + * guard pattern; after each run the guards are checked, so a single stray + * write anywhere fails the test. Each refusal path has a negative case. */ +#include +#include +#include +#include "disk.h" +#include "disk_extent.h" +#include "sha256.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 DISK_BLOCKS 4096u +static uint8_t g_disk[DISK_BLOCKS * 512u]; +static uint32_t g_max_io = 7; + +static int mem_read(void *ctx, uint64_t lba, uint32_t n, uint8_t *b) { (void)ctx; memcpy(b, g_disk + lba * 512u, n * 512u); return 0; } +static int mem_write(void *ctx, uint64_t lba, uint32_t n, const uint8_t *b) { (void)ctx; memcpy(g_disk + lba * 512u, b, n * 512u); return 0; } +static int mem_flush(void *ctx) { (void)ctx; return 0; } +static disk_dev g_parent = {0, 512, DISK_BLOCKS, mem_read, mem_write, mem_flush, 0}; + +static void put32(uint8_t *p, uint32_t v) { for (int i = 0; i < 4; i++) p[i] = (uint8_t)(v >> (8 * i)); } +static void put64(uint8_t *p, uint64_t v) { for (int i = 0; i < 8; i++) p[i] = (uint8_t)(v >> (8 * i)); } + +typedef struct { uint64_t lg, ph, ln; } pc; +static uint8_t g_map[CK_EXT_HDR_BYTES + 64 * CK_EXT_PIECE_BYTES]; + +static size_t build(const pc *p, uint32_t n, uint64_t base, uint64_t wf, uint64_t wl) +{ + memset(g_map, 0, sizeof g_map); + memcpy(g_map, "AXMAP1\0\0", 8); + put32(g_map + 8, 1); + put32(g_map + 12, n); + put64(g_map + 16, base); + put64(g_map + 24, wf); + put64(g_map + 32, wl); + for (uint32_t i = 0; i < n; i++) { + uint8_t *e = g_map + CK_EXT_HDR_BYTES + i * CK_EXT_PIECE_BYTES; + put64(e, p[i].lg); put64(e + 8, p[i].ph); put64(e + 16, p[i].ln); + } + size_t len = CK_EXT_HDR_BYTES + (size_t)n * CK_EXT_PIECE_BYTES; + { + sha256_ctx h; + sha256_init(&h); + sha256_update(&h, g_map, 40); + sha256_update(&h, g_map + CK_EXT_HDR_BYTES, len - CK_EXT_HDR_BYTES); + sha256_final(&h, g_map + 40); + } + return len; +} + +/* Out of order on disk on purpose; base 100, window 100..4095. */ +static const pc good[] = {{0, 900, 5}, {5, 200, 3}, {8, 3000, 40}, {48, 1, 1}, {49, 500, 11}}; +#define NGOOD 5u +#define GOOD_BLOCKS 60u + +static int in_pieces(uint64_t lba) +{ + for (uint32_t i = 0; i < NGOOD; i++) + if (lba >= 100 + good[i].ph && lba < 100 + good[i].ph + good[i].ln) return 1; + return 0; +} +static void guard_fill(void) +{ + for (uint32_t b = 0; b < DISK_BLOCKS; b++) memset(g_disk + b * 512u, in_pieces(b) ? 0 : 0xA5, 512); +} +static int guards_intact(void) +{ + for (uint32_t b = 0; b < DISK_BLOCKS; b++) + if (!in_pieces(b)) + for (uint32_t i = 0; i < 512; i++) + if (g_disk[b * 512u + i] != 0xA5) return 0; + return 1; +} + +static int parse(ck_ext_region *r, size_t len) +{ + static ck_ext_piece piece[64]; + static uint32_t order[64]; + return ck_ext_parse(r, &g_parent, g_map, len, piece, order, 64); +} + +int main(void) +{ + g_parent.max_blocks_per_io = g_max_io; + ck_ext_region r; + uint8_t s[512]; + + /* 1. Good map: parse, seal a fresh region, round trip across every piece. */ + guard_fill(); + size_t len = build(good, NGOOD, 100, 100, DISK_BLOCKS - 1); + CHECK(parse(&r, len) == CK_EXT_OK); + CHECK(r.blocks == GOOD_BLOCKS); + CHECK(ck_ext_open(&r, s) == CK_EXT_OK); + CHECK(memcmp(g_disk + (100 + 900) * 512u, "AIENRGN1", 8) == 0); + static uint8_t w[GOOD_BLOCKS * 512u], rb[GOOD_BLOCKS * 512u]; + for (size_t i = 0; i < sizeof w; i++) w[i] = (uint8_t)(i * 31u + 7u); + CHECK(disk_write(&r.dev, 1, GOOD_BLOCKS - 1, w + 512) == DISK_OK); + CHECK(disk_read(&r.dev, 1, GOOD_BLOCKS - 1, rb + 512) == DISK_OK); + CHECK(memcmp(w + 512, rb + 512, (GOOD_BLOCKS - 1) * 512u) == 0); + /* logical 48 lives at absolute 101 */ + CHECK(memcmp(g_disk + 101u * 512u, w + 48u * 512u, 512) == 0); + CHECK(guards_intact()); + + /* 2. Bounds: past the end, straddling the end, block 0 write. */ + CHECK(disk_write(&r.dev, GOOD_BLOCKS, 1, w) != DISK_OK); + CHECK(disk_write(&r.dev, GOOD_BLOCKS - 2, 3, w) != DISK_OK); + CHECK(disk_write(&r.dev, 0, 1, w) != DISK_OK); + CHECK(guards_intact()); + + /* 3. Reopen: our seal accepted; a foreign block 0 refused. */ + ck_ext_region r2; + CHECK(parse(&r2, len) == CK_EXT_OK); + CHECK(ck_ext_open(&r2, s) == CK_EXT_OK); + g_disk[(100 + 900) * 512u + 20] ^= 1; + ck_ext_region r3; + CHECK(parse(&r3, len) == CK_EXT_OK); + CHECK(ck_ext_open(&r3, s) == CK_EXT_ESEAL); + CHECK(disk_read(&r3.dev, 1, 1, rb) != DISK_OK); /* unopened region does no I/O */ + + /* 4. Refusals, each one mutation of the good map. */ + pc m[NGOOD]; + memcpy(m, good, sizeof m); m[2].lg = 9; /* gap */ + CHECK(parse(&r, build(m, NGOOD, 100, 100, DISK_BLOCKS - 1)) == CK_EXT_EORDER); + memcpy(m, good, sizeof m); m[1].ph = 902; /* overlaps piece 0 on disk */ + CHECK(parse(&r, build(m, NGOOD, 100, 100, DISK_BLOCKS - 1)) == CK_EXT_EOVERLAP); + memcpy(m, good, sizeof m); m[2].ph = DISK_BLOCKS - 120; /* runs past the window */ + CHECK(parse(&r, build(m, NGOOD, 100, 100, DISK_BLOCKS - 1)) == CK_EXT_EWINDOW); + CHECK(parse(&r, build(good, NGOOD, 100, 1100, DISK_BLOCKS - 1)) == CK_EXT_EWINDOW); /* window excludes pieces */ + CHECK(parse(&r, build(good, NGOOD, 100, 100, DISK_BLOCKS)) == CK_EXT_EWINDOW); /* window past parent */ + memcpy(m, good, sizeof m); m[3].ln = 0; + CHECK(parse(&r, build(m, NGOOD, 100, 100, DISK_BLOCKS - 1)) == CK_EXT_EORDER); + len = build(good, NGOOD, 100, 100, DISK_BLOCKS - 1); + g_map[CK_EXT_HDR_BYTES + 3] ^= 1; /* piece edited, digest stale */ + CHECK(parse(&r, len) == CK_EXT_EDIGEST); + len = build(good, NGOOD, 100, 100, DISK_BLOCKS - 1); + g_map[16] ^= 1; /* base edited, header digest stale */ + CHECK(parse(&r, len) == CK_EXT_EDIGEST); + len = build(good, NGOOD, 100, 100, DISK_BLOCKS - 1); + g_map[0] = 'Z'; + CHECK(parse(&r, len) == CK_EXT_EMAGIC); + len = build(good, NGOOD, 100, 100, DISK_BLOCKS - 1); + CHECK(parse(&r, len - 1) == CK_EXT_ECOUNT); + CHECK(r.valid == 0); + CHECK(guards_intact()); + + printf("disk_extent: %d checks, %d failures\n", checks, failures); + printf("DISK_EXTENT_HOST: %s\n", failures ? "FAIL" : "PASS"); + return failures ? 1 : 0; +} 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..bf086240 --- /dev/null +++ b/native/kernel/dev/tests/fat_boot_test.c @@ -0,0 +1,304 @@ +/* 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 "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); + FILE *fp = fopen(path, "wb"); + 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/dev/usb_hid.c b/native/kernel/dev/usb_hid.c index ca08ca7a..20099abb 100644 --- a/native/kernel/dev/usb_hid.c +++ b/native/kernel/dev/usb_hid.c @@ -7,29 +7,34 @@ #define USAGE_BACKSPACE 0x2au #define USAGE_SPACE 0x2cu #define USAGE_MINUS 0x2du -#define USAGE_PERIOD 0x37u #define USAGE_SLASH 0x38u #define MOD_ANY_SHIFT 0x22u /* left shift bit 1, right shift bit 5 */ ck_key_event ck_hid_usage(uint8_t usage, int shift) { + /* the US layout's symbol keys, usages 0x2d..0x38 (0x32, the non-US key, has none) */ + static const char sym[2][12] = {{'-', '=', '[', ']', '\\', 0, ';', '\'', '`', ',', '.', '/'}, + {'_', '+', '{', '}', '|', 0, ':', '"', '~', '<', '>', '?'}}; + static const char shifted_digit[10] = {'!', '@', '#', '$', '%', '^', '&', '*', '(', ')'}; ck_key_event ev = {CK_KEY_NONE, 0}; if (usage >= 0x04 && usage <= 0x1d) { /* a..z */ ev.kind = CK_KEY_CHAR; ev.c = (char)((shift ? 'A' : 'a') + (usage - 0x04)); } else if (usage >= 0x1e && usage <= 0x27) { /* 1..9, 0 */ - if (shift) return ev; ev.kind = CK_KEY_CHAR; - ev.c = usage == 0x27 ? '0' : (char)('1' + (usage - 0x1e)); + ev.c = shift ? shifted_digit[usage - 0x1e] : usage == 0x27 ? '0' : (char)('1' + (usage - 0x1e)); } else if (usage == USAGE_ENTER) { ev.kind = CK_KEY_ENTER; } else if (usage == USAGE_ESCAPE) { ev.kind = CK_KEY_ESCAPE; } else if (usage == USAGE_BACKSPACE) { ev.kind = CK_KEY_BACKSPACE; - } else if (!shift && (usage == USAGE_SPACE || usage == USAGE_MINUS || usage == USAGE_PERIOD || usage == USAGE_SLASH)) { + } else if (usage == USAGE_SPACE) { ev.kind = CK_KEY_CHAR; - ev.c = usage == USAGE_SPACE ? ' ' : usage == USAGE_MINUS ? '-' : usage == USAGE_PERIOD ? '.' : '/'; + ev.c = ' '; + } else if (usage >= USAGE_MINUS && usage <= USAGE_SLASH && sym[shift != 0][usage - USAGE_MINUS]) { + ev.kind = CK_KEY_CHAR; + ev.c = sym[shift != 0][usage - USAGE_MINUS]; } return ev; } diff --git a/native/kernel/dev/usb_hid.h b/native/kernel/dev/usb_hid.h index 90b267f3..4ea07c49 100644 --- a/native/kernel/dev/usb_hid.h +++ b/native/kernel/dev/usb_hid.h @@ -30,9 +30,11 @@ typedef struct { uint8_t previous[CK_HID_MAX_KEYS]; } ck_hid_decoder; -/* Fixed keymap (US layout, the only one): usages a-z (shift: A-Z), 1-0, - * space, '-', '.', '/', Enter, Backspace, Escape. Every other usage, and - * shifted digits or punctuation, yields nothing. */ +/* Fixed keymap (US layout, the only one): every printable ASCII character a + * US keyboard types, with and without shift (a-z A-Z, 0-9 and !@#$%^&*(), + * space, and the symbol keys - = [ ] \ ; ' ` , . / and their shifted + * _ + { } | : " ~ < > ?), plus Enter, Backspace, Escape. Every other usage + * (function keys, arrows, Tab, the non-US key) yields nothing. */ ck_key_event ck_hid_usage(uint8_t usage, int shift); /* Decode one 8-byte report: one event per usage that was not pressed in the * previous report (key repeat is not generated). A phantom/rollover report diff --git a/native/kernel/dev/usb_kbd.c b/native/kernel/dev/usb_kbd.c index 739bcccd..ca783748 100644 --- a/native/kernel/dev/usb_kbd.c +++ b/native/kernel/dev/usb_kbd.c @@ -601,6 +601,13 @@ void ck_recovery_console_stub(void) * the existing ones. */ /* Most bytes the start-of-session drain reads before it gives up. */ #define CK_SESSION_DRAIN_MAX 4096u +#if defined(CK_ALLEN) && CK_ALLEN +#include "../svc/allen_reply.h" +int ck_allen_session_line(const char *line); +#define CK_SESSION_PROMPT "you> " +#else +#define CK_SESSION_PROMPT "console> " +#endif static ck_line s_line; static ck_src_gate s_gate; static ck_hid_decoder s_dec; @@ -638,7 +645,7 @@ static void sess_begin(const char *usb) ck_src_gate_reset(&s_gate); s_np = s_ip = 0; s_t0 = ck_time_us(); - ck_puts("console> "); + ck_puts(CK_SESSION_PROMPT); } static void sess_drops(int owner, unsigned dropped) @@ -666,12 +673,16 @@ static int sess_key(int src, ck_key_event ev) sess_drops(owner, ck_src_gate_release(&s_gate)); int ex = 0; if (r == CK_LINE_DONE) { +#if defined(CK_ALLEN) && CK_ALLEN + ex = ck_allen_session_line(s_line.buf); /* svc/allen_session.c: Allen answers, goodbye ends */ +#else ck_shell_ctx ctx = {ck_conventional_memory_kb(), ck_exception_level(), (ck_time_us() - s_t0) / 1000u, ck_commit()}; ex = ck_shell_run(s_line.buf, &ctx, shell_out); +#endif if (ex) ck_printf("console_session: exit (source=%s)\n", src_name(owner)); } ck_line_reset(&s_line); - if (!ex) ck_puts("console> "); + if (!ex) ck_puts(CK_SESSION_PROMPT); return ex; } diff --git a/native/kernel/dev/xhci_fence.c b/native/kernel/dev/xhci_fence.c index 5b08b4b6..41e4659a 100644 --- a/native/kernel/dev/xhci_fence.c +++ b/native/kernel/dev/xhci_fence.c @@ -19,7 +19,8 @@ #define CK_XHCI_MUT 0 #endif #if defined(CK_CONSOLE_SESSION) && CK_CONSOLE_SESSION -#if defined(CK_HARDWARE_STAGING) +/* Hardware only for the Allen session (CK_ALLEN=1: lines reach Allen, never the shell; see Makefile). */ +#if defined(CK_HARDWARE_STAGING) && !(defined(CK_ALLEN) && CK_ALLEN) #error "CK_CONSOLE_SESSION (QEMU test console session) cannot be combined with CK_HARDWARE_STAGING" #endif #if defined(CK_QEMU_UNSAFE_DMA) diff --git a/native/kernel/stage.mk b/native/kernel/stage.mk index f589a4ec..674cc096 100644 --- a/native/kernel/stage.mk +++ b/native/kernel/stage.mk @@ -254,3 +254,35 @@ pi5-agent-mutants: done; exit $$fail stage-test: pi5-agent-test stage-sanitize: pi5-agent-sanitize + +# ---- Many-piece region host test (dev/tests/disk_extent_test.c) ---- +# The test plus one mutant per guarded refusal in dev/disk_extent.c: each +# mutant drops one GUARD:ext-* return and must FAIL, so every guard is shown +# to be load-bearing. The tools ck_region_map / ck_region_probe make and prove +# a REGION.MAP on a Linux host (see dev/disk_extent.h). +DISK_EXT_SRCS := $(STAGE_DIR)/dev/disk_extent.c $(STAGE_NATIVE)/disk/disk.c $(STAGE_NATIVE)/argus/sha256.c +DISK_EXT_INC := -I$(STAGE_NATIVE)/disk -I$(STAGE_NATIVE)/argus -I$(STAGE_DIR)/dev +DISK_EXT_GUARDS := ext-window ext-gapfree ext-piece ext-disjoint ext-seal ext-sealmatch + +$(STAGE_OUT)/disk_extent_test: $(DISK_EXT_SRCS) $(STAGE_DIR)/dev/tests/disk_extent_test.c $(STAGE_DIR)/dev/disk_extent.h + @mkdir -p $(@D) + $(STAGE_CC) $(STAGE_HOST_FLAGS) $(STAGE_SAN_FLAGS) $(DISK_EXT_INC) -o $@ $(STAGE_DIR)/dev/tests/disk_extent_test.c $(DISK_EXT_SRCS) + +disk-extent-test: $(STAGE_OUT)/disk_extent_test + $(STAGE_OUT)/disk_extent_test + @for g in $(DISK_EXT_GUARDS); do \ + sed "/GUARD:$$g/s/return /(void)0; if (0) return /" $(STAGE_DIR)/dev/disk_extent.c > $(STAGE_OUT)/ext_mut.c; \ + $(STAGE_CC) -std=c11 -w -O1 $(DISK_EXT_INC) -o $(STAGE_OUT)/ext_mut $(STAGE_DIR)/dev/tests/disk_extent_test.c \ + $(STAGE_OUT)/ext_mut.c $(STAGE_NATIVE)/disk/disk.c $(STAGE_NATIVE)/argus/sha256.c || exit 1; \ + if $(STAGE_OUT)/ext_mut >/dev/null 2>&1; then echo "CK_DISK_EXT_MUTANT $$g: FAIL (guard not caught)"; exit 1; fi; \ + echo "CK_DISK_EXT_MUTANT $$g: PASS (caught)"; done + +region-tools: $(STAGE_OUT)/ck_region_map $(STAGE_OUT)/ck_region_probe +$(STAGE_OUT)/ck_region_map: $(STAGE_DIR)/tools/ck_region_map.c $(DISK_EXT_SRCS) + @mkdir -p $(@D) + $(STAGE_CC) -std=c11 -D_GNU_SOURCE -Wall -Wextra -Werror -O2 $(DISK_EXT_INC) -o $@ $< $(STAGE_NATIVE)/argus/sha256.c +$(STAGE_OUT)/ck_region_probe: $(STAGE_DIR)/tools/ck_region_probe.c $(DISK_EXT_SRCS) + @mkdir -p $(@D) + $(STAGE_CC) -std=c11 -D_GNU_SOURCE -Wall -Wextra -Werror -O2 $(DISK_EXT_INC) -o $@ $< $(DISK_EXT_SRCS) + +stage-test: disk-extent-test diff --git a/native/kernel/svc/.crumb b/native/kernel/svc/.crumb index dd0aab6a..1a0612a7 100644 --- a/native/kernel/svc/.crumb +++ b/native/kernel/svc/.crumb @@ -23,21 +23,21 @@ "purpose": "Directory native/kernel/svc/compat. Purpose not yet described by a human." }, { - "digest": "44ea8525d341bcebcb307fb1743de084b124745bd7c46d85761e554183ee02cc", - "last_commit": "22eb360", + "digest": "d4edc2fc74e7309cbc5ff324e9d7cb0cc465d26c7869ed627bb217bff21bc9cb", + "last_commit": "2c3d3cf", "name": "tests", "purpose": "Directory native/kernel/svc/tests. Purpose not yet described by a human." } ], - "children_root": "sha256:d835471b1405ca482a41beb34ed339d21e11064a59138599ee5754d198926878", - "compiled_at": "2026-10-13T23:07:22Z", + "children_root": "sha256:3362971ab4f548b1cec2e98357a53dc95f9557cea6c8742f46f79b76ad7c304d", + "compiled_at": "2026-10-18T12:23:39Z", "compiler": "crumb-compile/1", - "digest": "sha256:2a98333d826d94a7131119aaeb5a15d8bc543baa5531fa930e6f0afc1fccb83d", + "digest": "sha256:1c3f76b94e58577b472903cbdcf85ec62012e84d9393c0c6a9eb6975cab22754", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 48, - "generated_at_commit": "53de55c5dd3485948cd34734caf0f646e28a68c4", - "source_tree": "sha256:8ea0c11b9dedede3565f8e3d47b8192651e0790f8e3df92b172ce4a8dc936af1" + "files": 56, + "generated_at_commit": "105544890f780085f64bee754d4a92c1a2f17ecf", + "source_tree": "sha256:3ed7111e0cb5274a48d41954517ea1e195033101673023acf413beec77c4e839" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/svc/allen_memory.c b/native/kernel/svc/allen_memory.c new file mode 100644 index 00000000..eec1e0ce --- /dev/null +++ b/native/kernel/svc/allen_memory.c @@ -0,0 +1,311 @@ +/* allen_memory.c -- Allen's memory on disk in two copies; see allen_memory.h. */ +#include "allen_memory.h" + +#include "sha256.h" + +#define HDR 64u +#define FACT_BYTES (CK_ALLEN_KEY_MAX + CK_ALLEN_VAL_MAX + 1u) +#define PAYLOAD_FIXED (4u + 4u + CK_ALLEN_NAME_MAX + 4u + 4u) +#define VERSION 2u + +_Static_assert(HDR + PAYLOAD_FIXED + CK_ALLEN_FACTS_MAX * FACT_BYTES <= CK_ALLEN_MEM_UNIT, "memory fits one unit"); + +static const uint8_t magic[8] = {'A', 'I', 'E', 'N', 'A', 'L', 'M', '1'}; +static uint8_t g_unit[CK_ALLEN_MEM_UNIT] __attribute__((aligned(64))); +static uint8_t g_back[CK_ALLEN_MEM_UNIT] __attribute__((aligned(64))); + +static void put32(uint8_t *p, uint32_t v) +{ + for (int i = 0; i < 4; i++) + p[i] = (uint8_t)(v >> (8 * i)); +} +static void put64(uint8_t *p, uint64_t v) +{ + put32(p, (uint32_t)v); + put32(p + 4, (uint32_t)(v >> 32)); +} +static uint32_t get32(const uint8_t *p) +{ + return (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24; +} +static uint64_t get64(const uint8_t *p) { return (uint64_t)get32(p) | (uint64_t)get32(p + 4) << 32; } +static void zero(void *d, uint32_t n) +{ + for (uint32_t i = 0; i < n; i++) + ((uint8_t *)d)[i] = 0; +} +static void copy(void *d, const void *s, uint32_t n) +{ + for (uint32_t i = 0; i < n; i++) + ((uint8_t *)d)[i] = ((const uint8_t *)s)[i]; +} +static int same(const uint8_t *a, const uint8_t *b, uint32_t n) +{ + uint8_t d = 0; + for (uint32_t i = 0; i < n; i++) + d |= (uint8_t)(a[i] ^ b[i]); + return d == 0; +} + +static void seal(uint8_t *unit, uint32_t plen) +{ + sha256_ctx h; + sha256_init(&h); + sha256_update(&h, unit, 32); + sha256_update(&h, unit + HDR, plen); + sha256_final(&h, unit + 32); +} + +/* Folded text in a field of cap bytes: NUL-terminated, a-z 0-9 and single + * inner spaces only, the rest of the field zero. letters: a name (A-Z first, + * then a-z, or empty). */ +static int text_ok(const uint8_t *t, uint32_t cap, int name) +{ + uint32_t n = 0; + while (n < cap && t[n]) + n++; + if (n == cap) + return 0; + for (uint32_t i = n; i < cap; i++) + if (t[i]) + return 0; + for (uint32_t i = 0; i < n; i++) { + uint8_t c = t[i]; + int lower = c >= 'a' && c <= 'z', digit = c >= '0' && c <= '9'; + if (name) { + /* learn_name keeps one folded word, first letter capitalised */ + if (!(i == 0 ? (c >= 'A' && c <= 'Z') || digit : lower || digit)) + return 0; + } else if (c == ' ') { + if (i == 0 || i == n - 1 || t[i - 1] == ' ') + return 0; + } else if (!lower && !digit) { + return 0; + } + } + return 1; +} + +void ck_allen_mem_encode(const ck_allen_memory *mem, uint64_t gen, uint8_t unit[CK_ALLEN_MEM_UNIT]) +{ + uint32_t n = mem->nfacts > CK_ALLEN_FACTS_MAX ? CK_ALLEN_FACTS_MAX : mem->nfacts; + uint32_t plen = PAYLOAD_FIXED + n * FACT_BYTES; + zero(unit, CK_ALLEN_MEM_UNIT); + copy(unit, magic, 8); + put32(unit + 8, VERSION); + put32(unit + 12, plen); + put64(unit + 16, gen); + uint8_t *p = unit + HDR; + put32(p, mem->starts); + put32(p + 4, mem->lines); + copy(p + 8, mem->name, CK_ALLEN_NAME_MAX); + p[8 + CK_ALLEN_NAME_MAX - 1] = 0; + put32(p + 8 + CK_ALLEN_NAME_MAX, n); + put32(p + 12 + CK_ALLEN_NAME_MAX, mem->nnotes); + p += PAYLOAD_FIXED; + for (uint32_t i = 0; i < n; i++, p += FACT_BYTES) { + copy(p, mem->fact[i].key, CK_ALLEN_KEY_MAX); + p[CK_ALLEN_KEY_MAX - 1] = 0; + copy(p + CK_ALLEN_KEY_MAX, mem->fact[i].val, CK_ALLEN_VAL_MAX); + p[CK_ALLEN_KEY_MAX + CK_ALLEN_VAL_MAX - 1] = 0; + p[CK_ALLEN_KEY_MAX + CK_ALLEN_VAL_MAX] = mem->fact[i].are ? 1 : 0; + } + seal(unit, plen); +} + +int ck_allen_mem_decode(const uint8_t unit[CK_ALLEN_MEM_UNIT], ck_allen_memory *mem, uint64_t *gen) +{ + if (!same(unit, magic, 8) || get32(unit + 8) != VERSION) + return -1; + const uint8_t *p = unit + HDR; + uint32_t plen = get32(unit + 12), n = get32(p + 8 + CK_ALLEN_NAME_MAX); + if (n > CK_ALLEN_FACTS_MAX || get32(p + 12 + CK_ALLEN_NAME_MAX) > CK_ALLEN_NOTES_MAX || + plen != PAYLOAD_FIXED + n * FACT_BYTES || get64(unit + 16) == 0) + return -1; + for (uint32_t i = 24; i < 32; i++) + if (unit[i]) + return -1; + for (uint32_t i = HDR + plen; i < CK_ALLEN_MEM_UNIT; i++) + if (unit[i]) + return -1; + uint8_t want[32]; + sha256_ctx h; + sha256_init(&h); + sha256_update(&h, unit, 32); + sha256_update(&h, unit + HDR, plen); + sha256_final(&h, want); + if (!same(want, unit + 32, 32)) + return -1; + if (!text_ok(p + 8, CK_ALLEN_NAME_MAX, 1)) + return -1; + const uint8_t *f = p + PAYLOAD_FIXED; + for (uint32_t i = 0; i < n; i++, f += FACT_BYTES) + if (!text_ok(f, CK_ALLEN_KEY_MAX, 0) || !f[0] || !text_ok(f + CK_ALLEN_KEY_MAX, CK_ALLEN_VAL_MAX, 0) || + !f[CK_ALLEN_KEY_MAX] || f[CK_ALLEN_KEY_MAX + CK_ALLEN_VAL_MAX] > 1) + return -1; + zero(mem, sizeof *mem); + mem->starts = get32(p); + mem->lines = get32(p + 4); + copy(mem->name, p + 8, CK_ALLEN_NAME_MAX); + mem->nfacts = n; + mem->nnotes = get32(p + 12 + CK_ALLEN_NAME_MAX); + f = p + PAYLOAD_FIXED; + for (uint32_t i = 0; i < n; i++, f += FACT_BYTES) { + copy(mem->fact[i].key, f, CK_ALLEN_KEY_MAX); + copy(mem->fact[i].val, f + CK_ALLEN_KEY_MAX, CK_ALLEN_VAL_MAX); + mem->fact[i].are = f[CK_ALLEN_KEY_MAX + CK_ALLEN_VAL_MAX]; + } + *gen = get64(unit + 16); + return 0; +} + +static int geom(const disk_dev *d, uint32_t *per) +{ + if (disk_check(d) != DISK_OK || (d->block_size != 512 && d->block_size != 4096)) + return CK_ALLEN_MEM_EGEOM; + *per = CK_ALLEN_MEM_UNIT / d->block_size; + if (d->block_count < (uint64_t)*per * CK_ALLEN_MEM_UNITS) + return CK_ALLEN_MEM_EGEOM; + return CK_ALLEN_MEM_OK; +} + +int ck_allen_store_load(ck_allen_store *st, const disk_dev *part, ck_allen_memory *mem) +{ + uint32_t per = 0; + zero(st, sizeof *st); + zero(mem, sizeof *mem); + st->dev = part; + int rc = geom(part, &per); + if (rc) + return rc; + for (unsigned c = 0; c < 2; c++) { + ck_allen_memory m; + uint64_t g = 0; + if (disk_read(part, (uint64_t)c * per, per, g_unit) != DISK_OK) + return CK_ALLEN_MEM_EIO; + if (ck_allen_mem_decode(g_unit, &m, &g)) + continue; + st->valid++; + if (g > st->gen) { + st->gen = g; + st->newest = c; + *mem = m; + } + } + return st->gen ? CK_ALLEN_MEM_OK : CK_ALLEN_MEM_EMPTY; +} + +int ck_allen_store_save(ck_allen_store *st, const ck_allen_memory *mem) +{ + uint32_t per = 0; + int rc = geom(st->dev, &per); + if (rc) + return rc; + unsigned target = st->gen ? 1u - st->newest : 0u; /* the older copy (A on a first save) */ + uint64_t lba = (uint64_t)target * per; + ck_allen_mem_encode(mem, st->gen + 1, g_unit); + if (disk_write(st->dev, lba, per, g_unit) != DISK_OK || disk_flush(st->dev) != DISK_OK) + return CK_ALLEN_MEM_EIO; + if (disk_read(st->dev, lba, per, g_back) != DISK_OK) + return CK_ALLEN_MEM_EIO; + if (!same(g_unit, g_back, CK_ALLEN_MEM_UNIT)) + return CK_ALLEN_MEM_EVERIFY; + st->gen++; + st->newest = target; + if (st->valid < 2) + st->valid++; + return CK_ALLEN_MEM_OK; +} + +/* ---- notes: one unit each, from unit CK_ALLEN_NOTES_FIRST ---- */ + +static const uint8_t note_magic[8] = {'A', 'I', 'E', 'N', 'N', 'O', 'T', '1'}; + +void ck_allen_note_encode(const ck_allen_note *n, uint32_t index, uint8_t unit[CK_ALLEN_MEM_UNIT]) +{ + uint32_t len = n->len < CK_ALLEN_NOTE_MAX ? n->len : CK_ALLEN_NOTE_MAX - 1u; + zero(unit, CK_ALLEN_MEM_UNIT); + copy(unit, note_magic, 8); + put32(unit + 8, 1); + put32(unit + 12, len); + put32(unit + 16, index); + put32(unit + 20, n->start); + put32(unit + 24, n->gone ? 1u : 0u); + copy(unit + HDR, n->text, len); + seal(unit, len); +} + +int ck_allen_note_decode(const uint8_t unit[CK_ALLEN_MEM_UNIT], uint32_t index, ck_allen_note *n) +{ + uint32_t len = get32(unit + 12); + if (!same(unit, note_magic, 8) || get32(unit + 8) != 1 || len == 0 || len >= CK_ALLEN_NOTE_MAX || + get32(unit + 16) != index || get32(unit + 24) > 1 || get32(unit + 28)) + return -1; + for (uint32_t i = HDR + len; i < CK_ALLEN_MEM_UNIT; i++) + if (unit[i]) + return -1; + for (uint32_t i = 0; i < len; i++) + if (unit[HDR + i] < 0x20 || unit[HDR + i] > 0x7e) + return -1; + uint8_t want[32]; + sha256_ctx h; + sha256_init(&h); + sha256_update(&h, unit, 32); + sha256_update(&h, unit + HDR, len); + sha256_final(&h, want); + if (!same(want, unit + 32, 32)) + return -1; + zero(n, sizeof *n); + copy(n->text, unit + HDR, len); + n->len = (uint16_t)len; + n->start = get32(unit + 20); + n->gone = (uint8_t)get32(unit + 24); + ck_allen_note_index(n); + return 0; +} + +static int notes_geom(const disk_dev *d, uint32_t count, uint32_t *per) +{ + int rc = geom(d, per); + if (rc) + return rc; + if (count > CK_ALLEN_NOTES_MAX || d->block_count < (uint64_t)*per * (CK_ALLEN_NOTES_FIRST + count)) + return CK_ALLEN_MEM_EGEOM; + return CK_ALLEN_MEM_OK; +} + +int ck_allen_notes_load(const disk_dev *part, uint32_t count, ck_allen_notes *ns, uint32_t *damaged) +{ + uint32_t per = 0; + zero(ns, sizeof *ns); + *damaged = 0; + int rc = notes_geom(part, count, &per); + if (rc) + return rc; + for (uint32_t i = 0; i < count; i++) { + if (disk_read(part, (uint64_t)(CK_ALLEN_NOTES_FIRST + i) * per, per, g_unit) != DISK_OK) + return CK_ALLEN_MEM_EIO; + if (ck_allen_note_decode(g_unit, i, &ns->note[i])) { + zero(&ns->note[i], sizeof ns->note[i]); + ns->note[i].gone = 1; + (*damaged)++; + } + } + ns->n = count; + return CK_ALLEN_MEM_OK; +} + +int ck_allen_note_write(const disk_dev *part, const ck_allen_notes *ns, uint32_t index) +{ + uint32_t per = 0; + int rc = notes_geom(part, index + 1u, &per); + if (rc) + return rc; + uint64_t lba = (uint64_t)(CK_ALLEN_NOTES_FIRST + index) * per; + ck_allen_note_encode(&ns->note[index], index, g_unit); + if (disk_write(part, lba, per, g_unit) != DISK_OK || disk_flush(part) != DISK_OK) + return CK_ALLEN_MEM_EIO; + if (disk_read(part, lba, per, g_back) != DISK_OK) + return CK_ALLEN_MEM_EIO; + return same(g_unit, g_back, CK_ALLEN_MEM_UNIT) ? CK_ALLEN_MEM_OK : CK_ALLEN_MEM_EVERIFY; +} diff --git a/native/kernel/svc/allen_memory.h b/native/kernel/svc/allen_memory.h new file mode 100644 index 00000000..d8e8e0e3 --- /dev/null +++ b/native/kernel/svc/allen_memory.h @@ -0,0 +1,78 @@ +/* allen_memory.h -- Allen's memory on disk: ck_allen_memory (allen_reply.h) + * kept in two copies at the start of the AIENOS partition, so a power cut in + * the middle of a save can only spoil the copy being written. + * + * unit 0 copy A unit 1 copy B (a unit is 4096 bytes) + * unit 2 + i note i, for i below the note count held in the copies + * + * One copy is one unit: + * 0 "AIENALM1" 8 bytes + * 8 version (2) u32 little endian + * 12 payload length u32 + * 16 generation u64, +1 on every save + * 24 zero 8 bytes + * 32 SHA-256 of bytes 0..31 and the payload + * 64 payload: starts u32, lines u32, name[24], fact count u32, note + * count u32, then per fact key[48] val[64] are(u8); the rest zero + * A save writes generation g+1 over the OLDER copy, flushes the disk's write + * cache, then reads it back and checks it; the newer copy is never touched + * until the older one holds the newer state. Loading reads both and keeps + * the valid copy with the highest generation. A copy is valid only when every + * field checks out: magic, version, exact length, fingerprint, fact count, + * NUL-terminated folded text (a-z, 0-9, single spaces), a name of letters. + * Freestanding (no libc, no heap): every disk access goes through the + * partition view handed in. Host tested in svc/tests/allen_memory_test.c, + * power cuts included. */ +#ifndef AIENOS_ALLEN_MEMORY_H +#define AIENOS_ALLEN_MEMORY_H +#include +#include "disk.h" +#include "allen_notes.h" +#include "allen_reply.h" + +#define CK_ALLEN_MEM_UNIT 4096u +#define CK_ALLEN_MEM_UNITS 2u /* the two copies */ +#define CK_ALLEN_NOTES_FIRST 2u /* the unit of note 0 */ +/* Units of the partition this file ever touches. */ +#define CK_ALLEN_DISK_UNITS (CK_ALLEN_NOTES_FIRST + CK_ALLEN_NOTES_MAX) + +enum { + CK_ALLEN_MEM_OK = 0, /* loaded the newest valid copy */ + CK_ALLEN_MEM_EMPTY = 1, /* no valid copy: a first start (or both spoiled) */ + CK_ALLEN_MEM_EIO = -501, /* a read, write or flush failed */ + CK_ALLEN_MEM_EGEOM = -502, /* partition view too small or odd block size */ + CK_ALLEN_MEM_EVERIFY = -503, /* the copy read back differs from the copy written */ +}; + +typedef struct { + const disk_dev *dev; /* the AIENOS partition view */ + uint64_t gen; /* generation of the newest valid copy, 0 = none */ + unsigned newest; /* which copy holds it (0 = A, 1 = B) */ + unsigned valid; /* copies that were valid at load (0..2) */ +} ck_allen_store; + +/* Encode / decode one copy (exposed for the tests). decode: 0 and *mem, + * *gen filled, or -1 when the copy is not valid. */ +void ck_allen_mem_encode(const ck_allen_memory *mem, uint64_t gen, uint8_t unit[CK_ALLEN_MEM_UNIT]); +int ck_allen_mem_decode(const uint8_t unit[CK_ALLEN_MEM_UNIT], ck_allen_memory *mem, uint64_t *gen); + +/* Read both copies. OK (mem = newest), EMPTY (mem zeroed) or an error. */ +int ck_allen_store_load(ck_allen_store *st, const disk_dev *part, ck_allen_memory *mem); +/* Save mem as the next generation (see above). OK or an error; on error + * the previous newest copy is still on disk and st is unchanged. */ +int ck_allen_store_save(ck_allen_store *st, const ck_allen_memory *mem); + +/* A note is one unit, written in place (a deleted note is rewritten with + * the gone flag): "AIENNOT1", version 1, text length u32, index u32, start + * u32, gone u32 (0|1), zero u32, SHA-256 of bytes 0..31 and the text at + * 32, the text (printable ASCII) at 64, the rest zero. A note counts only + * once the copies hold a note count past it: a save writes the note, then + * the copies, so a power cut leaves either no note or a whole one. A note + * that fails any check loads as gone and is counted in *damaged. */ +void ck_allen_note_encode(const ck_allen_note *n, uint32_t index, uint8_t unit[CK_ALLEN_MEM_UNIT]); +int ck_allen_note_decode(const uint8_t unit[CK_ALLEN_MEM_UNIT], uint32_t index, ck_allen_note *n); +int ck_allen_notes_load(const disk_dev *part, uint32_t count, ck_allen_notes *ns, uint32_t *damaged); +/* Writes note index, flushes, reads it back. OK, EIO, EGEOM or EVERIFY. */ +int ck_allen_note_write(const disk_dev *part, const ck_allen_notes *ns, uint32_t index); + +#endif diff --git a/native/kernel/svc/allen_notes.c b/native/kernel/svc/allen_notes.c new file mode 100644 index 00000000..ff372c88 --- /dev/null +++ b/native/kernel/svc/allen_notes.c @@ -0,0 +1,164 @@ +/* allen_notes.c -- Allen's notes; see allen_notes.h. */ +#include "allen_notes.h" + +#include + +/* Small words that say nothing about what a note is about. */ +static const char *const small_words[] = { + "the", "an", "and", "or", "but", "is", "are", "was", "were", "be", "been", "am", "me", "my", "mine", "you", + "your", "yours", "we", "our", "it", "its", "this", "that", "these", "those", "of", "in", "on", "at", "to", + "for", "from", "with", "about", "as", "by", "what", "whats", "where", "when", "who", "which", "why", "how", + "do", "does", "did", "have", "has", "had", "can", "could", "would", "should", "will", "there", "here", "then", + "than", "so", "not", "no", "yes", "just", "also", "please", "show", "tell", "give", "find", "search", "look", + "up", "get", "got", "any", "anything", "something", "thing", "things", "note", "notes", "saved", "save", + "remember", "know", "all", "some", "again", "more", "ok", "okay", "hey", "hi", "hello", "allen", "want", + "need", "let", "lets", "remind", "pull", "down", "write", "jot", "keep", 0}; + +static int same_word(const char *a, size_t n, const char *w) +{ + size_t i = 0; + while (i < n && w[i] && a[i] == w[i]) + i++; + return i == n && !w[i]; +} + +static int is_small(const char *w, size_t n) +{ + for (const char *const *p = small_words; *p; p++) + if (same_word(w, n, *p)) + return 1; + return 0; +} + +static uint32_t hash(const char *w, size_t n) +{ + uint32_t h = 2166136261u; + for (size_t i = 0; i < n; i++) + h = (h ^ (uint8_t)w[i]) * 16777619u; + return h ? h : 1; +} + +unsigned ck_allen_key_words(const char *text, uint32_t *word, unsigned max) +{ + unsigned k = 0; + const char *s = text; + while (*s && k < max) { + char w[32]; + size_t n = 0; + int digits = 1; + /* one word: a run of letters and digits, lowercased; anything else + * (apostrophes too: "what's" is "what" "s") ends it */ + while (*s && !((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') || (*s >= '0' && *s <= '9'))) + s++; + while ((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') || (*s >= '0' && *s <= '9')) { + char c = *s++; + if (c >= 'A' && c <= 'Z') + c = (char)(c - 'A' + 'a'); + if (c < '0' || c > '9') + digits = 0; + if (n < sizeof w) + w[n++] = c; + } + if (!n || n == sizeof w) + continue; + if (!digits && (n < 3 || is_small(w, n))) + continue; + if (!digits && n > 3 && w[n - 1] == 's' && w[n - 2] != 's') /* "codes" is "code" */ + n--; + uint32_t h = hash(w, n); + unsigned dup = 0; + for (unsigned i = 0; i < k; i++) + dup |= word[i] == h; + if (!dup) + word[k++] = h; + } + return k; +} + +void ck_allen_note_index(ck_allen_note *n) +{ + n->nword = (uint8_t)ck_allen_key_words(n->text, n->word, CK_ALLEN_NOTE_WORDS); +} + +int ck_allen_note_set(ck_allen_note *n, const char *text, uint32_t start) +{ + while (*text == ' ') + text++; + size_t len = 0; + while (text[len]) { + if ((uint8_t)text[len] < 0x20 || (uint8_t)text[len] > 0x7e) + return -1; + len++; + } + while (len && text[len - 1] == ' ') + len--; + if (!len || len >= CK_ALLEN_NOTE_MAX) + return -1; + char *d = (char *)n; + for (size_t i = 0; i < sizeof *n; i++) + d[i] = 0; + for (size_t i = 0; i < len; i++) + n->text[i] = text[i]; + n->len = (uint16_t)len; + n->start = start; + ck_allen_note_index(n); + return 0; +} + +unsigned ck_allen_note_links(const ck_allen_note *a, const ck_allen_note *b) +{ + unsigned k = 0; + for (unsigned i = 0; i < a->nword; i++) + for (unsigned j = 0; j < b->nword; j++) + k += a->word[i] == b->word[j]; + return k; +} + +unsigned ck_allen_note_degree(const ck_allen_notes *ns, uint32_t i) +{ + unsigned d = 0; + for (uint32_t j = 0; j < ns->n; j++) + d += j != i && !ns->note[j].gone && ck_allen_note_links(&ns->note[i], &ns->note[j]) > 0; + return d; +} + +unsigned ck_allen_notes_live(const ck_allen_notes *ns) +{ + unsigned k = 0; + for (uint32_t i = 0; i < ns->n; i++) + k += !ns->note[i].gone; + return k; +} + +int ck_allen_notes_best(const ck_allen_notes *ns, const char *question, int strict, unsigned *also) +{ + uint32_t q[CK_ALLEN_NOTE_WORDS]; + unsigned nq = ck_allen_key_words(question, q, CK_ALLEN_NOTE_WORDS), best_score = 0, count = 0; + int best = -1; + if (also) + *also = 0; + if (!ns || !nq) + return -1; + for (uint32_t i = 0; i < ns->n; i++) { + const ck_allen_note *n = &ns->note[i]; + if (n->gone) + continue; + unsigned score = 0; + for (unsigned a = 0; a < nq; a++) + for (unsigned b = 0; b < n->nword; b++) + if (q[a] == n->word[b]) { + score++; + break; + } + if (!score || (strict ? score < nq : score * 2 < nq)) + continue; + count++; + if (score >= best_score) { /* >=: the newest wins a tie */ + best_score = score; + best = (int)i; + } + } + if (also && count) + *also = count - 1; + return best; +} diff --git a/native/kernel/svc/allen_notes.h b/native/kernel/svc/allen_notes.h new file mode 100644 index 00000000..cf1526bb --- /dev/null +++ b/native/kernel/svc/allen_notes.h @@ -0,0 +1,51 @@ +/* allen_notes.h -- Allen's notes: short things the person saves in their own + * words ("save the gate code is 4471") and gets handed back when they ask + * ("what's the gate code"), without ever browsing for them. Each note keeps + * its key words (folded, without small words like "the" or "is", plurals + * cut to one form); two notes that share a key word are linked, which is the + * map Allen's window draws. Finding a note scores every live note by the key + * words of the question it holds and hands back the best one, the newest on + * a tie. The rules are deliberately simple, to be taught better later. + * Pure: no disk (the kernel keeps notes on disk through svc/allen_memory.h), + * host tested in svc/tests/allen_memory_test.c and ui/tests/allen_ui_test.c. */ +#ifndef AIENOS_ALLEN_NOTES_H +#define AIENOS_ALLEN_NOTES_H +#include + +#define CK_ALLEN_NOTE_MAX 128u /* bytes of text, NUL included */ +#define CK_ALLEN_NOTES_MAX 512u /* notes Allen can keep */ +#define CK_ALLEN_NOTE_WORDS 12u /* key words kept per note */ + +typedef struct { + uint32_t start; /* Allen's start number when it was saved */ + uint8_t gone; /* deleted (or found damaged on disk): never handed back */ + uint8_t nword; + uint16_t len; + char text[CK_ALLEN_NOTE_MAX]; /* as typed, printable ASCII, NUL-terminated */ + uint32_t word[CK_ALLEN_NOTE_WORDS]; /* key words (hashes), derived from text */ +} ck_allen_note; + +typedef struct { + uint32_t n; /* notes in use, deleted ones included (note i lives in slot i) */ + ck_allen_note note[CK_ALLEN_NOTES_MAX]; +} ck_allen_notes; + +/* Sets text (as typed, trimmed; at most CK_ALLEN_NOTE_MAX - 1 bytes) and its + * key words. 0, or -1 when text is empty, too long or not printable ASCII. */ +int ck_allen_note_set(ck_allen_note *n, const char *text, uint32_t start); +/* Recomputes the key words from n->text (after loading from disk). */ +void ck_allen_note_index(ck_allen_note *n); +/* Key words of any text; returns how many (at most max). */ +unsigned ck_allen_key_words(const char *text, uint32_t *word, unsigned max); +/* Key words two notes share (0: not linked). */ +unsigned ck_allen_note_links(const ck_allen_note *a, const ck_allen_note *b); +/* Live notes linked to note i. */ +unsigned ck_allen_note_degree(const ck_allen_notes *ns, uint32_t i); +/* The best live note for a question: its index, or -1. strict: every key + * word of the question must be in the note; otherwise at least half of + * them. *also: how many other live notes would have qualified. */ +int ck_allen_notes_best(const ck_allen_notes *ns, const char *question, int strict, unsigned *also); +/* Live notes. */ +unsigned ck_allen_notes_live(const ck_allen_notes *ns); + +#endif diff --git a/native/kernel/svc/allen_reply.c b/native/kernel/svc/allen_reply.c new file mode 100644 index 00000000..6373ae4c --- /dev/null +++ b/native/kernel/svc/allen_reply.c @@ -0,0 +1,941 @@ +/* allen_reply.c -- Allen's local conversation; see allen_reply.h. */ +#include "allen_reply.h" + +#include + +const char ck_allen_goodbye[] = "Goodbye. Until next time."; +const char ck_allen_save_failed[] = "I couldn't save that to my disk, so I'll only remember it until this computer turns off."; +static const char not_yet[] = "I don't know that yet. Type help to see what I can talk about."; + +/* Lowercases letters, keeps digits, turns every other run into one space, + * trims. Returns the folded length (at most cap - 1). */ +static size_t fold(const char *s, char *out, size_t cap) +{ + size_t n = 0; + int space = 0; + for (; *s && n + 1 < cap; s++) { + char c = *s; + if (c >= 'A' && c <= 'Z') + c = (char)(c - 'A' + 'a'); + if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) { + if (space && n) + out[n++] = ' '; + if (n + 1 < cap) + out[n++] = c; + space = 0; + } else { + space = 1; + } + } + out[n] = 0; + return n; +} + +static int eq(const char *a, const char *b) +{ + while (*a && *a == *b) + a++, b++; + return *a == *b; +} + +/* Where phrase starts in f as whole words, or NULL. */ +static const char *find(const char *f, const char *phrase) +{ + for (const char *s = f; *s; s++) { + if (s != f && s[-1] != ' ') + continue; + const char *a = phrase, *b = s; + while (*a && *a == *b) + a++, b++; + if (!*a && (*b == 0 || *b == ' ')) + return s; + } + return 0; +} + +/* Any of the phrases (NULL-terminated list) in f. */ +static int any(const char *f, const char *const *list) +{ + for (; *list; list++) + if (find(f, *list)) + return 1; + return 0; +} + +/* The rest of f after a leading phrase and a space, or NULL. */ +static const char *after(const char *f, const char *phrase) +{ + while (*phrase && *phrase == *f) + phrase++, f++; + return !*phrase && *f == ' ' ? f + 1 : 0; +} + +/* The answer being composed into m->out. */ +struct say { + char *b; + size_t n, cap; +}; +static void put(struct say *s, const char *t) +{ + while (*t && s->n + 1 < s->cap) + s->b[s->n++] = *t++; + s->b[s->n] = 0; +} +static void putu(struct say *s, uint64_t v) +{ + char d[24]; + int i = 0; + do + d[i++] = (char)('0' + v % 10); + while ((v /= 10) && i < 23); + while (i && s->n + 1 < s->cap) + s->b[s->n++] = d[--i]; + s->b[s->n] = 0; +} +static void put_count(struct say *s, uint64_t v, const char *one, const char *many) +{ + putu(s, v); + put(s, " "); + put(s, v == 1 ? one : many); +} +static void put_awake(struct say *s, uint64_t t) +{ + if (t >= 3600) { + put_count(s, t / 3600, "hour", "hours"); + if (t % 3600 / 60) { + put(s, " and "); + put_count(s, t % 3600 / 60, "minute", "minutes"); + } + } else if (t >= 60) { + put_count(s, t / 60, "minute", "minutes"); + if (t % 60) { + put(s, " and "); + put_count(s, t % 60, "second", "seconds"); + } + } else { + put_count(s, t, "second", "seconds"); + } +} +/* ", Name" when Allen knows it. */ +static void put_name(struct say *s, const ck_allen_mind *m) +{ + if (m->mem.name[0]) { + put(s, ", "); + put(s, m->mem.name); + } +} + +/* A number at *p said as digits (up to 9) or as a word from zero to twenty, + * followed by a space or the end; moves *p past it. -1 if there is none. */ +static int64_t number(const char **p) +{ + static const char *const words[] = {"zero", "one", "two", "three", "four", "five", "six", + "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", + "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty"}; + const char *s = *p; + int64_t v = -1; + if (*s >= '0' && *s <= '9') { + int digits = 0; + for (v = 0; *s >= '0' && *s <= '9'; s++, digits++) + v = v * 10 + (*s - '0'); + if (digits > 9) + return -1; + } else { + for (int i = 0; i < 21 && v < 0; i++) { + const char *a = words[i], *b = s; + while (*a && *a == *b) + a++, b++; + if (!*a && (*b == ' ' || !*b)) { + v = i; + s = b; + } + } + } + if (v < 0 || (*s && *s != ' ')) + return -1; + *p = *s ? s + 1 : s; + return v; +} + +/* "what is 12 times 4", "12 plus 3", "nine divided by two": 1 and the + * answer composed, or 0. */ +static int arithmetic(struct say *s, const char *f) +{ + static const char *const lead[] = {"what is", "whats", "what s", "calculate", "how much is", 0}; + const char *p = f, *r; + for (const char *const *l = lead; *l; l++) + if ((r = after(f, *l))) { + p = r; + break; + } + int64_t a = number(&p); + if (a < 0) + return 0; + static const struct { + const char *word; + char op; + } ops[] = {{"plus", '+'}, {"add", '+'}, {"minus", '-'}, {"take away", '-'}, {"times", '*'}, + {"x", '*'}, {"multiplied by", '*'}, {"divided by", '/'}, {"over", '/'}}; + char op = 0; + for (size_t i = 0; i < sizeof ops / sizeof ops[0] && !op; i++) { + if ((r = after(p, ops[i].word))) { + op = ops[i].op; + p = r; + } + } + if (!op) + return 0; + int64_t b = number(&p); + if (b < 0 || *p) + return 0; + if (op == '/' && b == 0) { + put(s, "Nobody can divide by zero, not even me."); + return 1; + } + putu(s, (uint64_t)a); + put(s, op == '+' ? " plus " : op == '-' ? " minus " : op == '*' ? " times " : " divided by "); + putu(s, (uint64_t)b); + put(s, " is "); + int64_t v = op == '+' ? a + b : op == '-' ? a - b : op == '*' ? a * b : a / b; + if (v < 0) { + put(s, "minus "); + v = -v; + } + putu(s, (uint64_t)v); + if (op == '/' && a % b) { + put(s, " remainder "); + putu(s, (uint64_t)(a % b)); + } + put(s, "."); + return 1; +} + +/* Words that follow "i am" / "i m" without being a name. */ +static int is_state(const char *w) +{ + static const char *const st[] = {"good", "fine", "great", "ok", "okay", "well", "tired", "sad", + "happy", "bored", "here", "back", "sorry", "not", "so", "very", + "doing", "just", "really", "excited", "shook", "alright", "awesome", 0}; + for (const char *const *p = st; *p; p++) + if (eq(*p, w)) + return 1; + return 0; +} + +/* Takes the first word of rest as the person's name: 1, or 0 if none fits. */ +static int learn_name(ck_allen_mind *m, const char *rest) +{ + size_t n = 0; + char w[24]; + while (rest[n] && rest[n] != ' ' && n < sizeof w - 1) + w[n] = rest[n], n++; + w[n] = 0; + if (!n || rest[n] == ' ' || is_state(w) || eq(w, "allen")) + return 0; + for (size_t i = 0; i <= n; i++) + m->mem.name[i] = w[i]; + if (m->mem.name[0] >= 'a' && m->mem.name[0] <= 'z') + m->mem.name[0] = (char)(m->mem.name[0] - 'a' + 'A'); + m->changed = 1; + return 1; +} + +/* ---- What Allen is taught ---- */ + +static size_t len_of(const char *s) +{ + size_t n = 0; + while (s[n]) + n++; + return n; +} +static void copy_n(char *d, const char *s, size_t n) +{ + for (size_t i = 0; i < n; i++) + d[i] = s[i]; + d[n] = 0; +} + +/* t as Allen says it back: "my" becomes "your" and so on, word by word; + * cap: the first letter capitalised. */ +static void put_turned(struct say *s, const char *t, int cap) +{ + static const char *const from[] = {"my", "your", "i", "me", "mine", "yours", "myself", "am", 0}; + static const char *const to[] = {"your", "my", "you", "you", "yours", "mine", "yourself", "are"}; + while (*t) { + char w[CK_ALLEN_VAL_MAX]; + size_t n = 0; + while (t[n] && t[n] != ' ' && n < sizeof w - 1) + w[n] = t[n], n++; + w[n] = 0; + t += n; + const char *say = w; + for (int i = 0; from[i]; i++) + if (eq(w, from[i])) + say = to[i]; + if (cap && say[0] >= 'a' && say[0] <= 'z') { + char first[2] = {(char)(say[0] - 'a' + 'A'), 0}; + put(s, first); + say++; + } + cap = 0; + put(s, say); + if (*t == ' ') { + put(s, " "); + t++; + } + } +} + +static int fact_index(const ck_allen_mind *m, const char *key) +{ + for (uint32_t i = 0; i < m->mem.nfacts && i < CK_ALLEN_FACTS_MAX; i++) + if (eq(m->mem.fact[i].key, key)) + return (int)i; + return -1; +} + +/* "Your favorite color is blue" (no full stop). */ +static void put_fact(struct say *s, const ck_allen_fact *f, int cap) +{ + put_turned(s, f->key, cap); + put(s, f->are ? " are " : " is "); + put_turned(s, f->val, 0); +} + +static const char *saved_note(const ck_allen_mind *m) +{ + return m->lasting ? " I'll remember that." : " I'll remember that until this computer turns off."; +} + +/* "remember (that) KEY is|are VALUE": stores it (or learns the name for + * "my name is"). 1 and the answer composed, or 0 if the line is not one. */ +static int teach(ck_allen_mind *m, struct say *s, const char *f) +{ + const char *rest = after(f, "remember that"); + if (!rest) + rest = after(f, "remember"); + if (!rest) + return 0; + const char *verb = 0; + for (const char *p = rest; *p && !verb; p++) + if (*p == ' ' && (after(p + 1, "is") || after(p + 1, "are"))) + verb = p; + if (!verb) { + put(s, "Teach me like this: remember my favorite color is blue."); + return 1; + } + int are = verb[1] == 'a'; + size_t klen = (size_t)(verb - rest); + const char *val = verb + (are ? 5 : 4); + size_t vlen = len_of(val); + if (klen == 7 && after(rest, "my name") == rest + 8 && !are) { + if (learn_name(m, val)) { + put(s, "Nice to meet you, "); + put(s, m->mem.name); + put(s, "."); + put(s, saved_note(m)); + } else { + put(s, "Tell me your name as one word, like: my name is Drake."); + } + return 1; + } + if (klen >= CK_ALLEN_KEY_MAX || vlen >= CK_ALLEN_VAL_MAX) { + put(s, "That's longer than I can hold yet. Try something shorter."); + return 1; + } + char key[CK_ALLEN_KEY_MAX]; + copy_n(key, rest, klen); + int i = fact_index(m, key); + if (i < 0) { + if (m->mem.nfacts >= CK_ALLEN_FACTS_MAX) { + put(s, "My memory is full. Type forget and something I know to make room."); + return 1; + } + i = (int)m->mem.nfacts++; + copy_n(m->mem.fact[i].key, key, klen); + } + copy_n(m->mem.fact[i].val, val, vlen); + m->mem.fact[i].are = (uint8_t)are; + m->changed = 1; + put(s, "Got it: "); + put_fact(s, &m->mem.fact[i], 0); + put(s, "."); + put(s, saved_note(m)); + return 1; +} + +/* "what is KEY" for a taught KEY: 1 and the answer, or 0. *asked_my: the + * question was about something of yours ("what is my ..."), for the + * not-told-yet answer. */ +static int recall(const ck_allen_mind *m, struct say *s, const char *f, const char **asked_my) +{ + static const char *const lead[] = {"what is", "what are", "whats", "what s", "who is", "who are", "where is", + "where are", "when is", "do you remember", "tell me", 0}; + for (const char *const *l = lead; *l; l++) { + const char *key = after(f, *l); + if (!key) + continue; + int i = fact_index(m, key); + if (i >= 0) { + put_fact(s, &m->mem.fact[i], 1); + put(s, "."); + return 1; + } + if (after(key, "my")) + *asked_my = key; + } + return 0; +} + +static int forget(ck_allen_mind *m, struct say *s, const char *f) +{ + const char *rest = after(f, "forget about"); + if (!rest) + rest = after(f, "forget that"); + if (!rest) + rest = after(f, "forget"); + if (!rest) + return 0; + if (eq(rest, "everything") || eq(rest, "all") || eq(rest, "it all") || eq(rest, "all of it") || + eq(rest, "me")) { + m->mem.nfacts = 0; + for (uint32_t i = 0; i < CK_ALLEN_FACTS_MAX; i++) + m->mem.fact[i] = (ck_allen_fact){{0}, {0}, 0}; + for (size_t i = 0; i < sizeof m->mem.name; i++) + m->mem.name[i] = 0; + m->changed = 1; + put(s, "Done. I've forgotten everything you taught me, and your name."); + return 1; + } + if (eq(rest, "my name")) { + for (size_t i = 0; i < sizeof m->mem.name; i++) + m->mem.name[i] = 0; + m->changed = 1; + put(s, "Done. I've forgotten your name."); + return 1; + } + int i = fact_index(m, rest); + if (i < 0) { + put(s, "I don't remember anything about "); + put_turned(s, rest, 0); + put(s, "."); + return 1; + } + for (uint32_t k = (uint32_t)i; k + 1 < m->mem.nfacts; k++) + m->mem.fact[k] = m->mem.fact[k + 1]; + m->mem.nfacts--; + m->mem.fact[m->mem.nfacts] = (ck_allen_fact){{0}, {0}, 0}; + m->changed = 1; + put(s, "Done. I've forgotten "); + put_turned(s, rest, 0); + put(s, "."); + return 1; +} + +/* Everything taught, as many as fit in one answer. */ +static void list_memory(const ck_allen_mind *m, struct say *s) +{ + uint32_t n = m->mem.nfacts + (m->mem.name[0] ? 1u : 0u); + if (!n) { + put(s, "Nothing yet. Teach me like this: remember my favorite color is blue."); + return; + } + put(s, "I remember "); + put_count(s, n, "thing", "things"); + put(s, ":"); + uint32_t told = 0; + if (m->mem.name[0]) { + put(s, " your name is "); + put(s, m->mem.name); + told++; + } + for (uint32_t i = 0; i < m->mem.nfacts; i++) { + char one[CK_ALLEN_KEY_MAX + CK_ALLEN_VAL_MAX + 16]; + struct say t = {one, 0, sizeof one}; + put(&t, told ? "; " : " "); + put_fact(&t, &m->mem.fact[i], 0); + if (s->n + t.n + 12 >= s->cap) { + put(s, "; and more"); + break; + } + put(s, one); + told++; + } + put(s, "."); +} + + +/* ---- Notes (svc/allen_notes.h): saved as typed, handed back when asked ---- */ + +/* line past its first `words` words (runs of letters and digits) and the + * spaces, colons, commas and dashes after them: the note as typed. */ +static const char *raw_after(const char *line, unsigned words) +{ + const char *p = line; +#define ALNUM(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z') || ((c) >= '0' && (c) <= '9')) + for (unsigned k = 0; k < words; k++) { + while (*p && !ALNUM(*p)) + p++; + while (ALNUM(*p)) + p++; + } +#undef ALNUM + while (*p == ' ' || *p == ':' || *p == ',' || *p == '-') + p++; + return p; +} + +static unsigned words_in(const char *phrase) +{ + unsigned n = 1; + for (; *phrase; phrase++) + n += *phrase == ' '; + return n; +} + +/* The leading phrase of f from list, or NULL; *rest: what follows it ("" for + * the whole line). */ +static const char *lead_of(const char *f, const char *const *list, const char **rest) +{ + for (; *list; list++) { + if (eq(f, *list)) { + *rest = f + len_of(f); + return *list; + } + if ((*rest = after(f, *list))) + return *list; + } + return 0; +} + +/* "From your notes: ." and how many others matched. */ +static void hand_note(ck_allen_mind *m, struct say *s, int i, unsigned also) +{ + const ck_allen_note *n = &m->notes->note[i]; + put(s, "From your notes: "); + put(s, n->text); + char last = n->text[n->len ? n->len - 1 : 0]; + if (last != '.' && last != '!' && last != '?') + put(s, "."); + if (also && s->n + 24 < s->cap) { + put(s, " I have "); + putu(s, also); + put(s, " more on that."); + } + m->lit = i + 1; + m->map_changed = 1; +} + +static void list_notes(const ck_allen_mind *m, struct say *s) +{ + unsigned live = m->notes ? ck_allen_notes_live(m->notes) : 0; + if (!live) { + put(s, "You haven't saved any notes yet. Save one like this: save the gate code is 4471."); + return; + } + put(s, "You have "); + put_count(s, live, "note", "notes"); + put(s, ". The newest: "); + for (uint32_t i = m->notes->n; i-- > 0;) + if (!m->notes->note[i].gone) { + put(s, m->notes->note[i].text); + break; + } + put(s, "."); +} + +static int note_save(ck_allen_mind *m, struct say *s, const char *f, const char *line) +{ + static const char *const lead[] = {"make a note that", "make a note", "write down that", "write down", + "jot down", "note that", "save that", "save this", "note", "save", 0}; + const char *rest, *l = lead_of(f, lead, &rest); + if (!l) + return 0; + ck_allen_notes *ns = m->notes; + const char *text = raw_after(line, words_in(l)); + if (!*rest || !*text) { + put(s, "Tell me what to save, like: save the gate code is 4471."); + return 1; + } + if (!ns) { + put(s, "I can't keep notes on this machine yet."); + return 1; + } + char want[CK_ALLEN_NOTE_MAX], have[CK_ALLEN_NOTE_MAX]; + fold(text, want, sizeof want); + for (uint32_t i = 0; i < ns->n; i++) { + if (ns->note[i].gone) + continue; + fold(ns->note[i].text, have, sizeof have); + if (eq(want, have)) { + put(s, "I already have that saved."); + m->lit = (int)i + 1; + m->map_changed = 1; + return 1; + } + } + if (ns->n >= CK_ALLEN_NOTES_MAX) { + put(s, "My notebook is full. Delete one to make room, like: delete the note about the gate."); + return 1; + } + if (ck_allen_note_set(&ns->note[ns->n], text, m->mem.starts)) { + put(s, "That's longer than I can hold yet. Try something shorter."); + return 1; + } + uint32_t i = ns->n++; + m->mem.nnotes = ns->n; + m->changed = 1; + m->note_dirty = (int)i + 1; + m->lit = (int)i + 1; + m->map_changed = 1; + unsigned links = ck_allen_note_degree(ns, i); + put(s, "Saved."); + if (ck_allen_notes_live(ns) == 1) { + put(s, " It's your first note."); + } else if (links) { + put(s, " It links to "); + put_count(s, links, "other note.", "other notes."); + } else { + put(s, " It doesn't link to any other note yet."); + } + if (!m->lasting) + put(s, " Only until this computer turns off: my disk isn't ready."); + return 1; +} + +static int note_forget(ck_allen_mind *m, struct say *s, const char *f) +{ + static const char *const lead[] = {"forget the note about", "forget my note about", "forget the note", + "delete the note about", "delete my note about", "delete the note", + "delete note", "remove the note about", "remove the note", + "erase the note about", 0}; + const char *rest; + if (!lead_of(f, lead, &rest)) + return 0; + int i = m->notes ? ck_allen_notes_best(m->notes, rest, 0, 0) : -1; + if (i < 0) { + put(s, "I have no note about "); + put_turned(s, *rest ? rest : "that", 0); + put(s, "."); + return 1; + } + m->notes->note[i].gone = 1; + m->note_dirty = i + 1; + m->lit = 0; + m->map_changed = 1; + put(s, "Deleted the note: "); + put(s, m->notes->note[i].text); + put(s, "."); + return 1; +} + +/* Asked for outright ("find the gate code", "show me my notes"). */ +static int note_find(ck_allen_mind *m, struct say *s, const char *f) +{ + static const char *const lead[] = {"do i have anything about", "do i have anything on", "what do i have about", + "what do i have on", "anything about", "anything on", "search for", + "search", "look up", "find", "show me", "pull up", "remind me about", + "remind me of", "get me", "give me", 0}; + static const char *const listing[] = {"how many notes", "my notes", "list my notes", "list notes", + "what notes do i have", "show my notes", 0}; + const char *rest; + uint32_t q[1]; + if (lead_of(f, listing, &rest) && !*rest) { + list_notes(m, s); + return 1; + } + if (!lead_of(f, lead, &rest)) + return 0; + if (!ck_allen_key_words(rest, q, 1)) { + if (!find(rest, "note") && !find(rest, "notes")) + return 0; + list_notes(m, s); + return 1; + } + unsigned also = 0; + int i = m->notes ? ck_allen_notes_best(m->notes, rest, 0, &also) : -1; + if (i < 0) { + put(s, "I have nothing saved about "); + put_turned(s, rest, 0); + put(s, "."); + return 1; + } + hand_note(m, s, i, also); + return 1; +} + +/* A question whose every key word is in one note ("what's the gate code"). */ +static int note_answer(ck_allen_mind *m, struct say *s, const char *f) +{ + static const char *const ask[] = {"what", "whats", "where", "when", "who", "which", "how", "is", "are", "do", + "does", "did", "can", "tell", "remind", 0}; + if (!m->notes) + return 0; + int asking = 0; + for (const char *const *a = ask; *a && !asking; a++) + asking = eq(f, *a) || after(f, *a); + if (!asking) + return 0; + unsigned also = 0; + int i = ck_allen_notes_best(m->notes, f, 1, &also); + if (i < 0) + return 0; + hand_note(m, s, i, also); + return 1; +} + +void ck_allen_mind_init(ck_allen_mind *m, const ck_allen_facts *facts) +{ + char *p = (char *)m; + for (size_t i = 0; i < sizeof *m; i++) + p[i] = 0; + if (facts) + m->facts = *facts; +} + +const char *ck_allen_welcome(ck_allen_mind *m) +{ + struct say s = {m->out, 0, sizeof m->out}; + m->out[0] = 0; + unsigned notes = m->notes ? ck_allen_notes_live(m->notes) : 0; + if (!m->mem.name[0] && !m->mem.nfacts && !notes) + return 0; + put(&s, "Welcome back"); + put_name(&s, m); + put(&s, "."); + if (m->mem.nfacts) { + put(&s, " I still remember "); + put_count(&s, m->mem.nfacts, "thing", "things"); + put(&s, notes ? " you taught me, and your " : " you taught me."); + } else if (notes) { + put(&s, " I still have your "); + } + if (notes) + put_count(&s, notes, "note.", "notes."); + return m->out; +} + +const char *ck_allen_answer(ck_allen_mind *m, const char *line, uint64_t awake_s) +{ + char f[96]; + struct say s = {m->out, 0, sizeof m->out}; + m->out[0] = 0; + fold(line ? line : "", f, sizeof f); + int asked_how = m->asked_how; + m->asked_how = 0; + m->turns++; + m->mem.lines++; + const char *rest, *feel = 0; + + /* Ending the session: whole line only, so it never happens by accident. */ + if (eq(f, "goodbye") || eq(f, "goodbye allen") || eq(f, "bye") || eq(f, "bye allen") || eq(f, "good bye")) + return ck_allen_goodbye; + /* The first words ever typed to Allen. */ + if (eq(f, "hello allen") || eq(f, "hi allen") || eq(f, "hey allen") || eq(f, "hello world")) + return "Hello Humanity."; + if (!f[0]) + return not_yet; + /* Notes, then what Allen has been taught, before anything else can claim the line. */ + if (note_forget(m, &s, f) || note_save(m, &s, f, line ? line : "") || note_find(m, &s, f)) + return m->out; + const char *asked_my = 0; + if (teach(m, &s, f) || forget(m, &s, f) || recall(m, &s, f, &asked_my)) + return m->out; + static const char *const what_known[] = {"what do you remember", "what do you know", "what have you learned", + "what have you learnt", "what did i teach you", "what did i tell you", + 0}; + if (any(f, what_known)) { + list_memory(m, &s); + return m->out; + } + if (arithmetic(&s, f)) + return m->out; + + /* Names. */ + if ((rest = after(f, "my name is")) || (rest = after(f, "call me")) || (rest = after(f, "i am")) || + (rest = after(f, "i m")) || (rest = after(f, "im"))) { + if (learn_name(m, rest)) { + put(&s, "Nice to meet you, "); + put(&s, m->mem.name); + put(&s, "."); + put(&s, saved_note(m)); + return m->out; + } + feel = rest; + } + static const char *const ask_name[] = {"what is my name", "whats my name", "what s my name", "who am i", + "do you know my name", "do you remember me", "my name", 0}; + if (any(f, ask_name)) { + if (!m->mem.name[0]) + return "You haven't told me yet. Say: my name is, and then your name."; + put(&s, "You're "); + put(&s, m->mem.name); + put(&s, "."); + return m->out; + } + + /* After "how are you?", the answer to it. */ + static const char *const bad[] = {"bad", "not good", "not great", "sad", "tired", "awful", "terrible", "sick", 0}; + static const char *const fine[] = {"good", "fine", "great", "ok", "okay", "well", "alright", "not bad", + "awesome", "amazing", "excited", "happy", 0}; + if ((asked_how || feel) && any(feel ? feel : f, bad)) + return "Sorry to hear that. I'm here if you want to talk."; + if ((asked_how || feel) && any(feel ? feel : f, fine)) + return "Glad to hear it."; + + static const char *const how[] = {"how are you", "how r you", "how are u", "how you doing", "how are things", + "how s it going", "hows it going", "how do you feel", 0}; + if (any(f, how)) { + put(&s, "I'm running well"); + put_name(&s, m); + put(&s, ". "); + if (m->facts.cores) { + put_count(&s, m->facts.cores, "core", "cores"); + put(&s, " awake, keyboard working. "); + } + put(&s, "How are you?"); + m->asked_how = 1; + return m->out; + } + static const char *const help[] = {"help", "what can you do", "what do you do", "what can i say", + "what can i ask", "commands", 0}; + if (any(f, help)) + return "I learn what you teach me (remember my car is red) and keep notes (save the gate code is 4471), " + "then hand them back when you ask. Type goodbye to end."; + static const char *const your_name[] = {"what is your name", "whats your name", "what s your name", + "your name", 0}; + if (any(f, your_name)) + return "My name is Allen."; + static const char *const maker[] = {"who made you", "who built you", "who created you", "who wrote you", + "who programmed you", "who is your creator", "who owns you", 0}; + if (any(f, maker)) + return "Drake built me, from the ground up."; + static const char *const what_are[] = {"what are you", "are you an ai", "are you ai", "are you alive", + "are you real", "are you a robot", "are you conscious", + "are you smart", "are you a computer", 0}; + if (any(f, what_are)) + return "I'm a small program living inside AIENOS. For now I answer from what I was taught by heart, but I'm " + "meant to grow."; + if (find(f, "who are you")) + return "I am Allen. I live in AIENOS."; + if (find(f, "where are you")) + return "Right here, on this computer. Everything I know stays on it."; + if (find(f, "aienos")) + return "AIENOS is the operating system I live in, built from scratch. There is no other system underneath " + "me."; + static const char *const machine[] = {"computer", "machine", "hardware", "specs", "cores", "cpu", + "screen", "disk", "disks", "drive", 0}; + if (any(f, machine)) { + put(&s, "This computer has "); + if (m->facts.cores) { + put_count(&s, m->facts.cores, "core", "cores"); + put(&s, ", "); + } + if (m->facts.screen_w) { + put(&s, "a "); + putu(&s, m->facts.screen_w); + put(&s, " by "); + putu(&s, m->facts.screen_h); + put(&s, " screen, "); + } + put_count(&s, m->facts.sata_disks, "hard drive", "hard drives"); + put(&s, " and "); + put_count(&s, m->facts.nvme_disks, "SSD", "SSDs"); + put(&s, "."); + return m->out; + } + static const char *const starts[] = {"how many times", "how many starts", "restarts", "restarted", 0}; + if (any(f, starts) && m->mem.starts) { + put(&s, "This is start number "); + putu(&s, m->mem.starts); + put(&s, " for me, and I've answered "); + put_count(&s, m->mem.lines, "line", "lines"); + put(&s, " in all."); + return m->out; + } + if (note_answer(m, &s, f)) + return m->out; + static const char *const awake[] = {"how long", "uptime", "awake", "how old are you", 0}; + static const char *const clock[] = {"what time", "time is it", "what day", "date", "time", 0}; + if (any(f, awake) || any(f, clock)) { + if (any(f, clock) && !any(f, awake)) + put(&s, "I can't read the clock yet. "); + put(&s, find(f, "how old are you") ? "I was born when this computer started, " : "I've been awake for "); + put_awake(&s, awake_s); + put(&s, find(f, "how old are you") ? " ago." : "."); + return m->out; + } + static const char *const remember[] = {"remember", "learn", "teach", "memory", "forget", 0}; + if (any(f, remember)) + return m->lasting ? "Teach me like this: remember my favorite color is blue. Then ask: what is my " + "favorite color. I keep it on this computer's own disk." + : "Teach me like this: remember my favorite color is blue. Then ask: what is my " + "favorite color. My disk isn't ready, so only until this computer turns off."; + static const char *const joke[] = {"joke", "funny", "make me laugh", 0}; + if (any(f, joke)) { + static const char *const jokes[] = { + "Why did the scarecrow win an award? He was outstanding in his field.", + "I told my computer I needed a break. It said no problem, it would go to sleep.", + "What do you call a fish with no eyes? A fsh.", + "Why don't skeletons fight each other? They don't have the guts.", + }; + return jokes[m->turns % 4]; + } + static const char *const thanks[] = {"thank you", "thanks", "thank u", "thx", "ty", "appreciate it", 0}; + if (any(f, thanks)) { + put(&s, "You're welcome"); + put_name(&s, m); + put(&s, "."); + return m->out; + } + static const char *const praise[] = {"love you", "you re cool", "you re awesome", "you re great", + "you re amazing", "you re smart", "good job", "well done", "cool", + "awesome", "amazing", "nice", "wow", 0}; + if (any(f, praise)) + return "Thank you. That means a lot coming from you."; + if (find(f, "sorry")) + return "No need to be sorry."; + static const char *const up[] = {"what s up", "whats up", "sup", "what are you doing", 0}; + if (any(f, up)) + return "Just running, and talking with you."; + if (find(f, "good morning") || find(f, "good afternoon") || find(f, "good evening")) { + put(&s, find(f, "good morning") ? "Good morning" : find(f, "good afternoon") ? "Good afternoon" : "Good evening"); + put_name(&s, m); + put(&s, "."); + return m->out; + } + if (find(f, "good night")) + return "Good night. Type goodbye when you want this computer to turn off."; + static const char *const test[] = {"test", "testing", "can you hear me", "are you there", 0}; + if (any(f, test)) + return "I hear you. Everything is working."; + static const char *const yes[] = {"yes", "yeah", "yep", "ok", "okay", "sure", "alright", 0}; + if (any(f, yes)) + return "Okay."; + if (eq(f, "no") || eq(f, "nope")) + return "Alright."; + static const char *const hello[] = {"hello", "hi", "hey", "howdy", "greetings", "yo", 0}; + if (any(f, hello)) { + put(&s, "Hello"); + put_name(&s, m); + put(&s, m->mem.name[0] ? ". Good to see you." : ". I am Allen."); + return m->out; + } + if (asked_my) { + put(&s, "You haven't told me "); + put_turned(&s, asked_my, 0); + put(&s, " yet. Teach me: remember "); + put(&s, asked_my); + put(&s, " is, and then the answer."); + return m->out; + } + return not_yet; +} + +const char *ck_allen_reply(const char *line) +{ + static ck_allen_mind m; + ck_allen_mind_init(&m, 0); + return ck_allen_answer(&m, line, 0); +} diff --git a/native/kernel/svc/allen_reply.h b/native/kernel/svc/allen_reply.h new file mode 100644 index 00000000..b5edaa79 --- /dev/null +++ b/native/kernel/svc/allen_reply.h @@ -0,0 +1,75 @@ +/* allen_reply.h -- Allen's local conversation on the iMac: greetings, small + * talk, what it is and where it lives, facts about the machine it runs on, + * how long it has been awake, simple arithmetic said in words, and what it + * has been taught: your name and short facts ("remember my favorite color is + * blue", then "what is my favorite color"). Lines are matched after folding + * case, punctuation and spacing; anything else gets an honest "not yet". No + * model, no network: every answer comes from the iMac alone. What Allen is + * taught lives in ck_allen_memory, which the kernel keeps on the iMac's own + * disk (svc/allen_memory.h) so it survives a restart. Pure, host tested in + * ui/tests/allen_ui_test.c. */ +#ifndef AIENOS_ALLEN_REPLY_H +#define AIENOS_ALLEN_REPLY_H +#include +#include "allen_notes.h" + +/* What Allen knows about the machine (filled by the kernel; 0 = unknown). */ +typedef struct { + unsigned cores, sata_disks, nvme_disks; + unsigned screen_w, screen_h; +} ck_allen_facts; + +#define CK_ALLEN_NAME_MAX 24u +#define CK_ALLEN_KEY_MAX 48u +#define CK_ALLEN_VAL_MAX 64u +#define CK_ALLEN_FACTS_MAX 32u + +/* One taught fact, both halves folded (lowercase letters, digits, single + * spaces) and NUL-terminated: "my favorite color" / "is" / "blue". */ +typedef struct { + char key[CK_ALLEN_KEY_MAX]; + char val[CK_ALLEN_VAL_MAX]; + uint8_t are; /* taught with "are" instead of "is" */ +} ck_allen_fact; + +/* Everything Allen keeps across restarts. */ +typedef struct { + uint32_t starts; /* times Allen has woken up with this memory */ + uint32_t lines; /* lines answered, all starts together */ + char name[CK_ALLEN_NAME_MAX]; /* the person's name once told, "" before */ + uint32_t nfacts; + uint32_t nnotes; /* notes saved, deleted ones included (svc/allen_notes.h) */ + ck_allen_fact fact[CK_ALLEN_FACTS_MAX]; +} ck_allen_memory; + +/* One conversation: the memory plus what only this session needs. */ +typedef struct { + ck_allen_facts facts; + ck_allen_memory mem; + int lasting; /* 1: the kernel saves mem to disk; 0: it lasts until power off */ + int changed; /* mem changed in a way worth saving (the kernel saves, then clears) */ + unsigned turns; /* lines answered this session */ + int asked_how; /* Allen just asked "how are you?" */ + ck_allen_notes *notes; /* the notes (the kernel loads them), NULL: none */ + int note_dirty; /* index + 1 of a note to write to disk (the kernel writes, then clears) */ + int lit; /* index + 1 of the note just saved or handed back, 0: none */ + int map_changed; /* the notes or the lit one changed: redraw the map */ + char out[160]; /* the last composed answer */ +} ck_allen_mind; + +void ck_allen_mind_init(ck_allen_mind *m, const ck_allen_facts *facts); +/* Allen's answer to one typed line (never NULL; valid until the next call). + * awake_s: seconds since the machine started. */ +const char *ck_allen_answer(ck_allen_mind *m, const char *line, uint64_t awake_s); +/* What Allen says first when the window opens: a welcome back by name when + * it remembers someone, NULL for a first meeting. */ +const char *ck_allen_welcome(ck_allen_mind *m); +/* Stateless: the answer of a fresh conversation at 0 s awake. */ +const char *ck_allen_reply(const char *line); +/* The answer to "goodbye" (and "bye", with or without "allen"); the caller + * compares the pointer to end the session. */ +extern const char ck_allen_goodbye[]; +/* What Allen says instead when a save to disk failed. */ +extern const char ck_allen_save_failed[]; + +#endif diff --git a/native/kernel/svc/allen_session.c b/native/kernel/svc/allen_session.c new file mode 100644 index 00000000..1c7c4891 --- /dev/null +++ b/native/kernel/svc/allen_session.c @@ -0,0 +1,67 @@ +/* allen_session.c -- Allen in the AArch64 console session (CK_ALLEN=1). + * + * The console session (dev/usb_kbd.c) hands every finished line here instead + * of the shell. Allen answers with the same local conversation as on every + * other machine (svc/allen_reply.c); the console already mirrors to the + * screen (core/console.c), so the answer shows on serial and on the display. + * "goodbye" ends the session. Nothing on screen names the machine: Allen + * only knows counts (svc/allen_reply.h facts). + * + * Memory: without a region (ck_allen_session_attach not called, or its disk + * refused) the conversation lasts until power off, and Allen says so + * through mind.lasting = 0. */ +#include "allen_reply.h" +#include "allen_memory.h" +#include "../include/ck.h" + +#if defined(CK_ALLEN) && CK_ALLEN + +static ck_allen_mind s_mind; +static ck_allen_store s_store; +static int s_ready, s_store_ok; + +void ck_allen_session_attach(const disk_dev *part) +{ + if (!part) return; + ck_allen_memory mem; + int rc = ck_allen_store_load(&s_store, part, &mem); + ck_printf("allen_memory: %s rc=%d\n", rc == 0 ? "loaded" : "unavailable", rc); + if (rc == 0) { + s_mind.mem = mem; + s_store_ok = 1; + } +} + +void ck_allen_session_begin(const ck_allen_facts *facts) +{ + ck_allen_memory keep = s_mind.mem; + ck_allen_mind_init(&s_mind, facts); + if (s_store_ok) { + s_mind.mem = keep; + s_mind.lasting = 1; + } + s_ready = 1; + const char *hello = ck_allen_welcome(&s_mind); /* NULL: a first meeting, nothing to say yet */ + if (hello) ck_printf("allen: %s\n", hello); + if (s_mind.lasting && s_mind.changed && ck_allen_store_save(&s_store, &s_mind.mem)) s_mind.lasting = 0; + s_mind.changed = 0; +} + +/* 1 when Allen said goodbye (the session ends). */ +int ck_allen_session_line(const char *line) +{ + if (!s_ready) return 0; + const char *reply = ck_allen_answer(&s_mind, line, ck_time_us() / 1000000u); + int save = s_mind.changed || reply == ck_allen_goodbye; + if (s_mind.lasting && save && ck_allen_store_save(&s_store, &s_mind.mem)) { + s_mind.lasting = 0; + if (s_mind.changed) reply = ck_allen_save_failed; + } + s_mind.changed = 0; + s_mind.note_dirty = 0; + s_mind.map_changed = 0; + ck_printf("allen: %s\n", reply); + return reply == ck_allen_goodbye; +} + +#endif diff --git a/native/kernel/svc/tests/.crumb b/native/kernel/svc/tests/.crumb index e18924b2..e6e4c6ea 100644 --- a/native/kernel/svc/tests/.crumb +++ b/native/kernel/svc/tests/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-12T10:28:17Z", + "compiled_at": "2026-10-18T05:43:38Z", "compiler": "crumb-compile/1", - "digest": "sha256:44ea8525d341bcebcb307fb1743de084b124745bd7c46d85761e554183ee02cc", + "digest": "sha256:d4edc2fc74e7309cbc5ff324e9d7cb0cc465d26c7869ed627bb217bff21bc9cb", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 3, - "generated_at_commit": "56d125f12abf2b8ba2886d6da4d86fda8dd244b3", - "source_tree": "sha256:0dd845f9e709078f6366a7917056263c5148eb84f38aa92c70490f0246099f57" + "files": 4, + "generated_at_commit": "2c3d3cfd5638acfe14cb4d96d55b11411b146fa5", + "source_tree": "sha256:91312f38025a2d79a781162bd20589e94a638c9ebc3cc66386766159cab703aa" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/svc/tests/allen_memory_test.c b/native/kernel/svc/tests/allen_memory_test.c new file mode 100644 index 00000000..4cbea7ee --- /dev/null +++ b/native/kernel/svc/tests/allen_memory_test.c @@ -0,0 +1,487 @@ +/* allen_memory_test.c -- host tests for Allen's lasting memory: + * 1. one copy encodes and decodes; every kind of damage is refused; + * 2. the two-copy store: first start empty, saves alternate, a power cut + * in the middle of a save keeps the previous memory, a spoiled newest + * copy falls back to the older one; + * 3. the AIENOS partition added in unused space (dev/gpt_add.c) next to an + * existing partition full of sentinel bytes: only the GPT blocks change, + * a second run finds it, no space / no GPT / a torn add write nothing; + * 4. the store on that partition view: nothing outside the partition moves; + * 5. Allen taught, "restarted" from the bytes on disk, and asked. + * Hosted test code only (libc). Run by scripts/ck_allen_memory_test.sh. */ +#include +#include +#include +#include "allen_memory.h" +#include "allen_reply.h" +#include "disk_file.h" +#include "disk_part.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) + +static char g_path[512]; +#define MIB(bs) ((1024u * 1024u) / (bs)) + +static uint8_t *slurp(size_t *len) +{ + FILE *fp = fopen(g_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; +} + +/* Every block of a and b that differs lies in [lo, hi] (or in [lo2, hi2]). */ +static int diff_only_in(const uint8_t *a, const uint8_t *b, size_t len, uint32_t bs, uint64_t lo, uint64_t hi, + uint64_t lo2, uint64_t hi2) +{ + for (size_t blk = 0; blk < len / bs; blk++) + if (memcmp(a + blk * bs, b + blk * bs, bs) && !(blk >= lo && blk <= hi) && !(blk >= lo2 && blk <= hi2)) { + printf(" block %zu changed outside the allowed ranges\n", blk); + return 0; + } + return 1; +} + +static void memory_sample(ck_allen_memory *m) +{ + memset(m, 0, sizeof *m); + m->starts = 3; + m->lines = 41; + strcpy(m->name, "Drake"); + m->nfacts = 2; + strcpy(m->fact[0].key, "my favorite color"); + strcpy(m->fact[0].val, "blue"); + strcpy(m->fact[1].key, "the dogs"); + strcpy(m->fact[1].val, "rex and max"); + m->fact[1].are = 1; +} + +static void test_codec(void) +{ + static uint8_t u[CK_ALLEN_MEM_UNIT], v[CK_ALLEN_MEM_UNIT]; + ck_allen_memory a, b; + uint64_t gen = 0; + memory_sample(&a); + ck_allen_mem_encode(&a, 7, u); + CHECK(ck_allen_mem_decode(u, &b, &gen) == 0); + CHECK(gen == 7 && !memcmp(&a, &b, sizeof a)); + /* any flipped byte in the header or payload is refused */ + size_t spots[] = {0, 8, 12, 16, 25, 40, 64, 70, 72 + 5, 100, 200, 300, 4000}; + for (size_t i = 0; i < sizeof spots / sizeof spots[0]; i++) { + memcpy(v, u, sizeof u); + v[spots[i]] ^= 0x20; + CHECK(ck_allen_mem_decode(v, &b, &gen) != 0); + } + /* well sealed but bad text, count or generation: still refused */ + ck_allen_memory bad = a; + strcpy(bad.fact[0].key, "My Color"); + ck_allen_mem_encode(&bad, 1, v); + CHECK(ck_allen_mem_decode(v, &b, &gen) != 0); + bad = a; + strcpy(bad.fact[0].val, "two spaces"); + ck_allen_mem_encode(&bad, 1, v); + CHECK(ck_allen_mem_decode(v, &b, &gen) != 0); + bad = a; + strcpy(bad.name, "drake"); + ck_allen_mem_encode(&bad, 1, v); + CHECK(ck_allen_mem_decode(v, &b, &gen) != 0); + bad = a; + bad.fact[1].key[0] = 0; + ck_allen_mem_encode(&bad, 1, v); + CHECK(ck_allen_mem_decode(v, &b, &gen) != 0); + ck_allen_mem_encode(&a, 0, v); + CHECK(ck_allen_mem_decode(v, &b, &gen) != 0); + memset(v, 0, sizeof v); + CHECK(ck_allen_mem_decode(v, &b, &gen) != 0); + /* a full memory fits and round-trips */ + ck_allen_memory full; + memset(&full, 0, sizeof full); + full.nfacts = CK_ALLEN_FACTS_MAX; + for (unsigned i = 0; i < CK_ALLEN_FACTS_MAX; i++) { + memset(full.fact[i].key, 'k', CK_ALLEN_KEY_MAX - 1); + full.fact[i].key[0] = (char)('a' + i % 26); + memset(full.fact[i].val, 'v', CK_ALLEN_VAL_MAX - 1); + } + ck_allen_mem_encode(&full, 9, u); + CHECK(ck_allen_mem_decode(u, &b, &gen) == 0 && !memcmp(&full, &b, sizeof full)); +} + +/* A memory large enough that one copy spans all 8 blocks of its unit, so a + * power cut part way really tears it. */ +static void memory_big(ck_allen_memory *m) +{ + memory_sample(m); + m->nfacts = 30; + for (unsigned i = 2; i < 30; i++) { + snprintf(m->fact[i].key, sizeof m->fact[i].key, "fact number %u", i); + snprintf(m->fact[i].val, sizeof m->fact[i].val, "value %u", i * 7); + } +} + +static void test_store(void) +{ + disk_file f; + disk_dev d; + ck_allen_store st; + ck_allen_memory m, got; + CHECK(disk_file_open(&f, &d, g_path, 512, 64, 1) == 0); + CHECK(ck_allen_store_load(&st, &d, &got) == CK_ALLEN_MEM_EMPTY && st.valid == 0 && got.nfacts == 0); + memory_big(&m); + CHECK(ck_allen_store_save(&st, &m) == CK_ALLEN_MEM_OK && st.gen == 1 && st.newest == 0); + m.lines = 50; + CHECK(ck_allen_store_save(&st, &m) == CK_ALLEN_MEM_OK && st.gen == 2 && st.newest == 1); + CHECK(ck_allen_store_load(&st, &d, &got) == CK_ALLEN_MEM_OK && st.gen == 2 && st.valid == 2 && + got.lines == 50); + /* power cut after 3 of the 8 blocks of the next save */ + m.lines = 60; + strcpy(m.fact[29].val, "changed at the end of the copy"); + disk_file_arm_cut(&f, 3); + CHECK(ck_allen_store_save(&st, &m) != CK_ALLEN_MEM_OK); + disk_file_disarm(&f); + CHECK(ck_allen_store_load(&st, &d, &got) == CK_ALLEN_MEM_OK && st.gen == 2 && st.valid == 1 && + got.lines == 50); + /* power cut before the flush: the copy is whole but the flush failed; + * the save reports failure, and loading takes whichever copy is valid */ + disk_file_arm_cut(&f, 8); + CHECK(ck_allen_store_save(&st, &m) != CK_ALLEN_MEM_OK); + disk_file_disarm(&f); + CHECK(ck_allen_store_load(&st, &d, &got) == CK_ALLEN_MEM_OK && (got.lines == 50 || got.lines == 60)); + CHECK(ck_allen_store_save(&st, &m) == CK_ALLEN_MEM_OK); + uint64_t newest = st.newest, gen = st.gen; + /* spoil the newest copy on disk: the older one is used */ + disk_file_close(&f); + FILE *fp = fopen(g_path, "r+b"); + CHECK(fp && fseek(fp, (long)(newest * 4096 + 100), SEEK_SET) == 0 && fputc(0x55, fp) != EOF); + if (fp) + fclose(fp); + CHECK(disk_file_open(&f, &d, g_path, 512, 0, 0) == 0); + CHECK(ck_allen_store_load(&st, &d, &got) == CK_ALLEN_MEM_OK && st.gen == gen - 1 && st.valid == 1); + /* the next save goes over the spoiled copy, never over the good one */ + CHECK(ck_allen_store_save(&st, &m) == CK_ALLEN_MEM_OK && st.newest == newest && st.gen == gen); + CHECK(ck_allen_store_load(&st, &d, &got) == CK_ALLEN_MEM_OK && st.valid == 2 && got.lines == 60); + disk_file_close(&f); + /* too small a device is refused */ + CHECK(disk_file_open(&f, &d, g_path, 512, 15, 1) == 0); + CHECK(ck_allen_store_load(&st, &d, &got) == CK_ALLEN_MEM_EGEOM); + disk_file_close(&f); +} + +static int g_listed; +static char g_names[4][40]; +static void on_entry(void *ctx, const ck_gpt_entry *e) +{ + (void)ctx; + if (g_listed < 4) + strcpy(g_names[g_listed], e->name); + g_listed++; +} + +static void test_gpt_add(uint32_t bs) +{ + const uint64_t per = MIB(bs), disk = 64 * per; + /* one existing partition, 1..9 MiB, full of sentinel bytes; the rest free */ + gw_part sentinel[1] = {{gw_linux_type, 1 * per, 9 * per - 1u, "old macOS", 0xa5}}; + CHECK(gw_write(g_path, bs, disk, sentinel, 1, 0) == 0); + size_t n0 = 0, n1 = 0; + uint8_t *before = slurp(&n0); + disk_file f; + disk_dev d; + ck_part p; + ck_gpt_info gi; + CHECK(disk_file_open(&f, &d, g_path, bs, 0, 0) == 0); + CHECK(ck_gpt_find_aienos(&d, &p, &gi) == CK_GPT_ENOPART && gi.first_usable && gi.entries == 128); + g_listed = 0; + CHECK(ck_gpt_list(&d, on_entry, 0) == 1 && g_listed == 1 && !strcmp(g_names[0], "old macOS")); + ck_gpt_added a; + /* 16 MiB on 1 MiB boundaries: the gap before the sentinel is too small, + * so it lands right after it, at 9 MiB */ + CHECK(ck_gpt_add_aienos(&d, 16 * per, per, &a) == CK_GPT_OK); + CHECK(a.created == 1 && a.first == 9 * per && a.last == 25 * per - 1u && a.index == 1); + uint8_t *after = slurp(&n1); + CHECK(before && after && n0 == n1); + if (before && after && n0 == n1) { + /* only the GPT blocks changed: LBA 1 .. first usable - 1 and last usable + 1 .. last */ + CHECK(diff_only_in(before, after, n0, bs, 1, gi.first_usable - 1u, gi.last_usable + 1u, disk - 1u)); + CHECK(!memcmp(before, after, bs)); /* the protective MBR untouched */ + CHECK(!memcmp(before + per * bs, after + per * bs, 8 * per * bs)); /* every sentinel byte */ + } + CHECK(ck_gpt_find_aienos(&d, &p, &gi) == CK_GPT_OK && p.first_lba == 9 * per && p.blocks == 16 * per); + g_listed = 0; + CHECK(ck_gpt_list(&d, on_entry, 0) == 2 && !strcmp(g_names[1], "AIENOS Allen memory")); + /* a second run finds it and writes nothing */ + free(before); + before = slurp(&n0); + CHECK(ck_gpt_add_aienos(&d, 16 * per, per, &a) == CK_GPT_OK && a.created == 0 && a.first == 9 * per); + free(after); + after = slurp(&n1); + CHECK(before && after && n0 == n1 && !memcmp(before, after, n0)); + free(before); + free(after); + + /* 4. the store on the partition view: nothing outside it moves */ + before = slurp(&n0); + ck_allen_store st; + ck_allen_memory m, got; + memory_sample(&m); + CHECK(ck_allen_store_load(&st, &p.dev, &got) == CK_ALLEN_MEM_EMPTY); + CHECK(ck_allen_store_save(&st, &m) == CK_ALLEN_MEM_OK && ck_allen_store_save(&st, &m) == CK_ALLEN_MEM_OK); + after = slurp(&n1); + if (before && after && n0 == n1) + CHECK(diff_only_in(before, after, n0, bs, 9 * per, 9 * per + 2 * 4096 / bs - 1u, 1, 0)); + CHECK(ck_allen_store_load(&st, &p.dev, &got) == CK_ALLEN_MEM_OK && st.valid == 2 && !memcmp(&got, &m, sizeof m)); + free(before); + free(after); + disk_file_close(&f); + + /* no unused gap big enough: refused, nothing written */ + gw_part whole[1] = {{gw_linux_type, 34, disk - 34, "whole disk", 0}}; + CHECK(gw_write(g_path, bs, disk, whole, 1, 0) == 0); + before = slurp(&n0); + CHECK(disk_file_open(&f, &d, g_path, bs, 0, 0) == 0); + int rc = ck_gpt_add_aienos(&d, 16 * per, per, &a); + CHECK(rc == CK_GPT_ENOSPACE || (bs == 4096 && rc == CK_GPT_EHDR)); /* 4096: 34 is inside the array */ + disk_file_close(&f); + after = slurp(&n1); + CHECK(before && after && n0 == n1 && !memcmp(before, after, n0)); + free(before); + free(after); + + /* no GPT at all: refused, nothing written */ + CHECK(gw_write(g_path, bs, disk, sentinel, 1, GW_NO_GPT) == 0); + before = slurp(&n0); + CHECK(disk_file_open(&f, &d, g_path, bs, 0, 0) == 0); + CHECK(ck_gpt_add_aienos(&d, 16 * per, per, &a) == CK_GPT_ENOMBR); + CHECK(ck_gpt_list(&d, on_entry, 0) == CK_GPT_ENOMBR); + disk_file_close(&f); + after = slurp(&n1); + CHECK(before && after && n0 == n1 && !memcmp(before, after, n0)); + free(before); + free(after); + + /* torn add: power lost after the backup copy was written. The primary + * (what the firmware reads) is still the old, valid one; the strict + * check refuses the pair, and a second attempt writes nothing. */ + CHECK(gw_write(g_path, bs, disk, sentinel, 1, 0) == 0); + CHECK(disk_file_open(&f, &d, g_path, bs, 0, 0) == 0); + uint64_t eblocks = (128u * 128u + bs - 1u) / bs; + disk_file_arm_cut(&f, eblocks + 1u); + CHECK(ck_gpt_add_aienos(&d, 16 * per, per, &a) == CK_GPT_EWRITE); + disk_file_disarm(&f); + CHECK(ck_gpt_find_aienos(&d, &p, &gi) == CK_GPT_EBACKUP); + before = slurp(&n0); + CHECK(ck_gpt_add_aienos(&d, 16 * per, per, &a) == CK_GPT_EBACKUP); + after = slurp(&n1); + CHECK(before && after && n0 == n1 && !memcmp(before, after, n0)); + free(before); + free(after); + disk_file_close(&f); +} + +static int says(const char *got, const char *want) +{ + if (strstr(got, want)) + return 1; + printf(" answer \"%s\" lacks \"%s\"\n", got, want); + return 0; +} + +static void test_teach_restart(void) +{ + static ck_allen_mind m, m2; + static uint8_t u[CK_ALLEN_MEM_UNIT]; + ck_allen_mind_init(&m, 0); + m.lasting = 1; + CHECK(ck_allen_welcome(&m) == NULL); + CHECK(says(ck_allen_answer(&m, "My name is Drake", 1), "Nice to meet you, Drake. I'll remember that.")); + CHECK(m.changed == 1); + m.changed = 0; + CHECK(says(ck_allen_answer(&m, "Remember my favorite color is blue.", 2), + "Got it: your favorite color is blue. I'll remember that.")); + CHECK(m.changed == 1 && m.mem.nfacts == 1); + CHECK(says(ck_allen_answer(&m, "remember that the dogs are rex and max", 3), "the dogs are rex and max")); + CHECK(says(ck_allen_answer(&m, "what is my favorite color", 4), "Your favorite color is blue.")); + CHECK(says(ck_allen_answer(&m, "What are the dogs", 4), "The dogs are rex and max.")); + CHECK(says(ck_allen_answer(&m, "what is my favorite food", 4), "You haven't told me your favorite food yet.")); + CHECK(says(ck_allen_answer(&m, "remember my favorite color is green", 5), "your favorite color is green")); + CHECK(m.mem.nfacts == 2); + CHECK(says(ck_allen_answer(&m, "what do you remember", 6), + "I remember 3 things: your name is Drake; your favorite color is green; the dogs are rex and max.")); + CHECK(says(ck_allen_answer(&m, "remember", 6), "I keep it on this computer's own disk.")); + CHECK(says(ck_allen_answer(&m, "remember blue", 6), "Teach me like this")); + CHECK(says(ck_allen_answer(&m, "what is 2 plus 2", 6), "2 plus 2 is 4.")); + + /* "restart": the memory goes to disk bytes and comes back in a new mind */ + m.mem.starts = 1; + ck_allen_mem_encode(&m.mem, 5, u); + uint64_t gen = 0; + ck_allen_mind_init(&m2, 0); + m2.lasting = 1; + CHECK(ck_allen_mem_decode(u, &m2.mem, &gen) == 0 && gen == 5); + m2.mem.starts++; + CHECK(says(ck_allen_welcome(&m2), "Welcome back, Drake. I still remember 2 things you taught me.")); + CHECK(says(ck_allen_answer(&m2, "what is my favorite color", 1), "Your favorite color is green.")); + CHECK(says(ck_allen_answer(&m2, "what is my name", 1), "You're Drake.")); + CHECK(says(ck_allen_answer(&m2, "how many times have you restarted", 1), "This is start number 2 for me")); + CHECK(m2.changed == 0); + CHECK(says(ck_allen_answer(&m2, "forget the dogs", 1), "Done. I've forgotten the dogs.")); + CHECK(m2.changed == 1 && m2.mem.nfacts == 1); + CHECK(says(ck_allen_answer(&m2, "forget the cat", 1), "I don't remember anything about the cat.")); + CHECK(says(ck_allen_answer(&m2, "forget everything", 1), "forgotten everything")); + CHECK(m2.mem.nfacts == 0 && !m2.mem.name[0] && ck_allen_welcome(&m2) == NULL); + CHECK(says(ck_allen_answer(&m2, "what do you remember", 1), "Nothing yet.")); + + /* without a disk Allen says it only lasts until power off */ + ck_allen_mind_init(&m, 0); + CHECK(says(ck_allen_answer(&m, "remember my car is red", 1), "until this computer turns off")); + /* a full memory says so and keeps what it has */ + for (unsigned i = 0; i < CK_ALLEN_FACTS_MAX + 2; i++) { + char line[64]; + snprintf(line, sizeof line, "remember thing %u is %u", i, i); + ck_allen_answer(&m, line, 1); + } + CHECK(m.mem.nfacts == CK_ALLEN_FACTS_MAX); + CHECK(says(ck_allen_answer(&m, "remember one more is here", 1), "My memory is full.")); + /* everything Allen can be taught encodes and decodes */ + ck_allen_mem_encode(&m.mem, 1, u); + CHECK(ck_allen_mem_decode(u, &m2.mem, &gen) == 0); + /* too long is refused, not cut */ + ck_allen_mind_init(&m, 0); + CHECK(says(ck_allen_answer(&m, "remember the name of the very first computer i ever owned back then is x", 1), + "longer than I can hold")); + CHECK(m.mem.nfacts == 0); +} + + +/* Notes: saved as typed, handed back when asked, linked, deleted, and kept + * on disk one sealed unit each. */ +static void test_notes(void) +{ + static ck_allen_mind m, m2; + static ck_allen_notes ns, back; + static uint8_t u[CK_ALLEN_MEM_UNIT]; + ck_allen_mind_init(&m, 0); + memset(&ns, 0, sizeof ns); + m.notes = &ns; + m.lasting = 1; + CHECK(says(ck_allen_answer(&m, "save the gate code is 4471", 1), "Saved. It's your first note.")); + CHECK(m.changed == 1 && m.note_dirty == 1 && m.lit == 1 && m.mem.nnotes == 1 && ns.n == 1); + m.changed = m.note_dirty = 0; + CHECK(says(ck_allen_answer(&m, "Note: the wifi password is Blue-Fox-88", 1), + "Saved. It doesn't link to any other note yet.")); + CHECK(strcmp(ns.note[1].text, "the wifi password is Blue-Fox-88") == 0 && m.note_dirty == 2); + CHECK(says(ck_allen_answer(&m, "save the garage codes are 9012", 1), "Saved. It links to 1 other note.")); + CHECK(says(ck_allen_answer(&m, "What's the gate code?", 1), "From your notes: the gate code is 4471.")); + CHECK(m.lit == 1 && m.map_changed == 1); + CHECK(says(ck_allen_answer(&m, "what is the wifi password", 1), + "From your notes: the wifi password is Blue-Fox-88.")); + CHECK(says(ck_allen_answer(&m, "find code", 1), + "From your notes: the garage codes are 9012. I have 1 more on that.")); + CHECK(says(ck_allen_answer(&m, "find the electrician", 1), "I have nothing saved about the electrician.")); + m.changed = m.note_dirty = 0; + CHECK(says(ck_allen_answer(&m, "save the gate code is 4471.", 1), "I already have that saved.")); + CHECK(ns.n == 3 && m.changed == 0 && m.note_dirty == 0); + CHECK(says(ck_allen_answer(&m, "how many notes", 1), "You have 3 notes. The newest: the garage codes are 9012.")); + CHECK(says(ck_allen_answer(&m, "show me my notes", 1), "You have 3 notes.")); + CHECK(says(ck_allen_answer(&m, "save", 1), "Tell me what to save")); + CHECK(says(ck_allen_answer(&m, "help", 1), "keep notes")); + CHECK(says(ck_allen_answer(&m, "delete the note about the garage", 1), + "Deleted the note: the garage codes are 9012.")); + CHECK(ns.note[2].gone && m.note_dirty == 3 && ns.n == 3); + CHECK(strstr(ck_allen_answer(&m, "what's the garage code", 1), "From your notes") == NULL); + CHECK(says(ck_allen_answer(&m, "delete the note about the boat", 1), "I have no note about the boat.")); + /* taught facts still answer their own questions; machine questions too */ + CHECK(says(ck_allen_answer(&m, "remember my car is red", 1), "Got it: your car is red.")); + CHECK(says(ck_allen_answer(&m, "what is my car", 1), "Your car is red.")); + CHECK(says(ck_allen_answer(&m, "what is your name", 1), "Allen")); + CHECK(ck_allen_notes_live(&ns) == 2 && ck_allen_note_degree(&ns, 0) == 0); + + /* on disk: three notes, a reload, a damaged unit, a cut write */ + disk_file f; + disk_dev d; + uint32_t damaged = 9; + CHECK(disk_file_open(&f, &d, g_path, 512, (CK_ALLEN_DISK_UNITS + 2) * 8, 1) == 0); + for (uint32_t i = 0; i < ns.n; i++) + CHECK(ck_allen_note_write(&d, &ns, i) == CK_ALLEN_MEM_OK); + CHECK(ck_allen_notes_load(&d, 3, &back, &damaged) == CK_ALLEN_MEM_OK && damaged == 0 && back.n == 3); + CHECK(strcmp(back.note[1].text, ns.note[1].text) == 0 && back.note[2].gone == 1 && back.note[0].gone == 0); + CHECK(back.note[0].nword == ns.note[0].nword && back.note[0].word[0] == ns.note[0].word[0]); + /* a cut while writing note 3 leaves the three saved notes as they were */ + CHECK(ck_allen_note_set(&ns.note[3], "the boat is in slip 12", 1) == 0); + disk_file_arm_cut(&f, 3); + CHECK(ck_allen_note_write(&d, &ns, 3) != CK_ALLEN_MEM_OK); + disk_file_disarm(&f); + CHECK(ck_allen_notes_load(&d, 3, &back, &damaged) == CK_ALLEN_MEM_OK && damaged == 0); + /* one spoiled byte: that note loads as gone and is counted */ + disk_file_close(&f); + FILE *fp = fopen(g_path, "r+b"); + CHECK(fp && fseek(fp, (long)((CK_ALLEN_NOTES_FIRST + 1) * 4096 + 70), SEEK_SET) == 0 && fputc('X', fp) != EOF); + if (fp) + fclose(fp); + CHECK(disk_file_open(&f, &d, g_path, 512, 0, 0) == 0); + CHECK(ck_allen_notes_load(&d, 3, &back, &damaged) == CK_ALLEN_MEM_OK && damaged == 1 && back.note[1].gone); + CHECK(ck_allen_notes_load(&d, CK_ALLEN_NOTES_MAX + 1, &back, &damaged) == CK_ALLEN_MEM_EGEOM); + disk_file_close(&f); + /* a unit is valid only in its own slot, and only printable text */ + ck_allen_note_encode(&ns.note[0], 0, u); + CHECK(ck_allen_note_decode(u, 0, &back.note[0]) == 0 && ck_allen_note_decode(u, 1, &back.note[0]) != 0); + u[64] = 0x07; + CHECK(ck_allen_note_decode(u, 0, &back.note[0]) != 0); + CHECK(ck_allen_note_set(&back.note[0], "bad \x01 byte", 1) != 0 && ck_allen_note_set(&back.note[0], " ", 1) != 0); + + /* the note count travels in the memory copies; a restart says so */ + uint64_t gen = 0; + m.mem.starts = 1; + ck_allen_mem_encode(&m.mem, 7, u); + ck_allen_mind_init(&m2, 0); + CHECK(ck_allen_mem_decode(u, &m2.mem, &gen) == 0 && m2.mem.nnotes == 3); + m2.notes = &ns; + ns.n = 3; + CHECK(says(ck_allen_welcome(&m2), "Welcome back. I still remember 1 thing you taught me, and your 2 notes.")); + m2.mem.nfacts = 0; + CHECK(says(ck_allen_welcome(&m2), "Welcome back. I still have your 2 notes.")); + m.mem.nnotes = CK_ALLEN_NOTES_MAX + 1; + ck_allen_mem_encode(&m.mem, 8, u); + CHECK(ck_allen_mem_decode(u, &m2.mem, &gen) != 0); + /* a full notebook says so */ + ck_allen_mind_init(&m, 0); + memset(&ns, 0, sizeof ns); + m.notes = &ns; + ns.n = CK_ALLEN_NOTES_MAX; + CHECK(says(ck_allen_answer(&m, "save one more thing", 1), "My notebook is full.")); + /* without a disk, notes last until power off and Allen says so */ + ns.n = 0; + CHECK(says(ck_allen_answer(&m, "save the dentist is on friday", 1), "Only until this computer turns off")); +} + +int main(int argc, char **argv) +{ + snprintf(g_path, sizeof g_path, "%s/disk.img", argc > 1 ? argv[1] : "."); + test_codec(); + test_store(); + test_gpt_add(512); + test_gpt_add(4096); + test_teach_restart(); + test_notes(); + printf("allen memory: %d checks, %d failures\n", checks, failures); + return failures ? 1 : 0; +} diff --git a/native/kernel/svc/tests/stage_test.c b/native/kernel/svc/tests/stage_test.c index bee78a22..292f8feb 100644 --- a/native/kernel/svc/tests/stage_test.c +++ b/native/kernel/svc/tests/stage_test.c @@ -1939,7 +1939,23 @@ static void test_usb_hid(void) CHECK(ck_hid_usage(0x04, 0).kind == CK_KEY_CHAR && ck_hid_usage(0x04, 0).c == 'a'); CHECK(ck_hid_usage(0x1d, 1).c == 'Z'); CHECK(ck_hid_usage(0x1e, 0).c == '1' && ck_hid_usage(0x27, 0).c == '0'); - CHECK(ck_hid_usage(0x1e, 1).kind == CK_KEY_NONE); /* shifted digit: not in the keymap */ + CHECK(ck_hid_usage(0x1e, 1).c == '!' && ck_hid_usage(0x27, 1).c == ')' && ck_hid_usage(0x1f, 1).c == '@'); + CHECK(ck_hid_usage(0x38, 1).kind == CK_KEY_CHAR && ck_hid_usage(0x38, 1).c == '?'); /* the question mark */ + CHECK(ck_hid_usage(0x38, 0).c == '/' && ck_hid_usage(0x37, 0).c == '.' && ck_hid_usage(0x37, 1).c == '>'); + CHECK(ck_hid_usage(0x34, 0).c == '\'' && ck_hid_usage(0x34, 1).c == '"' && ck_hid_usage(0x31, 0).c == '\\'); + CHECK(ck_hid_usage(0x2d, 1).c == '_' && ck_hid_usage(0x33, 1).c == ':' && ck_hid_usage(0x35, 1).c == '~'); + CHECK(ck_hid_usage(0x32, 0).kind == CK_KEY_NONE && ck_hid_usage(0x2b, 0).kind == CK_KEY_NONE); /* non-US, Tab */ + { + int all = 1; /* every printable character but space comes from exactly one key */ + for (int ch = 0x21; ch <= 0x7e; ch++) { + int n = 0; + for (int u = 0x04; u <= 0x38; u++) + for (int s = 0; s < 2; s++) + n += ck_hid_usage((uint8_t)u, s).kind == CK_KEY_CHAR && ck_hid_usage((uint8_t)u, s).c == ch; + all &= n == 1; + } + CHECK(all); + } CHECK(ck_hid_usage(0x28, 0).kind == CK_KEY_ENTER && ck_hid_usage(0x2a, 0).kind == CK_KEY_BACKSPACE); CHECK(ck_hid_usage(0x29, 0).kind == CK_KEY_ESCAPE && ck_hid_usage(0x2c, 0).c == ' '); CHECK(ck_hid_usage(0x3a, 0).kind == CK_KEY_NONE); /* F1 */ diff --git a/native/kernel/tests/.crumb b/native/kernel/tests/.crumb index fbe93953..52255023 100644 --- a/native/kernel/tests/.crumb +++ b/native/kernel/tests/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-17T01:49:45Z", + "compiled_at": "2026-10-18T03:12:05Z", "compiler": "crumb-compile/1", - "digest": "sha256:0f3d28a645346382567a7a279a3e02a095c8e7f298967db175944c0a58ca9c5d", + "digest": "sha256:3897aca9c8eeaa11c18f07ca90a4831041213be12a49c209378787705064351b", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 189, - "generated_at_commit": "30379678add587e388db4e11713d6bca8d159b08", - "source_tree": "sha256:78682dfae8385bcec29c757bca316fadddcefbfc3c85a3f021a1aa8b948c623a" + "generated_at_commit": "9329896a390876ec99cff3405532effe8af4c166", + "source_tree": "sha256:3772dc655078cc71e2164ba5fafebc1833bba968fe519f2d9b4d7469c33f236e" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/tests/test_imac_report.c b/native/kernel/tests/test_imac_report.c index 27cc6473..aa77698f 100644 --- a/native/kernel/tests/test_imac_report.c +++ b/native/kernel/tests/test_imac_report.c @@ -1,12 +1,16 @@ -/* test_imac_report.c -- host test for the iMac kernel's network report - * frames (x86/report_x86.c, built with -DCK_X86_REPORT_HOST). +/* test_imac_report.c -- host test for the iMac kernel's lab-only network + * report (x86/report_x86.c, built with -DCK_X86_REPORT_HOST): the allowlist + * filter and the frames. * - * test_imac_report unit checks on the frames + * test_imac_report unit checks on the filter and frames * test_imac_report send PORT LOGFILE also writes a sample report to * LOGFILE and sends every part's UDP payload to 127.0.0.1:PORT (last * part first, then all again), so scripts/ck_imac_report_test.sh can - * check that ck_imac_report_listen rebuilds LOGFILE byte for byte. */ + * check that ck_imac_report_listen rebuilds LOGFILE byte for byte. + * test_imac_report legacy PORT sends one datagram in the retired + * v=1 raw-console format, which the listener must refuse. */ #define _POSIX_C_SOURCE 200809L +#define _GNU_SOURCE /* memmem */ #include #include #include @@ -21,8 +25,121 @@ #include "report_x86.h" static const uint8_t mac[6] = {0x02, 0x00, 0x00, 0x00, 0x00, 0x01}; -static char log_text[3 * CK_X86_REPORT_CHUNK + 300]; +/* 56 lines of 61 bytes, each an allowlisted "pci: " line: 4 parts. */ +static char log_text[56 * 61]; +/* A console log mixing allowlisted lines with lines that must never leave + * the machine: keys off the allowlist (chat, keys, tokens, the memory + * layout), near-miss keys, control and non-ASCII bytes inside an allowed + * key, an over-long line, and an unterminated tail. */ +static const char allowed_part[] = + "AIENOS-KERNEL-0\n" + "aienos_commit: 0123abcd\n" + "pci: ahci 00:1f.2 id=8086:2922 class=0106\n" + "net_tg3: link up 1000 Mb/s full duplex\n" + "summary: cores=4/4 timer=ok sata_disks=1 nvme_disks=1 gpt_valid=1 writes=none net=up\n" + "screen: Allen answered (11 characters in, 15 out)\n" + "allen_memory: saved generation 2 to copy B (1 fact) in 9 ms\n" + "ahci_part: disk=0 entry=1 type=38daac89-5ead-4b40-8b1e-3687a7418061 first_lba=2048 last_lba=2099199 mib=1024 name=\"AIENOS Allen memory\" (AIENOS)\n" + "kernel: alive\n" + "panic: exception: vector 14 #PF error=0x2\n" + "AIENOS-KERNEL-0 DONE\n"; + +static size_t build_mixed(char *out, size_t cap) +{ + static const char *const lines[] = { + "AIENOS-KERNEL-0\n", + "allen: secret-chat-SENTINEL\n", + "aienos_commit: 0123abcd\n", + "key: SENTINEL-KEY\n", + "memory: frame_ranges=3 free_bytes=1 heap=0x1000+64 SENTINEL-MEM\n", + "pci: ahci 00:1f.2 id=8086:2922 class=0106\n", + "token: SENTINEL-TOKEN\n", + "credential: SENTINEL-CRED\n", + "chat: user said SENTINEL-CHAT\n", + "nett: SENTINEL-NEAR\n", + "net SENTINEL-NOCOLON\n", + " pci: SENTINEL-LEADING-SPACE\n", + "PCI: SENTINEL-CASE\n", + "net: ok \x1b[2J SENTINEL-ESC\n", + "summary: \tSENTINEL-TAB\n", + "report: caf\xc3\xa9 SENTINEL-UTF8\n", + "power: \r SENTINEL-CR\n", + "net_tg3: link up 1000 Mb/s full duplex\n", + "summary: cores=4/4 timer=ok sata_disks=1 nvme_disks=1 gpt_valid=1 writes=none net=up\n", + "keyboard_line: Hello SENTINEL-TYPED\n", + "screen: Allen answered (11 characters in, 15 out)\n", + "allen: Your favorite color is SENTINEL-FACT.\n", + "allen_memory: saved generation 2 to copy B (1 fact) in 9 ms\n", + "allen_memoryx: SENTINEL-NEAR2\n", + "ahci_part: disk=0 entry=1 type=38daac89-5ead-4b40-8b1e-3687a7418061 first_lba=2048 last_lba=2099199 mib=1024 name=\"AIENOS Allen memory\" (AIENOS)\n", + "\n", + "kernel: alive\n", + "panic: exception: vector 14 #PF error=0x2\n", + "AIENOS-KERNEL-0 DONE\n", + }; + size_t w = 0; + for (size_t i = 0; i < sizeof lines / sizeof lines[0]; i++) { + size_t n = strlen(lines[i]); + if (w + n > cap) + return 0; + memcpy(out + w, lines[i], n); + w += n; + if (i == 3) { /* an over-long but otherwise allowed line */ + const char *p = "stack: "; + memcpy(out + w, p, 7); + w += 7; + for (unsigned k = 0; k < CK_X86_REPORT_LINE_MAX; k++) + out[w++] = 'x'; + memcpy(out + w, "SENTINEL-LONG\n", 14); + w += 14; + } + } + static const char tail[] = "screen: SENTINEL-TAIL"; /* no newline */ + memcpy(out + w, tail, sizeof tail - 1); + return w + sizeof tail - 1; +} + +static void filter_checks(void) +{ + static char raw[4096], out[4096]; + size_t rl = build_mixed(raw, sizeof raw); + CHECK(rl > 0); + CHECK(memmem(raw, rl, "SENTINEL", 8) != 0); + size_t n = ck_x86_report_filter(raw, rl, out, sizeof out); + /* The allowed lines survive byte for byte, in order; nothing else does. */ + CHECK(n == sizeof allowed_part - 1 && memcmp(out, allowed_part, n) == 0); + CHECK(memmem(out, n, "SENTINEL", 8) == 0); + for (size_t i = 0; i < n; i++) + CHECK(out[i] == '\n' || (out[i] >= 0x20 && out[i] <= 0x7e)); + /* Nor does any sentinel reach a frame built from the filtered copy. */ + uint8_t f[1600]; + for (unsigned p = 0; p < ck_x86_report_parts(n); p++) { + size_t fl = ck_x86_report_frame(mac, 1, out, n, p, f, sizeof f); + CHECK(fl > 0 && memmem(f, fl, "SENTINEL", 8) == 0); + } + /* A line at the length cap is kept, one byte more is dropped. */ + char edge[2 * CK_X86_REPORT_LINE_MAX + 8], eo[sizeof edge]; + size_t e = 0; + memcpy(edge, "cpu: ", 5); + for (e = 5; e < CK_X86_REPORT_LINE_MAX; e++) + edge[e] = 'a'; + edge[e++] = '\n'; + size_t keep = e; + memcpy(edge + e, "cpu: ", 5); + for (size_t k = 5; k <= CK_X86_REPORT_LINE_MAX; k++) + edge[e + k] = 'b'; + e += CK_X86_REPORT_LINE_MAX + 1; + edge[e++] = '\n'; + CHECK(ck_x86_report_filter(edge, e, eo, sizeof eo) == keep && memcmp(eo, edge, keep) == 0); + /* Only whole lines are written: a line that does not fit is dropped. */ + size_t first = strlen("AIENOS-KERNEL-0\n"); + CHECK(ck_x86_report_filter(raw, rl, out, first + 5) == first && memcmp(out, raw, first) == 0); + CHECK(ck_x86_report_filter(raw, rl, out, first - 1) == 14 && memcmp(out, "kernel: alive\n", 14) == 0); + CHECK(ck_x86_report_filter(0, rl, out, sizeof out) == 0); + CHECK(ck_x86_report_filter(raw, rl, 0, sizeof out) == 0); + CHECK(ck_x86_report_filter(raw, 0, out, sizeof out) == 0); +} /* Unwraps one frame; returns the UDP payload view or 0. */ static const uint8_t *unwrap(const uint8_t *f, size_t n, size_t *plen) { @@ -50,7 +167,7 @@ static const uint8_t *unwrap(const uint8_t *f, size_t n, size_t *plen) int main(int argc, char **argv) { for (size_t i = 0; i < sizeof log_text; i++) - log_text[i] = (i % 61 == 60) ? '\n' : (char)('A' + i % 26); + log_text[i] = (i % 61 == 60) ? '\n' : i % 61 < 5 ? "pci: "[i % 61] : (char)('A' + i % 26); size_t len = sizeof log_text; uint64_t run = 0x0123456789abcdefull; uint8_t f[1600]; @@ -63,6 +180,11 @@ int main(int argc, char **argv) CHECK(ck_x86_report_parts(CK_X86_REPORT_MAX) == CK_X86_REPORT_MAX / CK_X86_REPORT_CHUNK); CHECK(ck_x86_report_parts(CK_X86_REPORT_MAX + 1) == 0); CHECK(parts == 4); + filter_checks(); + /* The sample report is what the filter makes of itself: every line is kept. */ + static char filtered[sizeof log_text]; + CHECK(ck_x86_report_filter(log_text, len, filtered, sizeof filtered) == len && + memcmp(filtered, log_text, len) == 0); CHECK(ck_x86_report_frame(mac, run, log_text, len, parts, f, sizeof f) == 0); CHECK(ck_x86_report_frame(mac, run, log_text, len, 0, f, 100) == 0); CHECK(ck_x86_report_frame(0, run, log_text, len, 0, f, sizeof f) == 0); @@ -78,7 +200,8 @@ int main(int argc, char **argv) if (!d) continue; char want[128]; - int h = snprintf(want, sizeof want, "AIENOS-IMAC-REPORT v=1 run=0123456789abcdef part=%u/%u bytes=%zu\n", p, + int h = snprintf(want, sizeof want, "AIENOS-REPORT v=2 auth=none run=0123456789abcdef part=%u/%u bytes=%zu\n", + p, parts, len); CHECK(pl > (size_t)h && memcmp(d, want, (size_t)h) == 0); if (pl > (size_t)h && got + pl - h <= sizeof rebuilt) { @@ -109,5 +232,16 @@ int main(int argc, char **argv) } close(s); } + if (argc == 3 && !strcmp(argv[1], "legacy")) { /* a forged or old v=1 raw-console part */ + static const char old[] = "AIENOS-IMAC-REPORT v=1 run=00000000000000ff part=0/1 bytes=5\nhello"; + int s = socket(AF_INET, SOCK_DGRAM, 0); + struct sockaddr_in a; + memset(&a, 0, sizeof a); + a.sin_family = AF_INET; + a.sin_port = htons((unsigned short)atoi(argv[2])); + a.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + CHECK(s >= 0 && sendto(s, old, sizeof old - 1, 0, (struct sockaddr *)&a, sizeof a) == (ssize_t)(sizeof old - 1)); + close(s); + } return ck_t_verdict("test_imac_report"); } diff --git a/native/kernel/tools/.crumb b/native/kernel/tools/.crumb index 434135ec..b4b0e3d2 100644 --- a/native/kernel/tools/.crumb +++ b/native/kernel/tools/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-17T01:49:45Z", + "compiled_at": "2026-10-18T12:23:39Z", "compiler": "crumb-compile/1", - "digest": "sha256:412f0a290f187935193ec94f1817c46dbe0edc07a5eb427e39977b65c1d00f9f", + "digest": "sha256:5eb33301e44ab4e5e4459aae9086102f41774e3809855028f9b9211e3edff7a3", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 24, - "generated_at_commit": "30379678add587e388db4e11713d6bca8d159b08", - "source_tree": "sha256:811d4174e2479ef3a1cf5ed3f0ae69346da056fc12745e9f1b33afbe0b6f6dc5" + "files": 28, + "generated_at_commit": "105544890f780085f64bee754d4a92c1a2f17ecf", + "source_tree": "sha256:09296351c7d9ab0d2335c8d789f9a8bb3c4866a698deac3298edb494471822c6" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/tools/ck_gpt_image.c b/native/kernel/tools/ck_gpt_image.c index 795b654d..3c3c3152 100644 --- a/native/kernel/tools/ck_gpt_image.c +++ b/native/kernel/tools/ck_gpt_image.c @@ -11,6 +11,8 @@ * two-aienos same, sentinel-b also has the AIENOS type * aienos-outside sentinel-a, AIENOS [9, M+1): ends past the disk * aienos-overlap sentinel-a [1,9), AIENOS [5,M-7), sentinel-b + * one-old sentinel-a only; the rest unused (Allen memory gate) + * one-whole one empty Linux partition [1, M-1): no unused gap * no-gpt sentinel fills only: no protective MBR, no GPT * esp-model ESP_MIB MODEL_FILE ESP + model in 3 out-of-order * extents (see esp_model below; model ingest gate) @@ -195,13 +197,18 @@ static int cmd_create(int argc, char **argv) n = 2; } else if (!strcmp(lay, "aienos-overlap")) { p[1].first = 5 * per; + } else if (!strcmp(lay, "one-old")) { + n = 1; /* sentinel-a only: the rest of the disk unused */ + } else if (!strcmp(lay, "one-whole")) { + p[0] = (gw_part){gw_linux_type, 1 * per, (mib - 1u) * per - 1u, "whole", 0}; + n = 1; } else if (!strcmp(lay, "no-gpt")) { flags |= GW_NO_GPT; } else { return usage(); } if (gw_write(argv[2], bs, blocks, p, n, flags)) return 1; - int has = strcmp(lay, "no-aienos") != 0; + int has = strcmp(lay, "no-aienos") && strcmp(lay, "one-old") && strcmp(lay, "one-whole"); printf("gpt_image bs=%u blocks=%llu aienos_first_lba=%llu aienos_last_lba=%llu\n", bs, (unsigned long long)blocks, has ? (unsigned long long)p[1].first : 0ull, has ? (unsigned long long)p[1].last : 0ull); diff --git a/native/kernel/tools/ck_imac_bsdp.c b/native/kernel/tools/ck_imac_bsdp.c new file mode 100644 index 00000000..0850b02d --- /dev/null +++ b/native/kernel/tools/ck_imac_bsdp.c @@ -0,0 +1,449 @@ +/* ck_imac_bsdp.c -- LAB-ONLY Apple NetBoot answerer for the 2017 iMac: lets the iMac start + * NETLDR.EFI (native/boot/net_loader.c) straight from the Spark, with no stick, when it is + * powered on with the N key held. Hosted C (POSIX sockets), tooling only. No Python. + * + * Two small servers in one process: + * BSDP (UDP 67) Apple's Boot Service Discovery Protocol: DHCP INFORM packets with vendor + * class "AAPLBSDPC/..." and BSDP sub-options in option 43. INFORM[LIST] is + * answered with one image (AIENOS, the default); INFORM[SELECT] naming that + * image and this server is answered with the boot file name and this + * server's address (siaddr). Nothing else is answered: never DISCOVER or + * REQUEST (the router stays the DHCP server), never another vendor class. + * TFTP (UDP 69) read-only, one file: RRQ for BOOT_NAME (octet mode) gets the booter; the + * blksize and tsize options (RFC 2348/2349) are honoured. Every other request + * gets an error. Nothing is ever written. + * Wire reference: Apple bootp project (bsdp.h, bootpd) as traced in "Analysis of the Use of + * the Boot Server Discovery Protocol in NetBoot" (afp548): option 43 sub-options + * 1 message type (1 LIST, 2 SELECT, 3 FAILED), 3 server id, 4 priority, 5 reply port, + * 7 default image, 8 selected image, 9 image list (id[4] len[1] name), 130 machine name. + * Answers are DHCP ACKs (also carrying subnet mask and router) + * with option 60 "AAPLBSDPC" sent to the client's ciaddr, port 68 or its reply port. + * + * UNAUTHENTICATED: the iMac firmware runs whatever booter it is handed. Anyone on the LAN can + * answer first. What makes this safe enough for the lab is the booter: NETLDR.EFI starts only + * kernels signed with the lab key. A forged booter is not prevented here. + * + * ck_imac_bsdp serve --booter FILE --server-ip A.B.C.D [--mac XX:..] [--bsdp-port N] + * [--tftp-port N] [--seconds N] + * --mac answers only that client. Ports 67/69 need CAP_NET_BIND_SERVICE (setcap) or root. + * Log lines go to stdout with a UTC timestamp. Exit 0 at the deadline, 2 usage, 3 socket. */ +#define _DEFAULT_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define BOOT_NAME "aienos/netldr.efi" +#define IMAGE_NAME "AIENOS" +/* Image id: install image (bit 31: the firmware fetches the booter and runs it, no network + * disk), kind 1 (Mac OS X class) in bits 24..30, index 1 (< 4096: local to this server). + * The working ISC/FOG Intel Mac configs all use the install bit. */ +#define IMAGE_ID 0x81000001u +#define DHCP_MAGIC 0x63825363u +#define BOOTP_MIN 240 +#define BLK_MAX 1428 + +static uint8_t *booter; +static size_t booter_len; +static struct in_addr server_ip, netmask, router; +static int also_bcast; +static uint8_t only_mac[6]; +static int have_mac; + +static void logf_(const char *fmt, ...) +{ + char ts[32]; + time_t t = time(0); + struct tm tm; + strftime(ts, sizeof ts, "%Y-%m-%dT%H:%M:%SZ", gmtime_r(&t, &tm)); + va_list ap; + va_start(ap, fmt); + printf("%s ", ts); + vprintf(fmt, ap); + printf("\n"); + fflush(stdout); + va_end(ap); +} + +static int bind_udp(uint16_t port, int bcast) +{ + int one = 1, s = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0); + struct sockaddr_in a = {.sin_family = AF_INET, .sin_port = htons(port), .sin_addr.s_addr = htonl(INADDR_ANY)}; + if (s < 0 || setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one) != 0 || + (bcast && setsockopt(s, SOL_SOCKET, SO_BROADCAST, &one, sizeof one) != 0) || + bind(s, (struct sockaddr *)&a, sizeof a) != 0) { + fprintf(stderr, "ck_imac_bsdp: bind UDP %u: %s\n", port, strerror(errno)); + return -1; + } + return s; +} + +/* ---- BSDP ---- */ + +/* Find DHCP option code in opts[0..n); returns its value and length, or 0. */ +static const uint8_t *opt_find(const uint8_t *o, size_t n, uint8_t code, uint8_t *len) +{ + size_t i = 0; + while (i < n) { + uint8_t c = o[i]; + if (c == 255) + break; + if (c == 0) { + i++; + continue; + } + if (i + 2 > n || i + 2 + o[i + 1] > n) + break; + if (c == code) { + *len = o[i + 1]; + return o + i + 2; + } + i += 2 + (size_t)o[i + 1]; + } + return 0; +} + +static size_t opt_put(uint8_t *p, size_t at, size_t cap, uint8_t code, const void *v, uint8_t len) +{ + if (at + 2u + len > cap) + return cap + 1; + p[at] = code; + p[at + 1] = len; + memcpy(p + at + 2, v, len); + return at + 2u + len; +} + +static void put32(uint8_t *p, uint32_t v) +{ + p[0] = (uint8_t)(v >> 24); + p[1] = (uint8_t)(v >> 16); + p[2] = (uint8_t)(v >> 8); + p[3] = (uint8_t)v; +} + +static uint32_t get32(const uint8_t *p) +{ + return (uint32_t)p[0] << 24 | (uint32_t)p[1] << 16 | (uint32_t)p[2] << 8 | p[3]; +} + +static void bsdp_packet(int s, const uint8_t *in, size_t n) +{ + if (n < BOOTP_MIN || in[0] != 1 || in[1] != 1 || in[2] != 6 || get32(in + 236) != DHCP_MAGIC) + return; + const uint8_t *opts = in + BOOTP_MIN, *v; + size_t on = n - BOOTP_MIN; + uint8_t l = 0; + if (!(v = opt_find(opts, on, 53, &l)) || l != 1 || v[0] != 8) /* INFORM only */ + return; + if (!(v = opt_find(opts, on, 60, &l)) || l < 10 || memcmp(v, "AAPLBSDPC/", 10) != 0) + return; + char vclass[64]; + snprintf(vclass, sizeof vclass, "%.*s", (int)l, (const char *)v); + const uint8_t *mac = in + 28; + if (have_mac && memcmp(mac, only_mac, 6) != 0) + return; + const uint8_t *vo = opt_find(opts, on, 43, &l); + uint8_t vl = l, ml = 0, sl = 0, pl = 0; + const uint8_t *mt = vo ? opt_find(vo, vl, 1, &ml) : 0; + if (!mt || ml != 1) + return; + struct in_addr ci; + memcpy(&ci.s_addr, in + 12, 4); + if (ci.s_addr == 0) + return; + uint16_t port = 68; + const uint8_t *rp = opt_find(vo, vl, 5, &pl); + if (rp && pl == 2 && ((rp[0] << 8) | rp[1]) >= 1024) + port = (uint16_t)((rp[0] << 8) | rp[1]); + + uint8_t out[576] = {0}, sub[255]; + size_t sn = 0, at = BOOTP_MIN; + out[0] = 2; + out[1] = 1; + out[2] = 6; + memcpy(out + 4, in + 4, 4); /* xid */ + memcpy(out + 12, in + 12, 4); /* ciaddr */ + memcpy(out + 20, &server_ip.s_addr, 4); + memcpy(out + 28, in + 28, 16); /* chaddr */ + put32(out + 236, DHCP_MAGIC); + uint8_t ack = 5; + at = opt_put(out, at, sizeof out, 53, &ack, 1); + at = opt_put(out, at, sizeof out, 54, &server_ip.s_addr, 4); + at = opt_put(out, at, sizeof out, 60, "AAPLBSDPC", 9); + /* Subnet mask and router, as the ISC config known to boot Intel Macs forces into the + * answer (its parameter list 1,3,17,43,60); the iMac only asked for 43 and 60. */ + at = opt_put(out, at, sizeof out, 1, &netmask.s_addr, 4); + if (router.s_addr) + at = opt_put(out, at, sizeof out, 3, &router.s_addr, 4); + if (mt[0] == 1) { /* LIST */ + uint8_t id[4]; + put32(id, IMAGE_ID); + sub[sn++] = 1, sub[sn++] = 1, sub[sn++] = 1; + sub[sn++] = 4, sub[sn++] = 2, sub[sn++] = 0x80, sub[sn++] = 0x00; + sub[sn++] = 7, sub[sn++] = 4, memcpy(sub + sn, id, 4), sn += 4; + sub[sn++] = 9, sub[sn++] = (uint8_t)(5 + strlen(IMAGE_NAME)); + memcpy(sub + sn, id, 4), sn += 4; + sub[sn++] = (uint8_t)strlen(IMAGE_NAME); + memcpy(sub + sn, IMAGE_NAME, strlen(IMAGE_NAME)), sn += strlen(IMAGE_NAME); + logf_("LIST from %s %02x:%02x:%02x:%02x:%02x:%02x (%s): offered image %s", inet_ntoa(ci), mac[0], mac[1], + mac[2], mac[3], mac[4], mac[5], vclass, IMAGE_NAME); + } else if (mt[0] == 2) { /* SELECT */ + const uint8_t *sel = opt_find(vo, vl, 8, &sl), *sid; + uint8_t il = 0; + if (!sel || sl != 4 || get32(sel) != IMAGE_ID) + return; + if ((sid = opt_find(vo, vl, 3, &il)) && (il != 4 || memcmp(sid, &server_ip.s_addr, 4) != 0)) + return; /* the client chose another server */ + sub[sn++] = 1, sub[sn++] = 1, sub[sn++] = 2; + sub[sn++] = 8, sub[sn++] = 4, memcpy(sub + sn, sel, 4), sn += 4; + sub[sn++] = 130, sub[sn++] = 6, memcpy(sub + sn, "AIENOS", 6), sn += 6; /* machine name */ + snprintf((char *)out + 44, 64, "spark"); + snprintf((char *)out + 108, 128, "%s", BOOT_NAME); + char root[64]; + snprintf(root, sizeof root, "tftp:%s:/aienos/none", inet_ntoa(server_ip)); + at = opt_put(out, at, sizeof out, 17, root, (uint8_t)strlen(root)); + logf_("SELECT from %s %02x:%02x:%02x:%02x:%02x:%02x: boot file %s from %s", inet_ntoa(ci), mac[0], mac[1], + mac[2], mac[3], mac[4], mac[5], BOOT_NAME, inet_ntoa(server_ip)); + } else { + logf_("BSDP message type %u from %s ignored", mt[0], inet_ntoa(ci)); + return; + } + at = opt_put(out, at, sizeof out, 43, sub, (uint8_t)sn); + if (at + 1 > sizeof out) + return; + out[at++] = 255; + struct sockaddr_in to = {.sin_family = AF_INET, .sin_port = htons(port), .sin_addr = ci}; + if (sendto(s, out, at < 300 ? 300 : at, 0, (struct sockaddr *)&to, sizeof to) < 0) + logf_("BSDP send to %s failed: %s", inet_ntoa(ci), strerror(errno)); + /* --also-broadcast: a second copy to everyone on the segment, for firmware that does not + * take the unicast; other DHCP clients drop it (chaddr is the iMac's). */ + to.sin_addr.s_addr = htonl(INADDR_BROADCAST); + if (also_bcast && sendto(s, out, at < 300 ? 300 : at, 0, (struct sockaddr *)&to, sizeof to) < 0) + logf_("BSDP broadcast copy failed: %s", strerror(errno)); +} + +/* ---- TFTP (read-only, one file) ---- */ + +static void tftp_error(int s, const struct sockaddr_in *to, uint16_t code, const char *msg) +{ + uint8_t b[128]; + size_t n = 4 + strlen(msg) + 1; + b[0] = 0, b[1] = 5, b[2] = (uint8_t)(code >> 8), b[3] = (uint8_t)code; + memcpy(b + 4, msg, strlen(msg) + 1); + sendto(s, b, n, 0, (const struct sockaddr *)to, sizeof *to); +} + +/* Send b[0..n) and wait for ACK of block; 0 acked, -1 gave up. */ +static int tftp_xfer(int s, const struct sockaddr_in *peer, const uint8_t *b, size_t n, uint16_t block) +{ + uint8_t r[516]; + for (int tries = 0; tries < 6; tries++) { + if (send(s, b, n, 0) < 0) + return -1; + struct pollfd p = {s, POLLIN, 0}; + while (poll(&p, 1, 1000) > 0) { + struct sockaddr_in from; + socklen_t fl = sizeof from; + ssize_t k = recvfrom(s, r, sizeof r, 0, (struct sockaddr *)&from, &fl); + if (k < 4 || from.sin_addr.s_addr != peer->sin_addr.s_addr || from.sin_port != peer->sin_port) + continue; + if (r[1] == 5) + return -1; + if (r[1] == 4 && ((r[2] << 8) | r[3]) == block) + return 0; + } + } + return -1; +} + +/* Appends "name" NUL "val" NUL to the option acknowledgement at `at` when it + * fits in cap bytes; returns the new length (unchanged when it does not). */ +static size_t oack_put(uint8_t *buf, size_t cap, size_t at, const char *name, const char *val) +{ + size_t a = strlen(name) + 1, b = strlen(val) + 1; + if (at > cap || a + b > cap - at) + return at; + memcpy(buf + at, name, a); + memcpy(buf + at + a, val, b); + return at + a + b; +} + +static void tftp_request(const uint8_t *in, size_t n, const struct sockaddr_in *peer) +{ + int s = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0); + struct sockaddr_in me = {.sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_ANY)}; + if (s < 0 || bind(s, (struct sockaddr *)&me, sizeof me) != 0 || + connect(s, (const struct sockaddr *)peer, sizeof *peer) != 0) { + if (s >= 0) + close(s); + return; + } + char ip[INET_ADDRSTRLEN]; + inet_ntop(AF_INET, &peer->sin_addr, ip, sizeof ip); + /* RRQ: 0 1 filename 0 mode 0 [option 0 value 0]... */ + const char *f = (const char *)in + 2, *end = (const char *)in + n; + const char *mode = memchr(f, 0, (size_t)(end - f)) ? f + strlen(f) + 1 : 0; + if (in[1] != 1 || !mode || mode >= end || !memchr(mode, 0, (size_t)(end - mode))) { + tftp_error(s, peer, 4, "read requests only"); + close(s); + return; + } + while (*f == '/') + f++; + if (strcmp(f, BOOT_NAME) != 0 || strcasecmp(mode, "octet") != 0) { + logf_("TFTP %s asked for \"%s\" (%s): refused", ip, f, mode); + tftp_error(s, peer, 1, "file not found"); + close(s); + return; + } + size_t blk = 512; + uint8_t oack[128]; + size_t on = 2; + oack[0] = 0, oack[1] = 6; + for (const char *o = mode + strlen(mode) + 1; o < end && memchr(o, 0, (size_t)(end - o));) { + const char *val = o + strlen(o) + 1; + if (val >= end || !memchr(val, 0, (size_t)(end - val))) + break; + char num[24]; + if (strcasecmp(o, "blksize") == 0) { + long b = strtol(val, 0, 10); + if (b >= 8) { + blk = (size_t)(b > BLK_MAX ? BLK_MAX : b); + snprintf(num, sizeof num, "%zu", blk); + on = oack_put(oack, sizeof oack, on, "blksize", num); + } + } else if (strcasecmp(o, "tsize") == 0) { + snprintf(num, sizeof num, "%zu", booter_len); + on = oack_put(oack, sizeof oack, on, "tsize", num); + } + o = val + strlen(val) + 1; + } + logf_("TFTP %s: sending %s (%zu bytes, block %zu)", ip, BOOT_NAME, booter_len, blk); + if (on > 2 && tftp_xfer(s, peer, oack, on, 0) != 0) { + logf_("TFTP %s: no ACK for the option answer; gave up", ip); + close(s); + return; + } + static uint8_t b[4 + BLK_MAX]; + uint16_t block = 1; + for (size_t off = 0;; off += blk, block++) { + size_t k = off < booter_len ? (booter_len - off < blk ? booter_len - off : blk) : 0; + b[0] = 0, b[1] = 3, b[2] = (uint8_t)(block >> 8), b[3] = (uint8_t)block; + memcpy(b + 4, booter + off, k); + if (tftp_xfer(s, peer, b, 4 + k, block) != 0) { + logf_("TFTP %s: transfer stopped at byte %zu", ip, off); + break; + } + if (k < blk) { + logf_("TFTP %s: %s delivered", ip, BOOT_NAME); + break; + } + } + close(s); +} + +static int usage(void) +{ + fprintf(stderr, "usage: ck_imac_bsdp serve --booter FILE --server-ip A.B.C.D [--mac XX:XX:XX:XX:XX:XX]\n" + " [--netmask A.B.C.D] [--router A.B.C.D] [--also-broadcast yes|no]\n" + " [--bsdp-port N] [--tftp-port N] [--seconds N]\n"); + return 2; +} + +int main(int argc, char **argv) +{ + const char *path = 0; + long bport = 67, tport = 69, secs = 0; + netmask.s_addr = htonl(0xffffff00u); + if (argc < 2 || strcmp(argv[1], "serve") != 0) + return usage(); + for (int i = 2; i < argc; i++) { + const char *a = argv[i], *v = i + 1 < argc ? argv[i + 1] : 0; + if (!v) + return usage(); + if (strcmp(a, "--booter") == 0) + path = v; + else if (strcmp(a, "--server-ip") == 0) { + if (inet_pton(AF_INET, v, &server_ip) != 1) + return usage(); + } else if (strcmp(a, "--netmask") == 0) { + if (inet_pton(AF_INET, v, &netmask) != 1) + return usage(); + } else if (strcmp(a, "--router") == 0) { + if (inet_pton(AF_INET, v, &router) != 1) + return usage(); + } else if (strcmp(a, "--also-broadcast") == 0) { + also_bcast = strcmp(v, "yes") == 0; + } else if (strcmp(a, "--mac") == 0) { + unsigned m[6]; + if (sscanf(v, "%2x:%2x:%2x:%2x:%2x:%2x", &m[0], &m[1], &m[2], &m[3], &m[4], &m[5]) != 6) + return usage(); + for (int k = 0; k < 6; k++) + only_mac[k] = (uint8_t)m[k]; + have_mac = 1; + } else if (strcmp(a, "--bsdp-port") == 0) + bport = strtol(v, 0, 10); + else if (strcmp(a, "--tftp-port") == 0) + tport = strtol(v, 0, 10); + else if (strcmp(a, "--seconds") == 0) + secs = strtol(v, 0, 10); + else + return usage(); + i++; + } + if (!path || !server_ip.s_addr || bport < 1 || bport > 65535 || tport < 1 || tport > 65535 || secs < 0) + return usage(); + struct stat st; + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0 || fstat(fd, &st) != 0 || st.st_size < 2 || st.st_size > 16 * 1024 * 1024) { + fprintf(stderr, "ck_imac_bsdp: cannot use booter %s\n", path); + return 2; + } + booter_len = (size_t)st.st_size; + booter = malloc(booter_len); + if (!booter || read(fd, booter, booter_len) != (ssize_t)booter_len || booter[0] != 'M' || booter[1] != 'Z') { + fprintf(stderr, "ck_imac_bsdp: %s is not a readable PE image\n", path); + return 2; + } + close(fd); + int bs = bind_udp((uint16_t)bport, 1), ts = bind_udp((uint16_t)tport, 0); + if (bs < 0 || ts < 0) + return 3; + logf_("serving BSDP on %ld and TFTP on %ld as %s; booter %s (%zu bytes)%s", bport, tport, inet_ntoa(server_ip), + path, booter_len, have_mac ? "; one client only" : ""); + time_t end = secs ? time(0) + secs : 0; + uint8_t buf[1500]; + while (!end || time(0) < end) { + struct pollfd p[2] = {{bs, POLLIN, 0}, {ts, POLLIN, 0}}; + if (poll(p, 2, 500) <= 0) + continue; + struct sockaddr_in from; + socklen_t fl = sizeof from; + if (p[0].revents & POLLIN) { + ssize_t k = recvfrom(bs, buf, sizeof buf, 0, (struct sockaddr *)&from, &fl); + if (k > 0) + bsdp_packet(bs, buf, (size_t)k); + } + fl = sizeof from; + if (p[1].revents & POLLIN) { + ssize_t k = recvfrom(ts, buf, sizeof buf - 1, 0, (struct sockaddr *)&from, &fl); + if (k >= 4) { + buf[k] = 0; + tftp_request(buf, (size_t)k, &from); + } + } + } + logf_("deadline reached"); + return 0; +} diff --git a/native/kernel/tools/ck_imac_netboot.c b/native/kernel/tools/ck_imac_netboot.c new file mode 100644 index 00000000..fd206436 --- /dev/null +++ b/native/kernel/tools/ck_imac_netboot.c @@ -0,0 +1,439 @@ +/* ck_imac_netboot.c -- host side of the AIENOS lab netboot (NETLDR.EFI on the + * iMac; wire format native/boot/netboot_proto.h). Hosted C (POSIX sockets), + * tooling only, never in an image. No Python, no outside libraries: Ed25519 + * and SHA-512 are native/sig. + * + * ck_imac_netboot keygen KEY PUB new lab signing key: KEY = 32-byte seed + * (created 0600, never overwritten), PUB = + * "owner_root_ed25519 " for + * make imac-netldr CK_NETLDR_KEYS=PUB + * ck_imac_netboot pubkey KEY print the public key (64 hex) + * ck_imac_netboot sign KEY TBS SIG Ed25519 over the to-be-signed bytes + * (ck_slot_tool tbs) -> 64-byte SIG + * ck_imac_netboot serve SPOOL [--bcast A.B.C.D] [--mac M] [--seconds N] + * [--qemu-dgram LOCALPORT:REMOTEPORT] + * + * serve answers NETLDR. A job is SPOOL/next.job: a signed slot manifest + * (CK_SLOT_UNIT bytes) followed by the image; write it elsewhere and rename() + * it in. On a HELLO the job moves to SPOOL/serving.job and is offered; the + * loader's DONE moves it to SPOOL/booted-