Blog · Embedded Rust · Part 2
Kumi: Writing Rust Firmware for a RISC-V Keyboard and CS43198 DAC Phone Case
How I reversed an undocumented 360 MHz RISC-V phone case over USB, built power-cut-safe Rust no_std firmware from scratch, and unlocked its keyboard and CS43198 DAC.
Snap-In Case Hardware
- MCU
- SpaceTouch SPV5048 (360 MHz RISC-V)
- DAC
- Cirrus Logic CS43198 (384 kHz / DSD256)
- Firmware
- Kumi · Rust no_std · Ed25519 A/B
No vendor SDK · no SWD probe · bit-for-bit stock restore
I bought the iKKO MindOne Snap-In Case because the hardware pairing was unusual: a 36-key physical QWERTY keyboard and a Cirrus Logic CS43198 headphone DAC built into a snap-in USB-C phone case.
What shipped out of the box: factory V0.1 firmware with no companion Android app, no firmware updater, and no user-facing configuration at all. The keyboard stayed locked to US QWERTY and the DAC ran on fixed defaults.
What runs on it now: Kumi, a from-scratch Rust no_std firmware paired with a rootless Android companion app, desktop CLI, and browser WebUSB tool. The host installer backs up the full 4 MiB factory flash before writing anything, restores stock bit for bit at any time, and turns the case into a programmable keyboard and 384 kHz / DSD256 audio player with on-case DSP.
Below is the full sequence: how I reversed the sealed case over USB, what hardware sits inside (and what the PCB physically cannot do), how the firmware and A/B updater are engineered, and what that unlocks for daily audio and keyboard use.
Reversing a sealed case over USB
The case is glued shut, with no exposed SWD or SPI header, no schematics, and no vendor SDK. The main break came from the controller’s immutable USB boot ROM.
On every boot, the ROM inspects flash offset 0 for the magic SPV@ at +0x04 and checks a modulo-232 byte sum at +0x2C. If either fails, or if software sets bit 31 of the reset-surviving scratch register (0x2100801C) before a warm reset, the ROM enumerates as a USB service device (0666:0888) speaking a framed BUXX protocol.
Service mode can read and write flash, upload code straight into RAM, and jump to it without opening the case. That became the whole bring-up loop: before touching flash, every new driver (clocks, I2C, I2S/DMA, USB, HID, USB Audio Class 2.0 / UAC2) booted from RAM over USB. If an experiment hung, unplugging the case returned it straight to stock in two seconds.
USB BootROM · 0666:0888
magic: "SPV@" @ +0x04
checksum: mod-2^32 sum @ +0x2C
reboot: 0x2100801C |= (1 << 31)From live register reads and bus probes I mapped the DAC bus, clocks, DMA, and the UART link to a separate keyboard microcontroller. That neighboring MCU sends framed key events and status queries (version, sample rate, stream status) to the SPV5048 starting with 0x4B and ending with a 16-bit checksum. Curiously, stock firmware transmitted that sum little-endian, while the one reply frame I captured from the keyboard MCU carried the same sum big-endian, and the stock receiver never checked it. Kumi accepts either byte order, counts mismatches in diagnostics, and answers those queries byte for byte like stock.
Hardware map and PCB limits
Probing the board revealed four separate hardware blocks, with Kumi running on only one of them (the SPV5048):
Phone USB-C (High-Speed 480 Mbit/s)
|
v
[ SpaceTouch SPV5048 · 360 MHz RV32IMCF · 576 KiB SRAM · 4 MiB NOR ]
|-- I2C0 (0x33) + I2S0/DMA2 ----> [ Cirrus Logic CS43198 DAC ] --> 3.5 mm jack
|-- UART (0x4B framed packets) -> [ Separate Keyboard MCU ] -----> 36-key matrix
|-- LRADC0 ---------------------> 3.5 mm jack plug-in sense
'-- GPIO5 ----------------------> board power keep-awake line
Not reachable over I2C from SPV5048:
[ Charger IC + 500 mAh cell + physical mode switch + charge-only bottom USB-C ]Under the hood, the MCU is a SpaceTouch SPV5048 (chip ID 0x49014480): an Andes D25F-class core configured as RV32IMCF (hardware f32 floating point, no A atomics, no D double precision), backed by 576 KiB of on-chip SRAM across three banks, a GigaDevice 4 MiB NOR flash (JEDEC C8 65 16), and a Mentor USB OTG (MUSB) High-Speed controller with 4096 bytes of internal FIFO RAM.
PCB limits firmware cannot fix:
- No case battery telemetry: live scans of
I2C0find only theCS43198at0x33, andI2C1finds zero responding devices. I found no I2C path from the charger IC and 500 mAh cell to theSPV5048. - No 3.5 mm headset microphone audio: I found no audio ADC path routed from the TRRS microphone pin (only low-rate
LRADCjack and remote bias sensing), so voice calls use the phone’s microphones. - Charging-only bottom USB-C: the case’s bottom port passes neither SPV5048 USB nor phone data. Desktop use requires a USB-C female-to-male adapter on the phone-side plug.
- Single DAC responding: although stock firmware tries to initialize both
0x33and0x31, on my unit only oneCS43198at0x33answers (3.5 mm single-ended only).
SRAM layout, Rust no_std, and overnight standby
Erasing a 4 KiB sector on the GigaDevice NOR flash takes about 32 ms (158 ms for a 64 KiB block). Executing code directly from flash (XIP) would freeze USB and drop audio packets during any flash write. Instead, Kumi runs entirely out of on-chip SRAM while flash acts as pure storage, splitting sections across all three banks in firmware/runtime/runtime.x:
- 01ILM · instruction SRAM (64 KiB)
Zero-wait-state instruction memory holding the entry point,
.text.hotaudio/USB loops, and low-level dispatch (56 KiB available above reserved low memory). - 02DLM · data SRAM (256 KiB)
.data/.bss, DMA stereo ring buffer, at least 64 KiB of stack (asserted at link time) plus trap stack, and a reserved top slice for the resident bootloader verifier. - 03RT40 · general SRAM (256 KiB)
Larger crates that would overflow ILM:
.rodata, DSP and audio state machines, host-pairing crypto, Embassy USB,postcard-rpc, QMK keymaps, and UART handling.
Two low-level Rust no_std pieces anchor the runtime. First, because the core has no A extension (no hardware compare-and-swap instructions), Kumi implements critical-section in inline RISC-V assembly: csrrci rd, mstatus, 8 saves and clears the machine interrupt-enable bit (MIE) on acquire, and release conditionally executes csrsi only if interrupts were previously enabled (so nested critical sections work), satisfying embassy-usb and portable-atomic on a single core. Second, Kumi implements the embassy-usb-driver traits (Driver, Bus, ControlPipe, EndpointIn, EndpointOut) directly over the Mentor MUSB registers, carving its 4096-byte FIFO RAM above the 64-byte EP0 slot and double-buffering the isochronous OUT endpoint for high-rate audio.
Even with code running from SRAM, synchronous SPI flash busy-polling still blocks the main loop during a 32 ms erase. Settings autosave therefore waits for a 250 ms audio and RPC quiet window and skips unchanged sectors, while crash logs stay cached in RAM at boot.
When idle (no active audio stream), the core parks in wfi (Wait For Interrupt) over 99.5% of the time according to firmware monotonic counters (the case is glued shut, so I did not cut USB traces for an inline current shunt). On stream stop, Kumi gates off the I2S clock and puts the CS43198 into low-power internal-RC (RCO) sleep.
| 4-tier clock scaling (fixed 1.4 V DC-DC) | Core PLL |
|---|---|
| USB suspend | 30 MHz |
| Idle & 44.1–48 kHz bit-perfect PCM | 90 MHz |
| DSP up to 96 kHz, 88.2–192 kHz PCM, DSD64 via DoP | 180 MHz |
| High-rate DSP, 352.8–384 kHz PCM, DSD128 via DoP, Native DSD | 360 MHz |
Daily carry caught an overnight standby bug that desk testing missed. Something outside the SPV5048 disconnects the case from USB after three minutes of inactivity unless GPIO5 stays active. On a sleeping phone, brief background wakeups for Wi-Fi or notifications resumed USB just long enough to reset Kumi’s 180-second keep-awake timer, preventing GPIO5 from releasing and keeping the case drawing power from the phone all night.
Idle time had also been tracked from USB Start-of-Frame (SOF) ticks, which freeze during USB suspend. Moving idle tracking to the hardware monotonic clock (resetting only on real keypresses, audio, RPC, or jack events) fixed the 180-second timeout so GPIO5 actually releases overnight. While waiting in USB suspend before timeout, enabling Mentor MUSB Deep Suspend (MUSB_POWER_ENSUSPEND), slowing the periodic wake timer from 20 ms to 250 ms, and pausing jack-sense ADC polling (LRADC0) while keeping analog bias intact quieted standby power without touching untested power rails.
Three audio bring-up bugs
Writing the audio crate against thin Rust register traits (Registers, I2cBus, FrameStore) let every state machine run under host cargo test before flashing. Two bugs showed up only on live silicon, while host tests caught the third before it ever reached the board.
1. The 0.67% Audio PLL calibration mystery
To generate 44.1 kHz and 48 kHz audio clock families, the SPV5048 sweeps 16 analog trim values (0..15). For each trim, two hardware timers race for 130 µs (timer0 on the 24 MHz crystal reference, timer1 on the Audio PLL), and firmware picks the midpoint of the single trim window within ±0.417% of the target ratio.
On the first hardware run (48 kHz family, 49.152 MHz Audio PLL), calibration failed every time with NoTrimWindow: the reference counted 3134..3137 ticks (accepted band 6391..6445), while trims 10..13 plateaued at 6461..6465 (+0.67% high). Stock firmware, meanwhile, picked trim 11 for 48 kHz and trim 12 for 44.1 kHz on the same chip.
At 49.152 MHz, even half a microsecond of bus latency between starting or reading two free-running timers adds ~25 extra ticks, enough to miss the ±0.417% band. Switching to back-to-back sw and lw instructions (without stopping the timers first, because stopping resets their readback to zero on this block) brought trims 10..13 to 6435..6441 inside that run’s 6416..6469 band (trim 11), and 44.1 kHz trims 11..14 to 5908..5915 inside 5876..5925 (trim 12). Both sweeps finished in 105.8 ms including PLL lock settling.
2. Direct-form biquads collapsed at 20 Hz
Stock firmware ran fixed-point Q28 (28 fractional bits) direct-form biquads. My first Rust EQ used f32 direct-form biquads, and its host unit test caught numerical collapse at 20 Hz and 384 kHz: 1 - cos(w) is roughly 5.35 × 10-8, below f32 resolution near 1.0 (2-24 ≈ 5.96 × 10-8), so the coefficient keeps almost no precision (~1 ULP quantization).
Switching to trapezoidal state-variable filters (Simper/Zavalishin) fixed it. Coefficients are computed in software f64 only when sliders move (since the core has no hardware D extension), while audio samples run on hardware RV32F. Compiling with -C target-feature=+f, inline fmadd.s, branchless fcvt.w.s rmm, moving the 1 KiB stereo scratch buffer off the stack, and interleaving left/right channels to hide FPU pipeline latency kept gain within 1% down to 20 Hz with plenty of CPU headroom left over.
3. 500 µs ISO FIFO window vs 100 kHz I2C at 352.8 kHz S32
At 352.8 and 384 kHz stereo 32-bit PCM, 250 µs USB packets into the double-buffered 2 × 1024-byte MUSB FIFO leave only 500 µs before an overrun. Because I2C runs synchronously in the main audio loop, a 100 kHz read-modify-write to the CS43198’s volume registers (which use 24-bit register addresses) took ~1 ms and dropped packets during volume sweeps.
- Switch
I2C0to 400 kHz Fast Mode while streaming, restoring 100 kHz on stop. - Enable
CS43198Soft Ramp + Zero Crossing (PCM_PATH_1 = 0xB0) so gain steps never pop. - Use a write-only fast volume path that skips duplicate writes.
- Drain the MUSB ISO OUT FIFO right before and right after each I2C transfer.
Across 16 rapid macOS CoreAudio volume steps at 352.8 kHz S32 with EQ, crossfeed, and limiter active, firmware logged overruns = 0, underruns = 0, dac_faults = 0. Adding a 12 ms soft-ramp mute before stopping I2S also cleared stop and rate-switch clicks (192 → 48 kHz).
Brick-proof Ed25519 A/B OTA and host authorization
The SPV5048 boot ROM only ever boots flash offset 0, with no hardware A/B fallback, and nobody wants to pry open a glued case to attach a test clip to the flash chip. Every flash layout rule serves one invariant: after a power cut at any point during an update, the case must boot stock, boot a complete verified Kumi image, or drop into USB service mode (0666:0888).
0x000000 [ 64 KiB ] stage0 bootloader (SPV@ header, Ed25519 pubkey, A/B selector)
0x010000 [ 8 KiB ] boot journal (slot state, trial counter, persisted min_generation)
0x040000 [ 1 MiB ] Slot A (signed Kumi runtime)
0x140000 [ 1 MiB ] Slot B (signed Kumi runtime)
0x240000 [ 64 KiB ] crash log
0x300000 [ 256 KiB ] on-flash copy of stock firmware image (host stores full 4 MiB dump)
0x3E0000 [ 128 KiB ] double-buffered settings journal (CRC-checked, trial-rollback safe)The companion app and CLI back up the full 4 MiB flash to the host for bit-for-bit restore, while 0x300000 keeps an on-flash 256 KiB copy of the stock firmware image itself. Every flash write in both stage0 and the runtime goes through one policy check (region_for_write). Two NOR-flash tricks rely on the fact that NOR flash can clear bits from 1 → 0 in place without erasing a sector:
- 01The
0xFFFFFFFFreverse-page commitDuring initial install, the flasher copies stock to
0x300000, writes Slot A, clears the old stock magic, and writesstage0’s body. It then programs sector 0 in reverse page order so theSPV@magic on page 0 is written last, with the 4-byte checksum at+0x2Cleft erased (0xFFFFFFFF). Because a byte sum over 4 MiB is at most0x3FC0_0000(<0xFFFFFFFF), any mid-write power loss drops into service mode; only the final 4-byte write commitsstage0. - 02Self-disarming loop breaker
If
stage0cannot boot either slot or hits a fault, it marks a boot-ROM request in the journal and triggers a warm reset with bit 31 armed. If it wakes up again with that marker still set, it clears its own 4-byteSPV@magic at offset4to zero in place (no erase needed), forcing the boot ROM into USB service mode on every subsequent power cycle.
Normal OTA updates write the inactive slot, verify its Ed25519 signature and persisted monotonic generation floor (anti-rollback) via stage0’s resident verifier, and arm a 3-attempt trial. If the new slot fails to stay healthy for 10 seconds of monotonic uptime, stage0 rolls back to the confirmed slot while keeping the prior settings sector intact. Reset-cause tracking separates crashes and watchdog resets from normal USB unplugs so routine power cycles never trip recovery mode.
Host authorization: a USB accessory acting as both a keyboard and a 2 Vrms DAC is risky if any page granted WebUSB access or any host app can remap keys, sniff live keypresses, or push full output into sensitive IEMs. Kumi therefore leaves routine audio, EQ, and metering open, while gating keymap edits, live key subscriptions, hearing-safety overrides, and OTA writes.
Privileged actions require either a 2-second physical LShift + Backspace chord or Ed25519 host pairing (up to 4 hosts, with the phone’s key wrapped in Android Keystore so daily use stays silent). Entering BootROM or wiping paired hosts always requires the physical chord, release builds omit debug endpoints, and the USB serial number can be rotated via a SipHash-2-4 salt (with stored host backups re-tagged automatically).
Emulating the real boot ROM in Unicorn (and catching a Unicorn bug)
Before letting the installer touch flash on my only case, I built a Python/Unicorn RV32 emulator (tools/brom_emu.py) that executes the dumped 64 KiB boot ROM and 4 MiB stock image, modeling NOR flash, Mentor MUSB (including suspend), the interrupt controller (PLIC), LRADC, and UART. None of the vendor ROM or flash dumps are committed to the repository; public CI runs the same emulator suite against a synthetic boot-ROM fixture.
- 01Rust host unit tests
Fast host-side
cargo testcoverage across DSP math, audio state machines, keymaps, flash layout policy, settings migration, and RPC framing. - 02Unicorn RV32 boot ROM tests
Full-firmware runs sampling 100+ simulated NOR flash power-cut points during install and exact restore (verifying the original stock SHA-256).
- 03Android JVM contract tests
Pinning the JNI contract, host-pairing state machine, keyboard auto-switch guards, and security boundaries between Rust and Kotlin.
Building the emulator’s snapshot cache turned up a real bug in Unicorn 2.1.4. Reading RISC-V floating-point CSRs via uc_reg_read_batch() while MSTATUS.FS == 0 (when the FPU is still disabled after reset) leaked uninitialized host stack memory into the output buffer while returning UC_ERR_OK, because qemu/target/riscv/unicorn.c ignored a -1 error return from riscv_csrrw(). I worked around it in Kumi’s snapshotter and opened an upstream fix with ASan/UBSan tests switching host CSR inspection to riscv_csrrw_debug() (unicorn-engine/unicorn#2510).
What this unlocks: audio, keyboard, and one Rust workspace
Kumi sticks to standard USB classes so typing and audio work out of the box without keeping any companion app running. Standard USB Audio Class 2.0 appears only while headphones are plugged in via LRADC0 jack sense (so Android does not route phone calls to an empty case), and because processing runs on the case itself, saved EQ and gain follow the case across every Android player and even a laptop via USB-C adapter.
Control traffic runs over a dedicated vendor bulk interface with one shared, versioned postcard-rpc schema and WinUSB descriptors. One Cargo workspace (including Kumi’s client and flasher libraries) powers the embedded firmware, the desktop CLI, the Android JNI bridge (libkumi_jni.so), and a WebAssembly build (kumi-wasm) behind the browser WebUSB configurator.
Audio
- High-res & bit-perfect: up to 384 kHz 32-bit PCM, DoP (DSD over PCM) up to DSD128, and Native DSD up to DSD256, with automatic bit-perfect bypass when EQ and effects are flat.
- Hardware volume & impedance: 120-step
CS43198hardware volume (0.5 dB steps) with remembered volume per impedance tier, built-inHPLOADimpedance measurement driving automatic 1 Vrms low-gain / 2 Vrms high-gain and auto-EQ slot selection, plus true fixed 2 Vrms Line-Out. - On-case DSP & metering: two-layer 10-band parametric EQ (AutoEQ base + 4 user slots) with 5-band tone and crossfeed, optional analog-inspired DSP modes (phase linearization, vinyl warmth, upper-treble restoration, and software 2x/4x linear-phase oversampling feeding the CS43198’s non-oversampling / NOS filter mode), EBU R128 loudness metering with optional Auto-Level, and a live 24-band post-DSP FFT spectrum (<0.4% MCU CPU, 30 Hz stream).
Keyboard and rootless companion app
- Programmable USB HID: four QMK-style key layers, macros and combos, hardware HOLD pocket lock (configurable long-press chord such as
Shift + Enterwithout waking the OLED screen), screen-off double-tap media controls (2x Shift/2x Space/2x Backspace), and instant auto-pause when unplugging headphones. - Works without root on stock Android 15+: the monochrome AMOLED companion app talks to both Kumi and the boot ROM over standard Android USB Host APIs, with a guided backup-and-flash wizard bound per case serial.
- Kumi Strip IME: a slim 46 dp autocomplete bar built for physical-keyboard typing on a 4-inch square screen, supporting 20 typing languages (including offline Japanese Mozc, Korean, and Chinese Pinyin), zero-root type-to-search, and automatic switch-back to your on-screen keyboard when you snap the case off.
Closing notes
Replacing the firmware turned a minimal factory accessory into a daily-driver pocket DAC and physical keyboard for the MindOne, while keeping a verified 4 MiB host backup so any owner can return to stock bit for bit.
Building bare-metal RISC-V firmware, a boot-ROM emulator, a desktop CLI, a WebAssembly bridge, and an Android app solo alongside a phone kernel port relied heavily on coding agents (Claude Code early in bring-up, and Antigravity during later DSP, app, and library passes). They sped up boilerplate, crate refactoring, and test authoring, but on undocumented hardware an agent will happily invent a register bit or forget a 32 ms NOR erase stall. I checked every register claim against a capture or a live hardware read before it went into code, backed by Rust host tests and 100+ Unicorn power-cut simulations.
All firmware, emulator, CLI, libraries, and Android app source code (source-available under the PolyForm Noncommercial License 1.0.0, plus signed release bundles and APKs) is public below:
- Overview & live WebUSB configuratornonbiri.dev/mindone/case
- Firmware, emulator, CLI & Android appgithub.com/iasnezhkov/kumi
- MindOne LineageOS 24 & WebUSB installernonbiri.dev/mindone · nonbiri.dev/mindone/install
- Upstream Unicorn RV32 CSR fixunicorn-engine/unicorn#2510