crates

designware_mobile_storage

check proofs license minimum Rust version

A Secure Digital (SD) card and eMMC (embedded multimedia card) driver for the Synopsys DesignWare Mobile Storage Host Controller (snps,dw-mshc, Linux's dw_mmc), as pure logic. It holds the register map, the command encoding and the polled controller sequences. It also holds the internal direct memory access controller (IDMAC), card identification, block reads and writes, and the decoding of the card registers. It reads no partition table: sector 0 comes back as bytes.

The crate never touches memory itself. You implement one small trait, host_controller::RegisterWindowAndClock, over your own mapped window. It reads a register, writes one and reads a microsecond clock. The crate is no_std, has no allocator, and names no system-on-chip: you pass the input clock and the first input, first output (FIFO) depth.

EXAMPLES

The crate is not on crates.io. Take it from this repository, pinned at a commit you have read:

[dependencies]
designware_mobile_storage = { git = "https://github.com/nifeos/designware_mobile_storage", rev = "<commit>" }

Hand HostController::new your register window, the controller's input clock and the first input, first output (FIFO) depth from the device tree. Then identify the card and move whole 512-byte blocks:

use designware_mobile_storage::host_controller::{HostController, RegisterWindowAndClock};
use designware_mobile_storage::sd;

fn first_sector<R: RegisterWindowAndClock>(registers: R) -> Option<[u8; 512]> {
    let (mut host, _id) = HostController::new(registers, 50_000_000, Some(32)).ok()?;
    let card = sd::identify(&mut host, 4).ok()?; // at most a 4-bit bus
    let mut buffer = [0u8; 512];
    sd::read_blocks(&mut host, &card, 0, &mut buffer).ok()?;
    Some(buffer)
}

An eMMC comes up on a 1-bit bus at 25 megahertz. A caller may then ask for a wider bus and high speed. Neither step has run on a real eMMC yet (see BUGS), and identify never takes either:

use designware_mobile_storage::host_controller::{HostController, RegisterWindowAndClock};
use designware_mobile_storage::sd;

fn faster_embedded_card<R: RegisterWindowAndClock>(host: &mut HostController<R>) -> Option<sd::Card> {
    let mut card = sd::identify(host, 8).ok()?; // the eMMC slot's bus-width
    if sd::switch_multimedia_card_bus_width(host, &mut card, 8).is_err()
        || sd::switch_multimedia_card_to_high_speed(host, &mut card).is_err()
    {
        // A failed switch leaves the card's width and timing unknown: start over at 1 bit.
        card = sd::identify(host, 8).ok()?;
    }
    Some(card)
}

HostController::with_internal_direct_memory_access moves later transfers through a direct memory access (DMA) region you supply. The region implements internal_direct_memory_access::DirectMemoryAccessRegion. The crate reads no device tree.

The simulator feature lets your own tests run against the simulated controller and card that this crate's tests use, the way embedded-hal-mock stands in for embedded-hal. It is off by default and needs std, so turn it on for your tests only. SimulatedHostController implements RegisterWindowAndClock, so it goes wherever your code takes a register window. Choose the card's kind and size, fill or check its blocks, fail the next block read, or leave the slot empty. attach_direct_memory_access_region hands back the memory its IDMAC reaches. A test of the first_sector function above:

[dev-dependencies]
designware_mobile_storage = { git = "https://github.com/nifeos/designware_mobile_storage", rev = "<commit>", features = ["simulator"] }
use designware_mobile_storage::SimulatedHostController;
use designware_mobile_storage::sd::CardKind;

#[test]
fn first_sector_reads_what_the_card_holds() {
    let mut simulator = SimulatedHostController::new(CardKind::SdHighCapacity, 8192);
    simulator.card_blocks_mut()[0][510..].copy_from_slice(&[0x55, 0xaa]);
    let sector = first_sector(simulator).expect("the simulated card reads");
    assert_eq!(sector[510..], [0x55, 0xaa]);
}

The crate's own tests/simulator.rs runs this test word for word.

Every error enum implements Display and core::error::Error. These are host_controller::Error, sd::InitializationError, sd::BlockTransferError and internal_direct_memory_access::Refusal. They and sd::CardKind are #[non_exhaustive]. A match on one needs a wildcard arm, and a later release can add a variant without breaking you.

What is proven

Each property below has a Kani harness in src/proofs.rs, twenty-four in all.

The harnesses below assume nothing of the controller. Every register read and every descriptor word in DMA memory is whatever the solver picks. The solver also picks the clock's readings, and the harnesses assume only that time passes. From some reading on, each reading is more than the deadline past every earlier one. Before that reading the clock may wrap past 2^64, stand still or jump either way.

They prove that no path panics, overflows or indexes out of bounds, and that each wait ends. They do not prove that the driver does the right thing with a faithful controller. The host tests against the simulated controller cover that. Only a board shows it for silicon.

The harnesses of whole sequences use a clock that passes every deadline at each reading. They bound their loops by what the controller reports rather than by time. The two wait harnesses above cover a clock that takes longer, and every wait in the driver is one of those two loops.

The bring-up harnesses below judge identify against the card state machine of the SD specification and the eMMC standard: idle, ready, identification, standby, transfer. The card starts in any state, with any address and bus width. The controller starts with any bus width and clock, as an earlier bring-up that failed anywhere might leave them.

For each command the solver picks whether the card answered, stayed silent or had its answer garbled, and it picks the response words. The controller reports that choice and otherwise carries out each command at once. A controller that fails some other way reaches the driver as the same error from the same call, and the harnesses above cover it. The harnesses assume one thing of a card: an SD card publishes a relative address other than zero.

Install Kani and run them as "Building and testing" below describes.

Building and testing

cargo build
cargo test --features simulator
rustup target add riscv64imac-unknown-none-elf
cargo build --lib --target riscv64imac-unknown-none-elf   # a RISC-V bare-metal target; CI also builds aarch64-unknown-none-softfloat and x86_64-unknown-none

Pass --features simulator to cargo test. Without it, Cargo skips tests/simulator.rs (that target needs the feature) and says nothing about the skip, so a plain cargo test looks green without running the simulator tests or the first_sector example above. With the feature, cargo test --features simulator runs the unit tests, the tests in tests/simulator.rs and the documentation tests. Run rustup target add once, before the first bare-metal build. Without it, that build stops with can't find crate for core.

Running the proofs

The proofs need Kani, which rustup does not install. Run cargo install --locked kani-verifier --version 0.68.0, then cargo kani setup. The setup step downloads a model checker, so it needs network access. CI uses version 0.68.0, and another version may verify differently.

Then cargo kani, from the crate's directory, runs all twenty-four harnesses one at a time. That took 29 minutes on an x86_64 Linux machine with 80 threads. The slowest harness took about 240 seconds and the next two about 210 each. The heaviest peaks near 3.5 gigabytes of resident memory (6 gigabytes counting the file cache of the whole run). CI runs two at a time with cargo kani --jobs 2 --output-format=terse; Kani verifies in parallel only with terse output, and two heavy harnesses fit a 16 gigabyte machine. To run one harness, give its full path and --exact. Most take seconds:

cargo kani --harness proofs::the_clock_divider_is_total --exact

A passing run prints several things that look alarming. All of them are expected:

Trust the last line of the run: Complete - 24 successfully verified harnesses, 0 failures, 24 total.

Running one falsification patch

patch -p1 --no-backup-if-mismatch < falsifications/proofs.the_clock_divider_is_total.patch
cargo kani --harness proofs::the_clock_divider_is_total --exact   # ends VERIFICATION:- FAILED
git checkout -- src

The harness name is the part of the patch's file name after proofs.. The run ends with Complete - 0 successfully verified harnesses, 1 failures, 1 total., and the failed check names the assertion that the patch breaks, here (divider == 0) == (base <= target). git checkout -- src reverts the patch.

Implementing the traits

host_controller::RegisterWindowAndClock is the register window and a clock, and each trait's documentation states its contract in a # Contract section. In short:

internal_direct_memory_access::DirectMemoryAccessRegion is the memory the IDMAC reads and writes, used only after HostController::with_internal_direct_memory_access. The region starts on a page (internal_direct_memory_access::PAGE_BYTES). It holds one page of descriptors, then 1 to MAXIMUM_DESCRIPTORS data pages, all below 4 GiB as the controller addresses them. The driver calls barrier twice in each transfer. The first call comes after it writes the descriptors and the data, before the register writes that start the controller. The second comes after the controller has finished, before the driver reads the data back. While the transfer runs, the driver polls each descriptor's own bit with read_u32, with no barrier in between.

BUGS

Minimum Rust version

Rust 1.88. To check it, install that toolchain and a bare-metal target, then test and build with it:

rustup toolchain install 1.88 --profile minimal --target riscv64imac-unknown-none-elf
cargo +1.88 test --features simulator
cargo +1.88 build --lib --target riscv64imac-unknown-none-elf

License

Licensed under either of the MIT license (LICENSE-MIT) or the Apache License, Version 2.0 (LICENSE-APACHE), at your option. Parts adapt OpenBSD's sys/dev/fdt/dwmmc.c (revision 1.33) under the Internet Systems Consortium (ISC) license: the register map, the reset, clock and bus width sequences, the command flags and the polled FIFO transfer. LICENSE-ISC holds that notice, and src/lib.rs carries it too. The manifest's SPDX expression is (MIT OR Apache-2.0) AND ISC. Card identification follows the SD specification. It takes only the order of its addressing commands from OpenBSD's sdmmc_mem.c, whose code the crate does not adapt. GPL sources (Linux, U-Boot, the device trees) served only as references for hardware facts, and the crate copies no GPL code.