E24 — SD first read after init: register order
| ID | E24 |
| Date | 2026-12-03 |
| Status | done |
| Decisions | D101 (supersedes D96) (DECISIONS.md) |
| Board | #1 (rev A, 12 MHz HSE), RP on the direct PC port, SD card read-only (LBA 0 and 0x800) |
| Firmware + results | fw/tests/2026-12-03-1-clocks-v5fdvp-sdorder (final sources, 7 CH32 builds, results.txt) |
| Scripts | sdgap.py |
Summary: The first SD read after init lost its first 32-bit word because sd_read wrote the DMA address before BLOCK_CFG; WCH’s example writes it after. With that order: 0 of 120 first reads wrong in every build and at every delay; the throw-away read is off by default.
What
sdfirst <lba> <d1> <d2> [rounds] [pos d3] re-inits the card without the throw-away read and does the first read into
a buffer with 0xEE guards, with delays at chosen points, then compares with a second read. Steps: delay sweeps
(before/after CMD17), function bisect (RP417_SD_FLASHFN: one SD function in flash), delays at each register write
before BLOCK_CFG and before the buffer prefill, then the WCH EVT register order (RP417_SD_WCHORDER) and its bisect.
Results
| test | old order (DMA_BEG1, TRAN_MODE, BLOCK_CFG) | WCH order (BLOCK_CFG 0, TRAN_MODE, BLOCK_CFG, DMA_BEG1) |
|---|---|---|
| RAM code, 96 MHz, no delay | 0/10 (one build), 10/10 (same code + a few instructions) | 0/10 |
| delay 1 µs–100 ms anywhere from the end of sd_init to BLOCK_CFG | 10/10 | 0/10 |
| delay before or after CMD17 (after BLOCK_CFG) | 0/10 | 0/10 |
| sd_read in flash, 96 MHz / all code in flash 48 MHz | 10/10 | 0/10 |
| bisect: only BLOCK_CFG = 0 first / only DMA_BEG1 last | 10/10 / 0/10 | — |
- When wrong: bytes 0..3 never written (0xEE stays); guards ±64 bytes untouched: the first word is dropped.
- Function bisect (old order): sd_gap, sd_cmd, sd_wait_data in flash → 0/10; sd_read in flash → 10/10.
- WCH order: SD check, 1- and 64-block reads (1650 KiB/s, 7.86 MB/s) and verified write streams unchanged.
- Final run on the committed sources (
results.txt): default ×32 build, ×32 flash code, ×16 flash code → 0 of 360 first reads wrong (LBA 0x800 and 0, no delay and delays at every position); the old-order buildRP417_SD_WCHORDER=0→ 120 of 120 wrong, plus 180 of 180 in the position sweep.
Lesson
Diff the register sequence against the vendor’s example before hunting timing: the WCH code says “MUST” next to the order we did not follow. A timing-dependent fault that flips with unrelated code changes is an ordering race.
Chip facts and numbers: fw/LEARNINGS.md. All experiments: index.