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/e2422a9cef85ab7b # 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#223 (code only) closed derived `e2422a9cef85ab7b` #223 Imported from GitHub aien-dev/aienux#223 (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 `899ef3f84472370878c7a4da5da8547b4920d991` · Head `234acfc1f6b69c1e03036ed407945c02ad1cf8cf` ### Fetch it A git bundle of the pull request's head, 23837 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/aienux/patches/e2422a9cef85ab7b.bundle -o e2422a9cef85ab7b.bundle git fetch e2422a9cef85ab7b.bundle refs/pull/223/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 223 234acfc1f6b69c1e03036ed407945c02ad1cf8cf ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aienux","number":223,"url":"https://github.com/aien-dev/aienux/pull/223","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:35:59Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/native/kernel/GATES.md b/native/kernel/GATES.md index fc3a5c94..f82e9f95 100644 --- a/native/kernel/GATES.md +++ b/native/kernel/GATES.md @@ -120,16 +120,40 @@ per-stream page tables, `ck_dma_confine` / `ck_dma_unconfine` / ## SEED-0A keyboard: scripts/qemu_keyboard_test.sh (SMMU=1 and SMMU=0) -> CK `KEYBOARD` +C child script: `scripts/qemu_ck_keyboard_test.sh` (DMA-safety rows only; both +modes in one run, boot `kbd-smmu` with QEMU `iommu=smmuv3` and boot +`kbd-nosmmu` without; same devices as the Rust gate: `qemu-xhci` + `usb-kbd`, +plus an NVMe disk for the normal full boot). It prints one +`KEYBOARD_ROW : PASS|FAIL|NOT_RUN` line per row, then +`AIENOS_CK_KEYBOARD_DMA: PASS|FAIL (rows 25-28,31,32)` and always +`AIENOS_CK_KEYBOARD: NOT_RUN (MISSING_IMPLEMENTATION: ...)`: the gate stays +NOT_RUN until rows 29-30 exist. C code: the post-exit bus-master sweep +`pci_sweep_bus_master` (native/kernel/dev/pci.c, port of the Rust +`dma_gate::sweep_bus_master`, run at the start of the devices stage before any +device gets DMA) and the xHCI DMA fence `native/kernel/dev/xhci_fence.c` +(same SMMU gate as NVMe and virtio-net: `ck_dma_confine` window first, then +memory decode + bus master; no SMMU means no DMA, no bypass build; controller +halted, bus master revoked, stream back to abort). No USB HID driver and no +console shell. Mutation self-test: `scripts/qemu_ck_keyboard_test.sh +--mutation` builds `make full CK_TEST_XHCI_MUTATION=` (TEST-ONLY, refused +with `CK_HARDWARE_STAGING=1` and with `CK_QEMU_UNSAFE_DMA=1`, by the Makefile +and by an `#error`; the default image is checked to carry no mutation banner) +and requires bm-left-on -> row 27, no-revoke -> row 31, grant-no-smmu -> row 28, +no-sweep -> row 26 to FAIL. Host tests (`stage_test`): sweep on a fake ECAM +(endpoints cleared, bridges untouched, multi-function rule, every bus) and the +fence fail-closed paths (no SMMU, bus master left on). Hardware NOT_RUN: no +physical xHCI or SMMU run. + | # | Rust check (pattern) | CK gate | Status | | --- | --- | --- | --- | -| 25 | xHCI found before exit (`keyboard: xhci `) | KEYBOARD | NOT_RUN (MISSING_IMPLEMENTATION: no xHCI/USB HID driver in the C kernel) | -| 26 | bus-master sweep after exit (`dma_sweep: seg `, no `dma_sweep: bme STUCK`) | KEYBOARD | NOT_RUN (MISSING_IMPLEMENTATION: no post-exit bus-master sweep) | -| 27 | xHCI bus master off before the DMA gate (`xhci_pci: command=0x.. bus_master=off`) | KEYBOARD | NOT_RUN (MISSING_IMPLEMENTATION) | -| 28 | fail-closed without SMMU (`dma_gate: xhci denied (NoSmmu)...`, `keyboard: unavailable (...)`, no grant, no `keyboard: ready`) | KEYBOARD | NOT_RUN (MISSING_IMPLEMENTATION) | -| 29 | keyboard attached and typed line echoed (`keyboard: ready`, `keyboard_echo:`, `keyboard_line:`, `keyboard: done (enter)`) | KEYBOARD | NOT_RUN (MISSING_IMPLEMENTATION) | +| 25 | xHCI found before exit (`keyboard: xhci `) | KEYBOARD | NOT_RUN (pending forge receipt; C would be DIFFERS: found after exit on the ECAM walk, class 0x0c0330, `keyboard: xhci 0000:BB:DD.F mmio 0x.. (found post-exit on the ECAM walk)`, both boots) | +| 26 | bus-master sweep after exit (`dma_sweep: seg `, no `dma_sweep: bme STUCK`) | KEYBOARD | NOT_RUN (pending forge receipt; C would be DIFFERS: same line text as Rust, `dma_sweep: seg 0000 bus .. functions=N ... still_enabled=0`, no `dma_sweep: bme STUCK`, and stricter: the sweep must come before the first `dma_gate: ` line and before `keyboard: xhci `; both boots; mutation no-sweep) | +| 27 | xHCI bus master off before the DMA gate (`xhci_pci: command=0x.. bus_master=off`) | KEYBOARD | NOT_RUN (pending forge receipt; C would be IDENTICAL prefix `xhci_pci: command=0x.... bus_master=off`, plus the order check: before `dma_gate: xhci `; both boots; mutation bm-left-on) | +| 28 | fail-closed without SMMU (`dma_gate: xhci denied (NoSmmu)...`, `keyboard: unavailable (...)`, no grant, no `keyboard: ready`) | KEYBOARD | NOT_RUN (pending forge receipt; C would be IDENTICAL lines `dma_gate: xhci denied (NoSmmu), bus master stays off` and `keyboard: unavailable (SMMU DMA isolation not active)`, absent `dma_gate: xhci granted` and `keyboard: ready`, plus C-only: COMMAND read back after the deny `bus_master=off`, no xHCI SMMU window; boot kbd-nosmmu; mutation grant-no-smmu) | +| 29 | keyboard attached and typed line echoed (`keyboard: ready`, `keyboard_echo:`, `keyboard_line:`, `keyboard: done (enter)`) | KEYBOARD | NOT_RUN (MISSING_IMPLEMENTATION: no USB HID driver in the C kernel; the image prints `keyboard: hid NOT_IMPLEMENTED ...`) | | 30 | shell commands (`commands: help mem el report uptime exit`, `EL1`, `conventional_memory_kb:`, `keyboard: done (exit)`) | KEYBOARD | NOT_RUN (MISSING_IMPLEMENTATION: no console shell) | -| 31 | xHCI bus master revoked after the phase (`dma_gate: xhci bus master revoked`) | KEYBOARD | NOT_RUN (MISSING_IMPLEMENTATION) | -| 32 | no panic or fault | KEYBOARD | NOT_RUN (MISSING_IMPLEMENTATION) | +| 31 | xHCI bus master revoked after the phase (`dma_gate: xhci bus master revoked`) | KEYBOARD | NOT_RUN (pending forge receipt; C would be DIFFERS (stronger): the same line after `smmu_dma_window: xhci only, translation active ...` and `dma_gate: xhci granted (Confined), bus master on`, controller halted first (`xhci: halt before revoke ... halted=yes`), COMMAND read back `xhci_pci: after phase command=0x.... bus_master=off`, `smmu: xhci stream 0x.. returned to abort (rc=0)`, in that order and before `devices: xhci=fenced (rc=0)`; no HID phase runs between grant and revoke; boot kbd-smmu; mutation no-revoke) | +| 32 | no panic or fault | KEYBOARD | NOT_RUN (pending forge receipt; C would be IDENTICAL: `report_kind: (panic\|fault)` absent, plus `report_kind: final`, QEMU exit 0 and every M1 check of scripts/lib_ck_m1_checks.sh, both boots) | ## SEED-0B / P2-5 artifact loader: scripts/qemu_artifact_test.sh -> CK `P2_ARTIFACT` (scripts/qemu_ck_artifact_test.sh) @@ -404,7 +428,7 @@ complete. **C kernel receipt tally (QEMU only, no physical run):** 9 of 14 CK gates PASS, 5 NOT_RUN (M0_ROLLBACK, M4_STORE_CRASH, M4_CONTINUITY, M4_RECOVERY, KEYBOARD), 0 FAIL, matching `evidence/ck_gates_929f287e9c950c45c7dcd569c7caa03709ea62ecfe393635b435058afa969c54.json` (run at 41aa0e6, which adds the kernel entropy rows 107-109; that commit was then rebased onto #210, which changed only README.md and CONTRIBUTING.md). The row counts below are per Rust-parity row, not per gate. -Rows 1-112 plus the M4 continuity/recovery sub-rows 83a-87i and 88a-91p: IDENTICAL 28, DIFFERS 39, NOT_RUN 86, counted from the table (the CK-5 contract branch split rows 81-91, 11 NOT_RUN rows, into 52 NOT_RUN rows, one per Rust QEMU check and host test, see `native/kernel/CONTINUITY_RECOVERY_CONTRACT.md`; that adds 41 NOT_RUN rows and changes no other row or gate; the CK gate tally is unchanged; rows 107-109, kernel entropy, are C-only and DIFFERS; row 102, virtio-net attach with ACCESS_PLATFORM, and rows 110-112, virtio-net SMMU fence, recovery and ACCESS_PLATFORM fail-closed, are C-only and NOT_RUN on this branch until a forge receipt covers them; the CK gate tally above and its receipt `ck_gates_929f...` predate them; no full `ck_gates.sh` run happened on this branch, only `scripts/qemu_ck_net_test.sh` alone, so rows 102 and 110-112 are shown as QEMU PASS (receipt `evidence/ck_net_qemu_8bdbc2e46b85d04c422f9d2830c1c4b263e254b3cfecfe21ff0063c9e33c86e8.log`, hardware NOT_RUN) and the NOT_RUN count still includes them as originally counted, not recounted); rows 34 and 39 now also cover the NVMe boot-disk source and its hostile disk cases (statuses unchanged) (the previous summary, 20/30/56, was miscounted: the table on main had 21/35/50; rows 33-41 then moved from NOT_RUN to 7 IDENTICAL + 2 DIFFERS with the C artifact loader; rows 92-95 have no CK gate at all; rows 96-112 are C-only). Rows 33-41 were checked against scripts/qemu_ck_artifact_test.sh. Rows 102-106 and 110-112 were checked against scripts/qemu_ck_net_test.sh (text only; rows 102 and 110-112 then run by the forge, see their rows). Rows 13, 24, 47-72, 76 and 96-101 were re-verified against scripts/qemu_ck_store_test.sh and scripts/lib_ck_m1_checks.sh at the commit that adds this line. +Rows 1-112 plus the M4 continuity/recovery sub-rows 83a-87i and 88a-91p: IDENTICAL 28, DIFFERS 39, NOT_RUN 86, counted from the table (the CK-5 contract branch split rows 81-91, 11 NOT_RUN rows, into 52 NOT_RUN rows, one per Rust QEMU check and host test, see `native/kernel/CONTINUITY_RECOVERY_CONTRACT.md`; that adds 41 NOT_RUN rows and changes no other row or gate; the CK gate tally is unchanged; recounted again after merging the KEYBOARD DMA-fence branch: 28 IDENTICAL, 39 DIFFERS, 82 NOT_RUN and 4 QEMU PASS rows (102, 110-112) counted as NOT_RUN as below, so 86, unchanged, with sub-rows 24a and 24b (C only) not counted; rows 25-28, 31 and 32 now have a C implementation and a child script, scripts/qemu_ck_keyboard_test.sh, but stay NOT_RUN (pending forge receipt), rows 29-30 stay NOT_RUN (MISSING_IMPLEMENTATION: no USB HID driver, no console shell), and the KEYBOARD gate stays NOT_RUN; rows 107-109, kernel entropy, are C-only and DIFFERS; row 102, virtio-net attach with ACCESS_PLATFORM, and rows 110-112, virtio-net SMMU fence, recovery and ACCESS_PLATFORM fail-closed, are C-only and NOT_RUN on this branch until a forge receipt covers them; the CK gate tally above and its receipt `ck_gates_929f...` predate them; no full `ck_gates.sh` run happened on this branch, only `scripts/qemu_ck_net_test.sh` alone, so rows 102 and 110-112 are shown as QEMU PASS (receipt `evidence/ck_net_qemu_8bdbc2e46b85d04c422f9d2830c1c4b263e254b3cfecfe21ff0063c9e33c86e8.log`, hardware NOT_RUN) and the NOT_RUN count still includes them as originally counted, not recounted); rows 34 and 39 now also cover the NVMe boot-disk source and its hostile disk cases (statuses unchanged) (the previous summary, 20/30/56, was miscounted: the table on main had 21/35/50; rows 33-41 then moved from NOT_RUN to 7 IDENTICAL + 2 DIFFERS with the C artifact loader; rows 92-95 have no CK gate at all; rows 96-112 are C-only). Rows 33-41 were checked against scripts/qemu_ck_artifact_test.sh. Rows 102-106 and 110-112 were checked against scripts/qemu_ck_net_test.sh (text only; rows 102 and 110-112 then run by the forge, see their rows). Rows 13, 24, 47-72, 76 and 96-101 were re-verified against scripts/qemu_ck_store_test.sh and scripts/lib_ck_m1_checks.sh at the commit that adds this line. `scripts/trust1_m5_qualify.sh --with-qemu` also runs three of these gates as qemu rows: `ck_m1_boot_qemu` (M1), `ck_store_kernel_qemu` (M4_STORE) and diff --git a/native/kernel/Makefile b/native/kernel/Makefile index f9c89be9..de368f2c 100644 --- a/native/kernel/Makefile +++ b/native/kernel/Makefile @@ -17,6 +17,11 @@ # both files; tools/ck_owner_gen.c checks them); its # Store stage refuses (production key source is # BLOCKED_OPERATOR). scripts/ck_owner_keys_check.sh +# make full CK_TEST_XHCI_MUTATION=bm-left-on|no-revoke|grant-no-smmu|no-sweep +# TEST-ONLY image that breaks one xHCI DMA fence row on +# purpose: $(OUT)/full-test-xhci-/ (only +# scripts/qemu_ck_keyboard_test.sh --mutation; refused +# with CK_HARDWARE_STAGING=1 or CK_QEMU_UNSAFE_DMA=1) # make owner-gen host tool $(OUT)/host/ck_owner_gen # make [full] CK_TEST_FWCFG_ARTIFACTS=1 # TEST-ONLY: loader takes candidates from the QEMU fw_cfg @@ -95,6 +100,23 @@ $(error CK_QEMU_UNSAFE_DMA must be empty or 1) endif endif +# TEST-ONLY xHCI DMA fence mutations (dev/xhci_fence.h), for the self-test of +# scripts/qemu_ck_keyboard_test.sh --mutation only: each one breaks one +# keyboard DMA-safety row on purpose. Own FULL_NAME, never a hardware image. +CK_TEST_XHCI_MUTATION ?= +ifneq ($(strip $(CK_TEST_XHCI_MUTATION)),) +ifneq ($(strip $(CK_HARDWARE_STAGING)),) +$(error CK_TEST_XHCI_MUTATION (TEST-ONLY xHCI DMA fence mutation) cannot be combined with CK_HARDWARE_STAGING) +endif +ifneq ($(strip $(CK_QEMU_UNSAFE_DMA)),) +$(error CK_TEST_XHCI_MUTATION cannot be combined with CK_QEMU_UNSAFE_DMA) +endif +XHCI_MUT_NUM := $(if $(filter bm-left-on,$(CK_TEST_XHCI_MUTATION)),1,$(if $(filter no-revoke,$(CK_TEST_XHCI_MUTATION)),2,$(if $(filter grant-no-smmu,$(CK_TEST_XHCI_MUTATION)),3,$(if $(filter no-sweep,$(CK_TEST_XHCI_MUTATION)),4,)))) +ifeq ($(XHCI_MUT_NUM),) +$(error CK_TEST_XHCI_MUTATION must be one of bm-left-on no-revoke grant-no-smmu no-sweep) +endif +endif + # Owner provisioning. The hardware staging image never embeds the TEST Store # keys, the TEST store uuid or the TEST machine id: it needs owner PUBLIC # material and the machine identity as files (format: tools/ck_owner_gen.c; @@ -189,6 +211,10 @@ else FULL_NAME := full STAGE_DMA_FLAGS := endif +ifneq ($(strip $(CK_TEST_XHCI_MUTATION)),) +FULL_NAME := full-test-xhci-$(strip $(CK_TEST_XHCI_MUTATION)) +STAGE_DMA_FLAGS += -DCK_TEST_XHCI_MUTATION=$(XHCI_MUT_NUM) +endif ifneq ($(strip $(CK_HARDWARE_STAGING)),) # Own OUT subdirectory: stage objects built with these flags never mix with # the default full image's objects. @@ -269,6 +295,17 @@ define fwcfg_check fi endef +# xhci_mut_check(elf): only a CK_TEST_XHCI_MUTATION image may carry the +# TEST-ONLY xHCI mutation banner (and it must carry it). +define xhci_mut_check + @if [ -n "$(strip $(CK_TEST_XHCI_MUTATION))" ]; then \ + grep -aqF "TEST-ONLY xHCI MUTATION BUILD" $(1) || { echo "xHCI mutation image lacks its TEST-ONLY banner"; rm -f $(1); exit 1; }; \ + else \ + if grep -aqF "TEST-ONLY xHCI MUTATION" $(1); then echo "default image carries the TEST-ONLY xHCI mutation"; rm -f $(1); exit 1; fi; \ + echo "no xHCI mutation code in $(1)"; \ + fi +endef + # owner_check(elf): a hardware staging image must carry no TEST Store label, # TEST store uuid, TEST Store print lines or TEST key symbols. define owner_check @@ -310,6 +347,7 @@ $(FULL_ELF): $(CORE_OBJS) $(STAGE_BUILT) $(BOOT)/image.ld $(KNM) $@ | grep -qE " [TW] $$s$$" || { echo "full image lacks $$s"; rm -f $@; exit 1; }; done $(call fwcfg_check,$@) $(call owner_check,$@) + $(call xhci_mut_check,$@) $(EFI): $(ELF) $(call pe_image,$<,$@) diff --git a/native/kernel/dev/devices.c b/native/kernel/dev/devices.c index e218cd0d..0cef877a 100644 --- a/native/kernel/dev/devices.c +++ b/native/kernel/dev/devices.c @@ -1,10 +1,12 @@ -/* devices.c -- ck_stage_devices: PCI, NVMe, virtio-net. Freestanding. */ +/* devices.c -- ck_stage_devices: PCI (with the post-exit bus-master sweep), + * NVMe, virtio-net, xHCI DMA fence. Freestanding. */ #include "devices.h" #include "ck.h" #include "nvme_bind.h" #include "pci.h" #include "virtio_net.h" #include "net_bind.h" +#include "xhci_fence.h" static pci_system g_pci; static ck_nvme g_nvme; @@ -40,6 +42,15 @@ int ck_stage_devices(void) { int rc = pci_stage_probe(&g_pci); if (rc) return rc; + /* Post-exit bus-master sweep (Rust dma_gate::sweep_bus_master): before any + * device is given DMA, clear BME on every endpoint firmware left with it + * set, so each device starts with DMA off. */ + if (ck_xhci_sweep_enabled()) { + pci_sweep sw; + pci_sweep_bus_master(&g_pci.acc, &sw); + pci_sweep_report(&g_pci.ecam, &sw); + } + ck_xhci_after_sweep(&g_pci); /* TEST-ONLY bm-left-on mutation hook; no-op otherwise */ int nrc = ck_nvme_bind(&g_nvme, &g_pci); if (nrc) ck_dev_nvme_release(); /* a failed bind never keeps DMA */ virtio_pci_caps caps; @@ -51,6 +62,11 @@ int ck_stage_devices(void) int netrc = (vrc == 0 && vf) ? ck_net_bind_selftest(vf, &caps) : 1; ck_printf("devices: pci=ok nvme=%s virtio_net=%s\n", g_nvme.bound ? "bound" : "unbound", vrc != 0 ? "caps-refused" : !vf ? "absent" : netrc == 0 ? "selftest-ok" : "selftest-failed"); + /* xHCI: DMA fence only (bus master off before the gate, SMMU-confined grant + * or fail-closed deny, halt, revoke, stream back to abort); no USB HID + * driver yet. Reported, never a devices-stage failure. */ + int xrc = ck_xhci_fence(&g_pci); + ck_printf("devices: xhci=%s (rc=%d)\n", ck_xhci_state(), xrc); if (nrc == -1) return 0; /* no NVMe present: not a devices failure; Store reports it */ return nrc; } @@ -63,10 +79,13 @@ void ck_stage_quiesce(void) { int net_live = ck_net_live(); if (net_live) ck_net_release(); + int xhci_live = ck_xhci_live(); + if (xhci_live) ck_xhci_release(); int was_live = g_nvme.pf && (g_nvme.bm_on || g_nvme.confined); if (was_live) ck_dev_nvme_release(); ck_printf("devices: quiesce before reset nvme=%s\n", !g_nvme.pf ? "none" : was_live ? "released-now" : "already-released"); if (net_live) ck_printf("devices: quiesce before reset virtio_net=released-now\n"); + if (xhci_live) ck_printf("devices: quiesce before reset xhci=released-now\n"); } diff --git a/native/kernel/dev/pci.c b/native/kernel/dev/pci.c index 407ead98..5990ee61 100644 --- a/native/kernel/dev/pci.c +++ b/native/kernel/dev/pci.c @@ -231,6 +231,63 @@ int pci_bus_master_off(const pci_func *f) return (pci_r16(f->cfg, CFG_COMMAND) & CMD_BM) ? -1 : 0; } + +void pci_sweep_bus_master(const pci_bus_access *a, pci_sweep *out) +{ + pci_sweep s; + uint8_t *z = (uint8_t *)&s; + for (size_t i = 0; i < sizeof s; i++) z[i] = 0; + for (uint32_t bus = a->start_bus; bus <= a->end_bus; bus++) { + for (uint8_t dev = 0; dev < 32; dev++) { + for (uint8_t fn = 0; fn < 8; fn++) { + volatile uint8_t *c = pci_cfg(a, (uint8_t)bus, dev, fn); + if (!c) break; + if ((pci_r32(c, CFG_VENDOR) & 0xffffu) == 0xffffu) { + if (fn == 0) break; + continue; + } + s.functions++; + uint8_t header = (uint8_t)(pci_r32(c, 0x0c) >> 16); + uint16_t cmd = pci_r16(c, CFG_COMMAND); + if ((header & 0x7fu) == 1u) { + s.bridges++; + if (cmd & CMD_BM) s.bridges_bme++; + } else if (cmd & CMD_BM) { + pci_w16(c, CFG_COMMAND, (uint16_t)(cmd & ~CMD_BM)); + uint16_t after = pci_r16(c, CFG_COMMAND); + if (s.endpoints_bme < PCI_SWEEP_FINDINGS) { + pci_bme_finding *f = &s.f[s.endpoints_bme]; + f->bus = (uint8_t)bus; + f->dev = dev; + f->fn = fn; + f->command_before = cmd; + f->command_after = after; + } + s.endpoints_bme++; + if (after & CMD_BM) s.still_enabled++; + } + if (fn == 0 && !(header & 0x80u)) break; + } + } + } + *out = s; +} + +void pci_sweep_report(const pci_ecam *e, const pci_sweep *s) +{ + ck_printf("dma_sweep: seg %04x bus %02x-%02x functions=%u bridges=%u bridges_bme=%u endpoints_bme_found=%u " + "still_enabled=%u\n", + e->segment, e->start_bus, e->end_bus, s->functions, s->bridges, s->bridges_bme, s->endpoints_bme, + s->still_enabled); + uint32_t n = s->endpoints_bme < PCI_SWEEP_FINDINGS ? s->endpoints_bme : PCI_SWEEP_FINDINGS; + for (uint32_t i = 0; i < n; i++) { + const pci_bme_finding *f = &s->f[i]; + ck_printf("dma_sweep: bme %s %04x:%02x:%02x.%u command 0x%04x -> 0x%04x\n", + (f->command_after & CMD_BM) ? "STUCK" : "cleared", e->segment, f->bus, f->dev, f->fn, + f->command_before, f->command_after); + } +} + const pci_func *pci_find_class(const pci_system *s, uint32_t cc, uint32_t mask) { for (uint32_t i = 0; i < s->n; i++) diff --git a/native/kernel/dev/pci.h b/native/kernel/dev/pci.h index 0275fc2a..81777418 100644 --- a/native/kernel/dev/pci.h +++ b/native/kernel/dev/pci.h @@ -101,6 +101,32 @@ void pci_enable(const pci_func *f, int bm); /* Clear Bus Master Enable and read it back: 0 when it reads clear. */ int pci_bus_master_off(const pci_func *f); + +/* Post-exit bus-master sweep (port of crates/aienos-kernel/src/dma_gate.rs + * sweep_bus_master): walk every bus in the ECAM window, every device and + * (when marked multi-function) every function, and clear Bus Master Enable + * on every endpoint (header type 0) that has it set, reading it back. + * Bridges (header type 1) are counted, never changed: a bridge's BME only + * forwards DMA from the endpoints below it, which are cleared one by one. + * Runs before any device is given DMA, so every device starts with DMA off. */ +#define PCI_SWEEP_FINDINGS 8u +typedef struct { + uint8_t bus, dev, fn; + uint16_t command_before, command_after; /* after: read back after the clear */ +} pci_bme_finding; +typedef struct { + uint16_t functions; /* functions that answered a config read */ + uint16_t bridges; /* header type 1 among them (left untouched) */ + uint16_t bridges_bme; /* bridges with BME set */ + uint16_t endpoints_bme; /* endpoints found with BME set (and cleared) */ + uint16_t still_enabled; /* endpoints whose BME still reads set after the clear */ + pci_bme_finding f[PCI_SWEEP_FINDINGS]; /* first PCI_SWEEP_FINDINGS endpoints */ +} pci_sweep; +void pci_sweep_bus_master(const pci_bus_access *a, pci_sweep *out); +/* Print the sweep in the Rust kernel's format: one "dma_sweep: seg ..." line + * plus one "dma_sweep: bme cleared|STUCK ..." line per recorded finding. */ +void pci_sweep_report(const pci_ecam *e, const pci_sweep *s); + /* First function with this class (class/subclass/progif masked by mask). */ const pci_func *pci_find_class(const pci_system *s, uint32_t class_code, uint32_t mask); const pci_func *pci_find_id(const pci_system *s, uint16_t vendor, uint16_t device); diff --git a/native/kernel/dev/xhci_fence.c b/native/kernel/dev/xhci_fence.c new file mode 100644 index 00000000..b54630c1 --- /dev/null +++ b/native/kernel/dev/xhci_fence.c @@ -0,0 +1,208 @@ +/* xhci_fence.c -- xHCI DMA fence (see xhci_fence.h). Freestanding. */ +#include "xhci_fence.h" +#include "ck.h" + +#if defined(CK_TEST_XHCI_MUTATION) && defined(CK_HARDWARE_STAGING) +#error "CK_TEST_XHCI_MUTATION (TEST-ONLY xHCI DMA fence mutation) cannot be combined with CK_HARDWARE_STAGING" +#endif +#if defined(CK_TEST_XHCI_MUTATION) && defined(CK_QEMU_UNSAFE_DMA) +#error "CK_TEST_XHCI_MUTATION cannot be combined with CK_QEMU_UNSAFE_DMA" +#endif +#if defined(CK_TEST_XHCI_MUTATION) +#if CK_TEST_XHCI_MUTATION < 1 || CK_TEST_XHCI_MUTATION > 4 +#error "CK_TEST_XHCI_MUTATION must be 1..4 (bm-left-on, no-revoke, grant-no-smmu, no-sweep)" +#endif +#define CK_XHCI_MUT CK_TEST_XHCI_MUTATION +#else +#define CK_XHCI_MUT 0 +#endif + +#define CMD_MEM 0x2u +#define CMD_BM 0x4u +/* xHCI capability / operational registers (xHCI 1.2 sections 5.3, 5.4). */ +#define XHCI_CAPLENGTH 0x00u /* bits 7:0 CAPLENGTH, 31:16 HCIVERSION */ +#define XHCI_USBCMD 0x00u /* operational */ +#define XHCI_USBSTS 0x04u +#define USBCMD_RS 0x1u +#define USBSTS_HCH 0x1u + +typedef struct { + const pci_func *pf; + volatile uint8_t *bar0; + uint32_t op; /* operational register offset (CAPLENGTH) */ + int bm_on, confined, mapped; + uint32_t stream_id; + const char *state; +} ck_xhci; + +static ck_xhci g_x; +static uint8_t *g_dma_mem; +static uint64_t g_dma_phys; + +static uint32_t x_r32(uint32_t off) { return *(volatile uint32_t *)(g_x.bar0 + off); } +static void x_w32(uint32_t off, uint32_t v) { *(volatile uint32_t *)(g_x.bar0 + off) = v; } + +int ck_xhci_live(void) { return g_x.pf && (g_x.bm_on || g_x.confined); } +const char *ck_xhci_state(void) { return g_x.state ? g_x.state : "absent"; } + +#if CK_XHCI_MUT +static const char *mut_name(void) +{ + switch (CK_XHCI_MUT) { + case CK_XHCI_MUT_BM_LEFT_ON: return "bm-left-on"; + case CK_XHCI_MUT_NO_REVOKE: return "no-revoke"; + case CK_XHCI_MUT_GRANT_NO_SMMU: return "grant-no-smmu"; + default: return "no-sweep"; + } +} +#endif + +int ck_xhci_sweep_enabled(void) +{ +#if CK_XHCI_MUT + ck_printf("WARNING: TEST-ONLY xHCI MUTATION BUILD (CK_TEST_XHCI_MUTATION=%s, QEMU gate self-test only, " + "never a PASS)\n", mut_name()); +#endif + return CK_XHCI_MUT != CK_XHCI_MUT_NO_SWEEP; +} + +void ck_xhci_after_sweep(const pci_system *pci) +{ +#if CK_XHCI_MUT == CK_XHCI_MUT_BM_LEFT_ON + const pci_func *f = pci_find_class(pci, CK_XHCI_CLASS, 0xffffffu); + if (f) pci_w16(f->cfg, 0x04, (uint16_t)(pci_r16(f->cfg, 0x04) | CMD_BM)); +#else + (void)pci; +#endif +} + +/* Make sure the controller is halted (R/S = 0, wait for HCH) while it may + * still DMA. Returns 0 when USBSTS.HCH reads 1. */ +static int halt(const char *when) +{ + if (!g_x.mapped) return 0; + uint32_t cmd = x_r32(g_x.op + XHCI_USBCMD); + if (cmd & USBCMD_RS) x_w32(g_x.op + XHCI_USBCMD, cmd & ~USBCMD_RS); + uint64_t t0 = ck_time_us(); + uint32_t sts; + while (!((sts = x_r32(g_x.op + XHCI_USBSTS)) & USBSTS_HCH) && ck_time_us() - t0 < CK_XHCI_HALT_WAIT_US) + ck_udelay(10); + int ok = (sts & USBSTS_HCH) != 0; + ck_printf("xhci: %s usbcmd=0x%08x usbsts=0x%08x halted=%s\n", when, cmd, sts, ok ? "yes" : "NO (TIMEOUT)"); + return ok ? 0 : -1; +} + +void ck_xhci_release(void) +{ + ck_xhci *x = &g_x; + if (!x->pf) return; + if (x->bm_on) { + (void)halt("halt before revoke"); +#if CK_XHCI_MUT == CK_XHCI_MUT_NO_REVOKE + /* TEST-ONLY mutation: bus mastering is left on. */ + int off = (pci_r16(x->pf->cfg, 0x04) & CMD_BM) ? -1 : 0; +#else + int off = pci_bus_master_off(x->pf); +#endif + if (off == 0) { + x->bm_on = 0; + ck_printf("dma_gate: xhci bus master revoked\n"); + } else /* bm_on stays set: the reset quiesce hook retries the revoke */ + ck_printf("dma_gate: xhci bus master revoke FAILED (command register still has BME)\n"); + uint16_t c = pci_r16(x->pf->cfg, 0x04); + ck_printf("xhci_pci: after phase command=0x%04x bus_master=%s\n", c, (c & CMD_BM) ? "on" : "off"); + } + if (x->confined) { + int urc = ck_dma_unconfine(x->stream_id); + x->confined = 0; + ck_printf("smmu: xhci stream 0x%x %s (rc=%d)\n", x->stream_id, urc == 0 ? "returned to abort" : "abort FAILED", + urc); + } +} + +int ck_xhci_fence(const pci_system *pci) +{ + ck_xhci *x = &g_x; + if (ck_xhci_live()) { + ck_printf("keyboard: unavailable (previous xHCI fence still live; release it first)\n"); + return CK_XHCI_E_ARG; + } + x->pf = 0; + x->bar0 = 0; + x->op = 0; + x->bm_on = x->confined = x->mapped = 0; + x->stream_id = 0; + x->state = "absent"; + const pci_func *f = pci ? pci_find_class(pci, CK_XHCI_CLASS, 0xffffffu) : 0; + if (!f) { + ck_printf("keyboard: unavailable (no xHCI controller)\n"); + return CK_XHCI_ABSENT; + } + x->pf = f; + const pci_bar *b = &f->bar[0]; + /* Rust: "keyboard: xhci {seg:04x}:{bus:02x}:{dev:02x}.{fn} mmio {:#x}". */ + ck_printf("keyboard: xhci %04x:%02x:%02x.%u mmio 0x%llx (found post-exit on the ECAM walk)\n", + pci->ecam.segment, f->bus, f->dev, f->fn, (unsigned long long)b->addr); + uint16_t command = pci_r16(f->cfg, 0x04); + ck_printf("xhci_pci: command=0x%04x bus_master=%s\n", command, (command & CMD_BM) ? "on" : "off"); + if (command & CMD_BM) { + /* The sweep could not clear it (or it came back): no gate, no DMA. The + * bus-master bit is left as found; the reset quiesce hook does not + * touch an unbound controller. */ + x->state = "bme-stuck"; + ck_printf("keyboard: unavailable (xHCI bus master would not clear)\n"); + return CK_XHCI_E_BME; + } + if (b->io || b->addr == 0 || b->size < 0x1000u) { + x->state = "bar-unusable"; + ck_printf("keyboard: unavailable (xHCI BAR0 unusable)\n"); + return CK_XHCI_E_ARG; + } + /* DMA gate: the window is exactly the region a driver would use. */ + if (!g_dma_mem) g_dma_mem = ck_dma_alloc(CK_XHCI_DMA_BYTES, 4096, &g_dma_phys); + if (!g_dma_mem) { + x->state = "dma-alloc-failed"; + ck_printf("keyboard: unavailable (DMA allocation of %u bytes failed)\n", (unsigned)CK_XHCI_DMA_BYTES); + return CK_XHCI_E_DMA; + } + uint32_t rid = ((uint32_t)f->bus << 8) | ((uint32_t)f->dev << 3) | (uint32_t)f->fn; + struct ck_dma_confinement cf; + int src = ck_dma_confine(rid, g_dma_phys, CK_XHCI_DMA_BYTES, &cf); + if (src == 0) { + x->confined = 1; + x->stream_id = cf.stream_id; + ck_printf("smmu: enabled base=0x%llx stream_id=0x%x\n", (unsigned long long)cf.smmu_base, cf.stream_id); + ck_printf("smmu_dma_window: xhci only, translation active iova=0x%llx len=0x%llx rid=0x%x\n", + (unsigned long long)cf.iova, (unsigned long long)cf.len, rid); + ck_printf("dma_gate: xhci granted (Confined), bus master on\n"); + } else { +#if CK_XHCI_MUT == CK_XHCI_MUT_GRANT_NO_SMMU + /* TEST-ONLY mutation: DMA granted without confinement. */ + ck_printf("dma_gate: xhci granted (TestMutationNoSmmu rc=%d), bus master on\n", src); +#else + if (src == CK_SMMU_ABSENT) + ck_printf("dma_gate: xhci denied (NoSmmu), bus master stays off\n"); + else + ck_printf("dma_gate: xhci denied (SmmuNotReady rc=%d), bus master stays off\n", src); + ck_printf("keyboard: unavailable (SMMU DMA isolation not active)\n"); + uint16_t c = pci_r16(f->cfg, 0x04); + ck_printf("xhci_pci: after deny command=0x%04x bus_master=%s\n", c, (c & CMD_BM) ? "on" : "off"); + x->state = "denied"; + return CK_XHCI_E_DENIED; +#endif + } + x->bar0 = (volatile uint8_t *)ck_mmio_map(b->addr, (size_t)b->size); + pci_enable(f, 1); + x->bm_on = 1; + x->mapped = 1; + uint32_t cap = x_r32(XHCI_CAPLENGTH); + x->op = cap & 0xffu; + ck_printf("xhci: caplength=0x%02x hciversion=0x%04x dma_window=0x%llx+0x%x\n", cap & 0xffu, cap >> 16, + (unsigned long long)g_dma_phys, (unsigned)CK_XHCI_DMA_BYTES); + int hrc = halt("halted after grant"); + /* Rows 29-30 (USB HID attach, typed line, console shell) are not built. */ + ck_printf("keyboard: hid NOT_IMPLEMENTED (no USB HID driver or console shell in the C kernel; DMA fence only)\n"); + x->state = hrc ? "halt-failed" : "fenced"; + ck_xhci_release(); + return hrc ? CK_XHCI_E_HALT : CK_XHCI_OK; +} diff --git a/native/kernel/dev/xhci_fence.h b/native/kernel/dev/xhci_fence.h new file mode 100644 index 00000000..4deb067d --- /dev/null +++ b/native/kernel/dev/xhci_fence.h @@ -0,0 +1,85 @@ +/* xhci_fence.h -- DMA fence for the xHCI (USB) controller: the DMA-safety + * half of the SEED-0A keyboard gate (GATES.md "SEED-0A keyboard", rows 25-28, + * 31, 32). Behaviour follows crates/aienos-boot/src/usb_keyboard.rs (run, + * revoke_dma) and the Rust dma_gate; observables use the Rust line texts + * where the Rust gate (scripts/qemu_keyboard_test.sh) greps them. + * + * What it does, after ExitBootServices, in the devices stage: + * 1. find the first class 0x0c0330 (xHCI) function on the ECAM bus walk + * ("keyboard: xhci SSSS:BB:DD.F mmio 0x.."); + * 2. the post-exit bus-master sweep (pci_sweep_bus_master) already ran at + * the start of the devices stage; read the controller's PCI COMMAND + * register back ("xhci_pci: command=0x.... bus_master=off") and stop if + * bus mastering is still on; + * 3. DMA gate, same rule as NVMe and virtio-net: no SMMU confinement means + * no DMA. The controller's DMA region is allocated first and becomes its + * stream's only SMMU window (ck_dma_confine); only then are memory + * decode and bus mastering enabled. Without an SMMU (or an SMMU that did + * not come up) the controller stays off: "dma_gate: xhci denied + * (NoSmmu), bus master stays off" + "keyboard: unavailable (SMMU DMA + * isolation not active)". There is no unconfined bypass for the xHCI, + * not even in the TEST-ONLY CK_QEMU_UNSAFE_DMA=1 build; + * 4. with the grant: map BAR0 and make sure the controller is halted + * (USBCMD.R/S = 0, USBSTS.HCH = 1, bounded wait); nothing is put on the + * controller's rings: there is NO USB HID driver and no console shell in + * the C kernel yet (rows 29-30 stay NOT_RUN, MISSING_IMPLEMENTATION); + * 5. release, in the NVMe halt order: controller halted while it can + * still DMA, bus master off with read-back ("dma_gate: xhci bus master + * revoked"), the controller's COMMAND register read back again + * ("xhci_pci: after phase command=0x.... bus_master=off"), stream back + * to abort ("smmu: xhci stream 0x.. returned to abort (rc=0)"). + * + * TEST-ONLY mutations (CK_TEST_XHCI_MUTATION, refused with + * CK_HARDWARE_STAGING by the Makefile and by an #error here); each must + * make scripts/qemu_ck_keyboard_test.sh --mutation see its rows FAIL: + * 1 bm-left-on the xHCI's bus mastering is switched back on after the + * sweep and left on before the gate (row 27) + * 2 no-revoke the release skips the bus-master clear (row 31) + * 3 grant-no-smmu with no SMMU the xHCI is granted DMA anyway (row 28) + * 4 no-sweep the post-exit bus-master sweep is skipped (row 26) + * A mutation image announces itself on the console. QEMU only. */ +#ifndef AIENOS_CK_XHCI_FENCE_H +#define AIENOS_CK_XHCI_FENCE_H +#include "pci.h" + +/* DMA region the controller is confined to (its only SMMU window). Sized for + * the HID cut that will follow (DCBAA, command/event rings, ERST, device and + * input contexts, one interrupt-IN buffer); nothing uses it yet. */ +#define CK_XHCI_DMA_BYTES (64u * 1024u) +#define CK_XHCI_CLASS 0x0c0330u +/* xHCI 1.2 section 5.4.1: the controller halts within 16 ms of R/S = 0. */ +#define CK_XHCI_HALT_WAIT_US 16000u + +enum { + CK_XHCI_OK = 0, + CK_XHCI_ABSENT = 1, /* no xHCI function: nothing to fence */ + CK_XHCI_E_ARG = -601, /* BAR0 unusable */ + CK_XHCI_E_BME = -602, /* bus mastering still on before the gate */ + CK_XHCI_E_DENIED = -603, /* no SMMU confinement: controller left off */ + CK_XHCI_E_DMA = -604, /* DMA region allocation failed */ + CK_XHCI_E_HALT = -605, /* controller would not halt (still released) */ +}; + +/* TEST-ONLY mutation numbers (CK_TEST_XHCI_MUTATION). */ +#define CK_XHCI_MUT_BM_LEFT_ON 1 +#define CK_XHCI_MUT_NO_REVOKE 2 +#define CK_XHCI_MUT_GRANT_NO_SMMU 3 +#define CK_XHCI_MUT_NO_SWEEP 4 + +/* Steps 1-5 above. Always leaves the controller released (bus master off, + * stream back to abort) before returning, except under the TEST-ONLY + * no-revoke mutation. Returns CK_XHCI_OK, CK_XHCI_ABSENT or a CK_XHCI_E_*. */ +int ck_xhci_fence(const pci_system *pci); +/* Halt, bus master off, stream back to abort if still live. Idempotent. */ +void ck_xhci_release(void); +/* 1 while the controller may still DMA (bus master on or stream confined). */ +int ck_xhci_live(void); +/* 1 when the post-exit bus-master sweep should run (0 only under the + * TEST-ONLY no-sweep mutation); prints the mutation banner once. */ +int ck_xhci_sweep_enabled(void); +/* Called by the devices stage right after the sweep (TEST-ONLY bm-left-on + * mutation hook; does nothing in every other build). */ +void ck_xhci_after_sweep(const pci_system *pci); +/* Short state for the devices summary line: absent, fenced, denied, ... */ +const char *ck_xhci_state(void); +#endif diff --git a/native/kernel/stage.mk b/native/kernel/stage.mk index dc904dcc..8788404e 100644 --- a/native/kernel/stage.mk +++ b/native/kernel/stage.mk @@ -14,7 +14,7 @@ STAGE_OUT ?= /tmp/aienos-ck-stage-$(shell id -u) # Own sources (image). STAGE_OWN_SRCS := $(STAGE_DIR)/dev/pci.c $(STAGE_DIR)/dev/nvme_bind.c $(STAGE_DIR)/dev/nvme_shutdown.c $(STAGE_DIR)/dev/virtio_net.c \ - $(STAGE_DIR)/dev/net_bind.c $(STAGE_DIR)/dev/net_udp.c \ + $(STAGE_DIR)/dev/net_bind.c $(STAGE_DIR)/dev/net_udp.c $(STAGE_DIR)/dev/xhci_fence.c \ $(STAGE_DIR)/dev/devices.c $(STAGE_DIR)/svc/security.c $(STAGE_DIR)/svc/store_boot.c \ $(STAGE_DIR)/svc/artifact_store.c # Native modules, compiled unmodified. diff --git a/native/kernel/svc/tests/stage_test.c b/native/kernel/svc/tests/stage_test.c index 7a857b56..419ce6ae 100644 --- a/native/kernel/svc/tests/stage_test.c +++ b/native/kernel/svc/tests/stage_test.c @@ -20,6 +20,7 @@ #include "sha256.h" #include "net_bind.h" #include "net_udp.h" +#include "xhci_fence.h" static int checks, failures; #define CHECK(c) \ @@ -622,6 +623,80 @@ static void test_net_udp(void) } +/* ---------------- post-exit bus-master sweep + xHCI DMA fence ---------------- */ + +static void test_xhci_fence(void) +{ + /* Sweep on a fake ECAM: endpoints with BME are cleared and read back, + * bridges are counted and left untouched, functions 1-7 are walked only + * when function 0 is marked multi-function (Rust dma_gate tests). */ + const size_t buses = 2; + uint8_t *ecam = aligned_alloc(1u << 20, buses << 20); + CHECK(ecam != NULL); + if (!ecam) return; + memset(ecam, 0xff, buses << 20); + uint8_t *c; + memset(c = cfgp(ecam, 0, 0, 0), 0, 4096); mkfn(c, 0x1b36, 0x0008, 0x060000, 0); put16(c + 4, 0x0002); + memset(c = cfgp(ecam, 0, 1, 0), 0, 4096); mkfn(c, 0x1b36, 0x000c, 0x060400, 1); put16(c + 4, 0x0007); + memset(c = cfgp(ecam, 0, 2, 0), 0, 4096); mkfn(c, 0x1b36, 0x000d, 0x0c0330, 0x80); put16(c + 4, 0x0006); + memset(c = cfgp(ecam, 0, 2, 3), 0, 4096); mkfn(c, 0x8086, 0x10d3, 0x020000, 0); put16(c + 4, 0x0004); + memset(c = cfgp(ecam, 0, 3, 0), 0, 4096); mkfn(c, 0x1af4, 0x1041, 0x020000, 0); put16(c + 4, 0x0006); + /* function 3 of a single-function device: never walked, BME stays */ + memset(c = cfgp(ecam, 0, 3, 3), 0, 4096); mkfn(c, 0x1af4, 0x1041, 0x020000, 0); put16(c + 4, 0x0004); + memset(c = cfgp(ecam, 1, 0, 0), 0, 4096); mkfn(c, 0x144d, 0xa808, 0x010802, 0); put16(c + 4, 0x0006); + pci_bus_access acc = {ecam, 0, (uint8_t)(buses - 1)}; + pci_sweep sw; + pci_sweep_bus_master(&acc, &sw); + CHECK(sw.functions == 6); + CHECK(sw.bridges == 1 && sw.bridges_bme == 1); + CHECK(sw.endpoints_bme == 4 && sw.still_enabled == 0); + CHECK(sw.f[0].bus == 0 && sw.f[0].dev == 2 && sw.f[0].fn == 0 && sw.f[0].command_before == 0x0006 && + sw.f[0].command_after == 0x0002); + CHECK(pci_r16(cfgp(ecam, 0, 1, 0), 4) == 0x0007); /* bridge untouched */ + CHECK((pci_r16(cfgp(ecam, 0, 2, 3), 4) & 0x4u) == 0); /* multi-function walked */ + CHECK((pci_r16(cfgp(ecam, 1, 0, 0), 4) & 0x4u) == 0); /* every bus in the window */ + CHECK((pci_r16(cfgp(ecam, 0, 3, 3), 4) & 0x4u) == 0x4u); /* not walked: single-function */ + CHECK(pci_r16(cfgp(ecam, 0, 0, 0), 4) == 0x0002); /* no BME: untouched */ + pci_ecam e = {0, 0, 0, (uint8_t)(buses - 1)}; + pci_sweep_report(&e, &sw); + /* Counter-example: a sweep that skipped bus 1 would leave its BME set. */ + put16(cfgp(ecam, 1, 0, 0) + 4, 0x0006); + pci_bus_access bus0 = {ecam, 0, 0}; + pci_sweep_bus_master(&bus0, &sw); + CHECK((pci_r16(cfgp(ecam, 1, 0, 0), 4) & 0x4u) == 0x4u && sw.endpoints_bme == 0); + + /* xHCI fence on the host shim (no IORT: CK_SMMU_ABSENT): fail closed, + * the command register never gets memory decode or bus master. */ + static pci_system s; + memset(&s, 0, sizeof s); + printf(" [xHCI fence, no xHCI, host, not hardware]\n"); + CHECK(ck_xhci_fence(&s) == CK_XHCI_ABSENT && strcmp(ck_xhci_state(), "absent") == 0); + static uint8_t cfg[4096]; + memset(cfg, 0, sizeof cfg); + s.n = 1; + s.f[0].vendor = 0x1b36; + s.f[0].device = 0x000d; + s.f[0].class_code = 0x0c0330; + s.f[0].cfg = cfg; + s.f[0].bar[0].addr = 0x10000000u; + s.f[0].bar[0].size = 0x4000u; + s.f[0].bar[0].is64 = 1; + printf(" [xHCI fence without SMMU, host, not hardware]\n"); + CHECK(ck_xhci_fence(&s) == CK_XHCI_E_DENIED); + CHECK((pci_r16(cfg, 4) & 0x6u) == 0); /* no MEM, no BM */ + CHECK(ck_xhci_live() == 0 && strcmp(ck_xhci_state(), "denied") == 0); + ck_xhci_release(); /* idempotent */ + CHECK((pci_r16(cfg, 4) & 0x6u) == 0); + /* Bus master still on before the gate: no gate at all. */ + put16(cfg + 4, 0x0004); + printf(" [xHCI fence with BME left on, host, not hardware]\n"); + CHECK(ck_xhci_fence(&s) == CK_XHCI_E_BME && strcmp(ck_xhci_state(), "bme-stuck") == 0); + CHECK(ck_xhci_live() == 0 && (pci_r16(cfg, 4) & 0x2u) == 0); + put16(cfg + 4, 0); + free(ecam); +} + + /* ---------------- signed-artifact objects in the boot disk Store ---------------- */ #define A_UNITS 2048u @@ -782,6 +857,7 @@ int main(void) test_security(); test_nvme_shutdown(); test_net_udp(); + test_xhci_fence(); printf("CK_STAGE_HOST: %s checks=%d failures=%d\n", failures ? "FAIL" : "PASS", checks, failures); return failures ? 1 : 0; } diff --git a/scripts/qemu_ck_keyboard_test.sh b/scripts/qemu_ck_keyboard_test.sh new file mode 100755 index 00000000..b4f0ed0e --- /dev/null +++ b/scripts/qemu_ck_keyboard_test.sh @@ -0,0 +1,309 @@ +#!/usr/bin/env bash +# KEYBOARD gate for the AIENOS C kernel, DMA-safety half only: rows 25-28, 31 +# and 32 of native/kernel/GATES.md "SEED-0A keyboard" (Rust oracle: +# scripts/qemu_keyboard_test.sh with SMMU=1 and SMMU=0). Rows 29-30 (keyboard +# attached, typed line echoed, console shell) stay NOT_RUN +# (MISSING_IMPLEMENTATION: the C kernel has no USB HID driver and no console +# shell), so the KEYBOARD gate itself stays NOT_RUN whatever this prints. +# QEMU is not hardware: a PASS here qualifies nothing physical. +# +# Boots the full C image (make full) in QEMU AArch64 with UEFI (AAVMF), an +# NVMe disk (normal full boot), a qemu-xhci controller with a usb-kbd on it +# (the Rust gate's devices) and no NIC. The devices stage +# (native/kernel/dev/devices.c) runs the post-exit bus-master sweep first and +# the xHCI DMA fence (native/kernel/dev/xhci_fence.c) last. +# +# boot kbd-smmu iommu=smmuv3 (Rust SMMU=1): +# row 25 "keyboard: xhci SSSS:BB:DD.F mmio 0x.." (found on the ECAM walk) +# row 26 "dma_sweep: seg 0000 bus .." before the first device DMA grant, +# no "dma_sweep: bme STUCK" +# row 27 "xhci_pci: command=0x.... bus_master=off" before the xHCI DMA gate +# row 31 grant confined ("smmu_dma_window: xhci only, translation active", +# "dma_gate: xhci granted (Confined), bus master on"), controller +# halted, "dma_gate: xhci bus master revoked", COMMAND read back +# "xhci_pci: after phase command=0x.... bus_master=off", "smmu: xhci +# stream 0x.. returned to abort (rc=0)", in that order, all before +# the "devices: xhci=fenced (rc=0)" line (so a later reset-time +# quiesce revoke cannot stand in for it) +# row 32 no "report_kind: (panic|fault)", "report_kind: final", QEMU exit 0 +# boot kbd-nosmmu no SMMU (Rust SMMU=0), same image: +# rows 25, 26, 27, 32 as above +# row 28 "dma_gate: xhci denied (NoSmmu), bus master stays off", "keyboard: +# unavailable (SMMU DMA isolation not active)", COMMAND read back +# after the deny with bus_master=off, no "dma_gate: xhci granted", +# no "keyboard: ready" +# Both boots must also pass every M1 check (scripts/lib_ck_m1_checks.sh) and +# carry no TEST-ONLY mutation banner and no "UNSAFE DMA BYPASS". +# +# --mutation (self-test of the checks above; TEST-ONLY images): builds +# "make full CK_TEST_XHCI_MUTATION=" for each mutation and boots it once; +# the named row must FAIL (and the boot must still reach "report_kind: final" +# with row 25 PASS, so the failure is the mutation's, not a dead boot): +# bm-left-on xHCI bus mastering switched back on after the sweep (smmu) -> row 27 +# no-revoke release skips the bus-master clear (smmu) -> row 31 +# grant-no-smmu DMA granted without an SMMU (nosmmu) -> row 28 +# no-sweep post-exit bus-master sweep skipped (nosmmu) -> row 26 +# It also checks the build refuses a mutation together with +# CK_HARDWARE_STAGING=1 (and with CK_QEMU_UNSAFE_DMA=1), and that the default +# image carries no mutation banner. +# +# Env: AIENOS_QEMU_SMMU=1 or 0 runs only that boot (default: both). +# Takes the machine quiet flag itself like the other qemu_ck_* scripts +# (AIENOS_QUIET_FLAG / AIENOS_QUIET_TAG). +# Final lines (normal run): one "KEYBOARD_ROW : PASS|FAIL|NOT_RUN (...)" +# per row 25-32, "AIENOS_CK_KEYBOARD_DMA: PASS|FAIL (rows 25-28,31,32)" and +# "AIENOS_CK_KEYBOARD: NOT_RUN (MISSING_IMPLEMENTATION: ...)". Exit 0 when +# the DMA rows PASS, 1 FAIL, 2 missing tools, 3 NOT_RUN (quiet flag held). +# --mutation: "AIENOS_CK_KEYBOARD_MUTATION: PASS|FAIL"; exit 0 / 1. +# Needs qemu-system-aarch64, AAVMF (Ubuntu: qemu-system-arm qemu-efi-aarch64) +# and a C compiler. +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "${repo_root}" + +mutation_run=0 +case "${1:-}" in + "") ;; + --mutation) mutation_run=1 ;; + *) echo "usage: $0 [--mutation]"; exit 2 ;; +esac +final_tag="AIENOS_CK_KEYBOARD_DMA" +[[ "${mutation_run}" == 0 ]] || final_tag="AIENOS_CK_KEYBOARD_MUTATION" + +code_fd="${AAVMF_CODE:-/usr/share/AAVMF/AAVMF_CODE.no-secboot.fd}" +vars_fd="${AAVMF_VARS:-/usr/share/AAVMF/AAVMF_VARS.fd}" +command -v qemu-system-aarch64 >/dev/null || { echo "qemu-system-aarch64 not installed"; echo "${final_tag}: NOT_RUN"; exit 2; } +[[ -r "${code_fd}" && -r "${vars_fd}" ]] || { echo "AAVMF firmware not found"; echo "${final_tag}: NOT_RUN"; exit 2; } + +cross="" +if [ "$(uname -m)" != "aarch64" ]; then cross="aarch64-linux-gnu-"; fi +commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)" +out="${repo_root}/target/native-kernel" +mk() { make -s -C native/kernel CROSS="${cross}" OUT="${out}" AIENOS_COMMIT="${commit}" "$@"; } +mk full >/dev/null +default_efi="${out}/full/BOOTAA64.EFI" +mutations=(bm-left-on no-revoke grant-no-smmu no-sweep) +if [[ "${mutation_run}" == 1 ]]; then + for m in "${mutations[@]}"; do mk full CK_TEST_XHCI_MUTATION="${m}" >/dev/null; done +fi + +quiet_flag="${AIENOS_QUIET_FLAG:-${HOME}/workspace/.spark-quiet}" +quiet_tag="${AIENOS_QUIET_TAG:-qemu_ck_keyboard_test $$}" +if ! ( set -C; echo "${quiet_tag}" > "${quiet_flag}" ) 2>/dev/null; then + echo "NOT_RUN quiet flag ${quiet_flag} is held: $(head -c 200 "${quiet_flag}" 2>/dev/null || true)" + echo "${final_tag}: NOT_RUN" + exit 3 +fi +own_flag=1 +release_flag() { + if [[ "${own_flag}" == 1 ]]; then + own_flag=0 + if [[ -f "${quiet_flag}" ]] && grep -qxF -- "${quiet_tag}" "${quiet_flag}"; then rm -f "${quiet_flag}"; fi + fi +} +top="$(mktemp -d)" +cleanup() { + rm -rf "${top}" + release_flag +} +trap cleanup EXIT + +# shellcheck source=scripts/lib_ck_m1_checks.sh +source "${repo_root}/scripts/lib_ck_m1_checks.sh" +img_bytes=67108864 +image="${top}/nvme.img" +truncate -s "${img_bytes}" "${image}" +m1_fail=0 + +# boot smmu|nosmmu: one QEMU boot; serial text in ${work}/serial.txt. +boot() { + work="${top}/$1" + mkdir -p "${work}/esp/EFI/BOOT" "${work}/esp/EFI/AIENOS" + touch "${work}/esp/EFI/AIENOS/BOOTREPORT.TXT" + cp "$2" "${work}/esp/EFI/BOOT/BOOTAA64.EFI" + cp "${vars_fd}" "${work}/vars.fd" + local machine="virt,virtualization=on,gic-version=3" + [[ "$3" != smmu ]] || machine+=",iommu=smmuv3" + set +e + # Issue #61: single-threaded TCG (see qemu_boot_test.sh). + timeout "${AIENOS_QEMU_TIMEOUT:-180}" qemu-system-aarch64 \ + -M "${machine}" -accel tcg,thread=single -cpu max -smp 4 -m 2048 \ + -drive if=pflash,format=raw,readonly=on,file="${code_fd}" \ + -drive if=pflash,format=raw,file="${work}/vars.fd" \ + -drive if=none,id=esp,format=raw,file=fat:rw:"${work}/esp" \ + -device virtio-blk-pci,drive=esp \ + -drive if=none,id=nvme0,format=raw,file="${image}" \ + -device nvme,drive=nvme0,serial=aienos-kbd-test \ + -device qemu-xhci,id=xhci -device usb-kbd,bus=xhci.0 \ + -device ramfb -display none -nic none \ + -serial file:"${work}/serial.log" -no-reboot + qemu_status=$? + set -e + tr -d '\r' <"${work}/serial.log" >"${work}/serial.txt" + [[ -z "${AIENOS_LOG_DIR:-}" ]] || cp "${work}/serial.txt" "${AIENOS_LOG_DIR}/qemu_ck_keyboard_$1.log" + echo "== boot $1 ($3): qemu exit ${qemu_status}" +} + +# Row bookkeeping: rowfail[n]=1 once any check of row n failed in this +# evaluation; rowmodes[n] lists the boots that checked it. +declare -A rowfail rowmodes +reset_rows() { for r in 25 26 27 28 31 32; do rowfail[$r]=0; rowmodes[$r]=""; done; } +reset_rows +mode="" +note_mode() { [[ " ${rowmodes[$1]} " == *" ${mode} "* ]] || rowmodes[$1]="${rowmodes[$1]:+${rowmodes[$1]} }${mode}"; } +rpass() { note_mode "$1"; echo "ROW $1 PASS ${mode}: $2"; } +rfail() { note_mode "$1"; rowfail[$1]=1; echo "ROW $1 FAIL ${mode}: $2"; } +rcheck() { # row, description, ERE pattern + if grep -qE -- "$3" "${work}/serial.txt"; then rpass "$1" "$2"; else rfail "$1" "$2"; fi +} +rabsent() { # row, description, ERE pattern + if grep -qE -- "$3" "${work}/serial.txt"; then rfail "$1" "$2"; else rpass "$1" "$2"; fi +} +line_of() { { grep -nE -m1 -- "$1" "${work}/serial.txt" || true; } | cut -d: -f1; } +before() { # row, description, earlier ERE, later ERE: both present, earlier first + local a b + a="$(line_of "$3")"; b="$(line_of "$4")" + if [[ -n "${a}" && -n "${b}" && "${a}" -lt "${b}" ]]; then rpass "$1" "$2 (lines ${a} < ${b})" + else rfail "$1" "$2 (lines ${a:-none} ${b:-none})"; fi +} + +# evaluate smmu|nosmmu: every DMA-safety row check on ${work}/serial.txt. +evaluate() { + mode="$1" + rcheck 25 "xHCI found on the ECAM walk (Rust: keyboard: xhci )" \ + '^keyboard: xhci 0000:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7] mmio 0x[0-9a-f]+ ' + rcheck 26 "post-exit bus-master sweep of the segment" \ + '^dma_sweep: seg 0000 bus [0-9a-f]{2}-[0-9a-f]{2} functions=[1-9][0-9]* bridges=[0-9]+ bridges_bme=[0-9]+ endpoints_bme_found=[0-9]+ still_enabled=0$' + rabsent 26 "no endpoint left with bus master stuck on" '^dma_sweep: bme STUCK' + before 26 "sweep before the first device DMA gate" '^dma_sweep: seg ' '^dma_gate: ' + before 26 "sweep before the xHCI is looked at" '^dma_sweep: seg ' '^keyboard: xhci ' + rcheck 27 "xHCI bus master off before the DMA gate (Rust: xhci_pci: command=0x.. bus_master=off)" \ + '^xhci_pci: command=0x[0-9a-f]{4} bus_master=off$' + before 27 "COMMAND read back before the xHCI DMA gate" '^xhci_pci: command=' '^dma_gate: xhci ' + if [[ "${mode}" == nosmmu ]]; then + rcheck 28 "xHCI DMA denied without an SMMU" '^dma_gate: xhci denied \(NoSmmu\), bus master stays off$' + rcheck 28 "keyboard fail-closed without an SMMU" '^keyboard: unavailable \(SMMU DMA isolation not active\)$' + rcheck 28 "COMMAND read back after the deny: bus master off" '^xhci_pci: after deny command=0x[0-9a-f]{4} bus_master=off$' + rabsent 28 "xHCI never granted DMA" 'dma_gate: xhci granted' + rabsent 28 "keyboard never attached" 'keyboard: ready' + rabsent 28 "no xHCI SMMU window claimed without an SMMU" '^smmu_dma_window: xhci' + rcheck 28 "devices stage reports the deny" '^devices: xhci=denied \(rc=-603\)$' + else + rcheck 31 "xHCI SMMU window (Rust: smmu_dma_window: xhci only, translation active)" \ + '^smmu_dma_window: xhci only, translation active iova=0x[0-9a-f]+ len=0x[0-9a-f]+ rid=0x[0-9a-f]+$' + rcheck 31 "xHCI DMA granted only as confined" '^dma_gate: xhci granted \(Confined\), bus master on$' + rabsent 31 "no unconfined xHCI grant" 'dma_gate: xhci granted \((UnsafeBypass|TestMutation)' + rcheck 31 "controller halted before the revoke" '^xhci: halt before revoke usbcmd=0x[0-9a-f]{8} usbsts=0x[0-9a-f]{8} halted=yes$' + rcheck 31 "xHCI bus master revoked after the phase" '^dma_gate: xhci bus master revoked$' + rcheck 31 "COMMAND read back after the phase: bus master off" '^xhci_pci: after phase command=0x[0-9a-f]{4} bus_master=off$' + rcheck 31 "xHCI SMMU stream returned to abort" '^smmu: xhci stream 0x[0-9a-f]+ returned to abort \(rc=0\)$' + rabsent 31 "no revoke failure" '^dma_gate: xhci bus master revoke FAILED' + before 31 "order: grant < revoke" '^dma_gate: xhci granted \(Confined\)' '^dma_gate: xhci bus master revoked$' + before 31 "order: revoke < COMMAND read back" '^dma_gate: xhci bus master revoked$' '^xhci_pci: after phase command=' + before 31 "order: read back < stream abort" '^xhci_pci: after phase command=' '^smmu: xhci stream .* returned to abort' + before 31 "order: stream abort < end of the xHCI phase (not a reset-time revoke)" \ + '^smmu: xhci stream .* returned to abort' '^devices: xhci=fenced \(rc=0\)$' + fi + rabsent 32 "no panic or fault" '^report_kind: (panic|fault)' + rcheck 32 "final report reached" 'report_kind: final' + if [[ "${qemu_status}" == 0 ]]; then rpass 32 "QEMU exit 0 after PSCI reset"; else rfail 32 "QEMU exit ${qemu_status} (expected 0)"; fi +} + +if [[ "${mutation_run}" == 0 ]]; then + modes=(smmu nosmmu) + case "${AIENOS_QEMU_SMMU:-}" in + 1) modes=(smmu) ;; + 0) modes=(nosmmu) ;; + "") ;; + *) echo "AIENOS_QEMU_SMMU must be 1, 0 or unset"; release_flag; echo "${final_tag}: NOT_RUN"; exit 2 ;; + esac + other_fail=0 + for md in "${modes[@]}"; do + boot "kbd-${md}" "${default_efi}" "${md}" + failed=0 + ck_m1_checks + [[ "${failed}" == 0 ]] || m1_fail=1 + failed=0 + check_absent "no TEST-ONLY mutation banner in the default image" "TEST-ONLY xHCI MUTATION" + check_absent "no unsafe DMA bypass in this image" "UNSAFE DMA BYPASS" + check "honest marker: no USB HID driver yet (rows 29-30 NOT_RUN)" \ + "^keyboard: hid NOT_IMPLEMENTED\|^keyboard: unavailable (SMMU DMA isolation not active)$" + [[ "${failed}" == 0 ]] || other_fail=1 + failed=0 + evaluate "${md}" + done + release_flag + if [[ "${m1_fail}${other_fail}" != 00 || -n "${AIENOS_QEMU_VERBOSE:-}" ]] || (( rowfail[25] + rowfail[26] + rowfail[27] + rowfail[28] + rowfail[31] + rowfail[32] )); then + for s in "${top}"/*/serial.txt; do + echo "---- serial console $(basename "$(dirname "${s}")") (device lines) ----" + grep -E '^(keyboard|xhci|xhci_pci|dma_sweep|dma_gate|smmu|devices:|stage |report_kind:)' "${s}" | head -60 || true + done + fi + dma_fail=$(( m1_fail | other_fail )) + echo "== per-row results (QEMU only; hardware NOT_RUN)" + for r in 25 26 27 28 31 32; do + if [[ -z "${rowmodes[$r]}" ]]; then + echo "KEYBOARD_ROW ${r}: NOT_RUN (not checked in this run's modes)" + [[ -n "${AIENOS_QEMU_SMMU:-}" ]] || dma_fail=1 + elif [[ "${rowfail[$r]}" == 0 && "${m1_fail}" == 0 ]]; then + echo "KEYBOARD_ROW ${r}: PASS (${rowmodes[$r]})" + else + echo "KEYBOARD_ROW ${r}: FAIL (${rowmodes[$r]}$([[ "${m1_fail}" == 0 ]] || echo '; an M1 check failed'))" + dma_fail=1 + fi + done + echo "KEYBOARD_ROW 29: NOT_RUN (MISSING_IMPLEMENTATION: no USB HID driver in the C kernel)" + echo "KEYBOARD_ROW 30: NOT_RUN (MISSING_IMPLEMENTATION: no console shell in the C kernel)" + [[ "${m1_fail}" == 0 ]] || echo "M1 checks failed on at least one boot: the DMA rows cannot pass" + [[ "${other_fail}" == 0 ]] || echo "image checks failed (mutation banner, unsafe bypass or HID marker)" + if [[ "${dma_fail}" == 0 ]]; then echo "${final_tag}: PASS (rows 25-28,31,32; modes ${modes[*]})"; else echo "${final_tag}: FAIL (rows 25-28,31,32; modes ${modes[*]})"; fi + echo "AIENOS_CK_KEYBOARD: NOT_RUN (MISSING_IMPLEMENTATION: no USB HID driver or console shell in the C kernel; rows 29-30)" + [[ "${dma_fail}" == 0 ]] && exit 0 + exit 1 +fi + +# ---- --mutation: every mutation must make its row FAIL ---- +mut_fail=0 +mut_ok() { echo "MUTATION PASS $1"; } +mut_bad() { echo "MUTATION FAIL $1"; mut_fail=1; } +if grep -aqF "TEST-ONLY xHCI MUTATION" "${default_efi}"; then mut_bad "default image carries the mutation banner"; else mut_ok "default image carries no mutation banner"; fi +for combo in "CK_HARDWARE_STAGING=1" "CK_QEMU_UNSAFE_DMA=1"; do + set +e + msg="$(make -s -n -C native/kernel OUT="${top}/refuse" full CK_TEST_XHCI_MUTATION=no-revoke "${combo}" 2>&1)" + st=$? + set -e + if [[ "${st}" != 0 ]] && grep -qE "CK_TEST_XHCI_MUTATION.*cannot be combined with ${combo%%=*}" <<<"${msg}"; then + mut_ok "build refuses CK_TEST_XHCI_MUTATION with ${combo}" + else + mut_bad "build did not refuse CK_TEST_XHCI_MUTATION with ${combo} (status ${st}): $(head -c 200 <<<"${msg}")" + fi +done +declare -A mut_mode=([bm-left-on]=smmu [no-revoke]=smmu [grant-no-smmu]=nosmmu [no-sweep]=nosmmu) +declare -A mut_row=([bm-left-on]=27 [no-revoke]=31 [grant-no-smmu]=28 [no-sweep]=26) +for m in "${mutations[@]}"; do + efi="${out}/full-test-xhci-${m}/BOOTAA64.EFI" + boot "mut-${m}" "${efi}" "${mut_mode[$m]}" + reset_rows + evaluate "${mut_mode[$m]}" + r="${mut_row[$m]}" + if ! grep -qF "WARNING: TEST-ONLY xHCI MUTATION BUILD (CK_TEST_XHCI_MUTATION=${m}," "${work}/serial.txt"; then + mut_bad "${m}: image did not announce the mutation" + elif ! grep -q "report_kind: final" "${work}/serial.txt" || [[ "${rowfail[25]}" != 0 ]]; then + mut_bad "${m}: boot did not reach the final report with the xHCI found (a dead boot proves nothing)" + elif [[ "${rowfail[$r]}" == 1 ]]; then + mut_ok "${m} (${mut_mode[$m]}): row ${r} FAILs as it must" + else + mut_bad "${m} (${mut_mode[$m]}): row ${r} still PASSES: the check does not catch this mutation" + fi +done +release_flag +if [[ "${mut_fail}" != 0 || -n "${AIENOS_QEMU_VERBOSE:-}" ]]; then + for s in "${top}"/*/serial.txt; do + echo "---- serial console $(basename "$(dirname "${s}")") (device lines) ----" + grep -E '^(WARNING|keyboard|xhci|xhci_pci|dma_sweep|dma_gate|smmu|devices:|report_kind:)' "${s}" | head -60 || true + done +fi +if [[ "${mut_fail}" == 0 ]]; then echo "${final_tag}: PASS (bm-left-on->27 no-revoke->31 grant-no-smmu->28 no-sweep->26)"; exit 0; fi +echo "${final_tag}: FAIL" +exit 1 ```