diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 701c800..d10a559 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -49,11 +49,24 @@ jobs: strategy: fail-fast: false matrix: + # Every Plaits image carries the eMMC storage and drive mode (#49); they differ + # only in whether the image FORMATS the card. Adara, 2026-10-08: + # plaits -> wakes-sp1.bin never formats (no formatter linked at all) + # fresh -> wakes-sp1-fresh.bin formats the eMMC once per build (SP1_FRESH) + # fallback -> the test-tone recovery image: no Plaits, never touches the eMMC include: - config: plaits plaits: y + extra: "" + bin: wakes-sp1 + - config: fresh + plaits: y + extra: -DCONFIG_SP1_FRESH=y + bin: wakes-sp1-fresh - config: fallback plaits: n + extra: "" + bin: wakes-sp1 defaults: run: working-directory: ws @@ -68,9 +81,9 @@ jobs: run: | python -m west build -p always -b stem_player wakes-sp1/firmware -d build \ -- -DBOARD_ROOT="$PWD/wakes-sp1" -DCONFIG_SP1_PLAITS=${{ matrix.plaits }} \ - 2>&1 | tee build.log + ${{ matrix.extra }} 2>&1 | tee build.log - # Both configs build with 0 warnings; keep it that way. This also catches a + # Every config builds with 0 warnings; keep it that way. This also catches a # Kconfig "assigned ... but got ..." warning, i.e. a -DCONFIG_ that did not take. - name: No warnings run: | @@ -83,6 +96,24 @@ jobs: - name: Check the image (0x20000, SAFETY.md constraints) run: python wakes-sp1/tools/ci/check_image.py build | tee check.txt + # A formatting image must never ship under the plain name, and the others must be + # what their names say. Checked from the build's own .config, not from the matrix. + - name: The configuration is what the name says + run: | + cfg=build/zephyr/.config + on() { grep -qx "CONFIG_$1=y" "$cfg"; } + fail() { echo "::error::${{ matrix.config }}: $1"; exit 1; } + case "${{ matrix.config }}" in + plaits) { on SP1_STORAGE && on SP1_DRIVE; } || fail "storage or drive mode missing" + if on SP1_FRESH; then fail "a formatting image named wakes-sp1"; fi ;; + fresh) { on SP1_STORAGE && on SP1_DRIVE && on SP1_FRESH; } || fail "not a fresh image" ;; + fallback) if on SP1_STORAGE; then fail "the recovery image must not touch the eMMC"; fi ;; + esac + for d in SP1_STORAGE_TEST SP1_EMMC_VERIFY; do + if on $d; then fail "diagnostic $d is on"; fi + done + echo "${{ matrix.config }}: OK" + - name: Size run: python wakes-sp1/tools/ci/size_report.py report build -o size-head.json @@ -106,7 +137,7 @@ jobs: run: | if ! python -m west build -p always -b stem_player base/firmware -d build-base \ -- -DBOARD_ROOT="$PWD/base" -DCONFIG_SP1_PLAITS=${{ matrix.plaits }} \ - > build-base.log 2>&1; then + ${{ matrix.extra }} > build-base.log 2>&1; then tail -n 40 build-base.log exit 1 fi @@ -136,6 +167,16 @@ jobs: echo "" } | tee "size-${{ matrix.config }}.md" >> "$GITHUB_STEP_SUMMARY" + # The tools all expect wakes-sp1.bin (CONFIG_KERNEL_BIN_NAME); the fresh image is + # RENAMED, not copied, so its artifact holds no file a person could take for the + # one that does not format. + - name: Name the image (${{ matrix.bin }}.bin) + if: always() && matrix.bin != 'wakes-sp1' + run: | + if [ -f build/zephyr/wakes-sp1.bin ]; then + mv build/zephyr/wakes-sp1.bin "build/zephyr/${{ matrix.bin }}.bin" + fi + - uses: actions/upload-artifact@v7 if: always() with: @@ -144,7 +185,7 @@ jobs: include-hidden-files: true if-no-files-found: warn path: | - ws/build/zephyr/wakes-sp1.bin + ws/build/zephyr/${{ matrix.bin }}.bin ws/build/zephyr/wakes-sp1-midi.md ws/build/zephyr/wakes-sp1-midi.csv ws/build/zephyr/wakes-sp1.elf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4ddda6a..2814775 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,7 +1,8 @@ -# Every PR to main, and every push to main, that touches a build input: build both -# configs, run the host suites, gate on check_image.py, and put the size diff in the -# run's summary. Administrative changes (see `paths`) run nothing. Tags always build -# (release.yml), and workflow_dispatch builds on demand. +# Every PR to main, and every push to main, that touches a build input: build every +# image (wakes-sp1, wakes-sp1-fresh, fallback), run the host suites, gate on +# check_image.py, and put the size diff in the run's summary. Administrative changes +# (see `paths`) run nothing. Tags always build (release.yml), and workflow_dispatch +# builds on demand. name: ci on: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index fe4290f..e9be2eb 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -9,8 +9,10 @@ # # It is attached twice: versioned, and as plain `wakes-sp1.bin`, so that # releases/latest/download/wakes-sp1.bin (the README's download link) always names -# the newest PUBLISHED release. GitHub's "latest" skips drafts and pre-releases, so -# that link moves only when a person publishes a full release. +# the newest PUBLISHED release. `wakes-sp1-fresh.bin`, the image that FORMATS the eMMC +# (#49), is attached the same two ways; the fallback is attached versioned only. +# GitHub's "latest" skips drafts and pre-releases, so that link moves only when a +# person publishes a full release. name: release on: @@ -85,6 +87,8 @@ jobs: mkdir dist cp in/wakes-sp1-plaits/build/zephyr/wakes-sp1.bin "dist/wakes-sp1-$t.bin" cp in/wakes-sp1-plaits/build/zephyr/wakes-sp1.bin dist/wakes-sp1.bin + cp in/wakes-sp1-fresh/build/zephyr/wakes-sp1-fresh.bin "dist/wakes-sp1-$t-fresh.bin" + cp in/wakes-sp1-fresh/build/zephyr/wakes-sp1-fresh.bin dist/wakes-sp1-fresh.bin cp in/wakes-sp1-fallback/build/zephyr/wakes-sp1.bin "dist/wakes-sp1-$t-fallback.bin" # The MIDI CC chart for exactly this build's script (M5a, tools/gen_midi.py). cp in/wakes-sp1-plaits/build/zephyr/wakes-sp1-midi.md "dist/wakes-sp1-$t-midi.md" @@ -105,13 +109,28 @@ jobs: echo echo "\`wakes-sp1.bin\` is the same file under a fixed name, for the README's download link." echo "Check the file against \`SHA256SUMS\` before flashing." - echo "\`wakes-sp1-$t-fallback.bin\` is the test-tone build without Plaits or Marbles," - echo "for diagnosing hardware only. It is not the instrument." + echo + echo "### Storage: \`wakes-sp1\` vs \`wakes-sp1-fresh\`" + echo + echo "- **\`wakes-sp1-$t.bin\` never formats the SP-1's internal storage (the eMMC).** Flash" + echo " it to update: your presets and files stay where they are." + echo "- **\`wakes-sp1-$t-fresh.bin\` FORMATS the eMMC** the first time it turns ON, and" + echo " **erases everything on it**, including whatever another firmware left there (stock" + echo " stems, tape-looper recordings). Flash it once to set the storage up, or to start" + echo " over; a progress bar shows on T1-T4 while it formats. Flashing the same fresh file" + echo " again does not format a second time. \`wakes-sp1-fresh.bin\` is the same file under" + echo " a fixed name." + echo "- Without a formatted card Wakes still plays; the storage features stay off." + echo + echo "\`wakes-sp1-$t-fallback.bin\` is the test-tone recovery build without Plaits or Marbles." + echo "It never touches the eMMC, and is for diagnosing hardware only. It is not the instrument." echo echo "## Size${PREV:+ vs $PREV}" echo cat in/wakes-sp1-plaits/size-plaits.md echo + cat in/wakes-sp1-fresh/size-fresh.md + echo cat in/wakes-sp1-fallback/size-fallback.md echo echo "## SHA-256" diff --git a/LICENSES/FatFs.txt b/LICENSES/FatFs.txt new file mode 100644 index 0000000..762a34d --- /dev/null +++ b/LICENSES/FatFs.txt @@ -0,0 +1,14 @@ +FatFs - Generic FAT Filesystem Module R0.16 +Copyright (C) 2025, ChaN, all right reserved. + +FatFs module is an open source software. Redistribution and use of FatFs in +source and binary forms, with or without modification, are permitted provided +that the following condition is met: + +1. Redistributions of source code must retain the above copyright notice, + this condition and the following disclaimer. + +This software is provided by the copyright holder and contributors "AS IS" +and any warranties related to this software are DISCLAIMED. +The copyright owner or contributors be NOT LIABLE for any damages caused +by use of this software. diff --git a/LICENSES/README.md b/LICENSES/README.md index b7f719e..af6c133 100644 --- a/LICENSES/README.md +++ b/LICENSES/README.md @@ -11,6 +11,7 @@ what was changed. | `MIT-feldd.txt` | Benjamin Reece | `third_party/feldd/` (the USB-MIDI 1.0 class and its packet parser) and the build-time patched copy of `usb_midi1.c` | | `MIT-sp1-tape-looper.txt` | chattock | the board definition, power-off and watchdog sequence, and codec bring-up adapted from chattock/sp1-tape-looper | | `MIT-SP-1-dev.txt` | Tim Knapen | the SP-1 pin map and hardware documentation from timknapen/SP-1-dev | +| `FatFs.txt` | ChaN | FatFs, the FAT filesystem on the eMMC (Zephyr's `fatfs` module, `modules/fs/fatfs`), compiled into images built with `CONFIG_SP1_STORAGE` | | `MIT-sp1-midi.txt` | Eric Lewis | the original `stem_player` Zephyr board that the board definition descends from | | `Apache-2.0.txt` | the Zephyr Project contributors; Ryan Gilmore | `third_party/sp1-usb-audio/` (USB audio out; it also carries its own `LICENSE` and `NOTICE`), `firmware/src/sp1_uac.{c,h}` and `tools/host-tests/uactest.c` (derived from it), `boards/teenageengineering/stem_player/Kconfig.defconfig`, `Kconfig.stem_player` and `stem_player_defconfig` (inherited from Zephyr's board template), `zephyr-patches/`, `firmware/src/sp1_usbd.c` (derived from Zephyr's USB sample helper), and the Zephyr RTOS compiled into every firmware image | diff --git a/NOTICE b/NOTICE index 1041f06..336d87c 100644 --- a/NOTICE +++ b/NOTICE @@ -22,19 +22,31 @@ SP-1 board definition and power/watchdog sequence 48 kHz clock topology, the bring-up order, the I2S stream configuration, and the TAS2505 and CS42L42 register sequences, ported verbatim; and (M3) the headphone auto-mute: CS42L42 jack sense (reg 0x1B77 bit 7), - 3-read debounce, TAS2505 speaker driver on/off (page 1 reg 0x2D). + 3-read debounce, TAS2505 speaker driver on/off (page 1 reg 0x2D); and + (M6) the 1-bit eMMC protocol in firmware/src/sp1_emmc.c: the eMMC pin map, + the power/reset/init sequence, the command framing and the response and + data sampling points (reduced, read-only and bit-banged here). SP-1 hardware documentation and pin map timknapen/SP-1-dev — Copyright (c) 2026 Tim Knapen — MIT https://github.com/timknapen/SP-1-dev Licence text: LICENSES/MIT-SP-1-dev.txt - Source of: the SP-1 pinout in firmware/src/sp1_board.h, and the CS42L42 - headphone-codec init sequence (via sp1-tape-looper) in sp1_audio.c. + Source of: the SP-1 pinout in firmware/src/sp1_board.h, the CS42L42 + headphone-codec init sequence (via sp1-tape-looper) in sp1_audio.c, and the + eMMC driver (emmc.c, via sp1-tape-looper) behind firmware/src/sp1_emmc.c. TAS2505 speaker amplifier configuration Texas Instruments, TAS2505 Application Reference Guide (SLAU472C), sec. 5.1 The register sequence in sp1_audio.c follows it, via sp1-tape-looper. +FAT filesystem on the eMMC (M6, images built with CONFIG_SP1_STORAGE) + FatFs R0.16 — Copyright (C) 2025, ChaN — FatFs licence (one condition: + keep the notice in source redistributions) + https://elm-chan.org/fsw/ff/ + Licence text: LICENSES/FatFs.txt + Used unmodified through Zephyr's fatfs module (zephyrproject-rtos/fatfs, + pinned by the Zephyr revision in west.yml) and Zephyr's fs layer. + Zephyr BSP precedent ericlewis/sp1-midi — Copyright (c) 2026 Eric Lewis — MIT https://github.com/ericlewis/sp1-midi diff --git a/README.md b/README.md index 2da3582..523a83b 100644 --- a/README.md +++ b/README.md @@ -3,34 +3,36 @@ alt="Wakes: a love letter to Mutable Instruments, by Worldwave">

-Wakes is a semimodular synthesizer, built as a custom firmware for the Teenage Engineering SP-1, Teenage Engineering's unreleased stem player. -It runs two Mutable Instruments modules combined: +Wakes is a semimodular synthesizer, built as a custom firmware for the SP-1, an unreleased Teenage Engineering stem player that was turned into a dev board by its community. + +Wakes combines two Mutable Instruments modules: - **Plaits**: A macro-synthesizer voice, featuring multiple sound engines - **Marbles**: A playful random sequencer The development of Wakes is unaffiliated with Teenage Engineering or Mutable Instruments. -IMPORTANT: Flashing custom firmware on the SP-1 is at your own risk. SP-1s are abandonware, they do not have manufacturer support. -REMEMBER: There is no way to go back to the base firmware once you've flashed it away. +**IMPORTANT:** Flash custom firmware on the SP-1 at your own risk. SP-1s are abandonware, they do not have manufacturer support. There is no way to go back to the base firmware once you've flashed it away. ## 📖 Manual -**[Wakes – Manual (PDF)](docs/Wakes%20-%20Manual.pdf)**: The manual details the layout of each page, with every control and how how to use them, in an aesthetically pleasing and readable format. Once you've installed Wakes on your SP-1, start there. +**[Wakes – Manual (PDF)](docs/Wakes%20-%20Manual.pdf)**: The manual details the layout of each page, with every control and how how to use them, in an aesthetically pleasing and readable format. Once you've installed Wakes on your SP-1 using the Flashing section below, start here. ## Status -**v0.7.2, pre-release for beta testing.** Report problems with the bug form under [Issues](https://github.com/Worldwave/Wakes/issues). +**v0.8.0, pre-release for beta testing.** Report problems with the bug form under [Issues](https://github.com/Worldwave/Wakes/issues). ## Flashing -1. **Download the latest [`wakes-sp1.bin`](https://github.com/Worldwave/Wakes/releases/latest/download/wakes-sp1.bin)**. - Older versions and release notes are on the [releases page](https://github.com/Worldwave/Wakes/releases). -2. Open . Hold down **T1+T4** while connecting the SP-1 over USB-C. -3. Follow solderless.engineering's instructions on how to connect to your SP-1 to flash it. +1. Wakes features new storage protocols for the SP-1. If you've never used Wakes before, you need to format your storage partition. + To do that, **Download the latest Fresh bin [`wakes-sp1-fresh.bin`](https://github.com/Worldwave/Wakes/releases/latest/download/wakes-sp1-fresh.bin)**. +2. If you've used Wakes before, and want to avoid touching your storage, **Download the latest regular bin [`wakes-sp1.bin`](https://github.com/Worldwave/Wakes/releases/latest/download/wakes-sp1.bin)**. +3. Older Wakes versions and release notes are available through the repo's [releases page](https://github.com/Worldwave/Wakes/releases). +4. Open . Hold down **T1+T4**. Keep them held while connecting the SP-1 over USB-C. +5. Follow solderless.engineering's instructions on how to connect to your SP-1 to flash it. 3. Select the `.bin` in Solderless Engineering's "firmware utility" page, flash it, and once done, you can unplug. -The T1+T4 recovery trigger in step 2 lives in Teenage Engineering's bootloader, not in Wakes, so it -works with whatever firmware is installed. Wakes never writes below `0x20000` (and neither should your CFW's), +The T1+T4 recovery trigger in step 4 lives in Teenage Engineering's bootloader, not in Wakes, so it +works with whatever firmware is installed. Wakes never writes below the flash memory's `0x20000` (and neither should your CFW's), because that's where the bootloader lives. ## Building diff --git a/docs/BUILD.md b/docs/BUILD.md index 4996f22..62a5b1f 100644 --- a/docs/BUILD.md +++ b/docs/BUILD.md @@ -23,6 +23,20 @@ Artifact: **`build\zephyr\wakes-sp1.bin`**. (`CONFIG_KERNEL_BIN_NAME="wakes-sp1" `firmware/prj.conf` renames the outputs from Zephyr's default `zephyr.*`. The `build\zephyr\` directory name itself comes from the CMake target and is unaffected.) +### The three images + +| Image | Build | eMMC | +|---|---|---| +| `wakes-sp1.bin` | as above | storage + drive mode; **never formats** (no formatter is linked) | +| `wakes-sp1-fresh.bin` | add `-DCONFIG_SP1_FRESH=y` after the `--` | **formats the eMMC** on its first ON, once per build | +| fallback | add `-DCONFIG_SP1_PLAITS=n` | test tone, recovery only; never touches the eMMC | + +The fresh build still writes `build\zephyr\wakes-sp1.bin`: **rename it to +`wakes-sp1-fresh.bin` straight away**, so it is never flashed by mistake as the image that +does not format. CI does the same, and checks each image's `.config` against its name. +Storage diagnostics, off in every shipped image: `-DCONFIG_SP1_STORAGE_TEST=y` (eMMC report ++ a 512 KB pattern test on each ON) and `-DCONFIG_SP1_EMMC_VERIFY=y` (every write read back). + ### Three things that are not optional **Quote `BOARD_ROOT` and use forward slashes.** Unquoted, the argument splits at the @@ -83,7 +97,7 @@ The failure modes that recur on this board: | a `pwm*`/`adc` node not found | the DTS label, and that the matching `CONFIG_*` driver is enabled | | `zephyr,deferred-init` unknown property, or `device_init()` undeclared | see **Deferred PWM init** below — there is a fallback | | pinctrl error on a `PSEL` | spelling in `stem_player-pinctrl.dtsi` | -| missing module | `west.yml`'s allowlist — `cmsis`, `cmsis_6`, `hal_nordic` are all required | +| missing module | `west.yml`'s allowlist — `cmsis`, `cmsis_6`, `fatfs`, `hal_nordic` are all required | | **LEDs work but wrong ones, or wrong order** | **not a build error.** pinctrl channel order vs LED index — see the comment block in `sp1_board.h` | | **ADC reads nonsense** | **not a build error.** Channel `reg` vs `io-channels` index vs the index used in C | @@ -261,6 +275,7 @@ git config --global --add safe.directory C:/sp1-ws/zephyr git config --global --add safe.directory C:/sp1-ws/modules/hal/cmsis git config --global --add safe.directory C:/sp1-ws/modules/hal/cmsis_6 git config --global --add safe.directory C:/sp1-ws/modules/hal/nordic +git config --global --add safe.directory C:/sp1-ws/modules/fs/fatfs git config --global --add safe.directory C:/sp1-ws/wakes-sp1 ``` diff --git a/docs/Wakes - Manual.pdf b/docs/Wakes - Manual.pdf index fd44f61..926d535 100644 Binary files a/docs/Wakes - Manual.pdf and b/docs/Wakes - Manual.pdf differ diff --git a/firmware/CMakeLists.txt b/firmware/CMakeLists.txt index 151e114..8460376 100644 --- a/firmware/CMakeLists.txt +++ b/firmware/CMakeLists.txt @@ -91,6 +91,14 @@ target_sources(app PRIVATE src/sp1_plaits_ui.c ) +# ---- M6 (#43): the eMMC and the FAT volume on it (src/sp1_store.h) ---- +if(CONFIG_SP1_STORAGE) + target_sources(app PRIVATE src/sp1_emmc.c src/sp1_store.c) + target_sources_ifdef(CONFIG_SP1_STORAGE_TEST app PRIVATE src/sp1_emmc_report.c) + # ff.h, for FATFS and MKFS_PARM (Zephyr's fatfs module, ELMFAT interface). + target_link_libraries(app PRIVATE ELMFAT) +endif() + # ---- M3: the Plaits voice (third_party/eurorack, vendored unmodified) ---- # Built as its own Zephyr library so it gets its OWN optimisation flags. The rest of # the firmware is built -Os (CONFIG_SIZE_OPTIMIZATIONS); the DSP is the one place where diff --git a/firmware/Kconfig b/firmware/Kconfig index 1d4b8c0..40abf54 100644 --- a/firmware/Kconfig +++ b/firmware/Kconfig @@ -87,6 +87,99 @@ config SP1_PROFILE_ICACHE engine. Reads the NVMC counter a few times per Plaits block (~0.05 % CPU). Off in release builds. +config SP1_STORAGE + bool "eMMC storage: a FAT32 volume and its own thread (M6, #43)" + default SP1_PLAITS + select FILE_SYSTEM + select FAT_FILESYSTEM_ELM + select DISK_ACCESS + help + The eMMC driver (src/sp1_emmc.c), FatFs on top of it, and a low-priority thread + that does all the work (src/sp1_store.h): below audio, main and USB, so it costs + the audio block nothing. Never formats -- that is SP1_FRESH alone. On in every + Plaits image (wakes-sp1, wakes-sp1-fresh); off in the fallback, the recovery image + that never touches the eMMC. + +config SP1_STORAGE_TEST + bool "Diagnostics: eMMC report and file test on every entry to ON (#43)" + depends on SP1_STORAGE + select INIT_STACKS # the storage thread's stack headroom, in the report + help + The card's identity, EXT_CSD and partition table (lines starting "EMMC"), then a + file test on the volume (lines starting "STORE"): a counter of ON entries that + survives power cycles and reflashes, 512 KB written in bursts, read back, compared + and deleted, free space and the WAKES directory. Off in release builds. + +config SP1_EMMC_VERIFY + bool "Diagnostics: read every eMMC write back and log any mismatch (#43)" + depends on SP1_STORAGE + help + Every written block is read straight back; a block that reads back wrong is logged + ("EMMC VERIFY FAIL": where in its burst, the card's token and busy, whether a slow + re-read agrees) and rewritten on its own. Halves write speed. Off in release builds. + (Built for the 2026-10-07 data hunt: every write verified; the fault was in burst + READS, src/sp1_emmc.c.) + +config SP1_FRESH + bool "wakes-sp1-fresh: FORMAT the eMMC on the first entry to ON (#43)" + depends on SP1_STORAGE + select FILE_SYSTEM_MKFS + select FS_FATFS_EXTRA_NATIVE_API # f_setlabel: the volume is labelled "SP-1" + help + ⚠️ Erases the whole eMMC: one FAT32 partition from 4 MB, the build's ID written to + WAKES/FRESH.ID, never again while that file matches (src/sp1_store.h). A normal + build contains no formatter at all, and tools/ci/check_image.py fails one that does. + +config SP1_DRIVE + bool "Drive mode: the eMMC as a USB drive in STANDBY (#43)" + depends on SP1_STORAGE + default y + select USBD_MSC_CLASS + help + A USB mass-storage interface, always in the descriptor (so going STANDBY <-> ON + never re-enumerates and MIDI / audio are never disturbed). In STANDBY with a host + attached the card is the host's; turning ON takes it back -- the host then sees "no + medium" -- after any command already in progress finishes (src/sp1_store.h). The + interface goes LAST, after CDC, MIDI and audio, so their numbers do not move, and + bcdDevice changes (SP1_USB_BCD_DEVICE) because the function set did. + +config SP1_USB_BCD_DEVICE + hex "USB bcdDevice" + default 0x0500 if SP1_DRIVE + default 0x0403 + help + The device release number. 0x0403 is what Zephyr 4.3 put there by default + (USB_BCD_DRN) and every release through v0.7.2 shipped with it. One PID for good: + when the set of USB functions changes, this changes instead (M5c), so a host that + cached the old layout treats the device as new. 0x0500 = + the drive (M6). + +# The drive's transfers: 16 blocks per disk call, so a host's large reads and writes become +# CMD18 / CMD25 bursts (sp1_emmc.h). 8 KB of RAM, only in drive builds. +config USBD_MSC_SCSI_BUFFER_SIZE + default 8192 if SP1_DRIVE + +config USBD_MSC_STACK_SIZE + default 2048 if SP1_DRIVE + +# ⚠️ Zephyr formats a volume it cannot mount unless told not to. The card arrives holding +# whatever an earlier firmware left there, so a failed mount must NEVER format: only +# SP1_FRESH formats, and only on purpose. These defaults come before Kconfig.zephyr's, so +# they win; check_image.py also fails an image built with MOUNT_MKFS on. +config FS_FATFS_MOUNT_MKFS + default n + +# Long file names (Adara, M6): presets are ".prst", which 8.3 cannot hold, and samples +# will want readable names. ~0.5 KB of RAM for the name buffer (BSS mode), a few KB of flash; +# nothing in the audio path. +config FS_FATFS_LFN + default y if SP1_STORAGE + +config FS_FATFS_CUSTOM_MOUNT_POINT_COUNT + default 1 if SP1_STORAGE + +config FS_FATFS_CUSTOM_MOUNT_POINTS + default "EMMC" if SP1_STORAGE + config SP1_LOGBUF_KB int "Stored log, in KB of RAM" default 96 diff --git a/firmware/src/main.c b/firmware/src/main.c index c653411..781fb79 100644 --- a/firmware/src/main.c +++ b/firmware/src/main.c @@ -84,6 +84,9 @@ #include "sp1_audio.h" #include "sp1_meter.h" #include "sp1_playrow.h" +#if defined(CONFIG_SP1_STORAGE) +#include "sp1_store.h" +#endif #if defined(CONFIG_SP1_PLAITS) #include "sp1_synth.h" #include "sp1_plaits_ui.h" @@ -868,6 +871,100 @@ static void marbles_buttons(bool fnc, uint32_t dt) #endif /* Survives a warm reset so a crash leaves a trace for the next boot. */ +#if defined(CONFIG_SP1_FRESH) +/* ---- the fresh format holds ON entry (M6 #43, Adara 2026-10-07) ---- + * "Formatting the eMMC should hold up the rest of the UI while the device is being turned + * on. We can still turn the SP-1 off during the process in case it hangs, using the 30s + * SHFT hold backstop." So between queuing the storage job and starting audio, main waits + * here: through the check (~0.1 s, nothing drawn), and through a format (several seconds) + * with the track row as a progress bar, ending in two 0 -> 100 % flickers and a quick + * fade into the page (sp1_ui_timing.h). A normal image never formats and never waits. + * + * ⚠️ POWER: sp1_power_tick() runs every tick with "••", so the 30 s backstop works exactly + * as in the ON loop -- it is evaluated first and unconditionally (rule 5a). Only the + * ordinary 3 s gesture is held off, through the existing shift suppression, because a + * format must not be cut short by an ordinary press (Adara). If the backstop completes + * while plugged in, sp1_power_tick() has already quiesced (which stops the format) and + * this returns false: the caller goes to STANDBY. Unplugged it powers off itself. + * The watchdog is fed here, by main -- never by the storage thread (sp1_emmc.h). */ +static bool storage_gate(void) +{ + int64_t last = k_uptime_get(); + bool announced = false; + uint32_t end_ms = 0u; /* into the completion animation */ + + for (;;) { + sp1_wdt_feed(); + const int64_t now = k_uptime_get(); + int64_t delta = now - last; + last = now; + if (delta < 1) { + delta = 1; + } else if (delta > 4 * TICK_MS) { + delta = 4 * TICK_MS; + } + const uint32_t dt = (uint32_t)delta; + + const bool fnc = sp1_fnc_pressed(); + if (fnc) { + (void)sp1_shift_used(); /* no 3 s shutdown mid-format; the backstop stays */ + } + const enum sp1_power_result pwr = sp1_power_tick(dt, fnc); + if (pwr == SP1_PWR_TO_STANDBY) { + printk("STORE format interrupted by the 30 s hold -- STANDBY\n"); + return false; + } + const bool row_free = (pwr != SP1_PWR_ANIMATING); + sp1_console_poll(dt, "FORMAT"); + + const enum sp1_store_phase ph = sp1_store_phase(); + if (ph == SP1_STORE_FORMATTING) { + if (!announced) { + printk("STORE formatting: the UI waits; only the 30 s \"••\" hold " + "powers off\n"); + announced = true; + } + if (row_free) { + sp1_led_bar(SP1_ROW_TRACK, sp1_store_progress(), 255u); + } + } else if (ph == SP1_STORE_READY) { + const enum sp1_store_format fr = sp1_store_format_result(); + if (fr == SP1_STORE_FMT_NONE) { + return true; /* nothing to show */ + } + if (fr == SP1_STORE_FMT_FAILED) { + /* No flicker: the bar as it stood, faded into the page. */ + uint8_t lv[4]; + const uint32_t p = sp1_store_progress(); + for (int i = 0; i < 4; i++) { + const uint32_t lo = (uint32_t)i * 255u / 4u; + const uint32_t hi = (uint32_t)(i + 1) * 255u / 4u; + lv[i] = (uint8_t)(p >= hi ? 255u + : (p > lo ? (p - lo) * 255u / (hi - lo) : 0u)); + } + sp1_display_flash(lv, 0u, SP1_FMT_FAIL_FADE_MS); + return true; + } + /* Done: off, on, off, on -- then full into the page. */ + end_ms += dt; + const uint32_t step = end_ms / SP1_FMT_FLICKER_MS; + if (step >= 4u) { + static const uint8_t full[4] = { 255u, 255u, 255u, 255u }; + sp1_display_flash(full, 0u, SP1_FMT_DONE_FADE_MS); + return true; + } + if (row_free) { + sp1_led_bar(SP1_ROW_TRACK, (step & 1u) ? 255u : 0u, 255u); + } + } + /* SP1_STORE_CHECKING: draw nothing -- the power-on fill finishes fading. */ + + sp1_led_tick(dt); + k_msleep(TICK_MS); + } +} +#endif + static __noinit uint32_t g_fault_key; static __noinit uint32_t g_fault_reason; static __noinit uint32_t g_fault_pc; @@ -1019,6 +1116,9 @@ int main(void) /* The audio thread is created here and parks immediately. It does no work * until ON starts it, and it is never created on a tap-and-release wake. */ sp1_audio_init(); +#if defined(CONFIG_SP1_STORAGE) + sp1_store_init(); /* the thread parks until an ON entry queues a job */ +#endif #if defined(CONFIG_SP1_PLAITS) sp1_pui_init(); /* page defaults: once per boot, kept across ON */ sp1_mui_init(); @@ -1062,6 +1162,19 @@ int main(void) * cannot be mis-assembled. Off once the tables exist. */ sp1_controls_reset_buttons(); +#if defined(CONFIG_SP1_STORAGE) + /* M6 (#43): the eMMC job runs in the storage thread, below main and audio; + * this only queues it. Every way out of ON stops it (sp1_quiesce_peripherals). */ + sp1_store_on_enter(); +#if defined(CONFIG_SP1_FRESH) + /* The fresh image's format holds ON entry, before audio (storage_gate). */ + if (!storage_gate()) { + standby = true; /* the 30 s backstop, plugged in */ + continue; + } +#endif +#endif + /* ---- M2: audio up on every entry to ON ---- * The way into STANDBY powers the codecs, the amp and the oscillator * down (sp1_quiesce_peripherals), so they are brought back here each diff --git a/firmware/src/sp1_board.h b/firmware/src/sp1_board.h index 6e686ad..168889d 100644 --- a/firmware/src/sp1_board.h +++ b/firmware/src/sp1_board.h @@ -41,6 +41,14 @@ #define SP1_OSC_EN_PIN 13u #define SP1_EMMC_VCCQ_PORT NRF_P0 /* eMMC I/O rail, active high */ #define SP1_EMMC_VCCQ_PIN 14u +/* eMMC bus (M6, #43): 1-bit MMC, bit-banged -- the nRF52840 has no SD/MMC peripheral. + * CLK, DAT0 and CMD must stay on port 0: sp1_emmc.c clocks data through NRF_P0's + * registers directly. Used only by sp1_emmc.c. */ +#define SP1_EMMC_CLK_PIN 6u /* P0.06 */ +#define SP1_EMMC_DAT0_PIN 7u /* P0.07 */ +#define SP1_EMMC_CMD_PIN 8u /* P0.08 */ +#define SP1_EMMC_RST_PORT NRF_P1 /* RST_n, active low */ +#define SP1_EMMC_RST_PIN 8u /* P1.08 */ #define SP1_BT_RST_PORT NRF_P0 /* CYBT module, active low */ #define SP1_BT_RST_PIN 10u diff --git a/firmware/src/sp1_emmc.c b/firmware/src/sp1_emmc.c new file mode 100644 index 0000000..80de8b9 --- /dev/null +++ b/firmware/src/sp1_emmc.c @@ -0,0 +1,880 @@ +/* + * wakes-sp1 — the SP-1's eMMC (M6, #43). See sp1_emmc.h. + * + * Derived from chattock/sp1-tape-looper firmware/src/sp1_emmc.c, Copyright (c) 2026 + * chattock, MIT, which is ported from timknapen/SP-1-dev emmc.c, Copyright (c) 2026 + * Tim Knapen, MIT. Licence texts: LICENSES/MIT-sp1-tape-looper.txt and + * LICENSES/MIT-SP-1-dev.txt. + * + * ---- the sampling points, which are the whole trick ---- + * They are the tape-looper's, unchanged, because they are what works on this board. + * The card changes CMD and DAT0 after a FALLING clock edge and the host reads them + * while CLK is high, so: + * - a response is found by pulsing CLK and reading CMD after the falling edge. The + * first read with CLK high afterwards sees the START BIT AGAIN -- so a captured + * response begins with its start bit: index 0 = start, 1 = transmission, 2..7 = + * the command index (or 111111), then the payload MSB first. + * (The tape-looper's own R1 parsing -- READY_FOR_DATA = r1[3] & 0x01, + * SWITCH_ERROR = r1[4] & 0x80 -- is only right with this alignment.) + * - a data block is found by reading DAT0 with CLK high; the bit after the start bit + * arrives after the next falling edge, so there is no re-read there. + * - a write puts each bit on DAT0 while CLK is low; the card latches it on the + * rising edge. The card's CRC-status token and its busy are read like data. + * Hardware 2026-10-07 (logs/sp1-20261007-152119.log, -173828.log): the CID's CRC7 + * matched at alignment 0; reads, writes and a FAT32 format ran with no error. + * + * ---- fast transfer (M6, Adara: "yes" to doing it with drive mode) ---- + * The tape-looper's, again: the 512-byte payloads (and their CRC16) ride SPIM3 + EasyDMA + * -- SPI mode 0 is the same wire format as eMMC DAT0 at default speed -- while the start + * bit hunt, the CRC-status token, the busy and every command stay bit-banged. SPIM3 is the + * only SPIM above 8 MHz and nothing else in Wakes uses it. We run it at 16 MHz, inside the + * card's 26 MHz default-speed limit (the looper's 32 MHz overclock glitched at 24 kHz). + * After identification, commands drop the 1 us half-period (the looper's CMDFAST: same + * edges, register-speed). Multi-block CMD18 / CMD25 + CMD12 replace one command per block. + * EVERY fast step has a slow one behind it: a failed multi-block transfer finishes block by + * block, a failed block is retried bit-banged (then at the 1 us clock), and a command that + * misses its response at speed is retried at the identification clock. + * ⚠️ nRF52840 anomaly 198 (SPIM3 TX data can be corrupted by CPU access to the same RAM + * block): harmless here BY DESIGN -- the card checks the CRC16 we computed from the source + * buffer before the DMA, rejects a corrupted block (token 101), and the block is retried. + */ +#include "sp1_emmc.h" +#include "sp1_board.h" + +#include +#include +#include + +#define PIN_CLK NRF_GPIO_PIN_MAP(0, SP1_EMMC_CLK_PIN) +#define PIN_DAT0 NRF_GPIO_PIN_MAP(0, SP1_EMMC_DAT0_PIN) +#define PIN_CMD NRF_GPIO_PIN_MAP(0, SP1_EMMC_CMD_PIN) +#define PIN_RST NRF_GPIO_PIN_MAP(1, SP1_EMMC_RST_PIN) /* SP1_EMMC_RST_PORT = NRF_P1 */ +#define PIN_VCCQ NRF_GPIO_PIN_MAP(0, SP1_EMMC_VCCQ_PIN) /* SP1_EMMC_VCCQ_PORT = NRF_P0 */ + +/* CLK, DAT0 and CMD through port 0's registers. A few NOPs of settle around each edge + * (the tape-looper's EDGE_SETTLE; JEDEC's minimum clock high/low is 10 ns, a NOP is + * 15.6 ns). The "slow" variants use a 1 us half-period: identification (400 kHz limit) + * and the last retry of anything. */ +#define P0_CLK (1u << SP1_EMMC_CLK_PIN) +#define P0_DAT0 (1u << SP1_EMMC_DAT0_PIN) +#define P0_CMD (1u << SP1_EMMC_CMD_PIN) +#define CLK_HI() (NRF_P0->OUTSET = P0_CLK) +#define CLK_LO() (NRF_P0->OUTCLR = P0_CLK) +#define DAT_HI() (NRF_P0->OUTSET = P0_DAT0) +#define DAT_LO() (NRF_P0->OUTCLR = P0_DAT0) +#define DAT0() ((NRF_P0->IN >> SP1_EMMC_DAT0_PIN) & 1u) +#define CMD_IN() ((NRF_P0->IN >> SP1_EMMC_CMD_PIN) & 1u) +#define SETTLE() __asm__ volatile("nop\nnop\nnop") +#define SLOW_HALF_US 1u + +#define INIT_TIMEOUT_MS 1000u /* CMD1 until ready: JEDEC's 1 s */ +#define DATA_TIMEOUT_MS 100u /* start bit of a data block */ +#define BUSY_TIMEOUT_MS 500u /* programming busy after a write / CMD12 */ + +#define R1_BITS_DATA 38u /* a response followed by a data block (send_cmd) */ +#define R1_BITS 48u +#define R2_BITS 138u /* 136 + 2 spare, for the CID alignment check */ + +/* Card-status bits in CMD24/25's own R1 that mean "this write must not go ahead": 31 + * ADDRESS_OUT_OF_RANGE, 30 ADDRESS_MISALIGN, 29 BLOCK_LEN_ERROR, 26 WP_VIOLATION, 25 + * DEVICE_IS_LOCKED. Deliberately NOT the whole JEDEC error set: COM_CRC_ERROR and + * ILLEGAL_COMMAND report the PREVIOUS command, so after any retried command they would + * refuse a perfectly good write. */ +#define WRITE_FATAL 0xe6000000u + +/* How a data block moves: SPIM3 DMA, bit-banged at register speed, or at 1 us. */ +enum mode { M_SPIM, M_FAST, M_SLOW }; + +static bool ready; +static volatile bool aborted; +static bool cmd_fast; /* identification done: commands at register speed */ +static bool spim_on; /* SPIM3 configured (power_down undoes it) */ +static uint32_t rca; /* relative card address, already << 16 */ +static uint32_t sectors; +static struct sp1_emmc_stats st; + +/* ---------------------------------------------------------------- CRCs */ + +static uint8_t crc7(const uint8_t *d, uint32_t n) +{ + uint8_t crc = 0; + for (uint32_t i = 0; i < n; i++) { + for (int b = 7; b >= 0; b--) { + crc <<= 1; + if ((((d[i] >> b) & 1u) ^ ((crc >> 7) & 1u)) != 0u) { + crc ^= 0x09; + } + crc &= 0x7f; + } + } + return (uint8_t)((crc << 1) | 1u); /* with the end bit, as it sits in a frame */ +} + +/* CRC-16/XMODEM (0x1021), table-driven: the bit loop costs ~0.5 ms a block, which at + * fast-transfer rates is most of the time. The table is built at init and checked + * against the standard answer ("123456789" -> 0x31C3); init fails if it is wrong. */ +static uint16_t crc_tab[256]; + +static void crc16_build(void) +{ + for (uint32_t i = 0; i < 256u; i++) { + uint16_t c = (uint16_t)(i << 8); + for (int b = 0; b < 8; b++) { + c = (c & 0x8000u) ? (uint16_t)((c << 1) ^ 0x1021u) : (uint16_t)(c << 1); + } + crc_tab[i] = c; + } +} + +static uint16_t crc16(const uint8_t *d, uint32_t n) +{ + uint16_t crc = 0; + while (n--) { + crc = (uint16_t)((crc << 8) ^ crc_tab[((crc >> 8) ^ *d++) & 0xffu]); + } + return crc; +} + +/* ---------------------------------------------------------------- SPIM3 */ + +#define SPIM_FREQ_16M 0x0A000000u + +static void spim_setup(void) +{ + NRF_SPIM3->ENABLE = 0; + NRF_SPIM3->PSEL.SCK = PIN_CLK; + NRF_SPIM3->PSEL.MOSI = 0xffffffffu; /* attached per transfer */ + NRF_SPIM3->PSEL.MISO = 0xffffffffu; + NRF_SPIM3->PSEL.CSN = 0xffffffffu; + NRF_SPIM3->FREQUENCY = SPIM_FREQ_16M; + NRF_SPIM3->CONFIG = 0; /* MSB first, CPOL 0 / CPHA 0 (mode 0) */ + NRF_SPIM3->ORC = 0xff; /* idle high */ + spim_on = true; +} + +/* One blocking DMA transfer with SPIM3 owning CLK and DAT0. On disable the pins fall + * back to their GPIO latches (CLK low, DAT0 as configured), so the bit-banged phases + * either side carry on. 516 bytes at 16 MHz is ~260 us. Bounded. */ +static bool spim_xfer(const uint8_t *tx, uint32_t txn, uint8_t *rx, uint32_t rxn) +{ + NRF_SPIM3->PSEL.MOSI = tx ? PIN_DAT0 : 0xffffffffu; + NRF_SPIM3->PSEL.MISO = rx ? PIN_DAT0 : 0xffffffffu; + NRF_SPIM3->ENABLE = 7; + NRF_SPIM3->TXD.PTR = (uint32_t)tx; + NRF_SPIM3->TXD.MAXCNT = tx ? txn : 0u; + NRF_SPIM3->RXD.PTR = (uint32_t)rx; + NRF_SPIM3->RXD.MAXCNT = rx ? rxn : 0u; + NRF_SPIM3->EVENTS_END = 0; + NRF_SPIM3->TASKS_START = 1; + const uint32_t c0 = k_cycle_get_32(); + while (NRF_SPIM3->EVENTS_END == 0u && + k_cyc_to_us_floor32(k_cycle_get_32() - c0) < 5000u) { + } + /* ⚠️ Read END AGAIN after the time check. This thread is the lowest priority there + * is: at ~70 % audio load it can be held off for several ms BETWEEN reading END and + * reading the clock, and then a transfer that finished meanwhile looked timed out. + * Hardware 2026-10-07 (logs/sp1-20261007-193746.log): 38 such false timeouts in + * 512 KB, each one dropping its burst to block-by-block -- data intact, speed lost. */ + const bool done = (NRF_SPIM3->EVENTS_END != 0u); + if (!done) { + st.spim_timeouts++; + NRF_SPIM3->TASKS_STOP = 1; + } + NRF_SPIM3->ENABLE = 0; + return done; +} + +/* ---------------------------------------------------------------- command phase */ + +static inline void half(bool slow) +{ + if (slow) { + k_busy_wait(SLOW_HALF_US); + } else { + SETTLE(); + } +} + +static inline void pulse(bool slow) +{ + CLK_HI(); + half(slow); + CLK_LO(); + half(slow); +} + +/* Send one command; capture `nbits` of the response (0 = none expected) into `resp`, + * MSB first, index 0 = the start bit (see the top of the file). False = no response. + * + * ⚠️ For a command followed by a data block FROM the card (CMD8, CMD17, CMD18), capture + * R1_BITS_DATA and no more: the block can start on DAT0 a couple of clocks after the + * response, and every extra clock here is one the data hunt never sees (the + * tape-looper found this the hard way). */ +static bool send_cmd(uint8_t index, uint32_t arg, uint8_t *resp, uint32_t nbits, bool slow) +{ + if (aborted) { + return false; + } + uint8_t f[6]; + f[0] = (uint8_t)(0x40u | (index & 0x3fu)); + f[1] = (uint8_t)(arg >> 24); + f[2] = (uint8_t)(arg >> 16); + f[3] = (uint8_t)(arg >> 8); + f[4] = (uint8_t)arg; + f[5] = crc7(f, 5); + + /* The gap before a command, on a RELEASED line: the tail of the previous response + * plus JEDEC's Nrc, without driving against the card's last bits. */ + nrf_gpio_cfg_input(PIN_CMD, NRF_GPIO_PIN_PULLUP); + for (int i = 0; i < 24; i++) { + pulse(slow); + } + NRF_P0->OUTSET = P0_CMD; + nrf_gpio_cfg_output(PIN_CMD); + for (int i = 0; i < 6; i++) { + for (int b = 7; b >= 0; b--) { + if ((f[i] >> b) & 1u) { + NRF_P0->OUTSET = P0_CMD; + } else { + NRF_P0->OUTCLR = P0_CMD; + } + pulse(slow); + } + } + nrf_gpio_cfg_input(PIN_CMD, NRF_GPIO_PIN_PULLUP); + + if (nbits == 0u) { + return true; + } + bool found = false; + for (int t = 0; t < 200 && !found; t++) { + pulse(slow); + found = (CMD_IN() == 0u); + } + if (!found) { + return false; + } + memset(resp, 0, (nbits + 7u) / 8u); + for (uint32_t i = 0; i < nbits; i++) { + CLK_HI(); + half(slow); + const uint32_t bit = CMD_IN(); + CLK_LO(); + half(slow); + resp[i / 8u] |= (uint8_t)(bit << (7u - (i % 8u))); + } + return true; +} + +/* Up to 8 tries; after identification the first four are at register speed and the + * rest at the identification clock, so a speed problem costs time, not the command. */ +static bool send_cmd_retry(uint8_t index, uint32_t arg, uint8_t *resp, uint32_t nbits) +{ + for (int t = 0; t < 8 && !aborted; t++) { + const bool slow = !cmd_fast || t >= 4; + if (send_cmd(index, arg, resp, nbits, slow)) { + return true; + } + st.cmd_retries++; + if (t == 0) { + for (int c = 0; c < 16; c++) { + pulse(slow); + } + } else { + k_msleep(2); + } + } + return false; +} + +/* `n` bits of a captured response from bit `first`, as an integer, MSB first. */ +static uint32_t resp_bits(const uint8_t *r, uint32_t first, uint32_t n) +{ + uint32_t v = 0; + for (uint32_t i = first; i < first + n; i++) { + v = (v << 1) | ((r[i / 8u] >> (7u - (i % 8u))) & 1u); + } + return v; +} + +/* ---------------------------------------------------------------- data phase */ + +/* One data block from the card, after its command's response (or the previous block of + * a CMD18): 512 bytes, the card's CRC16, the end bit. True only if the CRC matched. */ +static bool read_data(uint8_t *buf, enum mode m) +{ + const bool slow = (m == M_SLOW); + nrf_gpio_cfg_input(PIN_DAT0, NRF_GPIO_PIN_PULLUP); + + /* Start-bit hunt, bit-banged. The card only moves on our clock, so stopping to look + * at the time can never miss it. */ + const uint32_t t0 = k_uptime_get_32(); + bool got = false; + while (!got) { + for (int i = 0; i < 64; i++) { + CLK_HI(); + half(slow); + if (DAT0() == 0u) { + got = true; /* leave with CLK high */ + break; + } + CLK_LO(); + half(slow); + } + if (!got && ((k_uptime_get_32() - t0) >= DATA_TIMEOUT_MS || aborted)) { + st.hunt_timeouts++; + return false; + } + } + CLK_LO(); + half(slow); + + uint8_t c2[2]; + if (m == M_SPIM) { + /* The start bit is consumed, so the payload and CRC are byte-aligned: two DMA + * receives straight into the caller's buffer and c2 (no copy). */ + if (!spim_xfer(NULL, 0, buf, SP1_EMMC_BLOCK) || !spim_xfer(NULL, 0, c2, 2)) { + /* counted in spim_xfer */ + return false; + } + } else { + for (uint32_t i = 0; i < SP1_EMMC_BLOCK + 2u; i++) { + uint32_t byte = 0; + for (int b = 7; b >= 0; b--) { + CLK_HI(); + half(slow); + byte |= DAT0() << b; + CLK_LO(); + half(slow); + } + if (i < SP1_EMMC_BLOCK) { + buf[i] = (uint8_t)byte; + } else { + c2[i - SP1_EMMC_BLOCK] = (uint8_t)byte; + } + } + } + pulse(slow); /* end bit */ + + if (crc16(buf, SP1_EMMC_BLOCK) != (uint16_t)((c2[0] << 8) | c2[1])) { + st.crc_errs++; + return false; + } + return true; +} + +/* Wait while the card holds DAT0 low (programming). True once it lets go. The first + * clock here carries the token's end bit; each read comes after a falling edge and its + * settle, as the tape-looper's busy wait does -- read straight after the edge, it can + * still see the previous bit and call the card free one clock early. */ +static bool busy_wait(bool slow) +{ + nrf_gpio_cfg_input(PIN_DAT0, NRF_GPIO_PIN_PULLUP); + const uint32_t c0 = k_cycle_get_32(); + const uint32_t t0 = k_uptime_get_32(); + for (;;) { + for (int i = 0; i < 64; i++) { + pulse(slow); + if (DAT0() != 0u) { + const uint32_t us = k_cyc_to_us_floor32(k_cycle_get_32() - c0); + if (us > st.wr_busy_max_us) { + st.wr_busy_max_us = us; + } + return true; + } + } + const uint32_t el = k_uptime_get_32() - t0; + if (el >= BUSY_TIMEOUT_MS || aborted) { + st.busy_timeouts++; + return false; + } + if (el >= 1u) { + k_usleep(50); /* a long program: let others run */ + } + } +} + +/* The frame a write puts on DAT0 through SPIM3: Nwr idle (0xFF), 7 idle bits + the start + * bit (0xFE), the payload, its CRC16. ⚠️ It ends EXACTLY at the CRC's last bit: the end + * bit is clocked by hand right after, because the card's token comes 2 clocks after it + * and a trailing idle byte inside the DMA would let it fly past (the tape-looper). */ +static uint8_t txf[2u + SP1_EMMC_BLOCK + 2u]; + +/* The last write_data()'s CRC-status token (-1 = none seen) and busy, for the verify + * trace below. */ +static int last_tok; +static uint32_t last_busy_us; + +/* One data block TO the card after CMD24's response (or the previous block of a CMD25); + * then its CRC-status token (010 = accepted) and its busy. True only if accepted and + * programmed. */ +static bool write_data(const uint8_t *buf, enum mode m) +{ + const bool slow = (m == M_SLOW); + const uint16_t crc = crc16(buf, SP1_EMMC_BLOCK); + + DAT_HI(); + nrf_gpio_cfg(PIN_DAT0, NRF_GPIO_PIN_DIR_OUTPUT, NRF_GPIO_PIN_INPUT_DISCONNECT, + NRF_GPIO_PIN_NOPULL, NRF_GPIO_PIN_H0H1, NRF_GPIO_PIN_NOSENSE); + if (m == M_SPIM) { + txf[0] = 0xff; + txf[1] = 0xfe; + memcpy(&txf[2], buf, SP1_EMMC_BLOCK); /* also makes a flash source DMA-able */ + txf[2u + SP1_EMMC_BLOCK] = (uint8_t)(crc >> 8); + txf[3u + SP1_EMMC_BLOCK] = (uint8_t)crc; + if (!spim_xfer(txf, sizeof(txf), NULL, 0)) { + nrf_gpio_cfg_input(PIN_DAT0, NRF_GPIO_PIN_PULLUP); + /* counted in spim_xfer */ + return false; + } + } else { + for (int i = 0; i < 8; i++) { /* Nwr: idle high, so no early start bit */ + half(slow); + pulse(slow); + } + DAT_LO(); /* start bit */ + half(slow); + pulse(slow); + for (uint32_t i = 0; i < SP1_EMMC_BLOCK + 2u; i++) { + const uint32_t byte = (i < SP1_EMMC_BLOCK) ? buf[i] + : (i == SP1_EMMC_BLOCK ? (uint32_t)(crc >> 8) : (uint32_t)(crc & 0xffu)); + for (int b = 7; b >= 0; b--) { + if ((byte >> b) & 1u) { + DAT_HI(); + } else { + DAT_LO(); + } + half(slow); + pulse(slow); + } + } + } + DAT_HI(); /* end bit (SPIM left DAT0 on its latch) */ + half(slow); + pulse(slow); + nrf_gpio_cfg_input(PIN_DAT0, NRF_GPIO_PIN_PULLUP); /* the card drives from here */ + + /* CRC-status token: start bit (0), three status bits, end bit. */ + int status = -1; + for (int i = 0; i < 16 && status < 0; i++) { + CLK_HI(); + half(slow); + const uint32_t start = DAT0(); + CLK_LO(); + half(slow); + if (start == 0u) { + status = 0; + for (int k = 0; k < 3; k++) { + CLK_HI(); + half(slow); + status = (status << 1) | (int)DAT0(); + CLK_LO(); + half(slow); + } + } + } + /* Wait out the busy whatever the token said: a rejected block can still leave the + * card busy, and the next command must not land on it. */ + const uint32_t b0 = k_cycle_get_32(); + const bool done = busy_wait(slow); + last_tok = status; + last_busy_us = k_cyc_to_us_floor32(k_cycle_get_32() - b0); + if (status != 0x2) { + st.wr_rejects++; + return false; + } + return done; +} + +/* A command followed by one data block from the card; the block retried bit-banged, then + * at 1 us. */ +static bool read_cmd_block(uint8_t index, uint32_t arg, uint8_t *buf) +{ + static const enum mode modes[] = { M_SPIM, M_FAST, M_SLOW }; + uint8_t r[(R1_BITS_DATA + 7u) / 8u]; + for (unsigned t = 0; t < ARRAY_SIZE(modes) && !aborted; t++) { + if (!send_cmd_retry(index, arg, r, R1_BITS_DATA)) { + return false; + } + if (read_data(buf, modes[t])) { + return true; + } + } + return false; +} + +/* CMD12 STOP_TRANSMISSION. After a write burst it is R1b: the card holds DAT0 low while + * it commits, and returning before that makes the next command miss its response. */ +static bool stop_transmission(bool after_write) +{ + uint8_t r[(R1_BITS + 7u) / 8u]; + const bool ok = send_cmd_retry(12, 0, r, R1_BITS); + return (after_write ? busy_wait(false) : true) && ok; +} + +/* ---- burst READS are closed-ended (M6, proven 2026-10-07) ---- + * ⚠️ Open-ended CMD18 (the tape-looper's way: run until CMD12) RETURNS JUNK on this card. + * CMD12 lands while the card is already fetching the block after the last one wanted, and + * some later burst then hands back, as its SECOND block, the card's internal buffer -- with a + * valid CRC, so nothing below this layer can see it. Measured on hardware + * (logs/sp1-20261007-221018.log, 4 ON entries x 3 rounds of FAT scan + 512 KB read): + * open-ended 5 bad blocks, every one at position 1 of its burst, every one the same + * buffer-like bytes give or take a few bits; closed-ended 0. Earlier runs: the host's own + * FAT scan set it up and Wakes' next read caught it (-202944, -210404, -215523). + * So every burst read is CMD23 SET_BLOCK_COUNT + CMD18: the card stops itself after exactly + * n blocks, and CMD12 is sent only to cut a failed burst short. + * Burst WRITES stay open-ended (CMD25 ... CMD12): ~10 000 verified blocks, 0 wrong. */ +static bool set_block_count(uint32_t n) +{ + uint8_t r[(R1_BITS + 7u) / 8u]; + return send_cmd_retry(23, n & 0xffffu, r, R1_BITS); +} + +/* ---------------------------------------------------------------- API */ + +bool sp1_emmc_init(struct sp1_emmc_ident *id) +{ + struct sp1_emmc_ident local; + if (id == NULL) { + id = &local; + } + memset(id, 0, sizeof(*id)); + id->cid_shift = -128; + memset(&st, 0, sizeof(st)); + ready = false; + cmd_fast = false; + sectors = 0; + aborted = false; + + crc16_build(); + if (crc16((const uint8_t *)"123456789", 9) != 0x31c3u) { + return false; /* never move data with a broken check */ + } + + nrf_gpio_cfg(PIN_CLK, NRF_GPIO_PIN_DIR_OUTPUT, NRF_GPIO_PIN_INPUT_DISCONNECT, + NRF_GPIO_PIN_NOPULL, NRF_GPIO_PIN_H0H1, NRF_GPIO_PIN_NOSENSE); + CLK_LO(); + NRF_P0->OUTSET = P0_CMD; + nrf_gpio_cfg_output(PIN_CMD); + nrf_gpio_cfg_input(PIN_DAT0, NRF_GPIO_PIN_PULLUP); /* driven only while writing */ + nrf_gpio_cfg_output(PIN_RST); + nrf_gpio_cfg_output(PIN_VCCQ); + spim_setup(); + + /* Power and reset, as the tape-looper does it. RST_n only acts if the card's + * RST_n_FUNCTION is enabled -- it is not on this unit (EXT_CSD[162] = 0). */ + const uint32_t t_on = k_uptime_get_32(); + nrf_gpio_pin_set(PIN_VCCQ); + k_msleep(10); + nrf_gpio_pin_clear(PIN_RST); + k_msleep(1); + nrf_gpio_pin_set(PIN_RST); + k_msleep(2); + + for (int i = 0; i < 80; i++) { /* >= 74 clocks before the first command */ + pulse(true); + } + + (void)send_cmd(0, 0, NULL, 0, true); /* CMD0 GO_IDLE_STATE, no response */ + k_msleep(1); + + /* CMD1 SEND_OP_COND, sector addressing (HCS), until the power-up bit (OCR[31], + * response bit 8) is set. */ + uint8_t r[(R2_BITS + 7u) / 8u]; + bool up = false; + while (!up && !aborted && (k_uptime_get_32() - t_on) < INIT_TIMEOUT_MS) { + id->ocr_tries++; + if (send_cmd(1, 0x40ff8000u, r, R1_BITS, true)) { + id->ocr = resp_bits(r, 8, 32); + up = (id->ocr & 0x80000000u) != 0u; + } + if (!up) { + k_msleep(1); + } + } + id->ready_ms = k_uptime_get_32() - t_on; + if (!up) { + return false; + } + + /* CMD2 ALL_SEND_CID: R2, CID[127:0] from bit 8. Checked against the CID's own CRC7 + * at three alignments; the report says which matched. */ + if (!send_cmd_retry(2, 0, r, R2_BITS)) { + return false; + } + static const int8_t shifts[] = { 0, -1, 1 }; + for (unsigned s = 0; s < ARRAY_SIZE(shifts); s++) { + uint8_t cid[16]; + for (uint32_t k = 0; k < 16u; k++) { + cid[k] = (uint8_t)resp_bits(r, (uint32_t)(8 + shifts[s]) + 8u * k, 8); + } + if (crc7(cid, 15) == cid[15] || s == 0u) { + memcpy(id->cid, cid, sizeof(cid)); + } + if (crc7(cid, 15) == cid[15]) { + id->cid_shift = shifts[s]; + break; + } + } + + rca = 1u << 16; /* CMD3 SET_RELATIVE_ADDR: we choose 1 */ + if (!send_cmd_retry(3, rca, r, R1_BITS) || + !send_cmd_retry(7, rca, r, R1_BITS) || /* CMD7 SELECT_CARD -> transfer */ + !send_cmd_retry(16, SP1_EMMC_BLOCK, r, R1_BITS)) { /* CMD16 SET_BLOCKLEN */ + return false; + } + ready = true; + cmd_fast = true; /* identification over: full speed */ + + /* The size, from EXT_CSD SEC_COUNT [215:212]. */ + static uint8_t xcsd[SP1_EMMC_BLOCK]; + if (!read_cmd_block(8, 0, xcsd)) { + ready = false; + return false; + } + sectors = (uint32_t)xcsd[212] | ((uint32_t)xcsd[213] << 8) | + ((uint32_t)xcsd[214] << 16) | ((uint32_t)xcsd[215] << 24); + return sectors != 0u; +} + +bool sp1_emmc_ready(void) +{ + return ready && !aborted; +} + +uint32_t sp1_emmc_sectors(void) +{ + return sp1_emmc_ready() ? sectors : 0u; +} + +bool sp1_emmc_status(uint32_t *status) +{ + uint8_t r[(R1_BITS + 7u) / 8u]; + if (!send_cmd_retry(13, rca, r, R1_BITS)) { + return false; + } + *status = resp_bits(r, 8, 32); + return true; +} + +bool sp1_emmc_read_ext_csd(uint8_t buf[SP1_EMMC_BLOCK]) +{ + return sp1_emmc_ready() && read_cmd_block(8, 0, buf); +} + +bool sp1_emmc_read_block(uint32_t block, uint8_t buf[SP1_EMMC_BLOCK]) +{ + return sp1_emmc_ready() && block < sectors && read_cmd_block(17, block, buf); +} + +static bool write_block_raw(uint32_t block, const uint8_t *buf) +{ + static const enum mode modes[] = { M_SPIM, M_FAST, M_SLOW }; + uint8_t r[(R1_BITS + 7u) / 8u]; + for (unsigned t = 0; t < ARRAY_SIZE(modes) && !aborted; t++) { + /* CMD24 WRITE_BLOCK. Its R1 reports this command's own errors (address out + * of range, write protect, ...): never send data after one of those. */ + if (!send_cmd_retry(24, block, r, R1_BITS)) { + return false; + } + if ((resp_bits(r, 8, 32) & WRITE_FATAL) != 0u) { + return false; + } + if (write_data(buf, modes[t])) { + return true; + } + } + return false; +} + +#if defined(CONFIG_SP1_EMMC_VERIFY) +/* ---- read every write back (diagnostics, M6) ---- + * Hardware 2026-10-07 (logs/sp1-20261007-202944.log, -210404.log): in about a third of ON + * entries the 512 KB test file read back with one or two blocks still holding the card's + * OLD contents -- every token "accepted", no CRC error, no timeout, all in CMD25 bursts. + * So a write was lost or landed elsewhere. This reads each written block straight back, + * and on a mismatch says where in its burst it was, what the card answered for it, and + * whether a slow re-read agrees (a lost WRITE) or not (a READ problem); then rewrites it + * on its own and checks again. */ +static uint8_t vbuf[SP1_EMMC_BLOCK]; +static uint8_t vbuf2[SP1_EMMC_BLOCK]; + +static bool read_back(uint32_t block, uint8_t *dst, enum mode m) +{ + uint8_t r[(R1_BITS_DATA + 7u) / 8u]; + return send_cmd_retry(17, block, r, R1_BITS_DATA) && read_data(dst, m); +} + +static void hex16(char *out, const uint8_t *d) +{ + static const char hx[] = "0123456789abcdef"; + for (int i = 0; i < 16; i++) { + out[3 * i] = ' '; + out[3 * i + 1] = hx[d[i] >> 4]; + out[3 * i + 2] = hx[d[i] & 15u]; + } + out[48] = '\0'; +} + +static bool verify_block(uint32_t block, const uint8_t *src, const char *how, uint32_t pos, + uint32_t n, int tok, uint32_t busy_us, uint32_t prev_busy_us) +{ + if (read_back(block, vbuf, M_SPIM) && memcmp(vbuf, src, SP1_EMMC_BLOCK) == 0) { + return true; + } + st.verify_fails++; + const bool slow_ok = read_back(block, vbuf2, M_SLOW); + const bool slow_right = slow_ok && memcmp(vbuf2, src, SP1_EMMC_BLOCK) == 0; + const bool same = slow_ok && memcmp(vbuf2, vbuf, SP1_EMMC_BLOCK) == 0; + uint32_t diff = 0; + for (uint32_t i = 0; i < SP1_EMMC_BLOCK; i++) { + diff += (vbuf[i] != src[i]); + } + printk("EMMC VERIFY FAIL: %s LBA %u = block %u of %u; token %d, busy %u us (block before: " + "%u us); %u bytes differ; slow re-read %s\n", how, (unsigned)block, (unsigned)pos, + (unsigned)n, tok, (unsigned)busy_us, (unsigned)prev_busy_us, (unsigned)diff, + !slow_ok ? "FAILED" : (slow_right ? "is RIGHT -> a READ problem" + : (same ? "agrees -> the WRITE was lost" + : "differs from both"))); + char a[49], b[49]; + hex16(a, vbuf); + hex16(b, src); + printk("EMMC VERIFY FAIL: read %s\nEMMC VERIFY FAIL: wrote %s\n", a, b); + const bool fixed = write_block_raw(block, src) && read_back(block, vbuf, M_SPIM) && + memcmp(vbuf, src, SP1_EMMC_BLOCK) == 0; + if (fixed) { + st.verify_fixed++; + } + printk("EMMC VERIFY: rewritten on its own: %s\n", fixed ? "now right" : "STILL WRONG"); + return fixed; +} +#endif + +bool sp1_emmc_write_block(uint32_t block, const uint8_t buf[SP1_EMMC_BLOCK]) +{ + if (!sp1_emmc_ready() || block >= sectors || !write_block_raw(block, buf)) { + return false; + } +#if defined(CONFIG_SP1_EMMC_VERIFY) + return verify_block(block, buf, "CMD24", 0, 1, last_tok, last_busy_us, 0); +#else + return true; +#endif +} + +bool sp1_emmc_read_blocks(uint32_t block, uint8_t *buf, uint32_t n) +{ + if (!sp1_emmc_ready() || n == 0u || block >= sectors || n > sectors - block) { + return false; + } + /* The card reads ahead in a CMD18; ending one on the very last block can trip + * ADDRESS_OUT_OF_RANGE, so the device's last block always goes on its own. */ + uint32_t multi = (block + n == sectors) ? n - 1u : n; + uint32_t done = 0; + if (multi >= 2u) { + uint8_t r[(R1_BITS_DATA + 7u) / 8u]; + if (set_block_count(multi) && send_cmd_retry(18, block, r, R1_BITS_DATA)) { + while (done < multi && read_data(buf + done * SP1_EMMC_BLOCK, M_SPIM)) { + done++; + } + /* Complete: the card stopped by itself. Cut short: it must be told. */ + if (done < multi) { + (void)stop_transmission(false); + } + st.multi_blocks += done; + if (done < multi) { + st.multi_fallbacks++; + } + } + } + for (; done < n; done++) { /* the rest, or all of it, one by one */ + if (!sp1_emmc_read_block(block + done, buf + done * SP1_EMMC_BLOCK)) { + return false; + } + } + return true; +} + +bool sp1_emmc_write_blocks(uint32_t block, const uint8_t *buf, uint32_t n) +{ + if (!sp1_emmc_ready() || n == 0u || block >= sectors || n > sectors - block) { + return false; + } + uint32_t done = 0; + if (n >= 2u) { + uint8_t r[(R1_BITS + 7u) / 8u]; +#if defined(CONFIG_SP1_EMMC_VERIFY) + static int8_t btok[64]; + static uint32_t bbusy[64]; +#endif + if (send_cmd_retry(25, block, r, R1_BITS) && + (resp_bits(r, 8, 32) & WRITE_FATAL) == 0u) { + while (done < n && write_data(buf + done * SP1_EMMC_BLOCK, M_SPIM)) { +#if defined(CONFIG_SP1_EMMC_VERIFY) + if (done < 64u) { + btok[done] = (int8_t)last_tok; + bbusy[done] = last_busy_us; + } +#endif + done++; + } + if (!stop_transmission(true)) { + done = 0; /* unsure what landed: rewrite it all */ + } + st.multi_blocks += done; + if (done < n) { + st.multi_fallbacks++; + } +#if defined(CONFIG_SP1_EMMC_VERIFY) + for (uint32_t j = 0; j < done; j++) { + const bool rec = j < 64u; + if (!verify_block(block + j, buf + j * SP1_EMMC_BLOCK, "CMD25", j, n, + rec ? btok[j] : -2, rec ? bbusy[j] : 0u, + (rec && j > 0u) ? bbusy[j - 1u] : 0u)) { + return false; + } + } +#endif + } + } + for (; done < n; done++) { /* rewriting a block is harmless */ + if (!sp1_emmc_write_block(block + done, buf + done * SP1_EMMC_BLOCK)) { + return false; + } + } + return true; +} + +void sp1_emmc_get_stats(struct sp1_emmc_stats *s) +{ + *s = st; +} + +void sp1_emmc_power_down(void) +{ + ready = false; + cmd_fast = false; + if (spim_on) { + NRF_SPIM3->ENABLE = 0; + NRF_SPIM3->PSEL.SCK = 0xffffffffu; + NRF_SPIM3->PSEL.MOSI = 0xffffffffu; + NRF_SPIM3->PSEL.MISO = 0xffffffffu; + /* nRF52840 anomaly 195: SPIM3 keeps drawing current after disable unless + * this is written (nrfx_spim_uninit does the same). */ + *(volatile uint32_t *)0x4002F004 = 1; + spim_on = false; + } + nrf_gpio_pin_clear(PIN_RST); + nrf_gpio_cfg_default(PIN_CLK); + nrf_gpio_cfg_default(PIN_CMD); + nrf_gpio_cfg_default(PIN_DAT0); + nrf_gpio_cfg_default(PIN_RST); + nrf_gpio_cfg_output(PIN_VCCQ); + nrf_gpio_pin_clear(PIN_VCCQ); /* rail off; sp1_quiesce_peripherals agrees */ +} + +void sp1_emmc_abort(void) +{ + aborted = true; + sp1_emmc_power_down(); +} diff --git a/firmware/src/sp1_emmc.h b/firmware/src/sp1_emmc.h new file mode 100644 index 0000000..111012b --- /dev/null +++ b/firmware/src/sp1_emmc.h @@ -0,0 +1,96 @@ +/* + * wakes-sp1 — the SP-1's eMMC (M6, #43): Toshiba THGBMNG5D1LBAIL, 4 GB, wired 1-bit + * (CLK, CMD, DAT0, RST_n, VCCQ -- sp1_board.h). The nRF52840 has no SD/MMC peripheral, + * so the bus is bit-banged. + * + * Protocol from chattock/sp1-tape-looper firmware/src/sp1_emmc.c (MIT), itself ported + * from Tim Knapen's SP-1-dev emmc.c (MIT): the command framing, the response sampling + * points, the init sequence and the write framing are theirs, proven on this board. + * Payloads ride SPIM3 DMA at 16 MHz with bit-banged fallbacks (sp1_emmc.c, "fast + * transfer"); every block read is CRC-checked and every block write must get the card's + * "accepted" token. + * + * ⚠️ Commands sent: 0, 1, 2, 3, 7, 8, 12, 13, 16, 17, 18, 23, 24, 25. Nothing that touches EXT_CSD + * (CMD6), nothing that erases (CMD35/36/38), nothing that partitions. The card's OTP + * settings are never written. + * + * ⚠️ NOT watchdog-fed: this runs in the storage thread (sp1_store.c), and a background + * thread that fed the watchdog would hide a hung main loop. Every wait here is bounded. + * + * One caller at a time (the storage thread); sp1_emmc_abort() may come from main. + */ +#ifndef SP1_EMMC_H +#define SP1_EMMC_H + +#include +#include + +#define SP1_EMMC_BLOCK 512u + +/* What came back during identification, for the report. */ +struct sp1_emmc_ident { + uint32_t ocr; /* CMD1's final OCR */ + uint32_t ocr_tries; /* CMD1s until ready */ + uint32_t ready_ms; /* power-on to ready */ + uint8_t cid[16]; /* CID[127:0], MSB first */ + int8_t cid_shift; /* bit alignment the CID's CRC7 matched at (0 expected), */ + /* or -128 if no alignment matched */ +}; + +/* Counters since sp1_emmc_init(). */ +struct sp1_emmc_stats { + uint32_t cmd_retries; /* a command that needed more than one try */ + uint32_t crc_errs; /* data blocks whose CRC16 did not match (then retried) */ + uint32_t hunt_timeouts; /* a data block's start bit never came (100 ms) */ + uint32_t busy_timeouts; /* the card stayed busy after a write (500 ms) */ + uint32_t spim_timeouts; /* an SPIM3 transfer did not end (5 ms) */ + uint32_t wr_rejects; /* writes the card did not accept (then retried) */ + uint32_t wr_busy_max_us; /* longest programming busy after a write */ + uint32_t multi_blocks; /* blocks moved inside CMD18 / CMD25 bursts */ + uint32_t multi_fallbacks;/* bursts that had to finish block by block */ + uint32_t verify_fails; /* CONFIG_SP1_EMMC_VERIFY: written blocks read back wrong */ + uint32_t verify_fixed; /* ...and right after a single-block rewrite */ +}; + +/* Power the card, identify it, select it, block length 512, read its size. Bounded: + * gives up after ~1 s of CMD1 (JEDEC's allowance). `id` may be NULL. False = not + * usable; call sp1_emmc_power_down() either way. Clears a previous abort. */ +bool sp1_emmc_init(struct sp1_emmc_ident *id); + +bool sp1_emmc_ready(void); + +/* User-area size in blocks (EXT_CSD SEC_COUNT), 0 before a good init. */ +uint32_t sp1_emmc_sectors(void); + +/* CMD13: card status (bits 31..0). */ +bool sp1_emmc_status(uint32_t *status); + +/* CMD8 SEND_EXT_CSD: the 512-byte extended CSD. */ +bool sp1_emmc_read_ext_csd(uint8_t buf[SP1_EMMC_BLOCK]); + +/* CMD17 / CMD24: one block of the user area, by block number (sector-addressed card). + * Read: CRC-checked. Write: the card's CRC-status token must say "accepted", then its + * programming busy is waited out (bounded). Both retried up to 3 times. */ +bool sp1_emmc_read_block(uint32_t block, uint8_t buf[SP1_EMMC_BLOCK]); +bool sp1_emmc_write_block(uint32_t block, const uint8_t buf[SP1_EMMC_BLOCK]); + +/* `n` consecutive blocks in one CMD18 / CMD25 burst (fast transfer). A burst that fails + * part-way is stopped and the rest done block by block through the calls above, so the + * result is the same as n single calls, only faster. Reads are closed-ended (CMD23 first: + * open-ended reads return junk on this card -- sp1_emmc.c). `buf` must be in RAM for reads + * (SPIM3 DMAs into it); writes copy through a RAM frame, so any source works. */ +bool sp1_emmc_read_blocks(uint32_t block, uint8_t *buf, uint32_t n); +bool sp1_emmc_write_blocks(uint32_t block, const uint8_t *buf, uint32_t n); + +void sp1_emmc_get_stats(struct sp1_emmc_stats *s); + +/* Release the bus pins (disconnected inputs: nothing may back-feed an unpowered rail), + * RST_n low, VCCQ off. Safe at any time, and when init was never run. */ +void sp1_emmc_power_down(void); + +/* From the power-off path (sp1_store_abort): power down AND make every call fail until + * the next sp1_emmc_init(), so a storage thread caught mid-operation cannot drive the + * pins of a card whose rail is gone. */ +void sp1_emmc_abort(void); + +#endif /* SP1_EMMC_H */ diff --git a/firmware/src/sp1_emmc_report.c b/firmware/src/sp1_emmc_report.c new file mode 100644 index 0000000..dc5196e --- /dev/null +++ b/firmware/src/sp1_emmc_report.c @@ -0,0 +1,303 @@ +/* + * wakes-sp1 — the eMMC report (M6, #43). See sp1_emmc_report.h. + * + * Began as the read-only probe (2026-10-07, logs/sp1-20261007-152119.log): that run's + * full EXT_CSD and block-0 hex are in the log and private/docs/M6-PRST-PLAN.md, so the + * report now prints the decoded lines and only dumps a block it cannot classify. + * + * EXT_CSD field positions are JEDEC JESD84-B51 (eMMC 5.1), section 7.4. MBR and GPT + * layouts are the usual ones; FAT and exFAT boot sectors per Microsoft's specs. + */ +#include "sp1_emmc_report.h" +#include "sp1_emmc.h" +#include "sp1_console.h" + +#include +#include + +static uint8_t blk[SP1_EMMC_BLOCK]; +static uint8_t aux[SP1_EMMC_BLOCK]; + +static uint32_t le32(const uint8_t *p) +{ + return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | + ((uint32_t)p[3] << 24); +} + +static uint16_t le16(const uint8_t *p) +{ + return (uint16_t)(p[0] | (p[1] << 8)); +} + +/* printk is paced line by line: CDC ACM drops what it cannot send (sp1_console.c). + * No watchdog feed: this runs in the storage thread (sp1_emmc.h). */ +#define LINE(...) do { printk(__VA_ARGS__); sp1_console_pace(); } while (0) + +static void hexdump(const char *tag, const uint8_t *d, uint32_t n) +{ + for (uint32_t o = 0; o < n; o += 16u) { + char s[16 * 3 + 1]; + char *p = s; + for (uint32_t i = 0; i < 16u && o + i < n; i++) { + static const char hx[] = "0123456789abcdef"; + *p++ = ' '; + *p++ = hx[d[o + i] >> 4]; + *p++ = hx[d[o + i] & 15u]; + } + *p = '\0'; + LINE("EMMC %s %03x:%s\n", tag, (unsigned)o, s); + } +} + +/* Printable copy of a fixed-width text field. */ +static const char *text(const uint8_t *p, uint32_t n) +{ + static char s[40]; + if (n >= sizeof(s)) { + n = sizeof(s) - 1u; + } + for (uint32_t i = 0; i < n; i++) { + s[i] = (p[i] >= 0x20 && p[i] < 0x7f) ? (char)p[i] : '.'; + } + s[n] = '\0'; + return s; +} + +static void fill_counts(const uint8_t *d, uint32_t *zeros, uint32_t *ffs) +{ + *zeros = 0; + *ffs = 0; + for (uint32_t i = 0; i < SP1_EMMC_BLOCK; i++) { + *zeros += (d[i] == 0x00u); + *ffs += (d[i] == 0xffu); + } +} + +/* A volume boot sector: what filesystem, if any, starts at `lba`. Reads into aux. */ +static void boot_sector(const char *what, uint32_t lba) +{ + if (!sp1_emmc_read_block(lba, aux)) { + LINE("EMMC %s boot sector (block %u): READ FAILED\n", what, (unsigned)lba); + return; + } + const bool sig = (aux[510] == 0x55u && aux[511] == 0xaau); + if (memcmp(&aux[3], "EXFAT ", 8) == 0) { + LINE("EMMC %s: exFAT, %u-byte sectors, %u sectors/cluster, volume %u sectors, " + "sig %s\n", what, 1u << aux[108], 1u << aux[109], (unsigned)le32(&aux[72]), + sig ? "55aa" : "MISSING"); + } else if (memcmp(&aux[82], "FAT32", 5) == 0) { + LINE("EMMC %s: FAT32, OEM \"%s\"", what, text(&aux[3], 8)); + LINE(" label \"%s\", %u-byte sectors, %u sectors/cluster, %u reserved, %u FATs" + " of %u sectors, %u sectors total, sig %s\n", text(&aux[71], 11), + le16(&aux[11]), aux[13], le16(&aux[14]), aux[16], (unsigned)le32(&aux[36]), + (unsigned)le32(&aux[32]), sig ? "55aa" : "MISSING"); + } else if (memcmp(&aux[54], "FAT", 3) == 0) { + LINE("EMMC %s: %s,", what, text(&aux[54], 8)); + LINE(" OEM \"%s\",", text(&aux[3], 8)); + LINE(" label \"%s\", %u-byte sectors, %u sectors/cluster, sig %s\n", + text(&aux[43], 11), le16(&aux[11]), aux[13], sig ? "55aa" : "MISSING"); + } else if (memcmp(&aux[3], "NTFS", 4) == 0) { + LINE("EMMC %s: NTFS\n", what); + } else { + LINE("EMMC %s: no FAT/exFAT/NTFS boot sector (sig %s)\n", what, + sig ? "55aa" : "none"); + } + hexdump("vbr", aux, 64); +} + +static void decode_ext_csd(const uint8_t *x) +{ + static const char *const rev[] = { "4.0", "4.1", "4.2", "4.3", "?", "4.41", "4.5", + "5.0", "5.1" }; + const uint32_t sectors = le32(&x[212]); + LINE("EMMC EXT_CSD rev %u (eMMC %s), %u sectors = %u MB, device type 0x%02x\n", + x[192], x[192] < ARRAY_SIZE(rev) ? rev[x[192]] : "?", (unsigned)sectors, + (unsigned)(sectors / 2048u), x[196]); + LINE("EMMC EXT_CSD boot partitions 2 x %u KB, RPMB %u KB, boot config 0x%02x," + " partitioning support 0x%02x, setting completed %u\n", + x[226] * 128u, x[168] * 128u, x[179], x[160], x[155]); + LINE("EMMC EXT_CSD erase group %u KB (HC, def %u), WP group %u, trim mult %u," + " sec features 0x%02x\n", x[224] * 512u, x[175], x[221], x[230], x[229]); + LINE("EMMC EXT_CSD reliable write: param 0x%02x set 0x%02x sectors %u\n", + x[166], x[167], x[222]); + LINE("EMMC EXT_CSD cache %u (ctrl %u), power-off notify %u, RST_n function %u," + " HPI 0x%02x, BKOPS support %u\n", (unsigned)le32(&x[249]), x[33], x[34], x[162], + x[503], x[502]); + LINE("EMMC EXT_CSD bus width %u, HS timing %u, life A 0x%02x B 0x%02x," + " pre-EOL 0x%02x, firmware %02x%02x%02x%02x%02x%02x%02x%02x\n", + x[183], x[185], x[268], x[269], x[267], x[261], x[260], x[259], x[258], x[257], + x[256], x[255], x[254]); +} + +static void decode_cid(const struct sp1_emmc_ident *id) +{ + const uint8_t *c = id->cid; + hexdump("cid", c, 16); + if (id->cid_shift == -128) { + LINE("EMMC CID: CRC7 matched at NO alignment -- response sampling is off\n"); + } else { + LINE("EMMC CID: CRC7 ok at alignment %d%s\n", id->cid_shift, + id->cid_shift == 0 ? " (as expected)" : " -- NOT the expected 0"); + } + /* MDT: month in the high nibble; the year nibble counts from 1997, or from 2013 on + * an EXT_CSD rev > 4 part -- printed raw, the rev is on the EXT_CSD line. */ + LINE("EMMC CID: MID 0x%02x, CBX %u, OID 0x%02x, product \"%s\", rev %u.%u," + " serial 0x%08x, month %u year code %u\n", c[0], c[1] & 3u, c[2], + text(&c[3], 6), c[9] >> 4, c[9] & 15u, + (unsigned)(((uint32_t)c[10] << 24) | ((uint32_t)c[11] << 16) | + ((uint32_t)c[12] << 8) | c[13]), c[14] >> 4, c[14] & 15u); +} + +static void decode_gpt(void) +{ + if (!sp1_emmc_read_block(1, aux) || memcmp(aux, "EFI PART", 8) != 0) { + LINE("EMMC GPT: no header at block 1\n"); + return; + } + const uint32_t entries_lba = le32(&aux[72]); + const uint32_t n = le32(&aux[80]); + const uint32_t size = le32(&aux[84]); + LINE("EMMC GPT: %u entries of %u bytes at block %u\n", (unsigned)n, (unsigned)size, + (unsigned)entries_lba); + if (size != 128u || !sp1_emmc_read_block(entries_lba, blk)) { + return; + } + uint32_t first[4] = { 0 }; + for (uint32_t i = 0; i < 4u && i < n; i++) { + const uint8_t *e = &blk[i * 128u]; + bool used = false; + for (int k = 0; k < 16; k++) { + used |= (e[k] != 0u); + } + if (!used) { + continue; + } + char name[37]; + for (int k = 0; k < 36; k++) { /* UTF-16LE, ASCII only */ + const uint8_t ch = e[56 + 2 * k]; + name[k] = (ch >= 0x20 && ch < 0x7f) ? (char)ch : (ch ? '?' : '\0'); + } + name[36] = '\0'; + first[i] = le32(&e[32]); + LINE("EMMC GPT p%u: blocks %u..%u \"%s\"\n", (unsigned)(i + 1), + (unsigned)first[i], (unsigned)le32(&e[40]), name); + } + for (uint32_t i = 0; i < 4u; i++) { + if (first[i] != 0u) { + char what[8] = "p?"; + what[1] = (char)('1' + i); + boot_sector(what, first[i]); + } + } +} + +/* Block 0: MBR, a bare FAT volume, sp1-tape-looper's index, or something else. */ +static void decode_block0(void) +{ + if (!sp1_emmc_read_block(0, blk)) { + LINE("EMMC block 0: READ FAILED\n"); + return; + } + + const uint32_t magic = le32(blk); + if ((magic >> 16) == 0x5345u) { /* 'S' 'E' ..: the looper's META_MAGIC */ + LINE("EMMC block 0: sp1-tape-looper's song index (magic 0x%08x \"%s\")\n", + (unsigned)magic, text(blk, 4)); + } + const bool sig = (blk[510] == 0x55u && blk[511] == 0xaau); + if (!sig) { + uint32_t z, f; + fill_counts(blk, &z, &f); + LINE("EMMC block 0: no 55aa signature, so no MBR (%u x 00, %u x ff)\n", + (unsigned)z, (unsigned)f); + hexdump("b0", blk, 64); + return; + } + if ((blk[0] == 0xebu || blk[0] == 0xe9u) && + (memcmp(&blk[82], "FAT", 3) == 0 || memcmp(&blk[54], "FAT", 3) == 0 || + memcmp(&blk[3], "EXFAT", 5) == 0)) { + LINE("EMMC block 0: a filesystem with no partition table\n"); + boot_sector("vol", 0); + return; + } + LINE("EMMC block 0: MBR, disk signature 0x%08x\n", (unsigned)le32(&blk[440])); + uint32_t start[4] = { 0 }; + bool gpt = false; + for (uint32_t i = 0; i < 4u; i++) { + const uint8_t *e = &blk[446u + 16u * i]; + if (e[4] == 0u) { + continue; + } + start[i] = le32(&e[8]); + gpt |= (e[4] == 0xeeu); + LINE("EMMC MBR p%u: status 0x%02x type 0x%02x, blocks %u + %u (%u MB)\n", + (unsigned)(i + 1), e[0], e[4], (unsigned)start[i], (unsigned)le32(&e[12]), + (unsigned)(le32(&e[12]) / 2048u)); + } + if (gpt) { + decode_gpt(); + return; + } + for (uint32_t i = 0; i < 4u; i++) { + if (start[i] != 0u) { + char what[4] = "p?"; + what[1] = (char)('1' + i); + boot_sector(what, start[i]); + } + } +} + +void sp1_emmc_report_init(bool ok, const struct sp1_emmc_ident *id) +{ + LINE("EMMC init %s: %u CMD1s, %u ms to ready, OCR 0x%08x (%s), %u blocks\n", + ok ? "ok" : "FAILED", (unsigned)id->ocr_tries, (unsigned)id->ready_ms, + (unsigned)id->ocr, (id->ocr & 0x40000000u) ? "sector mode" : "byte mode", + (unsigned)sp1_emmc_sectors()); + if (!ok) { + struct sp1_emmc_stats s; + sp1_emmc_get_stats(&s); + LINE("EMMC gave up (command retries %u)\n", (unsigned)s.cmd_retries); + return; + } + decode_cid(id); +} + +void sp1_emmc_report_card(void) +{ + uint32_t status = 0; + if (sp1_emmc_status(&status)) { + static const char *const state[] = { "idle", "ready", "ident", "stby", "tran", + "data", "rcv", "prg", "dis", "btst", "slp" }; + const uint32_t s = (status >> 9) & 15u; + LINE("EMMC status 0x%08x: state %s%s\n", (unsigned)status, + s < ARRAY_SIZE(state) ? state[s] : "?", + /* JEDEC error bits: 31-26, 24-19, 16, 15, 7 */ + (status & 0xfdf98080u) ? ", ERROR BITS SET" : ""); + } else { + LINE("EMMC status: no response\n"); + } + + if (sp1_emmc_read_ext_csd(aux)) { + decode_ext_csd(aux); + } else { + LINE("EMMC EXT_CSD: READ FAILED\n"); + } + decode_block0(); +} + +void sp1_emmc_report_stats(void) +{ + struct sp1_emmc_stats s; + sp1_emmc_get_stats(&s); + LINE("EMMC errors: command retries %u, read CRC %u, write rejects %u, timeouts: " + "data %u busy %u spim %u; longest write busy %u us\n", (unsigned)s.cmd_retries, + (unsigned)s.crc_errs, (unsigned)s.wr_rejects, (unsigned)s.hunt_timeouts, + (unsigned)s.busy_timeouts, (unsigned)s.spim_timeouts, + (unsigned)s.wr_busy_max_us); + LINE("EMMC fast transfer: %u blocks in multi-block bursts, %u bursts finished " + "block by block\n", (unsigned)s.multi_blocks, (unsigned)s.multi_fallbacks); + if (IS_ENABLED(CONFIG_SP1_EMMC_VERIFY)) { + LINE("EMMC verify: %u written blocks read back wrong, %u right after a rewrite\n", + (unsigned)s.verify_fails, (unsigned)s.verify_fixed); + } +} diff --git a/firmware/src/sp1_emmc_report.h b/firmware/src/sp1_emmc_report.h new file mode 100644 index 0000000..80ff9ea --- /dev/null +++ b/firmware/src/sp1_emmc_report.h @@ -0,0 +1,19 @@ +/* + * wakes-sp1 — the eMMC report (M6, #43; CONFIG_SP1_STORAGE_TEST). + * + * Decoded console lines, every one starting "EMMC": what came back during init (CID, + * OCR, size), the card's state and EXT_CSD, block 0 (MBR / GPT / a bare FAT volume / + * sp1-tape-looper's index) with the boot sector of each partition, and the driver's + * error counters. Reads only. Storage thread only (sp1_store.c); paced for CDC ACM. + */ +#ifndef SP1_EMMC_REPORT_H +#define SP1_EMMC_REPORT_H + +#include +#include "sp1_emmc.h" + +void sp1_emmc_report_init(bool ok, const struct sp1_emmc_ident *id); +void sp1_emmc_report_card(void); +void sp1_emmc_report_stats(void); + +#endif /* SP1_EMMC_REPORT_H */ diff --git a/firmware/src/sp1_power.c b/firmware/src/sp1_power.c index b736dbd..3b90ae7 100644 --- a/firmware/src/sp1_power.c +++ b/firmware/src/sp1_power.c @@ -13,6 +13,9 @@ #include "sp1_led.h" #include "sp1_ui_timing.h" #include "sp1_audio.h" +#if defined(CONFIG_SP1_STORAGE) +#include "sp1_store.h" +#endif #include #include @@ -132,6 +135,13 @@ void sp1_quiesce_peripherals(void) * else succeeding. Safe when audio was never started. */ sp1_audio_stop(); +#if defined(CONFIG_SP1_STORAGE) + /* M6 (#43): stop the storage thread's eMMC job and release the card's bus pins + * BEFORE its rail goes, so nothing drives an unpowered card. Never waits: a job cut + * short just fails its remaining steps (sp1_store.h). */ + sp1_store_abort(); +#endif + /* The speaker amp, headphone codec, audio oscillator and eMMC I/O rail are * separate chips held up by retained GPIO levels. Leaving them powered is * what drains the battery overnight, and a clockless amp murmurs audibly. @@ -309,6 +319,17 @@ static void gesture_reset(void) bool sp1_power_on_hold(void) { uint32_t held = 0u; +#if defined(CONFIG_SP1_DRIVE) + /* Drive mode (M6, #43, Adara): while the computer reads or writes the card, ON + * would take the card from under it, so every transfer restarts the FILL (not the + * dark window). ON needs SP1_PWR_ON_FILL_MS of quiet with "••" held. Only real block + * transfers count (sp1_store_activity), never the host's "medium?" polls, so an idle + * computer delays nothing. No time limit, deliberately (Adara): a limit would undo + * the protection, and eject or unplug always ends the transfers. + * ⚠️ Delays power-ON only. Power-off and the 30 s backstop are not in this path. */ + uint32_t act_seen = sp1_store_activity(); + uint32_t held_back = 0u; +#endif /* DO NOT initialise the LEDs here. The PWM devices are deferred-init, so * during the silent window their pins are still untouched -- and that, not @@ -367,6 +388,17 @@ bool sp1_power_on_hold(void) return false; } +#if defined(CONFIG_SP1_DRIVE) + const uint32_t act = sp1_store_activity(); + if (act != act_seen) { + act_seen = act; + if (held > SP1_PWR_ON_DARK_MS) { + held = SP1_PWR_ON_DARK_MS; /* the fill starts again */ + held_back++; + } + } +#endif + if (held >= SP1_PWR_ON_DARK_MS) { /* Past the silent window: now it is safe to claim the pins. * Idempotent, so this costs nothing after the first tick. */ @@ -397,6 +429,13 @@ bool sp1_power_on_hold(void) held += SP1_TICK_MS; } +#if defined(CONFIG_SP1_DRIVE) + if (held_back > 0u) { + printk("PWR power-on fill restarted %u x by the computer's transfers\n", + held_back); + } +#endif + /* Accepted, so the device is booting: make sure the rows are up even if the * fill never ran (it always does, but do not depend on that). */ (void)sp1_led_init(); diff --git a/firmware/src/sp1_power.h b/firmware/src/sp1_power.h index b6b32b8..05ec8a8 100644 --- a/firmware/src/sp1_power.h +++ b/firmware/src/sp1_power.h @@ -69,6 +69,10 @@ bool sp1_fnc_pressed(void); * left DISARMED until "••" is released, so a continuous press cannot roll from * power-on straight into power-off. * + * With CONFIG_SP1_DRIVE, every block the computer reads or writes restarts the fill, so + * ON needs SP1_PWR_ON_FILL_MS without a transfer (M6, #43): turning ON takes the card + * from the computer. No time limit; the hold blocks for as long as the transfers last. + * * Does not power anything off; the caller decides what an early release means. */ bool sp1_power_on_hold(void); diff --git a/firmware/src/sp1_standby.c b/firmware/src/sp1_standby.c index c97a10f..5d3f107 100644 --- a/firmware/src/sp1_standby.c +++ b/firmware/src/sp1_standby.c @@ -5,6 +5,10 @@ #include "sp1_power.h" #include "sp1_ui_timing.h" #include "sp1_console.h" +#if defined(CONFIG_SP1_DRIVE) +#include "sp1_store.h" +#include "sp1_usbd.h" +#endif #include @@ -22,6 +26,14 @@ void sp1_standby_run(void) sp1_charger_enable(true); uint32_t poll_ms = SP1_STANDBY_POLL_MS; /* force a sample on entry */ uint32_t breath_ms = 0u; +#if defined(CONFIG_SP1_DRIVE) + /* Drive mode (M6): the activity chase on the model row, T1 T3 T2 T4. */ + static const uint8_t chase[4] = { 0u, 2u, 1u, 3u }; + uint32_t act_seen = sp1_store_activity(); + uint32_t step_ms = SP1_DRIVE_STEP_MS; + unsigned chase_i = 0u; + sp1_store_standby_enter(); +#endif sp1_leds_all_off(); sp1_console_set_status_period(SP1_CONSOLE_PERIOD_STANDBY_MS); @@ -113,13 +125,26 @@ void sp1_standby_run(void) draw_bar(level, SP1_STANDBY_BAR_LEVEL); } - /* Status lights, dim, on the model row: T2 = plugged, T3 = charging. - * T1/T4 stay dark so the pair reads as a symmetric indicator. */ - sp1_led_set(SP1_ROW_TRACK, 0, 0); - sp1_led_set(SP1_ROW_TRACK, 1, SP1_STANDBY_STATUS_LEVEL); - sp1_led_set(SP1_ROW_TRACK, 2, - charging ? SP1_STANDBY_STATUS_LEVEL : 0u); - sp1_led_set(SP1_ROW_TRACK, 3, 0); +#if defined(CONFIG_SP1_DRIVE) + /* Drive mode: a host (not a charger) gets the card, once per visit. Then each + * tick that saw host transfers -- at most one step per SP1_DRIVE_STEP_MS -- + * lights the next LED of the chase at 50 % and ramps it down. The transfer + * path only counts (sp1_store_activity); all of the drawing is here. */ + sp1_store_standby_tick(sp1_usbd_host()); + step_ms += SP1_TICK_MS; + const uint32_t act = sp1_store_activity(); + if (act != act_seen && step_ms >= SP1_DRIVE_STEP_MS) { + act_seen = act; + step_ms = 0u; + const int led = chase[chase_i++ & 3u]; + sp1_led_set(SP1_ROW_TRACK, led, SP1_DRIVE_LED_PEAK); + sp1_led_fade(SP1_ROW_TRACK, led, 0u, SP1_DRIVE_RAMP_MS); + } +#endif + + /* No status lights on the model row any more (Adara, M6): the play-row bar's + * breathing already says "charging", and the row belongs to the drive's + * activity. It stays dark otherwise. */ sp1_led_tick(SP1_TICK_MS); k_msleep(SP1_TICK_MS); diff --git a/firmware/src/sp1_store.c b/firmware/src/sp1_store.c new file mode 100644 index 0000000..25e6bc4 --- /dev/null +++ b/firmware/src/sp1_store.c @@ -0,0 +1,851 @@ +/* + * wakes-sp1 — storage on the eMMC (M6, #43). See sp1_store.h. + * + * FatFs (ChaN, R0.16, through Zephyr's fs layer) sits on a disk driver here that reads + * and writes single blocks through sp1_emmc.c. Every console line starts "STORE" (this + * file) or "EMMC" (sp1_emmc_report.c). + */ +#include "sp1_store.h" +#include "sp1_emmc.h" +#include "sp1_console.h" +#if defined(CONFIG_SP1_STORAGE_TEST) +#include "sp1_emmc_report.h" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include + +#define DISK_NAME "EMMC" /* = CONFIG_FS_FATFS_CUSTOM_MOUNT_POINTS */ +#define MNT "/EMMC:" +#define DIR_WAKES MNT "/WAKES" + +/* The partition starts one erase group in: 8192 blocks = 4 MB (EXT_CSD + * HC_ERASE_GRP_SIZE 8 x 512 KB on this card, logs/sp1-20261007-152119.log). */ +#define PART_START 8192u + +#define LINE(...) do { printk(__VA_ARGS__); sp1_console_pace(); } while (0) + +static volatile bool stop; + +/* ---- who owns the card (drive mode, M6) ---- + * Two disks over one card: "EMMC" is Wakes' (FatFs, this thread) and "DRIVE" the host's + * (the mass-storage class, its own thread). Exactly one may move data at a time, decided by + * `owner` and enforced by `card_lock`, which every transfer on either disk holds -- so a + * change of owner, made under the lock, waits for the transfer in flight and no other. */ +enum owner { OWN_NONE = 0, OWN_WAKES, OWN_HOST }; +static atomic_t owner = ATOMIC_INIT(OWN_NONE); +static K_MUTEX_DEFINE(card_lock); +static atomic_t activity; /* host transfers, for STANDBY's LEDs */ +static atomic_t vol_state = ATOMIC_INIT(SP1_STORE_VOL_UNKNOWN); + +#if defined(CONFIG_SP1_STORAGE_TEST) +/* Where the data region starts, from the last mount (FATFS database): the file test's + * mismatch report turns a cluster into an LBA with it. */ +static uint32_t r_data; +#endif + +/* Jobs waiting for the thread (a bit each), so a request made while another job runs is + * queued rather than dropped: turning ON must always take the card back from a host. */ +#define JOB_ON BIT(0) +#define JOB_HOST BIT(1) +static atomic_t pending; + +/* What main's storage_gate() reads (sp1_store.h). */ +static atomic_t phase = ATOMIC_INIT(SP1_STORE_READY); +static atomic_t fmt_result = ATOMIC_INIT(SP1_STORE_FMT_NONE); +static atomic_t progress; +static bool counting; /* a format is running: count its writes */ +static uint32_t fmt_written; +static uint32_t fmt_expected = 1u; + +/* Every block write goes through here, so a format's progress can be counted. */ +static bool wr(uint32_t block, const uint8_t *buf) +{ + if (!sp1_emmc_write_block(block, buf)) { + return false; + } + if (counting) { + fmt_written++; + const uint32_t p = fmt_written * 255u / fmt_expected; + atomic_set(&progress, (atomic_val_t)(p > 254u ? 254u : p)); /* 255 = stamped */ + } + return true; +} + +/* ---------------------------------------------------------------- the disk */ + +/* FatFs sees blocks [view_base, view_base + view_count). Normally the whole card; while + * formatting, the partition alone, so FatFs builds a volume that starts at the + * partition's first block (format_card). */ +static uint32_t view_base; +static uint32_t view_count; + +static int d_init(struct disk_info *d) +{ + ARG_UNUSED(d); + return sp1_emmc_ready() ? 0 : -EIO; /* the job powers the card up itself */ +} + +static int d_status(struct disk_info *d) +{ + ARG_UNUSED(d); + return sp1_emmc_ready() ? DISK_STATUS_OK : DISK_STATUS_UNINIT; +} + +static int d_read(struct disk_info *d, uint8_t *buf, uint32_t start, uint32_t n) +{ + ARG_UNUSED(d); + if (start >= view_count || n > view_count - start) { + return -EIO; + } + k_mutex_lock(&card_lock, K_FOREVER); + const bool ok = atomic_get(&owner) == OWN_WAKES && + sp1_emmc_read_blocks(view_base + start, buf, n); + k_mutex_unlock(&card_lock); + return ok ? 0 : -EIO; +} + +static int d_write(struct disk_info *d, const uint8_t *buf, uint32_t start, uint32_t n) +{ + ARG_UNUSED(d); + if (start >= view_count || n > view_count - start) { + return -EIO; + } + k_mutex_lock(&card_lock, K_FOREVER); + bool ok = atomic_get(&owner) == OWN_WAKES; + if (ok && counting) { /* a format: block by block, for the bar */ + for (uint32_t i = 0; ok && i < n; i++) { + ok = wr(view_base + start + i, buf + i * SP1_EMMC_BLOCK); + } + } else if (ok) { + ok = sp1_emmc_write_blocks(view_base + start, buf, n); + } + k_mutex_unlock(&card_lock); + return ok ? 0 : -EIO; +} + +static int d_ioctl(struct disk_info *d, uint8_t cmd, void *buf) +{ + ARG_UNUSED(d); + switch (cmd) { + case DISK_IOCTL_GET_SECTOR_COUNT: + *(uint32_t *)buf = view_count; + return 0; + case DISK_IOCTL_GET_SECTOR_SIZE: + *(uint32_t *)buf = SP1_EMMC_BLOCK; + return 0; + case DISK_IOCTL_GET_ERASE_BLOCK_SZ: /* in blocks: f_mkfs aligns the data area */ + *(uint32_t *)buf = PART_START; + return 0; + case DISK_IOCTL_CTRL_SYNC: /* the card's write cache is off */ + case DISK_IOCTL_CTRL_DEINIT: /* the job powers the card down itself */ + return 0; + case DISK_IOCTL_CTRL_INIT: + return sp1_emmc_ready() ? 0 : -EIO; + default: + return -EINVAL; + } +} + +static const struct disk_operations disk_ops = { + .init = d_init, .status = d_status, .read = d_read, .write = d_write, + .ioctl = d_ioctl, +}; + +static struct disk_info disk = { .name = DISK_NAME, .ops = &disk_ops }; + +#if defined(CONFIG_SP1_DRIVE) +/* ---------------------------------------------------------------- the host's disk */ + +#include + +/* The whole card, block 0 (the MBR) included, so the host sees the partition table and + * mounts the FAT32 volume itself. "No medium" whenever the host does not own it -- which + * is how the drive looks while ON (Adara: the interface stays, the card goes). */ +#define HOST_DISK "DRIVE" + +static int h_init(struct disk_info *d) +{ + ARG_UNUSED(d); + return 0; /* the HOST job powers the card */ +} + +static int h_status(struct disk_info *d) +{ + ARG_UNUSED(d); + return (atomic_get(&owner) == OWN_HOST && sp1_emmc_ready()) ? DISK_STATUS_OK + : DISK_STATUS_NOMEDIA; +} + +static int h_read(struct disk_info *d, uint8_t *buf, uint32_t start, uint32_t n) +{ + ARG_UNUSED(d); + k_mutex_lock(&card_lock, K_FOREVER); + const bool ok = atomic_get(&owner) == OWN_HOST && sp1_emmc_read_blocks(start, buf, n); + k_mutex_unlock(&card_lock); + atomic_inc(&activity); + return ok ? 0 : -EIO; +} + +static int h_write(struct disk_info *d, const uint8_t *buf, uint32_t start, uint32_t n) +{ + ARG_UNUSED(d); + k_mutex_lock(&card_lock, K_FOREVER); + const bool ok = atomic_get(&owner) == OWN_HOST && sp1_emmc_write_blocks(start, buf, n); + k_mutex_unlock(&card_lock); + atomic_inc(&activity); + return ok ? 0 : -EIO; +} + +static int h_ioctl(struct disk_info *d, uint8_t cmd, void *buf) +{ + ARG_UNUSED(d); + switch (cmd) { + case DISK_IOCTL_GET_SECTOR_COUNT: + *(uint32_t *)buf = sp1_emmc_sectors(); + return 0; + case DISK_IOCTL_GET_SECTOR_SIZE: + *(uint32_t *)buf = SP1_EMMC_BLOCK; + return 0; + case DISK_IOCTL_GET_ERASE_BLOCK_SZ: + *(uint32_t *)buf = PART_START; + return 0; + case DISK_IOCTL_CTRL_SYNC: /* the card's write cache is off */ + case DISK_IOCTL_CTRL_INIT: + case DISK_IOCTL_CTRL_DEINIT: + return 0; + default: + return -EINVAL; + } +} + +static const struct disk_operations host_ops = { + .init = h_init, .status = h_status, .read = h_read, .write = h_write, + .ioctl = h_ioctl, +}; + +static struct disk_info host_disk = { .name = HOST_DISK, .ops = &host_ops }; + +/* T10 identity: vendor 8 characters, product 16, revision 4. */ +USBD_DEFINE_MSC_LUN(sp1_drive, HOST_DISK, "Wakes", "SP-1 storage", "1.0"); +#endif /* CONFIG_SP1_DRIVE */ + +/* ---------------------------------------------------------------- the volume */ + +static FATFS fat; +static struct fs_mount_t mnt = { + .type = FS_FATFS, + .fs_data = &fat, + .mnt_point = MNT, + /* ⚠️ Never format on mount. The only formatter is format_card(), fresh only. */ + .flags = FS_MOUNT_FLAG_NO_FORMAT, +}; +static bool mounted; + +static int mount_vol(void) +{ + if (!mounted) { + const int rc = fs_mount(&mnt); + mounted = (rc == 0); +#if defined(CONFIG_SP1_STORAGE_TEST) + if (mounted) { + r_data = (uint32_t)fat.database; + } +#endif + return rc; + } + return 0; +} + +static void unmount_vol(void) +{ + if (mounted) { + (void)fs_unmount(&mnt); + mounted = false; + } +} + +/* Used by the fresh stamp and the storage test now; by PRST (#43) next. */ +__maybe_unused static int write_file(const char *path, const void *d, size_t n) +{ + struct fs_file_t f; + fs_file_t_init(&f); + int rc = fs_open(&f, path, FS_O_CREATE | FS_O_WRITE); + if (rc != 0) { + return rc; + } + rc = fs_truncate(&f, 0); + if (rc == 0) { + const ssize_t w = fs_write(&f, d, n); + rc = (w == (ssize_t)n) ? 0 : (w < 0 ? (int)w : -EIO); + } + const int rc2 = fs_close(&f); + return rc != 0 ? rc : rc2; +} + +__maybe_unused static int read_file(const char *path, void *d, size_t max, size_t *got) +{ + struct fs_file_t f; + fs_file_t_init(&f); + *got = 0; + int rc = fs_open(&f, path, FS_O_READ); + if (rc != 0) { + return rc; + } + const ssize_t r = fs_read(&f, d, max); + rc = (r < 0) ? (int)r : 0; + *got = (r > 0) ? (size_t)r : 0u; + (void)fs_close(&f); + return rc; +} + +/* ---------------------------------------------------------------- fresh */ + +#if defined(CONFIG_SP1_FRESH) + +#define STAMP DIR_WAKES "/FRESH.ID" + +static uint8_t sec[SP1_EMMC_BLOCK]; /* block 0, the boot sectors, the MBR */ + +/* Different for every build of the fresh image, so each one formats once. */ +static const char image_id[] = "Wakes v" APP_VERSION_STRING " fresh, built " + __DATE__ " " __TIME__; + +static void put32(uint8_t *p, uint32_t v) +{ + p[0] = (uint8_t)v; + p[1] = (uint8_t)(v >> 8); + p[2] = (uint8_t)(v >> 16); + p[3] = (uint8_t)(v >> 24); +} + +/* One FAT32 partition at PART_START, the MBR written last. */ +static int format_card(void) +{ + const uint32_t total = sp1_emmc_sectors(); + if (total < 4u * PART_START) { + return -EINVAL; + } + + /* The progress bar's denominator: what f_mkfs writes for FAT32 (R0.16) -- the boot + * sector, its backup and the two FSINFO sectors, both FATs, the root cluster -- plus + * our block 0 twice, the two HiddSec patches, then WAKES' own cluster (mkdir zeroes + * all 64 blocks of it) and the stamp. Hardware 2026-10-07: 2035 writes, against + * 1966 before the mkdir cluster was counted (logs/sp1-20261007-173828.log). */ + const uint32_t clusters = (total - PART_START) / 64u; + const uint32_t sz_fat = ((clusters + 2u) * 4u + SP1_EMMC_BLOCK - 1u) / SP1_EMMC_BLOCK; + fmt_expected = 4u + 2u * sz_fat + 64u + 4u + 64u + 6u; + fmt_written = 0u; + atomic_set(&progress, 0); + counting = true; + + /* 1. Invalidate block 0 first: a format cut short then leaves NO partition table, + * rather than an old one pointing at a half-made volume. */ + memset(sec, 0, sizeof(sec)); + if (!wr(0, sec)) { + return -EIO; + } + + /* 2. FAT32 into the partition, which FatFs sees as a whole disk. */ + view_base = PART_START; + view_count = total - PART_START; + MKFS_PARM opt = { + .fmt = FM_FAT32 | FM_SFD, /* no table of its own: we write the MBR */ + .n_fat = 2, /* as a computer's formatter would */ + .align = 0, /* from the disk: PART_START (erase group) */ + .n_root = 0, /* FAT32: root is a cluster chain */ + .au_size = 32768, /* 32 KB clusters */ + }; + int rc = fs_mkfs(FS_FATFS, (uintptr_t)DISK_NAME ":", &opt, 0); + view_base = 0; + view_count = total; + if (rc != 0) { + return rc; + } + + /* 3. BPB_HiddSec (offset 28) = the partition's start, in the boot sector and its + * backup (BPB_BkBootSec, offset 50). FatFs ignores it; other systems may not. */ + if (!sp1_emmc_read_block(PART_START, sec) || memcmp(&sec[82], "FAT32", 5) != 0) { + return -EIO; + } + const uint32_t backup = (uint32_t)sec[50] | ((uint32_t)sec[51] << 8); + put32(&sec[28], PART_START); + if (!wr(PART_START, sec)) { + return -EIO; + } + if (backup != 0u) { + if (!sp1_emmc_read_block(PART_START + backup, sec)) { + return -EIO; + } + put32(&sec[28], PART_START); + if (!wr(PART_START + backup, sec)) { + return -EIO; + } + } + + /* 4. The MBR: one partition, type 0x0C (FAT32, LBA). CHS fields are the + * "beyond CHS" marker; everything reads the LBA fields. */ + memset(sec, 0, sizeof(sec)); + put32(&sec[440], k_cycle_get_32() ^ total); /* disk signature */ + uint8_t *e = &sec[446]; + e[0] = 0x00; + e[1] = 0xfe; e[2] = 0xff; e[3] = 0xff; + e[4] = 0x0c; + e[5] = 0xfe; e[6] = 0xff; e[7] = 0xff; + put32(&e[8], PART_START); + put32(&e[12], total - PART_START); + sec[510] = 0x55; + sec[511] = 0xaa; + return wr(0, sec) ? 0 : -EIO; +} + +static void fresh(void) +{ + static char found[sizeof(image_id) + 8]; + size_t n = 0; + const int mrc = mount_vol(); + int rc = mrc; + if (rc == 0) { + rc = read_file(STAMP, found, sizeof(found) - 1u, &n); + found[rc == 0 ? n : 0u] = '\0'; + if (rc == 0 && strcmp(found, image_id) == 0) { + LINE("STORE fresh: formatted by this image already -- not formatting\n"); + return; + } + } + if (mrc != 0) { + LINE("STORE fresh: no Wakes filesystem on the card -- FORMATTING\n"); + } else if (rc != 0) { + LINE("STORE fresh: a filesystem with no fresh stamp -- FORMATTING\n"); + } else { + LINE("STORE fresh: formatted by \"%s\" -- FORMATTING\n", found); + } + unmount_vol(); + + /* From here main's storage_gate() shows the progress bar and holds the UI. */ + atomic_set(&fmt_result, SP1_STORE_FMT_FAILED); /* until it is stamped */ + atomic_set(&phase, SP1_STORE_FORMATTING); + const uint32_t t0 = k_uptime_get_32(); + rc = format_card(); + LINE("STORE fresh: format %s (%d) in %u ms: FAT32 at block %u, %u blocks\n", + rc == 0 ? "done" : "FAILED", rc, (unsigned)(k_uptime_get_32() - t0), + (unsigned)PART_START, (unsigned)(sp1_emmc_sectors() - PART_START)); + if (rc == 0 && !stop) { + rc = mount_vol(); + if (rc == 0) { + rc = fs_mkdir(DIR_WAKES); + } + if (rc == 0) { + /* The volume label: what a computer calls the drive instead of + * "Removable Disk" (Adara). FAT labels are upper case; '-' is legal. */ + const FRESULT fr = f_setlabel(DISK_NAME ":SP-1"); + rc = (fr == FR_OK) ? 0 : -EIO; + } + if (rc == 0) { + /* The stamp goes LAST: if anything before it failed, the next ON + * formats again. */ + rc = write_file(STAMP, image_id, strlen(image_id)); + } + LINE("STORE fresh: %s \"%s\"%s\n", rc == 0 ? "stamped" : "stamp FAILED", + image_id, rc == 0 ? "" : " -- will format again at the next ON"); + } + counting = false; + LINE("STORE fresh: %u block writes against %u expected\n", (unsigned)fmt_written, + (unsigned)fmt_expected); + if (rc == 0 && !stop) { + atomic_set(&progress, 255); + atomic_set(&fmt_result, SP1_STORE_FMT_DONE); + } + unmount_vol(); /* the ON job mounts again and decides the volume state */ +} + +#endif /* CONFIG_SP1_FRESH */ + +/* ---------------------------------------------------------------- the test */ + +#if defined(CONFIG_SP1_STORAGE_TEST) + +#define BOOTS DIR_WAKES "/BOOTS.TXT" +#define TESTFILE DIR_WAKES "/TEST.BIN" +#define TEST_KB 512u +/* 16 KB chunks: FatFs hands a whole-sector write straight to the disk, so each one is a + * 32-block burst -- what fast transfer is for. Test builds only. */ +#define CHUNK 16384u +static uint8_t bulk[CHUNK]; + +static uint8_t pattern(uint32_t i, uint32_t seed) +{ + return (uint8_t)(i * 131u + seed * 7u + (i >> 9)); +} + +static void file_test(void) +{ + int rc = fs_mkdir(DIR_WAKES); + if (rc != 0 && rc != -EEXIST) { + LINE("STORE test: mkdir WAKES FAILED (%d)\n", rc); + return; + } + + /* A counter that survives power cycles and reflashes: read, +1, write, read back. */ + char txt[16]; + size_t n = 0; + uint32_t boots = 0; + if (read_file(BOOTS, txt, sizeof(txt) - 1u, &n) == 0) { + for (size_t i = 0; i < n && txt[i] >= '0' && txt[i] <= '9'; i++) { + boots = boots * 10u + (uint32_t)(txt[i] - '0'); + } + } + boots++; + snprintk(txt, sizeof(txt), "%u\n", (unsigned)boots); + rc = write_file(BOOTS, txt, strlen(txt)); + char back[16]; + if (rc == 0) { + rc = read_file(BOOTS, back, sizeof(back) - 1u, &n); + } + const bool same = (rc == 0 && n == strlen(txt) && memcmp(back, txt, n) == 0); + LINE("STORE test: ON entries on this card: %u (%s)\n", (unsigned)boots, + same ? "written, read back" : "FAILED"); + + /* 512 KB of a pattern, in 16 KB chunks: write, read back, compare, delete. The + * pattern is generated outside the timed span so the figure is the transfer's. */ + struct fs_file_t f; + fs_file_t_init(&f); + uint32_t wms = 0; + rc = fs_open(&f, TESTFILE, FS_O_CREATE | FS_O_WRITE); + for (uint32_t c = 0; rc == 0 && c < TEST_KB * 1024u / CHUNK && !stop; c++) { + for (uint32_t i = 0; i < CHUNK; i++) { + bulk[i] = pattern(c * CHUNK + i, boots); + } + const uint32_t t0 = k_uptime_get_32(); + const ssize_t w = fs_write(&f, bulk, CHUNK); + wms += k_uptime_get_32() - t0; + rc = (w == (ssize_t)CHUNK) ? 0 : -EIO; + } + if (fs_close(&f) != 0 && rc == 0) { + rc = -EIO; + } + if (rc != 0 || stop) { + LINE("STORE test: write %u KB FAILED (%d)\n", (unsigned)TEST_KB, rc); + return; + } + uint32_t rms = 0; + uint32_t bad = 0; + uint32_t bad_blocks = 0; + int32_t first_bad = -1; /* block index within the file */ + uint8_t seen[32] = { 0 }; /* what the first bad block held */ + uint32_t sclust = 0; + fs_file_t_init(&f); + rc = fs_open(&f, TESTFILE, FS_O_READ); + if (rc == 0) { + sclust = (uint32_t)((FIL *)f.filep)->obj.sclust; + } + for (uint32_t c = 0; rc == 0 && c < TEST_KB * 1024u / CHUNK && !stop; c++) { + const uint32_t t0 = k_uptime_get_32(); + const ssize_t r = fs_read(&f, bulk, CHUNK); + rms += k_uptime_get_32() - t0; + rc = (r == (ssize_t)CHUNK) ? 0 : -EIO; + for (uint32_t b = 0; rc == 0 && b < CHUNK / SP1_EMMC_BLOCK; b++) { + uint32_t diff = 0; + for (uint32_t i = 0; i < SP1_EMMC_BLOCK; i++) { + const uint32_t at = b * SP1_EMMC_BLOCK + i; + diff += (bulk[at] != pattern(c * CHUNK + at, boots)); + } + if (diff != 0u) { + bad += diff; + bad_blocks++; + if (first_bad < 0) { + first_bad = (int32_t)(c * (CHUNK / SP1_EMMC_BLOCK) + b); + memcpy(seen, &bulk[b * SP1_EMMC_BLOCK], sizeof(seen)); + } + } + } + } + (void)fs_close(&f); + LINE("STORE test: %u KB written in %u ms (%u KB/s), read back in %u ms (%u KB/s):" + " %s\n", (unsigned)TEST_KB, (unsigned)wms, + wms ? (unsigned)(TEST_KB * 1000u / wms) : 0u, (unsigned)rms, + rms ? (unsigned)(TEST_KB * 1000u / rms) : 0u, + rc != 0 ? "read FAILED" : (bad ? "MISMATCH" : "identical")); + if (bad) { + /* Where it went wrong and what was there instead: a directory sector reads as + * 8.3 names, a FAT sector as little-endian cluster numbers, another file's + * data as anything else. The file's clusters are 64 blocks each; if they are + * contiguous, block k is at LBA data + (sclust - 2) * 64 + k. */ + LINE("STORE test: %u bytes differ in %u block(s); first bad block %d of the file, " + "file starts at cluster %u (LBA %u if contiguous: %u)\n", (unsigned)bad, + (unsigned)bad_blocks, (int)first_bad, (unsigned)sclust, + (unsigned)(r_data + (sclust - 2u) * 64u), + (unsigned)(r_data + (sclust - 2u) * 64u + (uint32_t)first_bad)); + char hex[sizeof(seen) * 3 + 1]; + for (size_t i = 0; i < sizeof(seen); i++) { + static const char hx[] = "0123456789abcdef"; + hex[3 * i] = ' '; + hex[3 * i + 1] = hx[seen[i] >> 4]; + hex[3 * i + 2] = hx[seen[i] & 15u]; + } + hex[sizeof(hex) - 1] = '\0'; + LINE("STORE test: it held:%s\n", hex); + } + rc = fs_unlink(TESTFILE); + LINE("STORE test: TEST.BIN %s\n", rc == 0 ? "deleted" : "delete FAILED"); + + struct fs_statvfs sv; + if (fs_statvfs(MNT, &sv) == 0) { + const uint64_t unit = (uint64_t)sv.f_frsize; + LINE("STORE test: volume %u MB, free %u MB, %u-byte clusters\n", + (unsigned)((sv.f_blocks * unit) >> 20), (unsigned)((sv.f_bfree * unit) >> 20), + (unsigned)unit); + } + struct fs_dir_t dir; + fs_dir_t_init(&dir); + if (fs_opendir(&dir, DIR_WAKES) == 0) { + struct fs_dirent ent; + while (fs_readdir(&dir, &ent) == 0 && ent.name[0] != '\0') { + LINE("STORE test: WAKES/%s %u B\n", ent.name, (unsigned)ent.size); + } + (void)fs_closedir(&dir); + } +} + +#endif /* CONFIG_SP1_STORAGE_TEST */ + +/* ---------------------------------------------------------------- the jobs */ + +/* Take the card for Wakes. Under the lock, so a host transfer in flight finishes first + * (Adara: "after any write already in progress", bounded by the driver's own timeouts) and + * no new one starts: from here the host's disk reads "no medium". */ +static void claim_for_wakes(void) +{ + const bool was_host = atomic_get(&owner) == OWN_HOST; + atomic_set(&owner, OWN_NONE); + k_mutex_lock(&card_lock, K_FOREVER); + atomic_set(&owner, OWN_WAKES); + k_mutex_unlock(&card_lock); +#if defined(CONFIG_SP1_DRIVE) + if (was_host) { + LINE("STORE drive: the host lets go -- the card is Wakes' again\n"); + } +#else + ARG_UNUSED(was_host); +#endif +} + +static void job_on_enter(void) +{ + const uint32_t t0 = k_uptime_get_32(); + claim_for_wakes(); + struct sp1_emmc_ident id; + const bool ok = sp1_emmc_init(&id); /* a fresh start whoever had the card */ + view_base = 0; + view_count = sp1_emmc_sectors(); +#if defined(CONFIG_SP1_STORAGE_TEST) + sp1_emmc_report_init(ok, &id); +#endif +#if defined(CONFIG_SP1_FRESH) + if (ok && !stop) { + fresh(); + } +#endif + /* Past the fresh step, whatever happened: main's storage_gate() lets the UI go. + * The report and the file test below run with the UI live. */ + atomic_set(&phase, SP1_STORE_READY); + if (!ok && !stop) { + atomic_set(&vol_state, SP1_STORE_VOL_NONE); + LINE("STORE PRST off: the eMMC did not start\n"); + } + if (ok && !stop) { +#if defined(CONFIG_SP1_STORAGE_TEST) + if (!stop) { + sp1_emmc_report_card(); + } +#endif + /* Is it formatted? (Adara: if not, boot, but PRST and its combos are off; + * only wakes-sp1-fresh formats.) */ + const int rc = stop ? -ECANCELED : mount_vol(); + if (!stop) { + atomic_set(&vol_state, rc == 0 ? SP1_STORE_VOL_OK : SP1_STORE_VOL_NONE); + if (rc == 0) { + LINE("STORE volume ok: PRST on\n"); + } else { + LINE("STORE PRST off: no filesystem on the eMMC (%d) -- nothing " + "written; wakes-sp1-fresh creates one\n", rc); + } + } +#if defined(CONFIG_SP1_STORAGE_TEST) + if (rc == 0 && !stop) { + file_test(); + } + sp1_emmc_report_stats(); +#endif + } + unmount_vol(); + if (!stop) { + sp1_emmc_power_down(); + } + atomic_set(&owner, OWN_NONE); + LINE("STORE %s after %u ms -- eMMC powered down\n", + stop ? "STOPPED by power-off" : (ok ? "done" : "eMMC not usable"), + (unsigned)(k_uptime_get_32() - t0)); +} + +#if defined(CONFIG_SP1_DRIVE) +/* STANDBY with a host attached: power the card and, if it holds a filesystem, hand it to + * the host until ON (claim_for_wakes) or power-off (sp1_store_abort). A card WITHOUT one + * is not offered: a computer shown a raw card offers to format it (possibly as exFAT, + * which Wakes cannot read), and only wakes-sp1-fresh formats (Adara). */ +static void job_host(void) +{ + k_mutex_lock(&card_lock, K_FOREVER); + struct sp1_emmc_ident id; + const bool ok = !stop && sp1_emmc_init(&id); + bool vol = false; + if (ok) { + /* Mount as Wakes for a moment: the same test the ON job uses, and it + * records where the volume's regions are for the diagnostics. */ + atomic_set(&owner, OWN_WAKES); + view_base = 0; + view_count = sp1_emmc_sectors(); + vol = (mount_vol() == 0); + unmount_vol(); + atomic_set(&vol_state, vol ? SP1_STORE_VOL_OK : SP1_STORE_VOL_NONE); + } + if (vol) { + atomic_set(&owner, OWN_HOST); + } else { + atomic_set(&owner, OWN_NONE); + sp1_emmc_power_down(); + } + k_mutex_unlock(&card_lock); + if (vol) { + LINE("STORE drive: the card is a USB drive (%u MB) until ON\n", + (unsigned)(sp1_emmc_sectors() / 2048u)); + } else if (ok) { + LINE("STORE drive: no filesystem on the eMMC -- no drive (wakes-sp1-fresh " + "creates one)\n"); + } else { + LINE("STORE drive: the eMMC did not start -- no drive this time\n"); + } +} +#endif + +/* ---------------------------------------------------------------- the thread */ + +static K_SEM_DEFINE(go, 0, 1); +static K_THREAD_STACK_DEFINE(store_stack, 4096); +static struct k_thread store_tcb; + +static void store_thread(void *a, void *b, void *c) +{ + ARG_UNUSED(a); + ARG_UNUSED(b); + ARG_UNUSED(c); + for (;;) { + k_sem_take(&go, K_FOREVER); + for (;;) { + const atomic_val_t jobs = atomic_get(&pending); + if (jobs & JOB_ON) { /* ON always wins: Wakes takes the card */ + atomic_and(&pending, ~JOB_ON); + job_on_enter(); + } else if (jobs & JOB_HOST) { + atomic_and(&pending, ~JOB_HOST); +#if defined(CONFIG_SP1_DRIVE) + job_host(); +#endif + } else { + break; + } +#if defined(CONFIG_SP1_STORAGE_TEST) + size_t unused = 0; + if (k_thread_stack_space_get(k_current_get(), &unused) == 0) { + LINE("STORE stack: %u of %u bytes never used\n", + (unsigned)unused, + (unsigned)K_THREAD_STACK_SIZEOF(store_stack)); + } +#endif + } + } +} + +void sp1_store_init(void) +{ + (void)disk_access_register(&disk); +#if defined(CONFIG_SP1_DRIVE) + (void)disk_access_register(&host_disk); +#endif + (void)k_thread_create(&store_tcb, store_stack, K_THREAD_STACK_SIZEOF(store_stack), + store_thread, NULL, NULL, NULL, K_PRIO_PREEMPT(5), 0, K_NO_WAIT); + (void)k_thread_name_set(&store_tcb, "store"); +} + +void sp1_store_on_enter(void) +{ + stop = false; + atomic_set(&fmt_result, SP1_STORE_FMT_NONE); + atomic_set(&progress, 0); + atomic_set(&vol_state, SP1_STORE_VOL_UNKNOWN); /* PRST waits for the ON job's look */ + /* Set HERE, before the job can run, so main never reads a stale READY. */ + atomic_set(&phase, IS_ENABLED(CONFIG_SP1_FRESH) ? SP1_STORE_CHECKING : SP1_STORE_READY); + atomic_and(&pending, ~JOB_HOST); + atomic_or(&pending, JOB_ON); + k_sem_give(&go); +} + +#if defined(CONFIG_SP1_DRIVE) +static bool host_requested; /* this STANDBY visit */ + +void sp1_store_standby_enter(void) +{ + host_requested = false; +} + +void sp1_store_standby_tick(bool host) +{ + /* A host (not a charger) has configured the device: give it the card, once per + * STANDBY visit. */ + if (host && !host_requested) { + host_requested = true; + stop = false; + atomic_or(&pending, JOB_HOST); + k_sem_give(&go); + } +} + +uint32_t sp1_store_activity(void) +{ + return (uint32_t)atomic_get(&activity); +} +#endif + +enum sp1_store_volume sp1_store_volume(void) +{ + return (enum sp1_store_volume)atomic_get(&vol_state); +} + +enum sp1_store_phase sp1_store_phase(void) +{ + return (enum sp1_store_phase)atomic_get(&phase); +} + +enum sp1_store_format sp1_store_format_result(void) +{ + return (enum sp1_store_format)atomic_get(&fmt_result); +} + +uint8_t sp1_store_progress(void) +{ + return (uint8_t)atomic_get(&progress); +} + +void sp1_store_abort(void) +{ + stop = true; + atomic_clear(&pending); + atomic_set(&owner, OWN_NONE); + sp1_emmc_abort(); +} diff --git a/firmware/src/sp1_store.h b/firmware/src/sp1_store.h new file mode 100644 index 0000000..e112710 --- /dev/null +++ b/firmware/src/sp1_store.h @@ -0,0 +1,108 @@ +/* + * wakes-sp1 — storage on the eMMC (M6, #43; CONFIG_SP1_STORAGE): a FAT32 volume and the + * thread that owns it. PRST's presets will live here; today it runs the fresh format + * and the storage test. + * + * ---- the card ---- + * One MBR partition, FAT32, starting at block 8192 (4 MB: the card's erase group, so the + * volume and its data area sit on erase boundaries), 32 KB clusters, two FATs, volume + * label "SP-1" (Adara: what the computer calls the drive) -- the layout an SD card + * formatter makes, so a computer sees an ordinary drive. Mounted at "/EMMC:". Long file + * names (Adara: presets are ".prst", ini inside): /EMMC:/WAKES/... + * + * ---- formatting: ONLY wakes-sp1-fresh (Adara, 2026-10-07) ---- + * "Flashing wakes-sp1-fresh formats the eMMC. Flashing a normal wakes-sp1 bin does not + * touch the eMMC." Enforced at build level: without CONFIG_SP1_FRESH the image contains + * no formatter at all (CONFIG_FILE_SYSTEM_MKFS off, so FatFs is built without f_mkfs), + * mounting never formats (FS_MOUNT_FLAG_NO_FORMAT, and CONFIG_FS_FATFS_MOUNT_MKFS off), + * and tools/ci/check_image.py fails a normal image that links f_mkfs. + * The fresh image formats on its first entry to ON and writes its own build ID to + * /EMMC:/WAKES/FRESH.ID; while that file matches, it never formats again. ⚠️ So flashing + * the SAME fresh file twice formats once: the second flash is indistinguishable from a + * reboot (the image cannot see its own flashing without writing the nRF's flash). + * + * ---- threading ---- + * Everything runs in one thread at K_PRIO_PREEMPT(5): below audio (0) and below main + * and the USB threads (1), so it only ever uses CPU they leave idle -- no cost to the + * audio block. It does NOT feed the watchdog (sp1_emmc.h). A format takes several + * seconds, during which main waits in storage_gate() -- still feeding the watchdog and + * still running sp1_power_tick(), so the 30 s backstop is untouched (rule 5a). + */ +#ifndef SP1_STORE_H +#define SP1_STORE_H + +#include + +/* Once at boot, before any other call: registers the disk and starts the thread. */ +void sp1_store_init(void); + +/* ---- the fresh format holds ON entry (Adara, 2026-10-07) ---- + * "Formatting the eMMC should hold up the rest of the UI while the device is being turned + * on. We can still turn the SP-1 off during the process in case it hangs, using the 30s + * SHFT hold backstop." main.c's storage_gate() waits on these between queuing the job and + * starting audio, drawing the progress bar from sp1_store_progress(). Fresh builds only: + * a normal image never formats, so it never waits. */ +enum sp1_store_phase { + SP1_STORE_READY = 0, /* no job, or the job is past its fresh step */ + SP1_STORE_CHECKING, /* job queued: powering the card, reading FRESH.ID */ + SP1_STORE_FORMATTING, /* formatting */ +}; +enum sp1_store_format { + SP1_STORE_FMT_NONE = 0, /* no format this ON entry */ + SP1_STORE_FMT_DONE, /* formatted and stamped */ + SP1_STORE_FMT_FAILED, /* tried and failed (or stopped): formats again next ON */ +}; +enum sp1_store_phase sp1_store_phase(void); +enum sp1_store_format sp1_store_format_result(void); +/* 0-255 through a format: the format's block writes so far against the count FatFs will + * make for this card (exact for FAT32: both FATs, the root cluster, the boot sectors). */ +uint8_t sp1_store_progress(void); + +/* ---- is there a filesystem to use? (Adara, 2026-10-07) ---- + * "On boot, check if the partition is formatted. If it's not formatted, don't format unless + * it's Fresh. In this state, boot, but disable the PRST feature and key combos related to + * it. As we add the PRST feature and related combos, we should build them with a check of + * whether the partition is formatted or not." + * So EVERY PRST feature and key combo asks sp1_store_volume() and does nothing unless it + * says OK. "Formatted" = a FAT volume FatFs can mount (wakes-sp1-fresh's, or a FAT32 a + * computer made); WAKES/ is created when first needed. Set by the ON job a fraction of a + * second after ON, and by the drive job in STANDBY. UNKNOWN means "not looked yet" -- + * treat it as NO, never as yes. Without a volume the drive is not offered either: a + * computer shown a raw card offers to format it, possibly as exFAT, which Wakes cannot + * read. */ +enum sp1_store_volume { + SP1_STORE_VOL_UNKNOWN = 0, + SP1_STORE_VOL_OK, + SP1_STORE_VOL_NONE, /* no card, or no FAT volume on it: PRST is off */ +}; +enum sp1_store_volume sp1_store_volume(void); + +/* Every entry to ON (main thread): queue the ON job -- take the card from a host (drive + * mode), the fresh check and format (CONFIG_SP1_FRESH), the report and file test + * (CONFIG_SP1_STORAGE_TEST). Returns at once. Never dropped: if another job is running it + * runs next, ahead of anything else queued. */ +void sp1_store_on_enter(void); + +#if defined(CONFIG_SP1_DRIVE) +#include + +/* ---- drive mode (M6, Adara 2026-10-07) ---- + * In STANDBY with a host attached the card is a USB drive (automatic, no gesture); turning + * ON takes it back after the transfer in flight. The mass-storage interface is always in + * the descriptor: while the host does not own the card it reads "no medium", so going + * STANDBY <-> ON never re-enumerates. ⚠️ A host that EJECTS the drive does not get it back + * until the next USB reset (a replug): Zephyr's class keeps "ejected" until then, the way + * a card reader keeps a removed card out. + * sp1_standby_run() calls these: enter once per visit, tick every control tick with + * sp1_usbd_host(). sp1_store_activity() counts the host's transfers, for the LEDs. */ +void sp1_store_standby_enter(void); +void sp1_store_standby_tick(bool host); +uint32_t sp1_store_activity(void); +#endif + +/* From sp1_quiesce_peripherals(), on every way out of ON and out of STANDBY: stop the job, + * take the card from a host, drop queued jobs, and power the card down now. A job cut short by this fails its remaining steps; a format cut short + * leaves no FRESH.ID, so the fresh image formats again at the next ON. Never waits. */ +void sp1_store_abort(void); + +#endif /* SP1_STORE_H */ diff --git a/firmware/src/sp1_ui_timing.h b/firmware/src/sp1_ui_timing.h index c3fe4bd..70ed305 100644 --- a/firmware/src/sp1_ui_timing.h +++ b/firmware/src/sp1_ui_timing.h @@ -109,10 +109,17 @@ /* ---- STANDBY (off, plugged in) ---- * The play row is a charge bar filling from the "••" end toward PLAY. It breathes - * while charging and sits solid when complete. Status lights live on the model - * row at T2/T3, dim so they read as indicators rather than as UI. */ -#define SP1_STANDBY_STATUS_LEVEL 38u /* ~15 % of 255 -- T2/T3 status */ + * while charging and sits solid when complete -- the only charging indicator now: the + * T2/T3 plugged/charging lights are gone (Adara, M6), to free the model row for the + * drive's activity below. */ #define SP1_STANDBY_BAR_LEVEL 77u /* ~30 % of 255 -- the charge bar */ +/* Drive mode's activity (Adara, M6 #43): on host reads and writes the model row steps + * T1, T3, T2, T4 (2 and 3 swapped on purpose), each LED a fast downward ramp from 50 %. + * One step at most every SP1_DRIVE_STEP_MS, so a transfer reads as a chase rather than + * all four glowing at once. Tune on hardware. */ +#define SP1_DRIVE_LED_PEAK 128u /* 50 % */ +#define SP1_DRIVE_STEP_MS 50u +#define SP1_DRIVE_RAMP_MS 150u #define SP1_STANDBY_BREATH_MS 2200u /* one full breath cycle */ #define SP1_STANDBY_BREATH_DEPTH 60u /* peak-to-trough at FULL brightness; * scaled down with the bar level so a @@ -182,6 +189,16 @@ #define SP1_RIP_BLACK_MS 500u /* black at the end of the hold */ #define SP1_RIP_FADEBACK_MS 500u /* after the reset: black -> the page */ #define SP1_RIP_CANCEL_FADE_MS 150u /* let go early: back to the page */ +/* ---- the fresh format at ON entry (Adara, M6 #43) ---- + * The UI waits while wakes-sp1-fresh formats the eMMC. The track row is a progress bar + * through the format (sp1_led_bar, full brightness); when it completes the row flickers + * twice, 0 -> 100 %, and fades quickly into the page. A format that fails leaves the bar + * and fades into the page with no flicker -- the flicker means "done". Only the 30 s + * backstop powers off meanwhile (storage_gate() in main.c). */ +#define SP1_FMT_FLICKER_MS 70u /* each off / on of the two flickers (as the rip) */ +#define SP1_FMT_DONE_FADE_MS 250u /* then full -> the page */ +#define SP1_FMT_FAIL_FADE_MS 250u /* failed: the bar -> the page */ + /* ---- UNPATCH: "••" held + T1-T4 held (Adara, M4e) ---- * Clears the routing belonging to that button -- on PLAITS the Marbles outputs aimed at * that parameter, on MARBLES that output's destination. The only destructive gesture diff --git a/firmware/src/sp1_usbd.c b/firmware/src/sp1_usbd.c index f6266cb..7a55305 100644 --- a/firmware/src/sp1_usbd.c +++ b/firmware/src/sp1_usbd.c @@ -107,12 +107,14 @@ static void usb_thread_find(const struct k_thread *t, void *user_data) found[0] = (k_tid_t)t; } else if (strcmp(name, "usbd") == 0) { found[1] = (k_tid_t)t; + } else if (strcmp(name, "usbd_msc") == 0) { + found[2] = (k_tid_t)t; } } static int usb_threads_below_audio(void) { - k_tid_t found[2] = { NULL, NULL }; + k_tid_t found[3] = { NULL, NULL, NULL }; int n = 0; k_thread_foreach_unlocked(usb_thread_find, found); @@ -122,6 +124,15 @@ static int usb_threads_below_audio(void) n++; } } + /* M6 drive mode: the mass-storage class runs every SCSI command -- and with it every + * eMMC transfer -- in its own thread, which Zephyr starts at the system work queue's + * COOPERATIVE priority. Left there, a host polling the drive while ON would run inside + * audio blocks. One step below main: in STANDBY it gets everything main leaves; in ON + * it only answers "no medium". Not counted in `n`, which the boot log reads as "the + * two core USB threads moved". */ + if (found[2] != NULL) { + k_thread_priority_set(found[2], K_PRIO_PREEMPT(CONFIG_MAIN_THREAD_PRIORITY + 1)); + } return n; } #endif @@ -156,8 +167,21 @@ int sp1_usbd_init(void) if (err == 0) { /* Every compiled-in class: CDC ACM (devicetree), feldd's MIDI class * (USBD_DEFINE_CLASS in usb_midi1.c) and USB audio out (wakes_uac, sp1_uac.c), - * in that order -- linker order is by name (sp1_uac.c says why it matters). */ - err = usbd_register_all_classes(&sp1_usbd, USBD_SPEED_FS, 1, NULL); + * in that order -- linker order is by name (sp1_uac.c says why it matters). + * Mass storage is held back from that list and added LAST (M6): by name it would + * land between CDC and MIDI and renumber every interface after it. */ + static const char *const later[] = { "msc_0", NULL }; + err = usbd_register_all_classes(&sp1_usbd, USBD_SPEED_FS, 1, later); + } +#if defined(CONFIG_SP1_DRIVE) + if (err == 0) { + err = usbd_register_class(&sp1_usbd, "msc_0", USBD_SPEED_FS, 1); + } +#endif + if (err == 0) { + /* The function set's version (Kconfig SP1_USB_BCD_DEVICE): changes when the + * functions do, so the PID never has to. */ + err = usbd_device_set_bcd_device(&sp1_usbd, CONFIG_SP1_USB_BCD_DEVICE); } if (err != 0) { return err; diff --git a/tools/ci/check_image.py b/tools/ci/check_image.py index 7460990..5956559 100644 --- a/tools/ci/check_image.py +++ b/tools/ci/check_image.py @@ -268,6 +268,31 @@ def check_uac_copies(zd): ", ".join(calls) or "word copies") +def check_storage(zd, cfg): + """Only wakes-sp1-fresh may format the eMMC (#43, Adara 2026-10-07). + + "Flashing wakes-sp1-fresh formats the eMMC. Flashing a normal wakes-sp1 bin does not + touch the eMMC." So a normal image must not even CONTAIN a formatter (FatFs' f_mkfs is + only compiled with CONFIG_FILE_SYSTEM_MKFS), and no image may format on a failed + mount -- Zephyr's default, which would wipe a card holding another firmware's data. + Nothing to check while storage is not linked. + """ + if cfg.get("CONFIG_SP1_STORAGE") != "y": + return + check(cfg.get("CONFIG_FS_FATFS_MOUNT_MKFS") != "y", + "storage: a failed mount never formats (FS_FATFS_MOUNT_MKFS off)", + f"got {cfg.get('CONFIG_FS_FATFS_MOUNT_MKFS')}") + with open(zd / f"{NAME}.elf", "rb") as fh: + mkfs = bool(ELFFile(fh).get_section_by_name(".symtab").get_symbol_by_name("f_mkfs")) + if cfg.get("CONFIG_SP1_FRESH") == "y": + check(mkfs, "storage: FRESH image links the formatter", "f_mkfs present") + print(" [NOTE] FRESH IMAGE: formats the eMMC on its first entry to ON. " + "Ship it as wakes-sp1-fresh, never as wakes-sp1.") + else: + check(not mkfs, "storage: normal image contains no formatter", + "f_mkfs LINKED" if mkfs else "no f_mkfs") + + def check_source(repo): # A header constant, not a build flag, so nothing else would catch a leftover 1: # the device would boot into the calibration wizard. @@ -294,6 +319,7 @@ def main(): check_layouts(zd) check_fast_clear(zd) check_uac_copies(zd) + check_storage(zd, cfg) check_source(a.repo) failed = results.count(False) diff --git a/west.yml b/west.yml index ba7576c..15009b7 100644 --- a/west.yml +++ b/west.yml @@ -9,6 +9,10 @@ # three reached a real build. Do not widen it to `import: true` (~2 GB more and # a full re-update) and do not drop `cmsis_6` -- the Kconfig fix in # zephyr-patches/ depends on modules/cmsis_6 being present. +# +# `fatfs` (M6, #43; added with Adara's approval, 2026-10-07): ChaN's FatFs as Zephyr +# packages it, for the FAT filesystem PRST keeps on the eMMC. Revision is whatever the +# pinned Zephyr's own west.yml names. Every module added here is Adara's call. manifest: remotes: - name: zephyrproject-rtos @@ -22,6 +26,7 @@ manifest: name-allowlist: - cmsis - cmsis_6 + - fatfs - hal_nordic self: