Přeskočit na hlavní obsah

SDMMC MCAL Module

Supported STM32 families: H5 · H7
Not supported: F4, F7, G4, L4, U3, U5

This module provides an abstraction layer for the SD / SDIO / eMMC host interface (SDMMCx) of STM32 MCUs: the bus configuration, the commands and the data path (the host layer), and on the top of it the identification of the card, the block read, write and erase (the card layer). It is the storage driver under a file system (FileX, FatFs ...) and the transport driver of SDIO devices. It is a low-level MCAL module: it owns the SDMMC hardware, the application and the other modules never touch the registers.

The public interface (Sdmmc_Port.h, Sdmmc_Types.h) is identical for all supported families. The implementation for a family lives in its own branch (Dev/<Family> for development, Releases/<Family> for the released versions), so a module or an application written against the interface does not change when the MCU family changes.

This README is the landing page and the specification of the interface (master). The family branches contain their own README with everything that is specific to the family: the instances of the device, their settings and the status of the implementation.

Status: design. No implementation exists yet, the interface below is a proposal. Stories and branches follow.


Intent and purpose​

  • A file system needs a block device: "read N blocks from the block X into this buffer". Between that and the SDMMC registers lies the whole SD protocol - the power-up and clock rules, the identification of the card (CMD0, CMD8, ACMD41, CMD2, CMD3 ...), the selection of the bus width and of the speed mode, the data timeouts, the CRC, the busy signalling after a write, the stop of a multi-block transfer. The module owns all of it and offers the block interface; a file system driver of a middleware is a few lines on the top.
  • The same hardware is used for the other cards: the module identifies a SD memory card (standard, high and extended capacity), an eMMC device and gives the raw command interface to an SDIO device (Wi-Fi modules, for example), where the protocol is in a middleware.
  • The throughput is limited by the way the data move: the module uses the internal DMA of the SDMMC (or the system DMA, according to the family) so that a multi-block transfer needs no CPU; the interrupt reports the end, the polling mode exists for simple and bare-metal applications.
  • The module hides the differences between the families: the SDIO of the old families, the SDMMC with the internal DMA of the new ones, the kernel clock, the delay block, the direction pins of the voltage level translators differ, the interface stays the same.

What the module is not: it does not implement a file system, it does not supply the card (the application / the board switches the supply through a callback) and it does not implement the SDIO function drivers. The SPI mode of the card (over the SPI module) is not part of it.


Concept​

Two layers in one module:

LayerFunctionsMeaning
HostSdmmc_Set_Power*, Sdmmc_Set_BusWidth, Sdmmc_Set_ClkFreq, Sdmmc_Set_SpeedMode, Sdmmc_Set_Command, Sdmmc_Set_TuningThe controller: power, the clock, the bus width, a raw command with the response, the sampling tuning (delay block).
CardSdmmc_Set_CardInit, Sdmmc_Get_CardInfo, Sdmmc_Set_BlockRead, Sdmmc_Set_BlockWrite, Sdmmc_Set_BlockErase, Sdmmc_Set_XferStopThe card: identification, the capacity, the block transfers, the erase, the state.

For an instance the module keeps:

ItemMeaning
Card stateSDMMC_CARD_ABSENT, SDMMC_CARD_PRESENT (inserted, not initialized), SDMMC_CARD_READY (identified and in the transfer state), SDMMC_CARD_ERROR. The insertion is detected by a pin (card detect) or by the application.
BusThe width (1 / 4 / 8 bits), the clock (Hz), the speed mode (sdmmc_SpeedMode_t: default 25 MHz, high speed 50 MHz, SDR50 / SDR104 / DDR50 and the eMMC DDR52 / HS200 where the controller and the board allow it).
TransferA request with the start block, the block count and the buffer; the state idle / busy / error and the callbacks.

Rules:

  1. Sdmmc_Init configures the instance, the pins and the interrupt and leaves the card not initialized. Sdmmc_Set_CardInit runs the identification: the power-up, the clock below 400 kHz, the card type recognition, the selection of the card, the 4-bit (8-bit for eMMC) bus and the fastest speed mode that the configuration allows (MaxClkFreq, MaxSpeedMode). The speed mode and the clock are raised step by step; the sampling is tuned when the mode needs it.
  2. A block transfer is a request: Sdmmc_Set_BlockRead( startBlock, blockCnt, buffer ) returns at once and the complete callback reports the end (DMA and ISR mode); in the POLL mode Sdmmc_Task serves the transfer. The same request and the same callbacks are used in all modes.
  3. A write is complete when the card is out of the busy state (the module polls the card status), so the complete callback of Sdmmc_Set_BlockWrite means the data are in the card.
  4. A multi-block transfer is terminated by the hardware (the stop command is sent automatically) or by Sdmmc_Set_XferStop; an error (CRC, timeout, overrun/underrun, the card status error) is reported by the error callback and the card state; a transfer in progress is stopped and the card is brought back to the transfer state.
  5. The block size is 512 bytes; the capacity and the addressing (byte / block) of the card are handled by the module - the application always uses block numbers.
  6. Each parameter is checked before a register is written; a request on a card that is not READY returns an error.

Supported families​

Every family gets its own story, its own tasks and its own branches Dev/<Family> and Releases/<Family> cut from this master.

FamilyBranchControllerStatus
STM32H5Dev/STM32H5SDMMC1, SDMMC2 (not on STM32H503; SDMMC2 on H563 / H573 / H5E / H5F), SD 6.0 / SDIO 4.0 / eMMC 5.1, 1 / 4 / 8-bit, internal DMA (IDMA) with a linked list, delay block (DLYBSD)planned (first)
STM32U5Dev/STM32U5SDMMC1, SDMMC2, IDMA with a linked list, delay blockplanned
STM32H7Dev/STM32H7SDMMC1, SDMMC2, IDMA (single / double buffer), delay blockplanned
STM32F7Dev/STM32F7SDMMC1, SDMMC2 on some lines, data FIFO, system DMAplanned
STM32L4Dev/STM32L4SDMMC1 on the lines that have itplanned
STM32F4Dev/STM32F4SDIO (a different, older controller: 1 / 4-bit, system DMA)planned
STM32G4Dev/STM32G4none (the module is a stub)planned
STM32U3Dev/STM32U3device dependentplanned

A function without a meaning in a family stays in the interface, returns SDMMC_REQUEST_ERROR and suppresses the unused parameters (for example the 8-bit bus or the tuning of an old controller, the second instance of a device that has only one).


Public interface in short (proposal)​

GroupFunctions
Module managementSdmmc_Get_ModuleVersion, Sdmmc_Init, Sdmmc_Deinit, Sdmmc_Task, Sdmmc_Get_DefaultConfig
HostSdmmc_Set_PowerActive, Sdmmc_Set_PowerInactive, Sdmmc_Set_BusWidth / Get, Sdmmc_Set_ClkFreq / Get, Sdmmc_Set_SpeedMode / Get, Sdmmc_Set_Tuning
Raw commandSdmmc_Set_Command, Sdmmc_Get_Response
CardSdmmc_Set_CardInit, Sdmmc_Get_CardState, Sdmmc_Get_CardInfo, Sdmmc_Get_CardStatus
Block transfersSdmmc_Set_BlockRead, Sdmmc_Set_BlockWrite, Sdmmc_Set_BlockErase, Sdmmc_Set_XferStop, Sdmmc_Get_XferState, Sdmmc_Get_XferError
InterruptsSdmmc_Set_IrqPriority, Sdmmc_Get_IrqPriority
PinsSdmmc_InitClkGpio, Sdmmc_InitCmdGpio, Sdmmc_InitDataGpio, Sdmmc_InitDirGpio, Sdmmc_InitDetectGpio
sdmmc_ModuleVersion_t Sdmmc_Get_ModuleVersion ( void );

sdmmc_RequestState_t Sdmmc_Init ( const sdmmc_Config_t * const sdmmcConfig );
sdmmc_RequestState_t Sdmmc_Deinit ( sdmmc_PeriphId_t periphId );
void Sdmmc_Task ( void );
sdmmc_RequestState_t Sdmmc_Get_DefaultConfig ( sdmmc_Config_t * const sdmmcConfig );

sdmmc_RequestState_t Sdmmc_Set_BusWidth ( sdmmc_PeriphId_t periphId, sdmmc_BusWidth_t busWidth );
sdmmc_RequestState_t Sdmmc_Set_ClkFreq ( sdmmc_PeriphId_t periphId, sdmmc_Frequency_Hz_t clkFreq );
sdmmc_RequestState_t Sdmmc_Set_SpeedMode ( sdmmc_PeriphId_t periphId, sdmmc_SpeedMode_t speedMode );
sdmmc_RequestState_t Sdmmc_Set_Tuning ( sdmmc_PeriphId_t periphId );

sdmmc_RequestState_t Sdmmc_Set_Command ( sdmmc_PeriphId_t periphId, const sdmmc_Command_t * const command );
sdmmc_RequestState_t Sdmmc_Get_Response ( sdmmc_PeriphId_t periphId, sdmmc_Response_t * const response );

sdmmc_RequestState_t Sdmmc_Set_CardInit ( sdmmc_PeriphId_t periphId );
sdmmc_RequestState_t Sdmmc_Get_CardState ( sdmmc_PeriphId_t periphId, sdmmc_CardState_t * const cardState );
sdmmc_RequestState_t Sdmmc_Get_CardInfo ( sdmmc_PeriphId_t periphId, sdmmc_CardInfo_t * const cardInfo );

sdmmc_RequestState_t Sdmmc_Set_BlockRead ( sdmmc_PeriphId_t periphId, sdmmc_BlockNo_t startBlock, sdmmc_BlockCnt_t blockCnt, sdmmc_Data_t * const buffer );
sdmmc_RequestState_t Sdmmc_Set_BlockWrite ( sdmmc_PeriphId_t periphId, sdmmc_BlockNo_t startBlock, sdmmc_BlockCnt_t blockCnt, const sdmmc_Data_t * const buffer );
sdmmc_RequestState_t Sdmmc_Set_BlockErase ( sdmmc_PeriphId_t periphId, sdmmc_BlockNo_t startBlock, sdmmc_BlockNo_t endBlock );
sdmmc_RequestState_t Sdmmc_Set_XferStop ( sdmmc_PeriphId_t periphId );
sdmmc_RequestState_t Sdmmc_Get_XferState ( sdmmc_PeriphId_t periphId, sdmmc_XferState_t * const xferState );
sdmmc_RequestState_t Sdmmc_Get_XferError ( sdmmc_PeriphId_t periphId, sdmmc_XferError_t * const xferError );

Every function returns SDMMC_REQUEST_OK / SDMMC_REQUEST_ERROR and checks its parameters and the state of the module before it touches a register.

TypeMeaning
sdmmc_Config_tInstance, transfer mode (SDMMC_XFER_MODE_POLL / ISR / DMA), kernel clock source, maximum bus width, MaxClkFreq, MaxSpeedMode, pins (clock, command, data, direction signals, card detect), callbacks, interrupt priority
sdmmc_CardType_tSDMMC_CARD_SD_V1, SDMMC_CARD_SD_V2, SDMMC_CARD_SDHC_SDXC, SDMMC_CARD_MMC, SDMMC_CARD_EMMC, SDMMC_CARD_SDIO
sdmmc_CardInfo_tCard type, the number of blocks, the block size, the relative address, the bus width and the speed mode in use, the write protection, the CID / CSD registers
sdmmc_XferError_tBit mask: command timeout, data timeout, CRC error, overrun / underrun, card status error, DMA error
CallbacksXferCompleteCallback, XferErrorCallback, CardDetectCallback (inserted / removed), PowerCallback (the board switches the card supply), VoltageSwitchCallback (the board switches the signalling to 1.8 V)

Usage​

A file system on the card​

#include "Sdmmc_Port.h"

static volatile sdmmc_FlagState_t xferDone = SDMMC_FLAG_INACTIVE;

static void App_SdDone( sdmmc_PeriphId_t periphId )
{
xferDone = SDMMC_FLAG_ACTIVE; /* a failure is reported by XferErrorCallback */
}

sdmmc_Config_t sdmmcConfig;
sdmmc_CardInfo_t cardInfo;

(void)Sdmmc_Get_DefaultConfig( &sdmmcConfig );

sdmmcConfig.PeriphId = SDMMC_PERIPH_1;
sdmmcConfig.XferMode = SDMMC_XFER_MODE_DMA;
sdmmcConfig.MaxBusWidth = SDMMC_BUS_WIDTH_4;
sdmmcConfig.MaxClkFreq = 50000000u;
sdmmcConfig.XferCompleteCallback = App_SdDone;

(void)Sdmmc_Init( &sdmmcConfig );
(void)Sdmmc_Set_CardInit( SDMMC_PERIPH_1 ); /* identification, 4-bit bus, high speed */
(void)Sdmmc_Get_CardInfo( SDMMC_PERIPH_1, &cardInfo );

/* the media driver of the file system: read 8 blocks from the block 2048 */
(void)Sdmmc_Set_BlockRead( SDMMC_PERIPH_1, 2048u, 8u, sectorBuffer );

Raw command (SDIO device, a card specific command)​

const sdmmc_Command_t cmd52 =
{
.Index = 52u,
.Argument = sdioArgument,
.Response = SDMMC_RESPONSE_SHORT,
};
sdmmc_Response_t response;

(void)Sdmmc_Set_Command( SDMMC_PERIPH_1, &cmd52 );
(void)Sdmmc_Get_Response( SDMMC_PERIPH_1, &response );

Behaviour and limits​

  • Clock. The bus clock is derived from the kernel clock of the SDMMC (the RCC module selects it). The identification runs below 400 kHz, the maximum clock is limited by the card, the speed mode, the configuration and the I/O speed of the device; the achieved clock is read back with Sdmmc_Get_ClkFreq.
  • High speed and tuning. The modes above the default speed (SDR50, SDR104, DDR50, HS200) need the 1.8 V signalling (the voltage switch is done by the application through the callback) and the sampling tuning with the delay block; without the board support (or without the Dlyb module) the module stays in the modes that need no tuning.
  • Unaligned buffers. The DMA needs the buffers aligned to words; the module rejects an unaligned buffer (or copies it through an internal block when it is enabled in the family). A buffer in a cached memory must be coherent with the DMA (non-cacheable region or a cache maintenance by the application).
  • Card removal. A removal during a transfer ends it with an error; the card state returns to ABSENT and the module has to be re-initialized (Sdmmc_Set_CardInit) for the next card.
  • Write protection and lock. The mechanical write protect switch is read through the card info; the password lock and the secure erase are not part of the first version.
  • Not part of the first version: the SDIO function layer (CMD52 / CMD53 helpers - only the raw command), the SPI mode, the eMMC boot partitions and the replay protected memory block, UHS-II, HS400, the hot-plug detection of the card without the detect pin.

Dependencies​

  • Rcc - peripheral clock, kernel clock source and its frequency, reset
  • Nvic - interrupt of the instance
  • Gpio - clock, command, data, direction and card detect pins
  • Gpdma - DMA transfers on the families whose SDMMC has no internal DMA (the families with the internal DMA use it)
  • Dlyb - the delay block for the sampling tuning of the high speed modes (a module of its own, planned)
  • RAL (Register Abstraction Layer) - used internally to access the registers

All mandatory RCC, NVIC, GPIO and DMA configurations are handled internally.


Testing​

  • Unit tests (host, Unity + CMock + RegMem): the clock divider calculation, the command and the response handling (short, long, none, the CRC-less responses), the identification sequence against a simulated card (SD v1, v2, SDHC, eMMC), the addressing (byte / block), the transfer state machine (read, write with the busy wait, erase, stop, error and timeout paths), the rejected requests (card not ready, unaligned buffer, block range beyond the capacity).
  • Integration tests (target, probe-rs): the identification of the real cards, the write - read - compare of a block range in every supported bus width and speed mode, the throughput measurement, the card removal during a transfer.

Interface conventions​

The module follows the common rules of the MCAL layer, so that it behaves like the other modules:

  • Lists instead of free members. Everything that the hardware restricts (the pins, the kernel clock sources, the DMA channels, the triggers and the other selectable sources) is a typedef enum list with exactly the items that are valid for the device line; a pin is an item SDMMC_<SIGNAL>_PIN_<INSTANCE>_P<port><pin> and there is an *_UNUSED item. A choice that is not in the list cannot be written.
  • Own peripheral only. The module calls only the registers / LL functions of its own peripheral. The clocks, the interrupts, the pins, the DMA and the EXTI lines go through the API of the Rcc, Nvic, Gpio, Gpdma and Exti modules; a missing function is added to that module, it is not bypassed.
  • Init verifies itself. Sdmmc_Init checks the result at the end; when it is not as required, the module is deinitialized and an error is returned. The waiting for the hardware is a loop on the register state with a timeout, never a blind delay.
  • Transfer modes. Where the module moves data, the POLL (served by Sdmmc_Task), ISR and DMA modes have the same configuration structure, the same request and the same callbacks (error, half transfer, transfer complete).
  • Flags and states are enums of the module (sdmmc_FunctionState_t, sdmmc_FlagState_t), the limits and the constants are named, there are no magic numbers in the interface.
  • Unsupported functions stay. A function without a meaning in a family keeps its signature, suppresses the unused parameters and returns SDMMC_REQUEST_ERROR.
  • Documentation. Every function and type has a Doxygen description, the main header has the \defgroup.

Repository layout and branches​

The master holds this README and the license. The family branches (Dev/<Family>, Releases/<Family>) hold:

PathContent
README.mdREADME of the family: the instances of the device, specifics, errata, status
Sdmmc_Port.h, Sdmmc_Types.hPublic interface (identical in all families)
Sdmmc*.c, Sdmmc.hImplementation of the family
CMakeLists.txtLibrary Sdmmc_Lib of the EmBi platform
Tests/UnitTestsUnit tests (Unity + CMock + RegMem)
Tests/IntegrationTestsIntegration tests on the target (probe-rs)

A change of the public interface is made in all families.


CMake integration​

target_link_libraries( User_Lib PRIVATE Sdmmc_Lib )
  1. Link Sdmmc_Lib to your CMake library.
  2. Include Sdmmc_Port.h in your project.
  3. Configure the module as needed for your hardware.

License​

This project is licensed under the Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0).

You are free to use, modify, and share this work for non-commercial purposes, provided appropriate credit is given.

See LICENSE.md for full terms or visit creativecommons.org/licenses/by-nc/4.0.


Authors​

Contributions are welcome! Please open a pull request.