aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
GitHub aien-dev/aienux#344 (code only)
Apply it
git checkout -b patch-2b921e813914bb51 5135477b491cffa8254fd2b62c02f46d3da81317 curl -fsSL https://interplane.io/drakestapleton/aienux/patches/2b921e813914bb51.patch | git am
Provenance
github-import 1
aien-dev/aienux
344
70970f57b33b6b3306bbe20d572ee4a6ca96d079
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":344,"url":"https://github.com/aien-dev/aienux/pull/344","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:14Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/.crumb b/.crumb index 1d416af4..9d5ba03c 100644 --- a/.crumb +++ b/.crumb @@ -33,27 +33,27 @@ "purpose": "Directory docs. Purpose not yet described by a human." }, { - "digest": "14abb7c618d5192662cfd3248161b7bb356c5b304611ff1d034c905f95e5d3c0", - "last_commit": "391fcd5", + "digest": "8303b3b9cfae4adb60d22cb79949b0152c95efd960b344371789b3ccf9ad018c", + "last_commit": "1994c4f", "name": "native", "purpose": "Directory native. Purpose not yet described by a human." }, { - "digest": "b0f4248c62a868c7b516d0a639ca2ecd1b1a5c0a4c732d64ad102749c8dfdd7b", - "last_commit": "391fcd5", + "digest": "80f03d413b7d49f38058ecbb8c712c6889dab80c227cf9f22999eaa885183abb", + "last_commit": "1994c4f", "name": "scripts", "purpose": "Directory scripts. Purpose not yet described by a human." } ], - "children_root": "sha256:fc2a422de557ffcd776711b98718080981836d9c43b5c2e209604ead08a49ad3", - "compiled_at": "2026-10-13T04:45:02Z", + "children_root": "sha256:d9b73eb821200bc7d967a967e0c3cc6702a15909a37d5e8ae02563569e6e6841", + "compiled_at": "2026-10-13T05:44:11Z", "compiler": "crumb-compile/1", - "digest": "sha256:2eac9ae595eba28a9f52f9d8efb615c63ce03951b245ecf07b6b0dcc73c0685c", + "digest": "sha256:06efc6bb5bbab7c5628162b2eb2daea545c4a3eb86d54b286597f4dea67d8197", "evidence_files": 156, "evidence_root": "sha256:cd53ab119be9de6ce28c4f5949b106c9622f1fe105611de3de21c3bce7932694", - "files": 3119, - "generated_at_commit": "391fcd54707b2ba006e0652c71259a17ef78ec6a", - "source_tree": "sha256:2776a1b24ed444cb4cab16e0376a23124e6ff067d135c441683042f84eee9e0e" + "files": 3124, + "generated_at_commit": "1994c4f8c4e8521d7febed45306515aa5085f207", + "source_tree": "sha256:1c9bf521ea3d699d57e9f1633a2adbeb59497b6adb6ee86b86f4b24ba25ee10b" }, "owner_lane": "", "provenance": { diff --git a/.github/workflows/native-suites.yml b/.github/workflows/native-suites.yml index 9fa36806..d712012d 100644 --- a/.github/workflows/native-suites.yml +++ b/.github/workflows/native-suites.yml @@ -14,8 +14,8 @@ # native/crypto test sanitize mutants this file # native/m5 test sanitize mutants this file # native/disk test sanitize mutants this file -# native/disk/qemu bare-metal NVMe payload under QEMU this file (QEMU is an -# emulator: PASS says nothing about a physical controller) +# native/disk/qemu bare-metal NVMe and SDHCI payloads under QEMU this file +# (QEMU is an emulator: PASS says nothing about a physical controller) # native/argus test sanitize this file # # SKIP list (declared, never green): @@ -36,6 +36,7 @@ on: - "native/**" - ".github/workflows/native-suites.yml" - "scripts/qemu_native_nvme_test.sh" + - "scripts/qemu_native_sdhci_test.sh" - "scripts/lib_gate_hold.sh" - "scripts/cap_abi_isolation_test.sh" - "crates/aienos-capability/**" @@ -145,7 +146,7 @@ jobs: grep -qx 'AIENOS_CAP_ABI_ISOLATION: PASS' abi.log disk-qemu: - name: native/disk qemu NVMe payload + name: native/disk qemu NVMe and SDHCI payloads runs-on: ubuntu-latest steps: - name: Checkout repository @@ -166,6 +167,15 @@ jobs: # The script exits 0 on NOT_RUN; only an explicit PASS counts. grep -qx 'AIENOS_STORE_NVME_QEMU: PASS' qemu.log + - name: Run QEMU SDHCI gate + env: + AIENOS_QUIET_FLAG: ${{ runner.temp }}/aienos-quiet-flag + AIENOS_GATE_LOCK: ${{ runner.temp }}/aienos-gate-lock + run: | + bash scripts/qemu_native_sdhci_test.sh 2>&1 | tee sdhci.log + # The script exits 0 on NOT_RUN; only an explicit PASS counts. + grep -qx 'AIENOS_DISK_SDHCI_QEMU: PASS' sdhci.log + argus-mutants: name: "native/argus mutants (SKIP: no mutants target in argus Makefile)" if: ${{ false }} diff --git a/native/.crumb b/native/.crumb index 1edf029f..3921b65a 100644 --- a/native/.crumb +++ b/native/.crumb @@ -73,14 +73,14 @@ "purpose": "Directory native/crypto. Purpose not yet described by a human." }, { - "digest": "31584482d53c2b82d89a44a8a12f67c7f808f740d95ad5ad050b58bcca6b47aa", - "last_commit": "2f9b95a", + "digest": "3508a201e84c9e6a53160c5c46395f17c376b0c460b3b81049803505876d4f07", + "last_commit": "1994c4f", "name": "disk", "purpose": "Directory native/disk. Purpose not yet described by a human." }, { "digest": "d42b02fe5930b1f65af466ecded139a8c4562a28ffcad4dc3e7481407894e13f", - "last_commit": "391fcd5", + "last_commit": "5135477", "name": "kernel", "purpose": "Directory native/kernel. Purpose not yet described by a human." }, @@ -109,15 +109,15 @@ "purpose": "Directory native/store. Purpose not yet described by a human." } ], - "children_root": "sha256:f81941d430e2ccb2a33a6d7bc6a68c57d864a45ab5427651bf543fb481f9e815", - "compiled_at": "2026-10-13T04:45:02Z", + "children_root": "sha256:311c1318e0867234ac0abe5ffc9455512707db230661932847feaa6255047129", + "compiled_at": "2026-10-13T05:44:11Z", "compiler": "crumb-compile/1", - "digest": "sha256:14abb7c618d5192662cfd3248161b7bb356c5b304611ff1d034c905f95e5d3c0", + "digest": "sha256:8303b3b9cfae4adb60d22cb79949b0152c95efd960b344371789b3ccf9ad018c", "evidence_files": 4, "evidence_root": "sha256:e410b845507e00568e15b51a5797af32a97e0e4b8ab4e8487bb7c98e7e0cf335", - "files": 489, - "generated_at_commit": "391fcd54707b2ba006e0652c71259a17ef78ec6a", - "source_tree": "sha256:f7ea589aa7b49f381e29dfaaf8500f601f6dc9457ffba18d57711c9e1524eeec" + "files": 493, + "generated_at_commit": "1994c4f8c4e8521d7febed45306515aa5085f207", + "source_tree": "sha256:ef584641d7c2b4c17ddf556295cb7d602eedc0bc1c45009f0566fe26dfd3352c" }, "owner_lane": "", "provenance": { diff --git a/native/disk/.crumb b/native/disk/.crumb index 3c070fea..25dc25bd 100644 --- a/native/disk/.crumb +++ b/native/disk/.crumb @@ -17,27 +17,27 @@ "generated": { "children": [ { - "digest": "ab636ddf6d518b35c2ebfbce3c32533aef415f32e676dfaa68b8fb4c2fe56603", - "last_commit": "950cc4c", + "digest": "54a25a2ce38d5cde54cce87582dfdcd66b3f21ba3ae18d330c8c66a7004b386a", + "last_commit": "1994c4f", "name": "qemu", "purpose": "Directory native/disk/qemu. Purpose not yet described by a human." }, { - "digest": "69c1958da6a4fb466d80bc8a4debe13b98ebf93913bc4cd08b4fa23cea900882", - "last_commit": "950cc4c", + "digest": "28bc8b4021cec8ccd5b90c15d11db3fe7dd396db65e062f5e1046631fa2e4755", + "last_commit": "1994c4f", "name": "tests", "purpose": "Directory native/disk/tests. Purpose not yet described by a human." } ], - "children_root": "sha256:1bd311046010486cd77dbaded82dd3df67ba171ef7df710da29ba89adf34e014", - "compiled_at": "2026-10-04T13:47:18Z", + "children_root": "sha256:fb9a25a745be4f0d38936d5ff30f3fafdc68a80d6aaeff667fde54d196d6b132", + "compiled_at": "2026-10-13T05:44:11Z", "compiler": "crumb-compile/1", - "digest": "sha256:31584482d53c2b82d89a44a8a12f67c7f808f740d95ad5ad050b58bcca6b47aa", + "digest": "sha256:3508a201e84c9e6a53160c5c46395f17c376b0c460b3b81049803505876d4f07", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 16, - "generated_at_commit": "a863d5c1f5bd89c88c5f6671eecfd27b599ee512", - "source_tree": "sha256:568f057e4d25f423ff84eb76da336b6415b6a8e3cf1a1528f3cf857747bd1955" + "files": 20, + "generated_at_commit": "1994c4f8c4e8521d7febed45306515aa5085f207", + "source_tree": "sha256:5aacdfa45187fd64a3b11a63ea0baa0a1445461e674422908bfc6ae1b8dbd9d7" }, "owner_lane": "", "provenance": { diff --git a/native/disk/Makefile b/native/disk/Makefile index a672dfd2..f58a500d 100644 --- a/native/disk/Makefile +++ b/native/disk/Makefile @@ -1,17 +1,18 @@ # AIENOS native disk layer in C: disk_dev core (bounds, split, ordered queue), # hosted file backend for tests, and a freestanding polled NVMe driver -# (disk_nvme.c) ported from the audited Rust path. No outside library. -# Library objects (disk.c, disk_nvme.c) import no libc symbols at all; the +# (disk_nvme.c) ported from the audited Rust path, and a polled PIO SD Host +# Controller driver (disk_sdhci.c) for the Pi 5 microSD. No outside library. +# Library objects (disk.c, disk_nvme.c, disk_sdhci.c) import no libc symbols at all; the # file backend and the tests use hosted libc. # # make build out/libaienos_disk.a (+ out/disk_file.o, hosted) -# make test disk core + file backend + NVMe driver vs software model +# make test disk core + file backend + NVMe and SDHCI drivers vs software models # make freestanding build library objects -ffreestanding; nm -u must be empty # make sanitize the same tests under ASan+UBSan (Linux) # make mutants delete each GUARD-tagged check in turn; tests must fail # make clean # -# Host tests and the NVMe model are not QEMU and not hardware. +# Host tests and the NVMe and SDHCI models are not QEMU and not hardware. CC ?= cc AR ?= ar @@ -28,13 +29,14 @@ endif OUT ?= out MUTANT_TIMEOUT ?= 60 -SRCS = disk.c disk_nvme.c +SRCS = disk.c disk_nvme.c disk_sdhci.c OBJS = $(SRCS:%.c=$(OUT)/%.o) FILE_OBJ = $(OUT)/disk_file.o LIB = $(OUT)/libaienos_disk.a -HDRS = disk.h disk_nvme.h disk_file.h +HDRS = disk.h disk_nvme.h disk_sdhci.h disk_file.h DTEST = $(OUT)/disk_test NTEST = $(OUT)/nvme_test +STEST = $(OUT)/sdhci_test SANFLAGS = -fsanitize=address,undefined -fno-omit-frame-pointer -fno-sanitize-recover=all -g all: $(LIB) $(FILE_OBJ) @@ -55,9 +57,12 @@ $(DTEST): tests/disk_test.c $(LIB) $(FILE_OBJ) $(HDRS) $(NTEST): tests/nvme_test.c $(LIB) $(HDRS) $(CC) $(CFLAGS) -o $@ tests/nvme_test.c $(LIB) -test: $(DTEST) $(NTEST) lib-checks +$(STEST): tests/sdhci_test.c $(LIB) $(HDRS) + $(CC) $(CFLAGS) -o $@ tests/sdhci_test.c $(LIB) + +test: $(DTEST) $(NTEST) $(STEST) lib-checks @rm -rf $(OUT)/scratch && mkdir -p $(OUT)/scratch; \ - rc=0; ./$(DTEST) $(OUT)/scratch || rc=1; ./$(NTEST) || rc=1; \ + rc=0; ./$(DTEST) $(OUT)/scratch || rc=1; ./$(NTEST) || rc=1; ./$(STEST) > $(OUT)/sdhci_test.log 2>&1 && tail -1 $(OUT)/sdhci_test.log || { cat $(OUT)/sdhci_test.log; rc=1; }; \ if [ $$rc -eq 0 ]; then echo "AIENOS_DISK_NATIVE: PASS"; else echo "AIENOS_DISK_NATIVE: FAIL"; exit 1; fi # The library objects must not allocate, read a clock, or do their own I/O. @@ -71,7 +76,8 @@ freestanding: | $(OUT) @mkdir -p $(OUT)/free $(CC) $(FREEFLAGS) -c -o $(OUT)/free/disk.o disk.c $(CC) $(FREEFLAGS) -c -o $(OUT)/free/disk_nvme.o disk_nvme.c - $(LD) -r -o $(OUT)/free/disk_all.o $(OUT)/free/disk.o $(OUT)/free/disk_nvme.o + $(CC) $(FREEFLAGS) -c -o $(OUT)/free/disk_sdhci.o disk_sdhci.c + $(LD) -r -o $(OUT)/free/disk_all.o $(OUT)/free/disk.o $(OUT)/free/disk_nvme.o $(OUT)/free/disk_sdhci.o @u=$$($(NM) -u $(OUT)/free/disk_all.o | awk 'NF==2 {print $$2}'); \ if [ -n "$$u" ]; then echo "freestanding FAIL: undefined symbols: $$u"; echo "AIENOS_DISK_FREESTANDING: FAIL"; exit 1; fi; \ echo "nm -u: (empty)"; echo "AIENOS_DISK_FREESTANDING: PASS" @@ -80,15 +86,17 @@ sanitize: | $(OUT) ifeq ($(shell uname -s),Linux) $(CC) $(CFLAGS) $(SANFLAGS) -o $(OUT)/disk_test_asan tests/disk_test.c disk_file.c $(SRCS) $(CC) $(CFLAGS) $(SANFLAGS) -o $(OUT)/nvme_test_asan tests/nvme_test.c $(SRCS) + $(CC) $(CFLAGS) $(SANFLAGS) -o $(OUT)/sdhci_test_asan tests/sdhci_test.c $(SRCS) @rm -rf $(OUT)/scratch_asan && mkdir -p $(OUT)/scratch_asan ASAN_OPTIONS=detect_leaks=1 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 ./$(OUT)/disk_test_asan $(OUT)/scratch_asan ASAN_OPTIONS=detect_leaks=1 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 ./$(OUT)/nvme_test_asan + ASAN_OPTIONS=detect_leaks=1 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 ./$(OUT)/sdhci_test_asan > $(OUT)/sdhci_asan.log 2>&1 || { cat $(OUT)/sdhci_asan.log; exit 1; } @echo "AIENOS_DISK_SANITIZE: PASS" else @echo "sanitize: Linux only" endif -# Mutants: delete each GUARD-tagged line in turn. Both test programs run +# Mutants: delete each GUARD-tagged line in turn. All three test programs run # against the mutant (under a timeout: deleting a poll bound can hang) and # at least one must fail, crash or time out. GUARDS = disk-zero disk-lba disk-end queue-bound queue-failstop \ @@ -96,7 +104,10 @@ GUARDS = disk-zero disk-lba disk-end queue-bound queue-failstop \ nvme-cfs-ready nvme-ready-bound nvme-cfs-cmd nvme-cmd-bound nvme-cid nvme-sqid \ nvme-sqes nvme-cqes nvme-nsid nvme-nsze nvme-flbas nvme-meta nvme-lbads \ nvme-failstop nvme-xfer nvme-range \ - prp-len-wrap prp-addr-wrap prp-list-cap atomic-unit atomic-boundary + prp-len-wrap prp-addr-wrap prp-list-cap atomic-unit atomic-boundary \ + sdhci-err-int sdhci-inhibit sdhci-r1 sdhci-ver sdhci-reset sdhci-volt sdhci-clock0 \ + sdhci-nocard sdhci-cmd8 sdhci-acmd41-bound sdhci-csd-zero sdhci-ready sdhci-range \ + sdhci-tran sdhci-failstop mutants: | $(OUT) @ulimit -c 0; fail=0; n=0; k=0; for g in $(GUARDS); do \ @@ -107,11 +118,13 @@ mutants: | $(OUT) d=$(OUT)/mut_$$g; rm -rf $$d; mkdir -p $$d/scratch; \ for s in $(SRCS); do if [ $$s = $$f ]; then sed "/GUARD:$$g \*\//d" $$s > $$d/$$s; else cp $$s $$d/$$s; fi; done; \ if cmp -s $$f $$d/$$f; then echo "mutant $$g: sed changed nothing (FAIL)"; fail=1; continue; fi; \ - $(CC) $(CFLAGS) -Wno-error -I. -o $$d/dt tests/disk_test.c disk_file.c $$d/disk.c $$d/disk_nvme.c 2> $$d/cc.log \ - && $(CC) $(CFLAGS) -Wno-error -I. -o $$d/nt tests/nvme_test.c $$d/disk.c $$d/disk_nvme.c 2>> $$d/cc.log \ + $(CC) $(CFLAGS) -Wno-error -I. -o $$d/dt tests/disk_test.c disk_file.c $$d/disk.c $$d/disk_nvme.c $$d/disk_sdhci.c 2> $$d/cc.log \ + && $(CC) $(CFLAGS) -Wno-error -I. -o $$d/nt tests/nvme_test.c $$d/disk.c $$d/disk_nvme.c $$d/disk_sdhci.c 2>> $$d/cc.log \ + && $(CC) $(CFLAGS) -Wno-error -I. -o $$d/st tests/sdhci_test.c $$d/disk.c $$d/disk_nvme.c $$d/disk_sdhci.c 2>> $$d/cc.log \ || { echo "mutant $$g: does not compile (FAIL)"; fail=1; continue; }; \ if timeout $(MUTANT_TIMEOUT) ./$$d/dt $$d/scratch > $$d/run.log 2>&1 && \ - timeout $(MUTANT_TIMEOUT) ./$$d/nt >> $$d/run.log 2>&1; then \ + timeout $(MUTANT_TIMEOUT) ./$$d/nt >> $$d/run.log 2>&1 && \ + timeout $(MUTANT_TIMEOUT) ./$$d/st >> $$d/run.log 2>&1; then \ echo "mutant $$g: SURVIVED (FAIL)"; fail=1; \ else echo "mutant $$g: killed"; k=$$((k+1)); fi; \ done; \ diff --git a/native/disk/README.md b/native/disk/README.md index 6faaff54..8e57d628 100644 --- a/native/disk/README.md +++ b/native/disk/README.md @@ -9,21 +9,30 @@ `crates/aienos-kernel/src/nvme*.rs` and `docs/P3_NVME_*.md`. It does not use libc or a heap. Platform access goes through `nvme_ops`, and DMA goes through one caller region carved into fixed pages plus a bounce buffer. -- `qemu/`: bare-metal AArch64 payload that runs the driver against QEMU's - emulated NVMe (`scripts/qemu_native_nvme_test.sh`). `STORE_OBJS=` links +- `disk_sdhci.h` / `disk_sdhci.c`: freestanding polled SD Host Controller + driver for the Raspberry Pi 5 microSD slot (BCM2712 `brcm,bcm2712-sdhci`, + a standard SDHCI). PIO only: no DMA, no heap, no libc, aligned 32-bit + register access only. SD 2.0+ cards (SDSC and SDHC/SDXC), 3.3 V, 25 MHz + default speed, 1- or 4-bit bus. +- `qemu/`: bare-metal AArch64 payloads that run the NVMe driver against + QEMU's emulated NVMe (`scripts/qemu_native_nvme_test.sh`) and the SD + driver against QEMU's `sdhci-pci` + `sd-card` + (`scripts/qemu_native_sdhci_test.sh`: spec 2.00 with a 64 MiB SDSC card, + spec 3.00 with a 4 GiB SDHC card). `STORE_OBJS=` links extra objects (for example native/store) later. ``` -make # out/libaienos_disk.a (disk.c, disk_nvme.c) + out/disk_file.o +make # out/libaienos_disk.a (disk.c, disk_nvme.c, disk_sdhci.c) + out/disk_file.o make test # last line: AIENOS_DISK_NATIVE: PASS make freestanding # nm -u of the linked library objects must be empty make sanitize # ASan + UBSan make mutants # each GUARD line deleted in turn; AIENOS_DISK_MUTANTS: PASS ``` -Host tests run against a software NVMe controller model written in -`tests/nvme_test.c`. QEMU runs against QEMU's NVMe model. Neither one -qualifies any physical controller. +Host tests run against software NVMe and SDHCI + SD card models written in +`tests/nvme_test.c` and `tests/sdhci_test.c`. QEMU runs against QEMU's +models. None of them qualifies any physical controller; the Pi 5 run is +separate evidence. ## Unsafe assumptions: what is now checked @@ -65,3 +74,32 @@ queue stays usable. test_atomicity covers that case. - The Rust readiness loop sleeps one more step than CAP.TO allows. The C port stops at exactly TO x 500 ms. + +## SD host driver: what is checked + +Each check below is a GUARD line that `make mutants` deletes; a test in +`tests/sdhci_test.c` fails for every one. The software model also flags any +command issued while CMD/DATA inhibit is set, any data command while the card +is still programming, a wrong response type, a wrong address mode (byte for +SDSC, block for SDHC), and any unaligned or out-of-window register access. + +| Check (mutant) | Error | +|---|---| +| any error bit in INT_STATUS ends the wait (sdhci-err-int) | SDHCI_ECMD / SDHCI_EDATA | +| command line (and data line for data/busy commands) idle before issue (sdhci-inhibit) | SDHCI_ETIMEOUT | +| R1 card-status error bits 0xfdf98008 (sdhci-r1) | SDHCI_ESTATUS | +| HOST_VERSION spec 2.00 or later (sdhci-ver) | SDHCI_EVER | +| software reset clears within 100 ms (sdhci-reset) | SDHCI_ERESET | +| controller supports 3.3 V (sdhci-volt) | SDHCI_EVOLT | +| a base clock, from CAPABILITIES or the caller (sdhci-clock0) | SDHCI_ECLOCK | +| card present (sdhci-nocard) | SDHCI_ENOCARD | +| CMD8 echo 0x1aa: SD 2.0+ cards only (sdhci-cmd8) | SDHCI_ECARD | +| ACMD41 power-up bounded to 100 polls (sdhci-acmd41-bound) | SDHCI_ETIMEOUT | +| CSD capacity non-zero (sdhci-csd-zero) | SDHCI_ECSD | +| no I/O after a failure until init runs again (sdhci-ready, sdhci-failstop) | DISK_ESTATE | +| lba/count inside the card, refused before any command (sdhci-range) | DISK_ERANGE | +| after a write, CMD13 until the card is back in transfer state (sdhci-tran) | SDHCI_ETIMEOUT | + +Not done yet: high-speed (50 MHz) and UHS modes, 1.8 V signalling, ADMA, card +removal while running, and the Pi 5 binding (base address and base clock come +from the ACPI tables dumped by AIENOS-PI5-ACPI-0). diff --git a/native/disk/disk.h b/native/disk/disk.h index 015f36d4..7e77df5b 100644 --- a/native/disk/disk.h +++ b/native/disk/disk.h @@ -7,6 +7,8 @@ * into a freestanding image), with power-cut injection. * disk_nvme.c freestanding NVMe driver ported from the audited Rust path * (crates/aienos-kernel/src/nvme*, docs/P3_NVME_*.md). No libc. + * disk_sdhci.c freestanding polled PIO SD Host Controller driver (Pi 5 + * microSD). No libc, no DMA. * * Geometry. The interface sector is 512 bytes (DISK_SECTOR_BYTES). A backend * reports its logical block size (512 or 4096); lba and count are in logical diff --git a/native/disk/disk_sdhci.c b/native/disk/disk_sdhci.c new file mode 100644 index 00000000..155b7872 --- /dev/null +++ b/native/disk/disk_sdhci.c @@ -0,0 +1,418 @@ +/* disk_sdhci.c -- AIENOS freestanding SD card driver over SDHCI; see + * disk_sdhci.h for the contract, sources and refusals. No libc. */ +#include "disk_sdhci.h" + +/* PRESENT_STATE */ +#define PS_CMD_INHIBIT 0x00000001u +#define PS_DATA_INHIBIT 0x00000002u +#define PS_CARD_PRESENT 0x00010000u +/* INT_STATUS */ +#define INT_CMD_DONE 0x00000001u +#define INT_XFER_DONE 0x00000002u +#define INT_BUF_WR 0x00000010u +#define INT_BUF_RD 0x00000020u +#define INT_ERROR 0x00008000u +#define INT_ERR_MASK 0xffff8000u +/* COMMAND (upper half of the 0x0C word) */ +#define CMD_RESP_NONE 0x00u +#define CMD_RESP_LONG 0x01u +#define CMD_RESP_SHORT 0x02u +#define CMD_RESP_BUSY 0x03u +#define CMD_CRC 0x08u +#define CMD_INDEX 0x10u +#define CMD_DATA 0x20u +/* TRANSFER_MODE (lower half of the 0x0C word) */ +#define TM_BLK_CNT_EN 0x02u +#define TM_AUTO_CMD12 0x04u +#define TM_READ 0x10u +#define TM_MULTI 0x20u +/* CLOCK word at 0x2C */ +#define CLK_INT_EN 0x0001u +#define CLK_INT_STABLE 0x0002u +#define CLK_CARD_EN 0x0004u +#define RST_ALL (1u << 24) +#define RST_CMD (1u << 25) +#define RST_DATA (1u << 26) +/* HOST word at 0x28 */ +#define HOST_4BIT 0x02u +#define PWR_330 (0x0eu << 8) +#define PWR_ON (0x01u << 8) + +/* Response kinds (SD Physical Layer 4.9). */ +enum { R_NONE, R1, R1B, R2, R3, R6, R7 }; + +/* R1 card status error bits: OUT_OF_RANGE..WP_VIOLATION (31:26), + * LOCK_UNLOCK_FAILED (24), COM_CRC_ERROR..ERROR (23:19), CSD_OVERWRITE (16), + * WP_ERASE_SKIP (15), AKE_SEQ_ERROR (3). */ +#define R1_ERRORS 0xfdf98008u +#define R1_READY_FOR_DATA 0x00000100u +#define R1_STATE(s) (((s) >> 9) & 0xfu) +#define STATE_TRAN 4u + +#define BLOCK 512u + +static uint32_t rd(sdhci_card *c, uint32_t off) { return c->ops.r32(c->ops.ctx, off); } +static void wr(sdhci_card *c, uint32_t off, uint32_t v) { c->ops.w32(c->ops.ctx, off, v); } +static void delay(sdhci_card *c, uint32_t us) { c->ops.delay_us(c->ops.ctx, us); } + +static int fail(sdhci_card *c, int cmd, int err) +{ + c->last_cmd = cmd; + c->last_err = err; + return err; +} + +/* Poll until (reg & mask) == want, every 10 us, at most ms milliseconds. */ +static int wait_reg(sdhci_card *c, uint32_t off, uint32_t mask, uint32_t want, uint32_t ms) +{ + for (uint32_t i = 0; i <= ms * 100u; i++) { + if ((rd(c, off) & mask) == want) + return 0; + delay(c, 10); + } + return -1; +} + +/* Software reset of the CMD/DATA lines (bits 25/26 of the 0x2C word). */ +static void line_reset(sdhci_card *c, uint32_t bits) +{ + uint32_t v = rd(c, SDHCI_R_CLOCK); + if (v & (RST_ALL | RST_CMD | RST_DATA)) /* a reset still running: do not re-trigger */ + (void)wait_reg(c, SDHCI_R_CLOCK, RST_ALL | RST_CMD | RST_DATA, 0, 100); + v = rd(c, SDHCI_R_CLOCK) & 0x00ffffffu; + wr(c, SDHCI_R_CLOCK, v | bits); + (void)wait_reg(c, SDHCI_R_CLOCK, bits, 0, 100); +} + +/* Wait for any of `mask` or an error bit in INT_STATUS. 0 ok (the mask bits + * seen are cleared), -1 error bit, -2 timeout. */ +static int wait_int(sdhci_card *c, uint32_t mask, uint32_t ms) +{ + for (uint32_t i = 0; i <= ms * 100u; i++) { + uint32_t s = rd(c, SDHCI_R_INT); + c->last_int = s; + if (s & (INT_ERROR | INT_ERR_MASK)) return -1; /* GUARD:sdhci-err-int */ + if (s & mask) { + wr(c, SDHCI_R_INT, s & mask); + return 0; + } + delay(c, 10); + } + c->last_int = rd(c, SDHCI_R_INT); + return -2; +} + +static uint32_t cmd_flags(int kind) +{ + switch (kind) { + case R1: + case R6: + case R7: + return CMD_RESP_SHORT | CMD_CRC | CMD_INDEX; + case R1B: + return CMD_RESP_BUSY | CMD_CRC | CMD_INDEX; + case R2: + return CMD_RESP_LONG | CMD_CRC; + case R3: + return CMD_RESP_SHORT; + default: + return CMD_RESP_NONE; + } +} + +/* Issue one command; for data commands the caller moves the data and waits + * for transfer complete. resp gets RESPONSE0..3 (long) or RESPONSE0. */ +static int command(sdhci_card *c, uint32_t idx, uint32_t arg, int kind, uint32_t tmode, uint32_t nblocks, + uint32_t resp[4]) +{ + uint32_t ms = c->cfg.timeout_ms; + int data = nblocks != 0; + uint32_t inhibit = PS_CMD_INHIBIT | ((data || kind == R1B) ? PS_DATA_INHIBIT : 0); + if (wait_reg(c, SDHCI_R_PRESENT, inhibit, 0, ms)) return fail(c, (int)idx, SDHCI_ETIMEOUT); /* GUARD:sdhci-inhibit */ + wr(c, SDHCI_R_INT, 0xffffffffu); + if (data) + wr(c, SDHCI_R_BLOCK, BLOCK | (nblocks << 16)); + wr(c, SDHCI_R_ARG, arg); + uint32_t f = cmd_flags(kind) | (data ? CMD_DATA : 0); + wr(c, SDHCI_R_CMD, ((idx << 8 | f) << 16) | tmode); + int w = wait_int(c, INT_CMD_DONE, ms); + if (w) { + line_reset(c, RST_CMD | RST_DATA); + return fail(c, (int)idx, w == -2 ? SDHCI_ETIMEOUT : SDHCI_ECMD); + } + if (resp) { + resp[0] = rd(c, SDHCI_R_RESP0); + if (kind == R2) + for (int i = 1; i < 4; i++) + resp[i] = rd(c, SDHCI_R_RESP0 + 4u * (uint32_t)i); + } + if (kind == R1B && wait_int(c, INT_XFER_DONE, ms)) { /* end of busy */ + line_reset(c, RST_CMD | RST_DATA); + return fail(c, (int)idx, SDHCI_ETIMEOUT); + } + if ((kind == R1 || kind == R1B) && resp && (resp[0] & R1_ERRORS)) return fail(c, (int)idx, SDHCI_ESTATUS); /* GUARD:sdhci-r1 */ + return 0; +} + +static int app_command(sdhci_card *c, uint32_t idx, uint32_t arg, int kind, uint32_t resp[4]) +{ + uint32_t r[4]; + int rc = command(c, 55, (uint32_t)c->rca << 16, R1, 0, 0, r); + if (rc) + return rc; + return command(c, idx, arg, kind, 0, 0, resp); +} + +/* SD clock: <= hz from the base clock. Spec 2.00: power-of-two divisor + * 1..256 (field = divisor / 2); 3.00+: 10-bit N, divisor 2N (N = 0: base). */ +static int set_clock(sdhci_card *c, uint32_t hz) +{ + uint32_t base = c->base_hz, field, actual; + if (c->spec >= 2) { + uint32_t n = base <= hz ? 0 : (base + 2 * hz - 1) / (2 * hz); + if (n > 0x3ff) + return SDHCI_ECLOCK; + actual = n ? base / (2 * n) : base; + field = ((n & 0xff) << 8) | ((n >> 8) & 0x3) << 6; + } else { + uint32_t div = 1; + while (div < 256 && base / div > hz) + div *= 2; + if (base / div > hz) + return SDHCI_ECLOCK; + actual = base / div; + field = (div / 2) << 8; + } + uint32_t v = rd(c, SDHCI_R_CLOCK) & 0xffff0000u; + wr(c, SDHCI_R_CLOCK, v); /* SD clock and internal clock off */ + wr(c, SDHCI_R_CLOCK, v | field | CLK_INT_EN); + if (wait_reg(c, SDHCI_R_CLOCK, CLK_INT_STABLE, CLK_INT_STABLE, 100)) + return SDHCI_ECLOCK; + wr(c, SDHCI_R_CLOCK, v | field | CLK_INT_EN | CLK_CARD_EN); + c->card_hz = actual; + return 0; +} + +/* Bits [hi:lo] of a long response as the controller stores it (R2 bits + * 127:8 in RESPONSE bits 119:0), addressed by register bit position. */ +static uint32_t rbits(const uint32_t r[4], unsigned hi, unsigned lo) +{ + uint32_t v = 0; + for (unsigned b = hi + 1; b-- > lo;) + v = (v << 1) | ((r[b / 32] >> (b % 32)) & 1u); + return v; +} +#define CSD(r, hi, lo) rbits((r), (hi) - 8, (lo) - 8) /* CSD bit numbers (Physical Layer 5.3) */ + +static int card_status(sdhci_card *c, uint32_t *st) +{ + uint32_t r[4]; + int rc = command(c, 13, (uint32_t)c->rca << 16, R1, 0, 0, r); + *st = r[0]; + return rc; +} + +/* After a write: wait until the card left programming (READY_FOR_DATA, tran). */ +static int wait_tran(sdhci_card *c) +{ + for (uint32_t i = 0; i <= c->cfg.timeout_ms; i++) { + uint32_t st = 0; + int rc = card_status(c, &st); + if (rc) + return rc; + if ((st & R1_READY_FOR_DATA) && R1_STATE(st) == STATE_TRAN) + return 0; + delay(c, 1000); + } + return fail(c, 13, SDHCI_ETIMEOUT); +} + +int sdhci_init(sdhci_card *c, const sdhci_ops *ops, const sdhci_cfg *cfg) +{ + if (!c || !ops || !ops->r32 || !ops->w32 || !ops->delay_us || !cfg) + return SDHCI_EARG; + for (uint8_t *p = (uint8_t *)c, *e = p + sizeof *c; p < e; p++) /* no memset: no libc */ + *p = 0; + c->ops = *ops; + c->cfg = *cfg; + c->last_cmd = -1; + if (!c->cfg.timeout_ms) + c->cfg.timeout_ms = 1000; + if (!c->cfg.max_blocks) + c->cfg.max_blocks = 128; + if (c->cfg.max_blocks > 65535) + return fail(c, -1, SDHCI_EARG); + c->spec = (rd(c, SDHCI_R_VERSION) >> 16) & 0xff; + if (c->spec < 1) return fail(c, -1, SDHCI_EVER); /* GUARD:sdhci-ver */ + wr(c, SDHCI_R_CLOCK, (rd(c, SDHCI_R_CLOCK) & 0x00ffffffu) | RST_ALL); + if (wait_reg(c, SDHCI_R_CLOCK, RST_ALL, 0, 100)) return fail(c, -1, SDHCI_ERESET); /* GUARD:sdhci-reset */ + uint32_t cap = rd(c, SDHCI_R_CAP); + if (!(cap & (1u << 24))) return fail(c, -1, SDHCI_EVOLT); /* GUARD:sdhci-volt */ + c->base_hz = c->cfg.base_clock_hz; + if (!c->base_hz) + c->base_hz = ((cap >> 8) & (c->spec >= 2 ? 0xffu : 0x3fu)) * 1000000u; + if (!c->base_hz) return fail(c, -1, SDHCI_ECLOCK); /* GUARD:sdhci-clock0 */ + /* 3.3 V bus power, 1-bit, normal speed. */ + uint32_t host = rd(c, SDHCI_R_HOST) & 0xffff0000u; + wr(c, SDHCI_R_HOST, host | PWR_330); + wr(c, SDHCI_R_HOST, host | PWR_330 | PWR_ON); + delay(c, 10000); + if (wait_reg(c, SDHCI_R_PRESENT, PS_CARD_PRESENT, PS_CARD_PRESENT, 100)) return fail(c, -1, SDHCI_ENOCARD); /* GUARD:sdhci-nocard */ + wr(c, SDHCI_R_INT_EN, INT_ERR_MASK | INT_BUF_RD | INT_BUF_WR | INT_XFER_DONE | INT_CMD_DONE); + wr(c, SDHCI_R_SIG_EN, 0); + wr(c, SDHCI_R_CLOCK, (rd(c, SDHCI_R_CLOCK) & 0x0000ffffu) | (0x0eu << 16)); /* data timeout: max */ + if (set_clock(c, 400000)) + return fail(c, -1, SDHCI_ECLOCK); + delay(c, 1000); /* >= 74 clocks before CMD0 */ + + uint32_t r[4] = { 0 }; + int rc = command(c, 0, 0, R_NONE, 0, 0, 0); + if (rc) + return rc; + if (command(c, 8, 0x1aa, R7, 0, 0, r) || (r[0] & 0xfff) != 0x1aa) return fail(c, 8, SDHCI_ECARD); /* GUARD:sdhci-cmd8 */ + for (uint32_t i = 0;; i++) { + rc = app_command(c, 41, 0x40ff8000u, R3, r); /* HCS, 2.7-3.6 V */ + if (rc) + return rc; + if (r[0] & 0x80000000u) + break; + if (i >= 100) return fail(c, 41, SDHCI_ETIMEOUT); /* GUARD:sdhci-acmd41-bound */ + delay(c, 10000); + } + c->high_capacity = (r[0] >> 30) & 1; + if ((rc = command(c, 2, 0, R2, 0, 0, c->cid))) + return rc; + if ((rc = command(c, 3, 0, R6, 0, 0, r))) + return rc; + c->rca = (uint16_t)(r[0] >> 16); + if ((rc = command(c, 9, (uint32_t)c->rca << 16, R2, 0, 0, c->csd))) + return rc; + uint32_t structure = CSD(c->csd, 127, 126); + if (structure == 1) { + c->blocks = ((uint64_t)CSD(c->csd, 69, 48) + 1) * 1024u; + } else if (structure == 0 && !c->high_capacity) { + uint64_t bytes = ((uint64_t)CSD(c->csd, 73, 62) + 1) << (CSD(c->csd, 49, 47) + 2) << CSD(c->csd, 83, 80); + c->blocks = bytes / BLOCK; + } else { + return fail(c, 9, SDHCI_ECSD); + } + if (!c->blocks) return fail(c, 9, SDHCI_ECSD); /* GUARD:sdhci-csd-zero */ + if (set_clock(c, 25000000)) + return fail(c, -1, SDHCI_ECLOCK); + if ((rc = command(c, 7, (uint32_t)c->rca << 16, R1B, 0, 0, r))) + return rc; + if (c->cfg.bus_4bit) { + if ((rc = app_command(c, 6, 2, R1, r))) + return rc; + wr(c, SDHCI_R_HOST, rd(c, SDHCI_R_HOST) | HOST_4BIT); + } + if (!c->high_capacity && (rc = command(c, 16, BLOCK, R1, 0, 0, r))) + return rc; + c->dev.ctx = c; + c->dev.block_size = BLOCK; + c->dev.block_count = c->blocks; + c->dev.read = sdhci_read; + c->dev.write = sdhci_write; + c->dev.flush = sdhci_flush; + c->dev.max_blocks_per_io = c->cfg.max_blocks; + c->ready = 1; + return 0; +} + +static int transfer(sdhci_card *c, uint64_t lba, uint32_t count, uint8_t *buf, int is_read) +{ + if (!c || !buf || !count || count > c->cfg.max_blocks) + return DISK_EARG; + if (!c->ready) return DISK_ESTATE; /* GUARD:sdhci-ready */ + if (lba >= c->blocks || count > c->blocks - lba) return DISK_ERANGE; /* GUARD:sdhci-range */ + uint64_t addr = c->high_capacity ? lba : lba * BLOCK; + if (addr > 0xffffffffu) + return DISK_ERANGE; + uint32_t idx, tm = is_read ? TM_READ : 0; + if (count == 1) { + idx = is_read ? 17 : 24; + } else { + idx = is_read ? 18 : 25; + tm |= TM_BLK_CNT_EN | TM_MULTI | TM_AUTO_CMD12; + } + uint32_t r[4]; + int rc = command(c, idx, (uint32_t)addr, R1, tm, count, r); + for (uint32_t b = 0; !rc && b < count; b++) { + int w = wait_int(c, is_read ? INT_BUF_RD : INT_BUF_WR, c->cfg.timeout_ms); + if (w) { + rc = fail(c, (int)idx, w == -2 ? SDHCI_ETIMEOUT : SDHCI_EDATA); + break; + } + uint8_t *p = buf + (uint64_t)b * BLOCK; + for (uint32_t i = 0; i < BLOCK; i += 4) { + if (is_read) { + uint32_t v = rd(c, SDHCI_R_BUF); + p[i] = (uint8_t)v; + p[i + 1] = (uint8_t)(v >> 8); + p[i + 2] = (uint8_t)(v >> 16); + p[i + 3] = (uint8_t)(v >> 24); + } else { + wr(c, SDHCI_R_BUF, (uint32_t)p[i] | (uint32_t)p[i + 1] << 8 | (uint32_t)p[i + 2] << 16 | + (uint32_t)p[i + 3] << 24); + } + } + } + if (!rc) { + int w = wait_int(c, INT_XFER_DONE, c->cfg.timeout_ms); + if (w) + rc = fail(c, (int)idx, w == -2 ? SDHCI_ETIMEOUT : SDHCI_EDATA); + } + if (!rc && !is_read) rc = wait_tran(c); /* GUARD:sdhci-tran */ + if (rc) { + line_reset(c, RST_CMD | RST_DATA); + c->ready = 0; /* fail closed: the Store sees DISK_ESTATE from now on */ /* GUARD:sdhci-failstop */ + return DISK_EIO; + } + return DISK_OK; +} + +int sdhci_read(void *ctx, uint64_t lba, uint32_t count, uint8_t *buf) +{ + return transfer(ctx, lba, count, buf, 1); +} + +int sdhci_write(void *ctx, uint64_t lba, uint32_t count, const uint8_t *buf) +{ + return transfer(ctx, lba, count, (uint8_t *)buf, 0); +} + +int sdhci_flush(void *ctx) +{ + sdhci_card *c = ctx; + if (!c) + return DISK_EARG; + if (!c->ready) + return DISK_ESTATE; + uint32_t st = 0; + if (card_status(c, &st) || !(st & R1_READY_FOR_DATA) || R1_STATE(st) != STATE_TRAN) { + c->ready = 0; + return DISK_EIO; + } + return DISK_OK; +} + +const char *sdhci_strerror(int rc) +{ + switch (rc) { + case SDHCI_OK: return "ok"; + case SDHCI_EARG: return "bad argument"; + case SDHCI_EVER: return "controller spec 1.00 unsupported"; + case SDHCI_ERESET: return "software reset did not clear"; + case SDHCI_ENOCARD: return "no card present"; + case SDHCI_EVOLT: return "no 3.3 V support"; + case SDHCI_ECLOCK: return "clock: no base clock, divider out of range, or not stable"; + case SDHCI_ECARD: return "CMD8 failed: not a physical layer 2.00+ card"; + case SDHCI_ETIMEOUT: return "timeout"; + case SDHCI_ECSD: return "CSD unsupported"; + case SDHCI_ECMD: return "command error interrupt"; + case SDHCI_EDATA: return "data error interrupt"; + case SDHCI_ESTATUS: return "card status error bits"; + case SDHCI_ESTATE: return "card not ready (failed closed)"; + default: return "unknown"; + } +} diff --git a/native/disk/disk_sdhci.h b/native/disk/disk_sdhci.h new file mode 100644 index 00000000..bcfbe156 --- /dev/null +++ b/native/disk/disk_sdhci.h @@ -0,0 +1,125 @@ +/* + * disk_sdhci.h -- AIENOS freestanding SD card driver over an SD Host + * Controller (SDHCI) (C, no libc, no heap). Raspberry Pi 5 microSD slot + * (Broadcom brcm,bcm2712-sdhci, Linux bcm2712.dtsi) and QEMU sdhci-pci. + * + * Polled, programmed I/O only (Buffer Data Port 0x20): no DMA, so the device + * never writes memory and no IOMMU window is needed. One command at a time. + * + * Register map: SD Host Controller Simplified Specification, as Linux + * drivers/mmc/host/sdhci.h names it. Card protocol: SD Physical Layer + * Simplified Specification (CMD0, CMD8, ACMD41, CMD2, CMD3, CMD9, CMD7, ACMD6, + * CMD16, CMD17/18, CMD24/25, CMD12, CMD13). + * + * Every register access is a naturally aligned 32-bit read or write: some + * Broadcom SDHCI blocks refuse 8/16-bit writes, so TRANSFER_MODE+COMMAND + * (0x0C) and BLOCK_SIZE+BLOCK_COUNT (0x04) are written as one word each, and + * the byte registers at 0x28 and 0x2C are updated read-modify-write (never + * while a SOFTWARE_RESET bit is still set). + * + * The caller provides sdhci_ops: 32-bit MMIO read/write at a byte offset from + * the controller base, and a bounded delay in microseconds. + * + * Bring-up (sdhci_init), each refusal its own SDHCI_E* code: + * - HOST_VERSION spec 2.00 or later (1.00 controllers unsupported). EVER + * - SOFTWARE_RESET ALL clears within 100 ms. ERESET + * - a card is present (PRESENT_STATE bit 16) within 100 ms. ENOCARD + * - capabilities offer 3.3 V; bus power is 3.3 V only (no UHS 1.8 V + * signalling, no voltage switch). EVOLT + * - base clock from cfg.base_clock_hz, else CAPABILITIES (bits 13:8 on + * 2.00, 15:8 on 3.00+, MHz); zero from both refuses. ECLOCK + * - identification at <= 400 kHz, then default speed <= 25 MHz (no CMD6 + * high speed), internal clock stable within 100 ms. ECLOCK + * - CMD8 echo 0x1AA (physical layer 2.00+ card; v1 cards refused). ECARD + * - ACMD41 ready within 1 s; CCS selects block addressing (SDHC/SDXC) or + * byte addressing (SDSC, CMD16 sets 512-byte blocks). ETIMEOUT + * - CSD structure 1 (SDHC/SDXC: (C_SIZE + 1) * 1024 blocks) or 0 (SDSC: + * (C_SIZE + 1) * 2^(C_SIZE_MULT + 2) * 2^READ_BL_LEN / 512). ECSD + * - 4-bit bus through ACMD6 when cfg.bus_4bit (else 1-bit). + * Every command: CMD_INHIBIT (and DATA_INHIBIT for data or busy) clear before + * issue; command complete, data ready and transfer complete each bounded + * (cfg.timeout_ms, default 1000 ms); any error interrupt bit fails the command + * (ECMD / EDATA) after CMD and DATA line resets. R1 card status error bits + * (31:19, 13) fail the command too (ESTATUS). + * Writes: transfer complete, then CMD13 until READY_FOR_DATA and state "tran" + * (programming finished). sdhci_flush therefore has nothing in flight; it + * still checks the card is in "tran" and ready. The SD cache (CMD48/49) is + * never enabled, so an acknowledged write is on the card. + */ +#ifndef AIENOS_DISK_SDHCI_H +#define AIENOS_DISK_SDHCI_H +#include <stdint.h> +#include "disk.h" + +typedef struct { + void *ctx; + uint32_t (*r32)(void *ctx, uint32_t off); + void (*w32)(void *ctx, uint32_t off, uint32_t v); + void (*delay_us)(void *ctx, uint32_t us); +} sdhci_ops; + +typedef struct { + uint32_t base_clock_hz; /* 0: from CAPABILITIES */ + uint32_t timeout_ms; /* per command / data phase; 0: 1000 */ + int bus_4bit; /* 1: switch to 4-bit after select */ + uint32_t max_blocks; /* per multi-block transfer, 1..65535; 0: 128 */ +} sdhci_cfg; + +enum { + SDHCI_OK = 0, + SDHCI_EARG = -20, + SDHCI_EVER = -21, + SDHCI_ERESET = -22, + SDHCI_ENOCARD = -23, + SDHCI_EVOLT = -24, + SDHCI_ECLOCK = -25, + SDHCI_ECARD = -26, + SDHCI_ETIMEOUT = -27, + SDHCI_ECSD = -28, + SDHCI_ECMD = -29, + SDHCI_EDATA = -30, + SDHCI_ESTATUS = -31, + SDHCI_ESTATE = -32, +}; + +typedef struct { + sdhci_ops ops; + sdhci_cfg cfg; + int ready; /* init succeeded and no failure since */ + uint32_t spec; /* HOST_VERSION spec field: 1 = 2.00, 2 = 3.00, ... */ + uint32_t base_hz; /* base clock used */ + uint32_t card_hz; /* SD clock after init */ + uint16_t rca; + int high_capacity; /* CCS: block addressing */ + uint64_t blocks; /* 512-byte blocks */ + uint32_t cid[4], csd[4]; + uint32_t last_int; /* INT_STATUS seen by the last failure (diagnostics) */ + int last_cmd; /* command index of the last failure, -1 none */ + int last_err; /* SDHCI_E* of the last failure, 0 none */ + disk_dev dev; +} sdhci_card; + +/* Reset the controller, power and clock it, identify and select the card. + * On success c->dev is a disk_dev (block_size 512) over the whole card. */ +int sdhci_init(sdhci_card *c, const sdhci_ops *ops, const sdhci_cfg *cfg); +/* disk_dev backend entry points (c->dev uses them; ctx is the sdhci_card). */ +int sdhci_read(void *ctx, uint64_t lba, uint32_t count, uint8_t *buf); +int sdhci_write(void *ctx, uint64_t lba, uint32_t count, const uint8_t *buf); +int sdhci_flush(void *ctx); +const char *sdhci_strerror(int rc); + +/* Register offsets and bits used (exported for the software model). */ +#define SDHCI_R_BLOCK 0x04 /* BLOCK_SIZE (15:0) | BLOCK_COUNT (31:16) */ +#define SDHCI_R_ARG 0x08 +#define SDHCI_R_CMD 0x0C /* TRANSFER_MODE (15:0) | COMMAND (31:16) */ +#define SDHCI_R_RESP0 0x10 +#define SDHCI_R_BUF 0x20 +#define SDHCI_R_PRESENT 0x24 +#define SDHCI_R_HOST 0x28 /* HOST_CONTROL 7:0, POWER_CONTROL 15:8 */ +#define SDHCI_R_CLOCK 0x2C /* CLOCK_CONTROL 15:0, TIMEOUT 23:16, SOFTWARE_RESET 31:24 */ +#define SDHCI_R_INT 0x30 +#define SDHCI_R_INT_EN 0x34 +#define SDHCI_R_SIG_EN 0x38 +#define SDHCI_R_CAP 0x40 +#define SDHCI_R_VERSION 0xFC /* HOST_VERSION is bits 31:16 of the word at 0xFC */ +#endif diff --git a/native/disk/qemu/.crumb b/native/disk/qemu/.crumb index 6f03f214..c6819a14 100644 --- a/native/disk/qemu/.crumb +++ b/native/disk/qemu/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-04T13:47:18Z", + "compiled_at": "2026-10-13T05:44:11Z", "compiler": "crumb-compile/1", - "digest": "sha256:ab636ddf6d518b35c2ebfbce3c32533aef415f32e676dfaa68b8fb4c2fe56603", + "digest": "sha256:54a25a2ce38d5cde54cce87582dfdcd66b3f21ba3ae18d330c8c66a7004b386a", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 5, - "generated_at_commit": "a863d5c1f5bd89c88c5f6671eecfd27b599ee512", - "source_tree": "sha256:54043669333efaf1c280f4c443cce59fada8c96b60fb69edf72e673019b3e30e" + "files": 6, + "generated_at_commit": "1994c4f8c4e8521d7febed45306515aa5085f207", + "source_tree": "sha256:4d0fc11e9b44f17aac5aaf0d404e6a384fb933c953e68d948403f563f6a054d4" }, "owner_lane": "", "provenance": { diff --git a/native/disk/qemu/Makefile b/native/disk/qemu/Makefile index d41f2ef4..41042cdf 100644 --- a/native/disk/qemu/Makefile +++ b/native/disk/qemu/Makefile @@ -1,8 +1,10 @@ -# Bare-metal AArch64 payload: the C NVMe driver (../disk_nvme.c, ../disk.c) -# against QEMU's emulated NVMe on the virt machine. Run it with -# scripts/qemu_native_nvme_test.sh. QEMU is not hardware. +# Bare-metal AArch64 payloads: the C NVMe driver (../disk_nvme.c, ../disk.c) +# against QEMU's emulated NVMe, and the C SD host driver (../disk_sdhci.c) +# against QEMU's sdhci-pci + sd-card, on the virt machine. Run them with +# scripts/qemu_native_nvme_test.sh and scripts/qemu_native_sdhci_test.sh. +# QEMU is not hardware. # -# make build out/nvme_payload.elf +# make build out/nvme_payload.elf and out/sdhci_payload.elf # STORE_OBJS=... extra freestanding objects (e.g. native/store) to link in # later; empty by default, nothing here depends on them. @@ -17,8 +19,10 @@ PFLAGS = -std=gnu11 -O2 -Wall -Wextra -Werror -ffreestanding -nostdlib -fno-buil OBJS = $(OUT)/start.o $(OUT)/payload.o $(OUT)/disk.o $(OUT)/disk_nvme.o ELF = $(OUT)/nvme_payload.elf +SOBJS = $(OUT)/start.o $(OUT)/sdhci_payload.o $(OUT)/disk.o $(OUT)/disk_sdhci.o +SELF = $(OUT)/sdhci_payload.elf -all: $(ELF) +all: $(ELF) $(SELF) $(OUT): mkdir -p $(OUT) @@ -27,6 +31,10 @@ $(OUT)/start.o: start.S | $(OUT) $(CC) -c -o $@ $< $(OUT)/payload.o: payload.c ../disk.h ../disk_nvme.h | $(OUT) $(CC) $(PFLAGS) -c -o $@ $< +$(OUT)/sdhci_payload.o: sdhci_payload.c ../disk.h ../disk_sdhci.h | $(OUT) + $(CC) $(PFLAGS) -c -o $@ $< +$(OUT)/disk_sdhci.o: ../disk_sdhci.c ../disk_sdhci.h ../disk.h | $(OUT) + $(CC) $(PFLAGS) -c -o $@ $< $(OUT)/disk.o: ../disk.c ../disk.h | $(OUT) $(CC) $(PFLAGS) -c -o $@ $< $(OUT)/disk_nvme.o: ../disk_nvme.c ../disk_nvme.h ../disk.h | $(OUT) @@ -36,6 +44,10 @@ $(ELF): $(OBJS) $(STORE_OBJS) payload.ld $(LD) -nostdlib -static -T payload.ld -o $@ $(OBJS) $(STORE_OBJS) @u=$$($(NM) -u $@); if [ -n "$$u" ]; then echo "payload has undefined symbols: $$u"; rm -f $@; exit 1; fi +$(SELF): $(SOBJS) payload.ld + $(LD) -nostdlib -static -T payload.ld -o $@ $(SOBJS) + @u=$$($(NM) -u $@); if [ -n "$$u" ]; then echo "payload has undefined symbols: $$u"; rm -f $@; exit 1; fi + clean: rm -rf $(OUT) diff --git a/native/disk/qemu/sdhci_payload.c b/native/disk/qemu/sdhci_payload.c new file mode 100644 index 00000000..37396d6e --- /dev/null +++ b/native/disk/qemu/sdhci_payload.c @@ -0,0 +1,199 @@ +/* + * sdhci_payload.c -- bare-metal AArch64 test of native/disk/disk_sdhci.c + * against QEMU's emulated PCI SD Host Controller (sdhci-pci) and SD card on + * the "virt" machine (highmem=off: PCIe ECAM at 0x3f000000, 32-bit MMIO + * window at 0x10000000). MMU off, so every access is Device-nGnRnE. The + * driver is PIO only: no DMA, no bus mastering. + * + * QEMU is an emulator. A PASS here says the C driver works against QEMU's + * SDHCI and SD card models; it says nothing about the Pi 5's controller. + */ +#include <stdint.h> +#include "../disk.h" +#include "../disk_sdhci.h" + +#define UART 0x09000000ul +#define ECAM 0x3f000000ul +#define MMIO_BASE 0x10000000ul + +static void putc_(char c) +{ + volatile uint32_t *dr = (volatile uint32_t *)UART; + volatile uint32_t *fr = (volatile uint32_t *)(UART + 0x18); + while (*fr & (1u << 5)) + ; + *dr = (uint32_t)(uint8_t)c; +} +static void puts_(const char *s) { while (*s) { if (*s == '\n') putc_('\r'); putc_(*s++); } } +static void putdec(int64_t v) +{ + char b[24]; + int n = 0; + uint64_t u = v < 0 ? (uint64_t)(-v) : (uint64_t)v; + if (v < 0) putc_('-'); + do { b[n++] = (char)('0' + u % 10); u /= 10; } while (u); + while (n) putc_(b[--n]); +} +static void puthex(uint64_t v) +{ + puts_("0x"); + for (int i = 60; i >= 0; i -= 4) putc_("0123456789abcdef"[(v >> i) & 15]); +} + +static int fails, checks; +static void check(int ok, const char *what, int64_t got) +{ + checks++; + if (!ok) { + fails++; + puts_("FAIL: "); + puts_(what); + puts_(" (got "); + putdec(got); + puts_(")\n"); + } +} + +/* ---- platform ops ---- */ +static volatile uint8_t *bar0; +static uint32_t r32(void *c, uint32_t o) { (void)c; return *(volatile uint32_t *)(bar0 + o); } +static void w32(void *c, uint32_t o, uint32_t v) { (void)c; *(volatile uint32_t *)(bar0 + o) = v; } +static uint64_t cntfrq(void) { uint64_t v; __asm__ volatile("mrs %0, cntfrq_el0" : "=r"(v)); return v; } +static uint64_t cntvct(void) { uint64_t v; __asm__ volatile("isb; mrs %0, cntvct_el0" : "=r"(v)); return v; } +static void delay(void *c, uint32_t us) +{ + (void)c; + uint64_t f = cntfrq(), t0 = cntvct(), ticks = (f * us) / 1000000u + 1; + while (cntvct() - t0 < ticks) + ; +} + +/* ---- PCIe: find the SD host controller (class 08 05), assign BAR0, enable MEM ---- */ +static volatile uint32_t *cfg(uint32_t bus, uint32_t dev, uint32_t fn, uint32_t off) +{ + return (volatile uint32_t *)(ECAM + (bus << 20) + (dev << 15) + (fn << 12) + off); +} +static int pci_find_sdhci(void) +{ + for (uint32_t d = 0; d < 32; d++) { + uint32_t id = *cfg(0, d, 0, 0); + if ((id & 0xffff) == 0xffff) continue; + uint32_t cls = *cfg(0, d, 0, 8) >> 8; /* class/subclass/progif */ + if ((cls >> 8) != 0x0805) continue; + puts_("pci: SDHCI at 00:"); + putdec(d); + puts_(".0 id "); + puthex(id); + puts_("\n"); + *cfg(0, d, 0, 4) = 0; /* disable decode while sizing */ + *cfg(0, d, 0, 0x10) = 0xffffffffu; + uint32_t lo = *cfg(0, d, 0, 0x10); + int is64 = ((lo >> 1) & 3) == 2; + uint32_t size = ~(lo & ~0xfu) + 1; + if (size < 0x100 || size > 0x1000000) { puts_("pci: bad BAR0 size\n"); return -1; } + *cfg(0, d, 0, 0x10) = (uint32_t)MMIO_BASE; + if (is64) *cfg(0, d, 0, 0x14) = 0; + *cfg(0, d, 0, 4) = 1u << 1; /* memory space only: PIO driver, no bus master */ + bar0 = (volatile uint8_t *)MMIO_BASE; + puts_("pci: BAR0 size "); + puthex(size); + puts_("\n"); + return 0; + } + return -1; +} + +static uint8_t wbuf[256u * 512u], rbuf[256u * 512u]; + +static void fill(uint8_t *b, uint32_t n, uint32_t seed) +{ + for (uint32_t i = 0; i < n; i++) b[i] = (uint8_t)(seed * 37u + i * 13u + (i >> 8)); +} +static void zero(uint8_t *b, uint32_t n) { for (uint32_t i = 0; i < n; i++) ((volatile uint8_t *)b)[i] = 0; } +static int same(const uint8_t *a, const uint8_t *b, uint32_t n) +{ + for (uint32_t i = 0; i < n; i++) if (a[i] != b[i]) return 0; + return 1; +} + +/* The host script reads this block back out of the card image file. */ +static const char MARK[] = "AIENOS-SDHCI-QEMU block 5 written by disk_sdhci.c"; + +static sdhci_card C; +static const sdhci_ops OPS = {0, r32, w32, delay}; + +void payload_main(void) +{ + puts_("AIENOS native SDHCI payload (C driver, QEMU virt)\n"); + if (pci_find_sdhci()) { + puts_("no SD host controller found\nSDHCI_QEMU_PAYLOAD: FAIL\n"); + return; + } + sdhci_cfg scfg = {0, 0, 1, 64}; /* 4-bit bus, at most 64 blocks per command */ + int rc = sdhci_init(&C, &OPS, &scfg); + check(rc == SDHCI_OK, "sdhci_init", rc); + if (rc) { + puts_("last_cmd "); + putdec(C.last_cmd); + puts_(" last_int "); + puthex(C.last_int); + puts_("\nSDHCI_QEMU_PAYLOAD: FAIL\n"); + return; + } + puts_("card: spec "); + putdec(C.spec); + puts_(" base_hz "); + putdec(C.base_hz); + puts_(" card_hz "); + putdec(C.card_hz); + puts_(" high_capacity "); + putdec(C.high_capacity); + puts_(" blocks "); + putdec((int64_t)C.blocks); + puts_(" rca "); + puthex(C.rca); + puts_("\n"); + check(C.card_hz <= 25000000u && C.card_hz > 0, "card clock at or below 25 MHz", C.card_hz); + disk_dev *d = &C.dev; + check(d->block_size == 512, "block size", d->block_size); + + /* 1, 8, 64 (one command), 200 (split into 64-block commands) blocks */ + uint32_t sizes[] = {1, 8, 64, 200}; + uint64_t lba = 16; + for (uint32_t i = 0; i < 4; i++) { + uint32_t n = sizes[i], bytes = n * 512u; + fill(wbuf, bytes, i + 1); + check(disk_write(d, lba, n, wbuf) == DISK_OK, "disk_write", n); + zero(rbuf, bytes); + check(disk_read(d, lba, n, rbuf) == DISK_OK, "disk_read", n); + check(same(wbuf, rbuf, bytes), "read-back matches write", n); + lba += n + 1; + } + zero(wbuf, 512); + for (uint32_t i = 0; MARK[i]; i++) wbuf[i] = (uint8_t)MARK[i]; + check(disk_write(d, 5, 1, wbuf) == DISK_OK, "write marker block", 0); + check(disk_flush(d) == DISK_OK, "flush", 0); + /* out of range: refused by the driver, never sent */ + check(sdhci_read(&C, C.blocks, 1, rbuf) == DISK_ERANGE, "range refusal", 0); + check(disk_read(d, d->block_count - 1, 2, rbuf) == DISK_ERANGE, "disk range refusal", 0); + check(C.ready, "still ready after refusals", 0); + /* last block */ + fill(wbuf, 512, 99); + check(disk_write(d, d->block_count - 1, 1, wbuf) == DISK_OK, "write last block", 0); + /* full re-init (controller reset, card re-identified), data still there */ + rc = sdhci_init(&C, &OPS, &scfg); + check(rc == SDHCI_OK, "re-init", rc); + zero(rbuf, 512); + check(disk_read(d, d->block_count - 1, 1, rbuf) == DISK_OK && same(wbuf, rbuf, 512), + "last block survives re-init", 0); + fill(wbuf, 200u * 512u, 4); + zero(rbuf, 200u * 512u); + check(disk_read(d, lba - 201, 200, rbuf) == DISK_OK && same(wbuf, rbuf, 200u * 512u), + "200-block extent survives re-init", 0); + puts_("payload checks "); + putdec(checks); + puts_(", failures "); + putdec(fails); + puts_("\n"); + puts_(fails == 0 && checks > 0 ? "SDHCI_QEMU_PAYLOAD: PASS\n" : "SDHCI_QEMU_PAYLOAD: FAIL\n"); +} diff --git a/native/disk/tests/.crumb b/native/disk/tests/.crumb index 940eba3b..92672421 100644 --- a/native/disk/tests/.crumb +++ b/native/disk/tests/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-04T13:47:18Z", + "compiled_at": "2026-10-13T05:44:11Z", "compiler": "crumb-compile/1", - "digest": "sha256:69c1958da6a4fb466d80bc8a4debe13b98ebf93913bc4cd08b4fa23cea900882", + "digest": "sha256:28bc8b4021cec8ccd5b90c15d11db3fe7dd396db65e062f5e1046631fa2e4755", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 2, - "generated_at_commit": "a863d5c1f5bd89c88c5f6671eecfd27b599ee512", - "source_tree": "sha256:add9fa133a7a45e33477763278e0cfa71946149a21936d74c8ba1f3ab953d566" + "files": 3, + "generated_at_commit": "1994c4f8c4e8521d7febed45306515aa5085f207", + "source_tree": "sha256:cccd4c2564da56cc8dfc304b792f4f7949c5fa157a28feb973042d2dd93d93cb" }, "owner_lane": "", "provenance": { diff --git a/native/disk/tests/sdhci_test.c b/native/disk/tests/sdhci_test.c new file mode 100644 index 00000000..ba392dfc --- /dev/null +++ b/native/disk/tests/sdhci_test.c @@ -0,0 +1,573 @@ +/* sdhci_test.c -- disk_sdhci.c against a software SDHCI + SD card model. + * Hosted test; not QEMU and not hardware. The model offers only aligned + * 32-bit access, flags every protocol violation it can see (command issued + * while inhibited, data command while the card is programming, wrong + * response type, wrong address mode, block size not 512, unaligned or + * out-of-window access), and injects faults on request. */ +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include "../disk_sdhci.h" + +static int failures; +#define CHECK(x) \ + do { \ + if (!(x)) { \ + printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #x); \ + failures++; \ + } \ + } while (0) + +enum { ST_IDLE = 0, ST_READY = 1, ST_IDENT = 2, ST_STBY = 3, ST_TRAN = 4, ST_DATA = 5, ST_RCV = 6, ST_PRG = 7 }; + +typedef struct { + uint32_t reg[64]; + /* card */ + uint8_t *mem; + uint64_t blocks; + int sdsc, v1_card, present, state, app, acmd41_polls, acmd41_needed, bus4; + uint16_t rca; + uint32_t blocklen; + /* transfer */ + int xfer_dir; /* 0 none, 1 read, 2 write */ + uint64_t xfer_block; + uint32_t xfer_left, xfer_word; + int prg_polls, prg_after_write; + /* timing */ + int cmd_inhibit_reads, data_inhibit_reads; + uint64_t now_us; + /* faults */ + int reset_stuck, data_err_at_block, data_err_armed, r1_err_cmd, csd_override; + uint32_t csd_raw[4]; + /* observations */ + int violations, commands, accesses; + uint32_t last_arg[64]; +} model; + +static void violation(model *m, const char *why) +{ + m->violations++; + printf(" model violation: %s\n", why); +} + +static uint32_t r1(model *m) { return (uint32_t)m->state << 9 | (m->state == ST_TRAN ? 0x100u : 0) | (m->app ? 0x20u : 0); } + +/* Put an R2 value given as CSD/CID bits 127:8 into RESPONSE 119:0. */ +static void set_r2(model *m, const uint32_t v[4]) +{ + for (int i = 0; i < 4; i++) + m->reg[0x10 / 4 + i] = v[i]; +} + +static void put_bits(uint32_t r[4], unsigned hi, unsigned lo, uint32_t val) /* CSD bit numbers */ +{ + for (unsigned b = lo; b <= hi; b++, val >>= 1) { + unsigned rb = b - 8; + if (val & 1) + r[rb / 32] |= 1u << (rb % 32); + else + r[rb / 32] &= ~(1u << (rb % 32)); + } +} + +static void raise_int(model *m, uint32_t bits) { m->reg[0x30 / 4] |= bits; } +static void next_block_ready(model *m); + +static void do_command(model *m, uint32_t word) +{ + uint32_t tmode = word & 0xffff, cmdreg = word >> 16, idx = (cmdreg >> 8) & 0x3f, flags = cmdreg & 0xff; + uint32_t arg = m->reg[0x08 / 4]; + int app = m->app; + m->app = 0; + m->commands++; + m->last_arg[idx] = arg; + int data = (flags & 0x20) != 0; + if (m->cmd_inhibit_reads > 0 || (data && m->data_inhibit_reads > 0)) + violation(m, "command issued while CMD/DATA inhibit set"); + m->cmd_inhibit_reads = 1; + if (data) + m->data_inhibit_reads = 1; + uint32_t want = 0; + uint32_t resp = 0; + int error = 0; + if (app) { + switch (idx) { + case 41: /* R3 */ + want = 0x02; + if (++m->acmd41_polls >= m->acmd41_needed && m->acmd41_needed >= 0) { + m->state = ST_READY; + resp = 0x80000000u | (m->sdsc ? 0 : 0x40000000u) | 0x00ff8000u; + } else { + resp = 0x00ff8000u; + } + break; + case 6: + want = 0x1a; + if (m->state != ST_TRAN || (arg != 0 && arg != 2)) + violation(m, "ACMD6 outside tran or bad width"); + m->bus4 = arg == 2; + resp = r1(m); + break; + default: + violation(m, "unexpected app command"); + } + } else { + switch (idx) { + case 0: + want = 0x00; + m->state = ST_IDLE; + break; + case 8: + want = 0x1a; + if (m->v1_card) + error = 0x00018000; /* command timeout */ + else + resp = arg & 0xfff; + break; + case 55: + want = 0x1a; + m->app = 1; + resp = r1(m) | 0x20u; + break; + case 2: { + want = 0x09; + uint32_t cid[4] = { 0x11223344, 0x55667788, 0x99aabbcc, 0x00ddeeff }; + set_r2(m, cid); + m->state = ST_IDENT; + break; + } + case 3: + want = 0x1a; + m->rca = 0x1234; + m->state = ST_STBY; + resp = (uint32_t)m->rca << 16 | 0x0500; + break; + case 9: { + want = 0x09; + if (arg != (uint32_t)m->rca << 16) + violation(m, "CMD9 wrong RCA"); + uint32_t csd[4] = { 0 }; + if (m->csd_override) { + memcpy(csd, m->csd_raw, sizeof csd); + } else if (m->sdsc) { /* CSD 1.0: C_SIZE, C_SIZE_MULT, READ_BL_LEN = 9 */ + put_bits(csd, 127, 126, 0); + put_bits(csd, 83, 80, 9); + uint64_t mult = 7; /* 2^(7+2) = 512 */ + uint64_t csize = m->blocks / 512 - 1; + put_bits(csd, 73, 62, (uint32_t)csize); + put_bits(csd, 49, 47, (uint32_t)mult); + } else { + put_bits(csd, 127, 126, 1); + put_bits(csd, 69, 48, (uint32_t)(m->blocks / 1024 - 1)); + } + set_r2(m, csd); + break; + } + case 7: + want = 0x1b; + if (arg != (uint32_t)m->rca << 16) + violation(m, "CMD7 wrong RCA"); + m->state = ST_TRAN; + resp = r1(m); + raise_int(m, 0x2); /* busy end */ + break; + case 13: + want = 0x1a; + if (m->prg_polls > 0 && --m->prg_polls == 0) + m->state = ST_TRAN; + resp = r1(m); + break; + case 16: + want = 0x1a; + m->blocklen = arg; + resp = r1(m); + break; + case 17: + case 18: + case 24: + case 25: { + want = 0x3a; + if (m->state != ST_TRAN) + violation(m, "data command while the card is not in tran (programming?)"); + uint32_t bs = m->reg[0x04 / 4] & 0xfff, bc = m->reg[0x04 / 4] >> 16; + if (bs != 512) + violation(m, "block size not 512"); + int multi = idx == 18 || idx == 25; + if (multi && (tmode & 0x26) != 0x26) + violation(m, "multi-block without BLK_CNT_EN|MULTI|AUTO_CMD12"); + if (!multi && (tmode & 0x20)) + violation(m, "single-block with MULTI"); + int rd = idx == 17 || idx == 18; + if (!!(tmode & 0x10) != rd) + violation(m, "TRANSFER_MODE read bit does not match the command"); + uint64_t blk; + if (m->sdsc) { + if (arg % 512) + violation(m, "SDSC address not a byte address of a block"); + blk = arg / 512; + } else { + blk = arg; + } + uint32_t n = multi ? bc : 1; + resp = r1(m); + if (blk >= m->blocks || n > m->blocks - blk) { + resp |= 0x80000000u; /* OUT_OF_RANGE */ + break; + } + if ((int)idx == m->r1_err_cmd) { + resp |= 0x40000000u; /* ADDRESS_ERROR, no data follows */ + break; + } + m->xfer_dir = rd ? 1 : 2; + m->xfer_block = blk; + m->xfer_left = n; + m->xfer_word = 0; + m->state = rd ? ST_DATA : ST_RCV; + next_block_ready(m); + break; + } + default: + violation(m, "unexpected command"); + } + } + if ((flags & 0x3f) != want) { + char b[96]; + snprintf(b, sizeof b, "CMD%u flags 0x%02x, want 0x%02x", idx, flags & 0x3f, want); + violation(m, b); + } + if (error) { + raise_int(m, (uint32_t)error); + return; + } + m->reg[0x10 / 4] = (flags & 3) == 1 ? m->reg[0x10 / 4] : resp; + raise_int(m, 0x1); +} + +/* Make the next block ready, or report the injected data CRC error in its place + * (real controllers raise the error instead of BUF_RD_READY). */ +static void next_block_ready(model *m) +{ + if (m->xfer_dir == 1 && m->data_err_armed && (int64_t)m->xfer_block == m->data_err_at_block) { + m->data_err_armed = 0; + m->xfer_dir = 0; + m->state = ST_TRAN; + m->data_inhibit_reads = 2; + raise_int(m, 0x00208000); + return; + } + raise_int(m, m->xfer_dir == 1 ? 0x20 : 0x10); +} + +static void block_done(model *m) +{ + m->xfer_word = 0; + m->xfer_block++; + if (--m->xfer_left == 0) { + if (m->xfer_dir == 2) { + m->state = ST_PRG; + m->prg_polls = m->prg_after_write ? m->prg_after_write : 1; + } else { + m->state = ST_TRAN; + } + m->xfer_dir = 0; + m->data_inhibit_reads = 2; + raise_int(m, 0x2); + return; + } + next_block_ready(m); +} + +static uint32_t m_r32(void *ctx, uint32_t off) +{ + model *m = ctx; + m->accesses++; + if (off % 4 || off >= 0x100) { + violation(m, "unaligned or out-of-window read"); + return 0; + } + if (off == 0x24) { + uint32_t v = (m->present ? 0x00010000u : 0) | (m->cmd_inhibit_reads > 0 ? 1u : 0) | + (m->data_inhibit_reads > 0 ? 2u : 0); + if (m->cmd_inhibit_reads > 0) + m->cmd_inhibit_reads--; + if (m->data_inhibit_reads > 0) + m->data_inhibit_reads--; + return v; + } + if (off == 0x20) { + if (m->xfer_dir != 1) { + violation(m, "buffer read with no read transfer"); + return 0; + } + const uint8_t *p = m->mem + m->xfer_block * 512 + m->xfer_word * 4; + uint32_t v = (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24; + if (++m->xfer_word == 128) + block_done(m); + return v; + } + return m->reg[off / 4]; +} + +static void m_w32(void *ctx, uint32_t off, uint32_t v) +{ + model *m = ctx; + m->accesses++; + if (off % 4 || off >= 0x100) { + violation(m, "unaligned or out-of-window write"); + return; + } + switch (off) { + case 0x0c: + do_command(m, v); + return; + case 0x20: { + if (m->xfer_dir != 2) { + violation(m, "buffer write with no write transfer"); + return; + } + uint8_t *p = m->mem + m->xfer_block * 512 + m->xfer_word * 4; + p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24); + if (++m->xfer_word == 128) + block_done(m); + return; + } + case 0x2c: { + uint32_t old = m->reg[0x2c / 4]; + if ((old >> 24) && (v >> 24)) + violation(m, "SOFTWARE_RESET written while a reset bit is still set"); + if (v & (1u << 24)) { /* reset all */ + uint32_t cap = m->reg[0x40 / 4], ver = m->reg[0xfc / 4]; + memset(m->reg, 0, sizeof m->reg); + m->reg[0x40 / 4] = cap; + m->reg[0xfc / 4] = ver; + m->reg[0x2c / 4] = m->reset_stuck ? (1u << 24) : 0; + m->xfer_dir = 0; + return; + } + if (v & (3u << 25)) { /* line resets clear at once */ + m->xfer_dir = 0; + v &= ~(3u << 25); + } + if (v & 1) + v |= 2; /* internal clock stable at once */ + m->reg[0x2c / 4] = v | (m->reset_stuck ? (1u << 24) : 0); + return; + } + case 0x30: + m->reg[0x30 / 4] &= ~v; + if (!(m->reg[0x30 / 4] & 0xffff0000u)) + m->reg[0x30 / 4] &= ~0x8000u; + return; + case 0x40: + case 0xfc: + violation(m, "write to a read-only register"); + return; + default: + m->reg[off / 4] = v; + } +} + +static void m_delay(void *ctx, uint32_t us) { ((model *)ctx)->now_us += us; } + +static void model_init(model *m, uint64_t blocks, uint32_t version, uint32_t base_mhz) +{ + memset(m, 0, sizeof *m); + m->mem = calloc(blocks, 512); + m->blocks = blocks; + m->present = 1; + m->acmd41_needed = 3; + m->data_err_at_block = -1; + m->r1_err_cmd = -1; + m->reg[0xfc / 4] = version << 16; + m->reg[0x40 / 4] = (1u << 24) | ((base_mhz & 0xff) << 8); +} + +static sdhci_ops ops_for(model *m) +{ + sdhci_ops o = { m, m_r32, m_w32, m_delay }; + return o; +} + +static const sdhci_cfg cfg4 = { 0, 0, 1, 4 }; + +static void test_sdhc_round_trip(void) +{ + model m; + sdhci_card c; + model_init(&m, 8192, 2, 200); /* spec 3.00, 200 MHz base clock (Pi 5 class) */ + sdhci_ops o = ops_for(&m); + CHECK(sdhci_init(&c, &o, &cfg4) == 0); + CHECK(c.ready && c.high_capacity == 1 && c.blocks == 8192 && c.rca == 0x1234 && m.bus4 == 1); + CHECK(c.spec == 2 && c.base_hz == 200000000u && c.card_hz == 25000000u); + CHECK(c.dev.block_size == 512 && c.dev.block_count == 8192 && c.dev.max_blocks_per_io == 4); + uint8_t w[10 * 512], r[10 * 512]; + for (size_t i = 0; i < sizeof w; i++) + w[i] = (uint8_t)(i * 7 + 3); + CHECK(disk_write(&c.dev, 100, 10, w) == DISK_OK); /* split into 4 + 4 + 2 */ + CHECK(memcmp(m.mem + 100 * 512, w, sizeof w) == 0); + CHECK(disk_write(&c.dev, 8191, 1, w) == DISK_OK); /* last block, single */ + CHECK(disk_flush(&c.dev) == DISK_OK); + memset(r, 0, sizeof r); + CHECK(disk_read(&c.dev, 100, 10, r) == DISK_OK && memcmp(r, w, sizeof w) == 0); + CHECK(disk_read(&c.dev, 8191, 1, r) == DISK_OK && memcmp(r, w, 512) == 0); + CHECK(m.last_arg[18] == 108 && m.last_arg[25] == 108); /* block addressing */ + /* Range refused before the card sees it. */ + int before = m.commands; + CHECK(sdhci_read(&c, 8190, 3, r) == DISK_ERANGE && m.commands == before); + CHECK(c.ready); + CHECK(m.violations == 0); + free(m.mem); +} + +static void test_sdsc_and_clock_v2(void) +{ + model m; + sdhci_card c; + model_init(&m, 4096, 1, 52); /* spec 2.00, 52 MHz */ + m.sdsc = 1; + sdhci_ops o = ops_for(&m); + sdhci_cfg cfg = { 0, 0, 0, 0 }; + CHECK(sdhci_init(&c, &o, &cfg) == 0); + CHECK(c.high_capacity == 0 && c.blocks == 4096 && m.blocklen == 512 && m.bus4 == 0); + CHECK(c.card_hz == 13000000u); /* 52 MHz / 4: the largest power-of-two step <= 25 MHz */ + CHECK(c.dev.max_blocks_per_io == 128); + uint8_t w[3 * 512], r[3 * 512]; + for (size_t i = 0; i < sizeof w; i++) + w[i] = (uint8_t)(i ^ 0x5a); + CHECK(disk_write(&c.dev, 7, 3, w) == DISK_OK && m.last_arg[25] == 7 * 512); + CHECK(disk_read(&c.dev, 7, 3, r) == DISK_OK && memcmp(r, w, sizeof w) == 0 && m.last_arg[18] == 7 * 512); + CHECK(m.violations == 0); + free(m.mem); +} + +static void test_busy_after_write(void) +{ + model m; + sdhci_card c; + model_init(&m, 2048, 2, 100); + m.prg_after_write = 5; /* card programs for five CMD13 polls */ + sdhci_ops o = ops_for(&m); + CHECK(sdhci_init(&c, &o, &cfg4) == 0); + uint8_t w[512] = { 1, 2, 3 }, r[512]; + CHECK(disk_write(&c.dev, 1, 1, w) == DISK_OK); + CHECK(disk_read(&c.dev, 1, 1, r) == DISK_OK && memcmp(r, w, 512) == 0); + CHECK(m.violations == 0); /* no data command while programming */ + free(m.mem); +} + +static void test_failstop_on_data_error(void) +{ + model m; + sdhci_card c; + model_init(&m, 2048, 2, 100); + sdhci_ops o = ops_for(&m); + CHECK(sdhci_init(&c, &o, &cfg4) == 0); + uint8_t r[4 * 512]; + m.data_err_at_block = 11; + m.data_err_armed = 1; + CHECK(disk_read(&c.dev, 10, 4, r) == DISK_EIO); + CHECK(c.last_err == SDHCI_EDATA && c.last_cmd == 18 && (c.last_int & 0x00200000u)); + CHECK(disk_read(&c.dev, 10, 1, r) == DISK_ESTATE); /* failed closed */ + CHECK(disk_flush(&c.dev) == DISK_ESTATE); + CHECK(m.violations == 0); + free(m.mem); +} + +static void test_r1_error_bits(void) +{ + model m; + sdhci_card c; + model_init(&m, 2048, 2, 100); + m.r1_err_cmd = 17; + sdhci_ops o = ops_for(&m); + CHECK(sdhci_init(&c, &o, &cfg4) == 0); + uint8_t r[512]; + CHECK(disk_read(&c.dev, 3, 1, r) == DISK_EIO && c.last_err == SDHCI_ESTATUS && c.last_cmd == 17); + CHECK(m.violations == 0); + free(m.mem); +} + +static int init_rc(void (*setup)(model *), uint32_t version, uint32_t base_mhz, uint32_t cfg_hz) +{ + model m; + sdhci_card c; + model_init(&m, 2048, version, base_mhz); + if (setup) + setup(&m); + sdhci_ops o = ops_for(&m); + sdhci_cfg cfg = { cfg_hz, 0, 1, 0 }; + int rc = sdhci_init(&c, &o, &cfg); + free(m.mem); + return rc; +} +static void no_volt(model *m) { m->reg[0x40 / 4] &= ~(1u << 24); } +static void no_card(model *m) { m->present = 0; } +static void v1_card(model *m) { m->v1_card = 1; } +static void never_ready(model *m) { m->acmd41_needed = -1; } +static void stuck_reset(model *m) { m->reset_stuck = 1; } +static void zero_csd(model *m) +{ + m->sdsc = 1; + m->csd_override = 1; /* CSD 1.0 with C_SIZE 0, C_SIZE_MULT 0, READ_BL_LEN 0: 4 bytes */ +} + +static void test_refusals(void) +{ + CHECK(init_rc(0, 0, 100, 0) == SDHCI_EVER); + CHECK(init_rc(stuck_reset, 2, 100, 0) == SDHCI_ERESET); + CHECK(init_rc(no_volt, 2, 100, 0) == SDHCI_EVOLT); + CHECK(init_rc(0, 2, 0, 0) == SDHCI_ECLOCK); /* no base clock anywhere */ + CHECK(init_rc(0, 2, 0, 100000000u) == 0); /* base clock from cfg */ + CHECK(init_rc(no_card, 2, 100, 0) == SDHCI_ENOCARD); + CHECK(init_rc(v1_card, 2, 100, 0) == SDHCI_ECARD); + CHECK(init_rc(never_ready, 2, 100, 0) == SDHCI_ETIMEOUT); + CHECK(init_rc(zero_csd, 2, 100, 0) == SDHCI_ECSD); + sdhci_card c; + model m; + model_init(&m, 16, 2, 100); + sdhci_ops o = ops_for(&m); + sdhci_cfg big = { 0, 0, 1, 70000 }; + CHECK(sdhci_init(&c, &o, &big) == SDHCI_EARG); + CHECK(sdhci_init(&c, 0, &cfg4) == SDHCI_EARG); + free(m.mem); +} + +static void test_clock_math(void) +{ + model m; + sdhci_card c; + model_init(&m, 2048, 2, 100); /* 3.00, 100 MHz: 25 MHz is N = 2 */ + sdhci_ops o = ops_for(&m); + CHECK(sdhci_init(&c, &o, &cfg4) == 0 && c.card_hz == 25000000u); + CHECK(((m.reg[0x2c / 4] >> 8) & 0xff) == 2 && (m.reg[0x2c / 4] & 0x7) == 0x7); + free(m.mem); + model_init(&m, 2048, 1, 48); /* 2.00, 48 MHz: divisor 2 gives 24 MHz */ + CHECK(sdhci_init(&c, &o, &cfg4) == 0 && c.card_hz == 24000000u && ((m.reg[0x2c / 4] >> 8) & 0xff) == 1); + free(m.mem); +} + +int main(void) +{ + setvbuf(stdout, 0, _IONBF, 0); + printf("- %s\n", "test_sdhc_round_trip"); + test_sdhc_round_trip(); + printf("- %s\n", "test_sdsc_and_clock_v2"); + test_sdsc_and_clock_v2(); + printf("- %s\n", "test_busy_after_write"); + test_busy_after_write(); + printf("- %s\n", "test_failstop_on_data_error"); + test_failstop_on_data_error(); + printf("- %s\n", "test_r1_error_bits"); + test_r1_error_bits(); + printf("- %s\n", "test_refusals"); + test_refusals(); + printf("- %s\n", "test_clock_math"); + test_clock_math(); + if (failures) { + printf("AIENOS_DISK_SDHCI_MODEL: FAIL (%d)\n", failures); + return 1; + } + printf("AIENOS_DISK_SDHCI_MODEL: PASS\n"); + return 0; +} diff --git a/scripts/.crumb b/scripts/.crumb index 8b15200f..1c034ecc 100644 --- a/scripts/.crumb +++ b/scripts/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-13T04:45:02Z", + "compiled_at": "2026-10-13T05:44:11Z", "compiler": "crumb-compile/1", - "digest": "sha256:b0f4248c62a868c7b516d0a639ca2ecd1b1a5c0a4c732d64ad102749c8dfdd7b", + "digest": "sha256:80f03d413b7d49f38058ecbb8c712c6889dab80c227cf9f22999eaa885183abb", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 90, - "generated_at_commit": "391fcd54707b2ba006e0652c71259a17ef78ec6a", - "source_tree": "sha256:763aa9b66254d5dbc5b8403b52ef11c8d34f48058d3758d2e0779f3dd77ef5d8" + "files": 91, + "generated_at_commit": "1994c4f8c4e8521d7febed45306515aa5085f207", + "source_tree": "sha256:c2a6ab2e0eb878412e4f28aebc36f452d1dc07c12f60ca6d874b00223701dac6" }, "owner_lane": "", "provenance": { diff --git a/scripts/qemu_native_sdhci_test.sh b/scripts/qemu_native_sdhci_test.sh new file mode 100755 index 00000000..6ac22b98 --- /dev/null +++ b/scripts/qemu_native_sdhci_test.sh @@ -0,0 +1,110 @@ +#!/usr/bin/env bash +# qemu_native_sdhci_test.sh -- boot a bare-metal AArch64 payload that drives +# QEMU's emulated PCI SD Host Controller and SD card with the C driver in +# native/disk (disk_sdhci.c, the Pi 5 microSD driver). +# +# Two boots: +# spec2-sdsc host controller spec 2.00, 64 MiB card (standard capacity, +# byte addressing, power-of-two clock divider) +# spec3-sdhc host controller spec 3.00, 4 GiB card (high capacity, block +# addressing, 10-bit divided clock) +# Each boot writes, reads back, flushes, checks range refusal, re-initialises +# the controller and card and checks the data is still there. Afterwards this +# script reads block 5 out of the card image file and checks the marker the +# payload wrote, so the data is known to have reached the medium. +# +# Verdict line: AIENOS_DISK_SDHCI_QEMU: PASS | FAIL | NOT_RUN +# QEMU is an emulator. PASS here qualifies nothing about physical hardware. +# +# Respects the shared quiet flag: refuses to run (NOT_RUN, exit 0) while +# ~/workspace/.spark-quiet exists, which it only reads, or while another gate +# holds the QEMU gate lock (scripts/lib_gate_hold.sh, aienos#278). +set -euo pipefail + +repo="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +qemu_timeout="${AIENOS_QEMU_TIMEOUT:-60}" +out_rel="out" +out="${repo}/native/disk/qemu/${out_rel}" +. "${repo}/scripts/lib_gate_hold.sh" + +if ! gh_quiet_check; then + echo "NOT_RUN ${gh_why}" + echo "AIENOS_DISK_SDHCI_QEMU: NOT_RUN" + exit 0 +fi +for tool in qemu-system-aarch64 timeout make truncate dd; do + if ! command -v "${tool}" >/dev/null 2>&1; then + echo "required tool ${tool} not found" + echo "AIENOS_DISK_SDHCI_QEMU: NOT_RUN" + exit 0 + fi +done + +# One QEMU gate at a time; the gate lock record is removed only if it is still +# this run's own (never another run's hold). +if ! gh_lock_take qemu_native_sdhci_test "${AIENOS_GATE_MINUTES:-60}"; then + echo "NOT_RUN ${gh_why}" + echo "AIENOS_DISK_SDHCI_QEMU: NOT_RUN" + exit 0 +fi +cleanup() { gh_lock_release; } +trap cleanup EXIT + +cross="" +if [ "$(uname -m)" != "aarch64" ]; then cross="aarch64-linux-gnu-"; fi +if ! make -s -C "${repo}/native/disk/qemu" OUT="${out_rel}" \ + CC="${cross}gcc" LD="${cross}ld" NM="${cross}nm" >"${repo}/native/disk/qemu/build.log" 2>&1; then + tail -20 "${repo}/native/disk/qemu/build.log" + echo "payload build failed" + echo "AIENOS_DISK_SDHCI_QEMU: FAIL" + exit 1 +fi +rm -f "${repo}/native/disk/qemu/build.log" + +mark="AIENOS-SDHCI-QEMU block 5 written by disk_sdhci.c" +verdict=0 +run_one() { # name spec-version image-size + local name="$1" spec="$2" size="$3" + local img="${out}/sd-${name}.img" log="${out}/qemu-${name}.log" qrc + rm -f "${img}" "${log}" + truncate -s "${size}" "${img}" + echo "== ${name}: sd-spec-version=${spec}, card ${size}" + set +e + timeout --kill-after=5 "${qemu_timeout}" qemu-system-aarch64 \ + -M virt,highmem=off -cpu cortex-a57 -m 256M -smp 1 \ + -nographic -monitor none -serial stdio -no-reboot \ + -kernel "${out}/sdhci_payload.elf" \ + -drive "file=${img},if=none,id=aienos_sd,format=raw" \ + -device "sdhci-pci,sd-spec-version=${spec}" \ + -device sd-card,drive=aienos_sd \ + </dev/null >"${log}" 2>&1 + qrc=$? + set -e + tr -d '\r' <"${log}" | grep -v '^$' | tail -12 + if [ "${qrc}" -eq 124 ] || [ "${qrc}" -eq 137 ]; then + echo "QEMU did not power off within ${qemu_timeout} s" + fi + if ! tr -d '\r' <"${log}" | grep -qx 'SDHCI_QEMU_PAYLOAD: PASS' || [ "${qrc}" -ne 0 ]; then + echo "${name}: FAIL" + verdict=1 + return + fi + if [ "$(dd if="${img}" bs=512 skip=5 count=1 status=none | head -c "${#mark}")" != "${mark}" ]; then + echo "${name}: marker not found in block 5 of the card image (FAIL)" + verdict=1 + return + fi + echo "${name}: PASS (marker read back from the card image file)" +} + +run_one spec2-sdsc 2 64M +run_one spec3-sdhc 3 4G +rm -f "${out}"/sd-*.img + +if [ "${verdict}" -eq 0 ]; then + echo "(QEMU emulated SD host controller and card only; not a physical-hardware qualification)" + echo "AIENOS_DISK_SDHCI_QEMU: PASS" + exit 0 +fi +echo "AIENOS_DISK_SDHCI_QEMU: FAIL" +exit 1