diff --git a/libraries/SDIO/README.md b/libraries/SDIO/README.md new file mode 100644 index 0000000000..7d51fee977 --- /dev/null +++ b/libraries/SDIO/README.md @@ -0,0 +1,216 @@ +# STM32 SDIO / SDMMC + +Raw sector access for STM32F1, F2, F4, F7 and H5 devices that actually have +SDIO or SDMMC. F0/F3 devices without those peripherals cannot use this driver. +The library selects SDIO, SDMMC1 or SDMMC2 from the chosen pins or from +`setInstance()`. SDMMC1 and SDMMC2 have independent ownership and IRQ routing. +It does not implement a filesystem or SPI mode. + +Use `#include ` and the global **`SDCard`** object. `SDIO` remains +the CMSIS hardware macro and cannot also name a C++ object on F1/F2/F4. +`begin()` returns a success flag; `getError()` returns the active SD or MMC +HAL error code. `getHandle()` exposes the SD handle; `getMMCHandle()` exposes +the separate MMC handle when HAL MMC is enabled. + +The public object is `SDCard`. Card-detection callback registration uses +`setDetectionCallback(callback)`. No object or callback aliases are provided. +The sector units of `read()`/`write()` are unchanged. + +Core 2.9 and the repository's 3.x core are supported by the same sources. +The EXTI bridge selects the 2.9 port/HAL-pin-mask registration API or the +3.x `PinName` API at compile time. Callback detachment remains in C++ for +correct linkage on both cores; disabled EXTI builds remain supported. + +## Configurable data clock and diagnostic history + +Call `setClock(hz)` before `begin()` or `beginMMC()`. It accepts a requested +maximum between 1 Hz and 52 MHz, rejecting zero, higher rates, and changes +while initialized without changing the previous setting. In 1-bit mode, +requests above 25 MHz are rejected. `begin()` also validates width and +medium: SD 4-bit requests are limited to 50 MHz; MMC/eMMC 4/8-bit requests +are limited to 52 MHz. Changing the width after `setClock()` cannot bypass +these checks. The peripheral's +divider range imposes a family/clock-dependent minimum: `begin()` returns +false if it cannot represent the requested speed. `getClock()` returns the +requested limit; `getActualClock()` returns the clock read back from the +controller's divider after successful initialization, or zero before +initialization and after `end()`. Dividers round up, so the actual clock +does not exceed the requested limit (e.g. 15 MHz gives 12 MHz from 48 MHz). +The setting persists across `end()`. The default remains 25 MHz. + +Identification and width negotiation always run at a safe clock. Before +raising the data clock above 25 MHz, SD cards must confirm CMD6 High Speed; +MMC/eMMC must advertise a suitable SDR speed in EXT_CSD DEVICE_TYPE and +accept HS_TIMING=1. The legacy HALs use the LL CMD6/status path; H5 SD uses +the HAL speed-negotiation API. Unsupported or failed switching makes +initialization fail without enabling the faster clock. `entry.high_speed` +records successful negotiation. The configured clock remains bounded by +both the requested limit and the controller: legacy SDIO/SDMMC uses divider +bypass only up to 48 MHz, so a 50/52 MHz request often yields 48 MHz. If a +divider can only yield a rate <=25 MHz, no High Speed switch is needed. +This implementation covers 3.3 V SDR High Speed, not UHS, DDR, HS200 or HS400. +For SD speed modes, see the +[SD Association specification](https://www.sdcard.org/cms/wp-content/themes/sdcard-org/dl.php?f=Part1_Physical_Layer_Simplified_Specification_Ver7.10.pdf). + +Diagnostic logging is disabled by default. Enable it before initialization: + +```cpp +alignas(32) static uint8_t sector[512]; +SDCard.setClock(15000000U); +SDCard.setLogging(); +if (SDCard.begin(true) && SDCard.read(sector, 0, 1)) { + SDCard.wait(1000); +} +sd_log_entry_t entry; +for (uint32_t i = 0; i < SDCard.getLogCount(); ++i) { + if (SDCard.getLog(i, entry)) { + // inspect entry.operation, phase, status, error, command and response[] + } +} +SDCard.end(); +``` + +Each instance retains its own last 10 entries in a fixed ring without heap +allocation. `getLog(0, entry)` copies the oldest retained entry; out-of-range +indices return false. `clearLog()` clears the history, and `setLogging(false)` +stops new entries while retaining existing ones. The history survives `end()` +and reinitialization. + +Entries describe initialization, read/write/erase submissions and failures, +observed transfer completion, aborts and shutdown. They include millisecond +timestamps, controller, sector/count, SD/MMC, DMA, width, requested/actual +clock, HAL error bits, and snapshots of CMD/ARG/RESP1-4. `registers_valid` +is false if the object does not own a live controller (e.g. pin validation +failed). This is an operation diagnostic log, not a trace of every low-level +HAL command. Completion is recorded when `wait()`/`isBusy()` observes the +result, or before a subsequent valid transfer; no log work is added to IRQ +handlers. A pending operation stopped by `end()` is recorded as cancelled +(`SD_ERROR`). Read the log from the foreground, like the other public APIs. + +`SDIO_LOG_CAPACITY` is a build-wide definition controlling the ring size. +Set it to 0 to remove log storage and recording, keeping the API available +with zero entries. Increasing it increases RAM per `SDIOClass` object. + +## SD and MMC/eMMC + +| Medium | Width | Initialization | +| --- | --- | --- | +| SD card | 1 or 4 bits | `setDataMode(SDIO_MODE_1B/4B)`, then `begin(useDMA)` | +| MMC/eMMC | 1, 4 or 8 bits | select width, then `beginMMC(useDMA)` | +| MMC/eMMC | 8 bits | `setDataMode(SDIO_MODE_8B)`, then `begin(useDMA)` also selects MMC | + +Eight-bit mode uses **HAL MMC**, including its card identification, bus-width +negotiation, capacity, transfers, errors and IRQ handler. It is not an attempt +to put a normal SD card into 8-bit mode. This is SDR sector access, not an +HS200/HS400, RPMB or boot-partition API. + +Enable the HAL modules for the **whole build**, for example in the sketch's +`build_opt.h`: + +```text +-DHAL_SD_MODULE_ENABLED= +-DHAL_MMC_MODULE_ENABLED= +-DHAL_UART_MODULE_ENABLED= +``` + +UART is only needed for example diagnostics. External DMA also requires +HAL DMA, normally enabled by the core. MMC is optional: without its HAL +module, SD still compiles and requesting MMC/8-bit initialization returns +false with `HAL_SD_ERROR_UNSUPPORTED_FEATURE`. + +## Pins and controller selection + +Configure pins and width before initialization. Common SDIO/SDMMC1 wiring +on the requested MCU families is: + +| Signal | Pin | +| --- | --- | +| D0-D3 | PC8, PC9, PC10, PC11 | +| CK, CMD | PC12, PD2 | +| D4-D7 for MMC 8-bit | PB8, PB9, PC6, PC7 | + +Check the selected **package**, variant pin map and board wiring. Pins left +as `NC` default to entries for the same controller. Mixed-controller pins +or missing signals are rejected. H562 LQFP64 does not expose PB9/D5 and +therefore supports this wiring only in 1/4-bit mode; VFQFPN68 and larger +applicable packages expose D5. See the ST +[H562/H563 pin table](https://www.st.com/resource/en/datasheet/stm32h562vg.pdf). + +For the second controller on a device that has it, use a separate object: + +```cpp +SDIOClass second; +second.setInstance(SDMMC2); // guarded by #if defined(SDMMC2) in portable code +second.setDataMode(SDIO_MODE_8B); +bool ready = second.beginMMC(true); // defaults to this variant's SDMMC2 pins +``` + +Pin setters `setD0()` through `setD7()`, `setCMD()` and `setSCK()` accept +Arduino pin numbers or `PinName` values. Use the latter for explicit alternate +pin mappings, such as `PB_8_ALT1`. When reusing an object for a different +controller, reset its old pins to `NC` or supply all new pins. One object may +own each controller at a time. Objects cannot be copied or moved. Do not call +the API concurrently or from an ISR. Board-specific transceiver routing can +be implemented through the weak `SDIO_MspInit/DeInit` hooks; the default +H5 configuration uses direct 3.3 V signaling without a transceiver. + +## Clocks and DMA + +The library reads the selected kernel clock and calculates the data divider; +it does not reconfigure the board's PLLs. F1 uses HCLK; the F1 SD/MMC HAL +identification dividers in this core are corrected for HCLK up to 72 MHz. +F2/F4/F7 use their PLLQ/CLK48 and SDMMC muxes, not PCLK2. Their legacy HAL +uses a fixed identification divider, so a selected input above 48 MHz is +rejected rather than exceeding the initial 400 kHz card clock. H5 queries +RCC for the selected SDMMC instance and uses its `clock / (2 * divider)` +formula, with the HAL handling the identification divider. Normal requested +data speed defaults to 25 MHz and can be increased after High Speed negotiation. + +The generic H562 variant has an empty `SystemClock_Config()`. The examples +explicitly call `SDIOExampleConfigureClock()` to supply SDMMC1 from a 48 MHz +PLL2R/CSI source if the kernel clock is stopped. This optional helper assumes +PLL2 is available. Applications sharing PLL2 should configure the clock at +board level instead. + +| Family / controller | DMA engine and reserved IRQs | +| --- | --- | +| F1 SDIO | DMA2 Channel4 (RX/TX); Channel4 or shared Channel4/5 vector | +| F2/F4 SDIO | DMA2 Stream3 RX, Stream6 TX, channel4; SDIO IRQ | +| F7 SDMMC1 | DMA2 Stream3 RX, Stream6 TX, channel4; SDMMC1 IRQ | +| F7 SDMMC2 | DMA2 Stream0 RX, Stream5 TX, channel11; SDMMC2 IRQ | +| H5 SDMMC1/2 | SDMMC internal DMA (IDMA); only that SDMMC IRQ, no GPDMA allocation | + +Do not allocate the reserved streams/channels/vectors to another peripheral. +On high-density F103, the shared Channel4/5 vector is reserved as a whole. +`SDIO_IRQ_PRIORITY` defaults to 5 and is configurable for the whole build. + +Buffers must be word aligned, or **32-byte aligned on F7**, where the driver +cleans TX cache lines and cleans/invalidates RX lines before DMA, then +invalidates RX again on completion, error or abort. Full-sector sizes cover +whole cache lines. Buffers must be in DMA-accessible memory; F4 CCM is +rejected. Keep DMA buffers alive and untouched until `wait()` succeeds or +`isBusy()` becomes false and `getError()` has been checked. + +External DMA permits 1-511 sectors per call. H5 IDMA and polling permit +1-65535 sectors. The caller supplies `blocks * 512` bytes and splits larger +requests. Addresses are logical 512-byte sectors, including on SDSC cards. +Erase endpoints are inclusive; check the medium's erase granularity. + +Polling read/write wait for card readiness. DMA read/write return after +starting the transfer. Always wait before accessing its buffer: + +```cpp +alignas(32) static uint8_t sector[512]; +if (SDCard.begin(true) && SDCard.read(sector, 0, 1) && SDCard.wait(1000)) { + // sector can now be used +} +SDCard.end(); +``` + +`wait(timeout)` checks HAL, DMA and card programming status, aborts DMA on +timeout, and returns false on error. Failed starts also stop DMA before +returning. `end()` stops transfers, disables owned IRQs and releases SDIO/ +SDMMC pins and clocks, leaving the shared DMA2 clock enabled. Optional card +detection uses `setDetectionInput(arduinoPin, LOW/HIGH)` and +`setDetectionCallback(callback)`. Callbacks run in interrupt context and are detached by +`end()`. Without a detect pin, initialization still probes the medium. diff --git a/libraries/SDIO/SDIO.cpp b/libraries/SDIO/SDIO.cpp new file mode 100644 index 0000000000..7b9a3e5780 --- /dev/null +++ b/libraries/SDIO/SDIO.cpp @@ -0,0 +1,283 @@ +/** + * @file SDIO.cpp + * @brief Arduino wrapper for controller ownership, media I/O and card detection. + * based on ST's https://github.com/stm32duino/STM32SD/blob/main/src/bsp_sd.c + */ +#include "SDIO.h" + +#if defined(STM32_SDIO_ENABLED) + +SDIOClass SDCard; + +// The core EXTI registration API has C++ linkage. Keep its bridge here. +/** + * @brief Detach the owned card-detect EXTI registration through the C++ core API. + * @param obj Controller whose detection interrupt is to be disabled. + */ +extern "C" void sd_detachDetectionInterrupt(sd_t *obj) +{ +#if !defined(HAL_EXTI_MODULE_DISABLED) + if (obj && obj->detection_interrupt) { + stm32_interrupt_disable(obj->SD_detect_gpio_port, STM_GPIO_PIN(obj->pin_detect)); + obj->detection_interrupt = false; + } +#else + UNUSED(obj); +#endif +} + +/** + * @brief Construct an uninitialized SDIO/SDMMC controller. + * @param pin_d0 Arduino D0 pin, or NC for automatic selection. + * @param pin_d1 Arduino D1 pin, or NC for automatic selection. + * @param pin_d2 Arduino D2 pin, or NC for automatic selection. + * @param pin_d3 Arduino D3 pin, or NC for automatic selection. + * @param pin_cmd Arduino command pin, or NC for automatic selection. + * @param sclk Arduino clock pin, or NC for automatic selection. + * @note PinMap defaults are resolved during initialization. All required + * signals must belong to one controller; only one object may own it. + */ +SDIOClass::SDIOClass(uint32_t pin_d0, uint32_t pin_d1, uint32_t pin_d2, uint32_t pin_d3, uint32_t pin_cmd, uint32_t sclk) +{ + memset((void *)&_sd, 0, sizeof(_sd)); + _sd.pin_d0 = digitalPinToPinName(pin_d0); + _sd.pin_d1 = digitalPinToPinName(pin_d1); + _sd.pin_d2 = digitalPinToPinName(pin_d2); + _sd.pin_d3 = digitalPinToPinName(pin_d3); + _sd.pin_d4 = _sd.pin_d5 = _sd.pin_d6 = _sd.pin_d7 = NC; + _sd.pin_cmd = digitalPinToPinName(pin_cmd); + _sd.pin_sck = digitalPinToPinName(sclk); + _sd.pin_detect = NC; + _sd.busMode = SDIO_MODE_4B; + _sd.requested_clock = SDIO_SPEED_CLOCK_DEFAULT; +} + +/** +* @brief Initialize SD media, or MMC when eight-bit mode is selected. +* @param useDMA Request DMA; falls back to blocking transfers if HAL DMA is disabled. +* @return True if pins, media, clock negotiation and DMA setup succeed. +*/ +bool SDIOClass::begin(bool useDMA) +{ + return sd_init(&_sd, _sd.requested_clock, _sd.busMode, useDMA) == SD_OK; +} + +/** + * @brief Initialize MMC/eMMC with the configured bus width and clock. + * @param useDMA Request DMA; falls back to blocking transfers if HAL DMA is disabled. + * @return True on successful initialization. + * @note Eight-bit mode requires all eight data signals and HAL MMC support. + */ +bool SDIOClass::beginMMC(bool useDMA) +{ + return sd_init_mmc(&_sd, _sd.requested_clock, _sd.busMode, useDMA) == SD_OK; +} + +/** + * @brief Set the maximum data clock for the next initialization. + * @param hz Requested frequency in Hz; must be nonzero. + * @return False while initialized, above 52 MHz, or above 25 MHz in one-bit mode. + * @note Initialization also enforces the media limit (SD: 50 MHz; MMC: 52 MHz), + * negotiates High Speed above 25 MHz and selects a realizable peripheral clock. + */ +bool SDIOClass::setClock(uint32_t hz) +{ + if (_sd.initialized || !hz || hz > SDIO_SPEED_CLOCK_MAX || + (_sd.busMode == SDIO_MODE_1B && hz > 25000000U)) { + return false; + } + _sd.requested_clock = hz; + return true; +} + +/** + * @brief Stop transfers and release the controller, DMA resources and detection interrupt. + */ +void SDIOClass::end(void) +{ + sd_deinit(&_sd); +} + + +/** + * @brief Configure a card-detect input with an internal pull-up. + * @param ulPin Arduino pin number for the detection input. + * @param ulLvl Active level: zero for low, nonzero for high. + * @return True if the pin can be configured. + */ +bool SDIOClass::setDetectionInput(uint32_t ulPin, uint32_t ulLvl) +{ + bool ret = false; + PinName p = digitalPinToPinName(ulPin); + if (p != NC) { + ret = sd_setDetectionInput(&_sd, p, ulLvl); + } + return ret; +} + +/** + * @brief Register a callback for both edges of the card-detect input. + * @param callback Non-null function executed in EXTI interrupt context. + * @return False if detection is unconfigured, callback is null or EXTI is disabled. + * @note The historical spelling is retained for source compatibility. + */ +bool SDIOClass::setDetectionCallback(void (*callback)(void)) +{ +#if !defined(HAL_EXTI_MODULE_DISABLED) + if (_sd.pin_detect != NC && callback != nullptr) { +#if STM32_CORE_VERSION < 0x03000000 + // Core 2.9 registers EXTI with GPIO port + HAL pin mask. + stm32_interrupt_enable(_sd.SD_detect_gpio_port, STM_GPIO_PIN(_sd.pin_detect), callback, GPIO_MODE_IT_RISING_FALLING); +#else + stm32_interrupt_enable(_sd.pin_detect, callback, GPIO_MODE_IT_RISING_FALLING); +#endif + _sd.detection_interrupt = true; + return true; + } +#else + UNUSED(callback); +#endif + return false; +} + +/** + * @brief Return whether the configured detection input matches its active level. + * @return False if no detection input is configured. + */ +bool SDIOClass::isDetected(void) +{ + return sd_isDetected(&_sd); +} + +/** + * @brief Poll transfer and card-programming progress. + * @return True while HAL, DMA or card programming is busy. + * @note False also occurs on error; inspect getError() or use wait(). + */ +bool SDIOClass::isBusy(void) +{ + return sd_isBusy(&_sd); +} + +/** + * @brief Wait for transfer completion and card readiness. + * @param timeout Maximum wait in milliseconds. + * @return True on success; false on error or timeout. + * @note A DMA timeout aborts the transfer before returning. + */ +bool SDIOClass::wait(uint32_t timeout) +{ + return sd_wait(&_sd, timeout) == SD_OK; +} + +/** + * @brief Read consecutive 512-byte logical sectors. + * @param[out] buf Buffer for at least blocks * 512 bytes. + * @param address First logical sector (not a byte address). + * @param blocks Number of sectors. + * @return True on blocking completion or acceptance of a DMA transfer. + * @note With DMA, keep the buffer alive and untouched until wait() succeeds. + * Buffers require four-byte alignment, or 32-byte alignment with Cortex-M7 DMA, + * and must reside in DMA-accessible memory. Inspect getError() on failure. + */ +bool SDIOClass::read(void *buf, uint32_t address, size_t blocks) +{ + bool ret = false; + if (sd_read(&_sd, (uint8_t *)buf, address, blocks) == 0) { + ret = true; + } + return ret; +} + +/** + * @brief Write consecutive 512-byte logical sectors. + * @param[in] buf Source containing at least blocks * 512 bytes. + * @param address First logical sector (not a byte address). + * @param blocks Number of sectors. + * @return True on blocking completion or acceptance of a DMA transfer. + * @note With DMA, retain the source unchanged until wait() succeeds, including + * card programming. Alignment and memory requirements are the same as read(). + */ +bool SDIOClass::write(const void *buf, uint32_t address, size_t blocks) +{ + bool ret = false; + if (sd_write(&_sd, (const uint8_t *)buf, address, blocks) == 0) { + ret = true; + } + return ret; +} + +/** + * @brief Erase an inclusive logical-sector range and wait for the card. + * @param startAddress First 512-byte logical sector. + * @param endAddress Last 512-byte logical sector. + * @return True on successful completion. + */ +bool SDIOClass::erase(uint32_t startAddress, uint32_t endAddress) +{ + bool ret = false; + if (sd_erase(&_sd, startAddress, endAddress) == 0) { + ret = true; + } + return ret; +} + +/** + * @brief Select bus width before initialization. + * @param mode SDIO_MODE_1B, SDIO_MODE_4B or SDIO_MODE_8B. + * @note Changes are ignored while initialized. Eight-bit operation requires MMC/eMMC. + */ +void SDIOClass::setDataMode(uint8_t mode) +{ + setDataMode((SDIOMode)mode); +} + +/** + * @brief Select bus width before initialization. + * @param mode SDIO_MODE_1B, SDIO_MODE_4B or SDIO_MODE_8B. + * @note Changes are ignored while initialized. Eight-bit operation requires MMC/eMMC. + */ +void SDIOClass::setDataMode(SDIOMode mode) +{ + // Like pin setters, mode changes apply on the next begin(). + if (!_sd.initialized) { + _sd.busMode = mode; + } +} + +/** + * @brief Compatibility placeholder; performs no operation. + * @param interruptNumber Ignored interrupt number. + */ +void SDIOClass::usingInterrupt(int interruptNumber) +{ + UNUSED(interruptNumber); +} + +/** +* @brief Compatibility placeholder; performs no operation. +* @param interruptNumber Ignored interrupt number. +*/ +void SDIOClass::notUsingInterrupt(int interruptNumber) +{ + UNUSED(interruptNumber); +} + +/** +* @brief Compatibility placeholder; performs no operation. +*/ +void SDIOClass::attachInterrupt(void) +{ + // Should be enableInterrupt() +} + +/** +* @brief Compatibility placeholder; performs no operation. +*/ +void SDIOClass::detachInterrupt(void) +{ + // Should be disableInterrupt() +} + +#endif // STM32_SDIO_ENABLED + diff --git a/libraries/SDIO/SDIO.h b/libraries/SDIO/SDIO.h new file mode 100644 index 0000000000..7a2f38ee0b --- /dev/null +++ b/libraries/SDIO/SDIO.h @@ -0,0 +1,429 @@ +/** + * \file + * \brief Arduino SDIO/SDMMC interface for SD and MMC/eMMC media. + * based on ST's https://github.com/stm32duino/STM32SD/blob/main/src/SDIO.c + */ + +#ifndef _SDIO_H_INCLUDED +#define _SDIO_H_INCLUDED + +#include +#include "utility/sdio_com.h" + +#if defined(STM32_SDIO_ENABLED) + +/** + * @brief Own one SDIO/SDMMC controller and its optional DMA resources. + * @note Configure pins, width and clock before begin() or beginMMC(). + * Unspecified pins are resolved from the variant PinMap tables. + * Instances cannot be copied and require serialized access. + */ +class SDIOClass { + public: + /** + * @brief Construct an uninitialized controller with optional Arduino pin numbers. + * @param pin_d0 Data signal D0, or NC for PinMap selection. + * @param pin_d1 Data signal D1, or NC for PinMap selection. + * @param pin_d2 Data signal D2, or NC for PinMap selection. + * @param pin_d3 Data signal D3, or NC for PinMap selection. + * @param pin_cmd Command signal, or NC for PinMap selection. + * @param sclk Clock signal, or NC for PinMap selection. + */ + SDIOClass(uint32_t pin_d0 = NC, uint32_t pin_d1 = NC, uint32_t pin_d2 = NC, uint32_t pin_d3 = NC, uint32_t pin_cmd = NC, uint32_t sclk = NC); + /** + * @brief Release owned resources by calling end(). + */ + ~SDIOClass() + { + end(); + } + + // setD0...D3/CMD/SCLK have to be called before begin() + /** + * @brief Configure the D0 signal before initialization. + * @param pin Arduino pin number; NC requests automatic PinMap selection. + */ + void setD0(uint32_t pin) + { + _sd.pin_d0 = digitalPinToPinName(pin); + } + /** + * @brief Configure the D1 signal before initialization. + * @param pin Arduino pin number; NC requests automatic PinMap selection. + */ + void setD1(uint32_t pin) + { + _sd.pin_d1 = digitalPinToPinName(pin); + } + /** + * @brief Configure the D2 signal before initialization. + * @param pin Arduino pin number; NC requests automatic PinMap selection. + */ + void setD2(uint32_t pin) + { + _sd.pin_d2 = digitalPinToPinName(pin); + } + /** + * @brief Configure the D3 signal before initialization. + * @param pin Arduino pin number; NC requests automatic PinMap selection. + */ + void setD3(uint32_t pin) + { + _sd.pin_d3 = digitalPinToPinName(pin); + } + /** + * @brief Configure the D4 signal before initialization. + * @param pin Arduino pin number; NC requests automatic PinMap selection. + */ + void setD4(uint32_t pin) + { + _sd.pin_d4 = digitalPinToPinName(pin); + } + /** + * @brief Configure the D5 signal before initialization. + * @param pin Arduino pin number; NC requests automatic PinMap selection. + */ + void setD5(uint32_t pin) + { + _sd.pin_d5 = digitalPinToPinName(pin); + } + /** + * @brief Configure the D6 signal before initialization. + * @param pin Arduino pin number; NC requests automatic PinMap selection. + */ + void setD6(uint32_t pin) + { + _sd.pin_d6 = digitalPinToPinName(pin); + } + /** + * @brief Configure the D7 signal before initialization. + * @param pin Arduino pin number; NC requests automatic PinMap selection. + */ + void setD7(uint32_t pin) + { + _sd.pin_d7 = digitalPinToPinName(pin); + } + /** + * @brief Configure the CMD signal before initialization. + * @param pin Arduino pin number; NC requests automatic PinMap selection. + */ + void setCMD(uint32_t pin) + { + _sd.pin_cmd = digitalPinToPinName(pin); + }; + /** + * @brief Configure the SCK signal before initialization. + * @param pin Arduino pin number; NC requests automatic PinMap selection. + */ + void setSCK(uint32_t pin) + { + _sd.pin_sck = digitalPinToPinName(pin); + }; + + /** + * @brief Configure the D0 signal before initialization. + * @param pin STM32 PinName; NC requests automatic PinMap selection. + */ + void setD0(PinName pin) + { + _sd.pin_d0 = pin; + } + /** + * @brief Configure the D1 signal before initialization. + * @param pin STM32 PinName; NC requests automatic PinMap selection. + */ + void setD1(PinName pin) + { + _sd.pin_d1 = pin; + } + /** + * @brief Configure the D2 signal before initialization. + * @param pin STM32 PinName; NC requests automatic PinMap selection. + */ + void setD2(PinName pin) + { + _sd.pin_d2 = pin; + } + /** + * @brief Configure the D3 signal before initialization. + * @param pin STM32 PinName; NC requests automatic PinMap selection. + */ + void setD3(PinName pin) + { + _sd.pin_d3 = pin; + } + /** + * @brief Configure the D4 signal before initialization. + * @param pin STM32 PinName; NC requests automatic PinMap selection. + */ + void setD4(PinName pin) + { + _sd.pin_d4 = pin; + } + /** + * @brief Configure the D5 signal before initialization. + * @param pin STM32 PinName; NC requests automatic PinMap selection. + */ + void setD5(PinName pin) + { + _sd.pin_d5 = pin; + } + /** + * @brief Configure the D6 signal before initialization. + * @param pin STM32 PinName; NC requests automatic PinMap selection. + */ + void setD6(PinName pin) + { + _sd.pin_d6 = pin; + } + /** + * @brief Configure the D7 signal before initialization. + * @param pin STM32 PinName; NC requests automatic PinMap selection. + */ + void setD7(PinName pin) + { + _sd.pin_d7 = pin; + } + /** + * @brief Configure the CMD signal before initialization. + * @param pin STM32 PinName; NC requests automatic PinMap selection. + */ + void setCMD(PinName pin) + { + _sd.pin_cmd = pin; + }; + /** + * @brief Configure the SCK signal before initialization. + * @param pin STM32 PinName; NC requests automatic PinMap selection. + */ + void setSCK(PinName pin) + { + _sd.pin_sck = pin; + }; + // Optional explicit controller selection, applied before begin(). + /** + * @brief Select an SDIO/SDMMC controller before initialization. + * @param instance Peripheral register address; pins must belong to this controller. + */ + void setInstance(SD_TypeDef *instance) + { + _sd.requested_instance = instance; + } + + // Returns false if pins, clock, card initialization or DMA setup fail. + /** + * @brief Initialize SD media, or MMC when eight-bit mode is selected. + * @param useDma Request DMA; falls back to blocking transfers if HAL DMA is disabled. + * @return True if pins, media, clock negotiation and DMA setup succeed. + */ + bool begin(bool useDma = false); + // MMC/eMMC in 1/4/8-bit mode. begin() also selects MMC for 8-bit mode. + /** + * @brief Initialize MMC/eMMC with the configured bus width and clock. + * @param useDma Request DMA; falls back to blocking transfers if HAL DMA is disabled. + * @return True on successful initialization. + * @note Eight-bit mode requires all eight data signals and HAL MMC support. + */ + bool beginMMC(bool useDma = false); + /** + * @brief Stop transfers and release the controller, DMA resources and detection interrupt. + */ + void end(void); + // Requested maximum data clock, applied by the next begin()/beginMMC(). + /** + * @brief Set the maximum data clock for the next initialization. + * @param hz Requested frequency in Hz; must be nonzero. + * @return False while initialized, above 52 MHz, or above 25 MHz in one-bit mode. + * @note Initialization also enforces the media limit (SD: 50 MHz; MMC: 52 MHz), + * negotiates High Speed above 25 MHz and selects a realizable peripheral clock. + */ + bool setClock(uint32_t hz); + /** + * @brief Return the requested maximum data clock in Hz. + */ + uint32_t getClock(void) const + { + return _sd.requested_clock; + } + /** + * @brief Return the configured data clock in Hz (zero when unavailable). + */ + uint32_t getActualClock(void) const + { + return _sd.actual_clock; + } + /** + * @brief Enable or disable bounded operation logging. + * @param enabled Whether subsequent operations should be recorded. + */ + void setLogging(bool enabled = true) + { + sd_setLogging(&_sd, enabled); + } + /** + * @brief Discard retained diagnostic entries without changing the logging setting. + */ + void clearLog(void) + { + sd_clearLog(&_sd); + } + /** + * @brief Return the number of retained diagnostic entries. + */ + uint32_t getLogCount(void) const + { + return sd_getLogCount(&_sd); + } + // Index 0 is the oldest retained entry. Entries are returned by copy. + /** + * @brief Copy a retained diagnostic entry. + * @param index Zero-based index, oldest entry first. + * @param[out] entry Destination for the copied snapshot. + * @return False if the index is invalid or logging storage is disabled. + */ + bool getLog(uint32_t index, sd_log_entry_t &entry) const + { + return sd_getLog(&_sd, index, &entry); + } + + /* Addresses are 512-byte logical sectors. Polling calls wait for the + * card; DMA calls start a transfer. Use wait() before reusing the buffer. + */ + /** + * @brief Read consecutive 512-byte logical sectors. + * @param[out] buf Buffer for at least blocks * 512 bytes. + * @param address First logical sector (not a byte address). + * @param blocks Number of sectors. + * @return True on blocking completion or acceptance of a DMA transfer. + * @note With DMA, keep the buffer alive and untouched until wait() succeeds. + * Buffers require four-byte alignment, or 32-byte alignment with Cortex-M7 DMA, + * and must reside in DMA-accessible memory. Inspect getError() on failure. + */ + bool read(void *buf, uint32_t address, size_t blocks); + /** + * @brief Write consecutive 512-byte logical sectors. + * @param[in] buf Source containing at least blocks * 512 bytes. + * @param address First logical sector (not a byte address). + * @param blocks Number of sectors. + * @return True on blocking completion or acceptance of a DMA transfer. + * @note With DMA, retain the source unchanged until wait() succeeds, including + * card programming. Alignment and memory requirements are the same as read(). + */ + bool write(const void *buf, uint32_t address, size_t blocks); + /** + * @brief Erase an inclusive logical-sector range and wait for the card. + * @param startAddress First 512-byte logical sector. + * @param endAddress Last 512-byte logical sector. + * @return True on successful completion. + */ + bool erase(uint32_t startAddress, uint32_t endAddress); + + /** + * @brief Configure a card-detect input with an internal pull-up. + * applied before begin(). + * @param ulPin Arduino pin number for the detection input. + * @param ulLvl Active level: zero for low, nonzero for high. + * @return True if the pin can be configured. + */ + bool setDetectionInput(uint32_t ulPin, uint32_t ulLvl); + /** + * @brief Register a callback for both edges of the card-detect input. + * @param callback Non-null function executed in EXTI interrupt context. + * @return False if detection is unconfigured, callback is null or EXTI is disabled. + */ + bool setDetectionCallback(void (*callback)(void)); + /** + * @brief Return whether the configured detection input matches its active level. + * @return False if no detection input is configured. + */ + bool isDetected(void); + /** + * @brief Poll transfer and card-programming progress. + * @return True while HAL, DMA or card programming is busy. + * @note False also occurs on error; inspect getError() or use wait(). + */ + bool isBusy(void); + /** + * @brief Wait for transfer completion and card readiness. + * @param timeout Maximum wait in milliseconds. + * @return True on success; false on error or timeout. + * @note A DMA timeout aborts the transfer before returning. + */ + bool wait(uint32_t timeout = SD_TRANSFER_TIMEOUT); + /** + * @brief Return the active SD or MMC HAL error bitmask. + */ + uint32_t getError(void) const + { + return sd_getError(&_sd); + } + + // Select before begin(); SD supports 1/4 bits, MMC/eMMC supports 1/4/8. + /** + * @brief Select bus width before initialization. + * @details Accepts SDIO_MODE_1B, SDIO_MODE_4B or SDIO_MODE_8B. + * @note Changes are ignored while initialized. Eight-bit operation requires MMC/eMMC. + */ + void setDataMode(uint8_t); + /** + * @brief Select bus width before initialization. + * @details Accepts SDIO_MODE_1B, SDIO_MODE_4B or SDIO_MODE_8B. + * @note Changes are ignored while initialized. Eight-bit operation requires MMC/eMMC. + */ + void setDataMode(SDIOMode); + + // Not implemented functions. Kept for compatibility. + /** + * @brief Compatibility placeholder; performs no operation. + * @param interruptNumber Ignored interrupt number. + */ + void usingInterrupt(int interruptNumber); + /** + * @brief Compatibility placeholder; performs no operation. + * @param interruptNumber Ignored interrupt number. + */ + void notUsingInterrupt(int interruptNumber); + /** + * @brief Compatibility placeholder; performs no operation. + */ + void attachInterrupt(void); + /** + * @brief Compatibility placeholder; performs no operation. + */ + void detachInterrupt(void); + + // Could be used to mix Arduino API and STM32Cube HAL API (ex: DMA). Use at your own risk. + /** + * @brief Return the SD HAL handle for advanced integration. + * @warning Direct HAL access must not conflict with library-owned transfers. + */ + inline SD_HandleTypeDef *getHandle(void) + { + return &(_sd.handle); + } +#if defined(HAL_MMC_MODULE_ENABLED) + /** + * @brief Return the MMC HAL handle when HAL MMC support is enabled. + * @warning Direct HAL access must not conflict with library-owned transfers. + */ + MMC_HandleTypeDef *getMMCHandle(void) + { + return &_sd.mmc; + } +#endif + + // The peripheral and DMA handles cannot be copied or moved. + SDIOClass(const SDIOClass &) = delete; + SDIOClass &operator=(const SDIOClass &) = delete; + + protected: + // SD instance + sd_t _sd; +}; +/** @brief Default Arduino SD/MMC controller object. */ +// SDIO is reserved by CMSIS for the peripheral register address. +extern SDIOClass SDCard; + +#endif // STM32_SDIO_ENABLED +#endif // _SDIO_H_INCLUDED + diff --git a/libraries/SDIO/SDIOExampleClock.h b/libraries/SDIO/SDIOExampleClock.h new file mode 100644 index 0000000000..1df84e0205 --- /dev/null +++ b/libraries/SDIO/SDIOExampleClock.h @@ -0,0 +1,41 @@ +// Optional clock setup for examples on generic H562 boards. The SDIO driver +// itself never changes the board's PLLs. Call explicitly from setup(). +#pragma once +#include + +inline bool SDIOExampleConfigureClock() +{ +#if defined(STM32H5xx) + // Respect a clock already supplied by the board. The generic H562 variant + // leaves SystemClock_Config empty, so its SDMMC kernel clock is stopped. + if (HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SDMMC1) != 0U) { + return true; + } + RCC_OscInitTypeDef osc = {}; + osc.OscillatorType = RCC_OSCILLATORTYPE_CSI; + osc.CSIState = RCC_CSI_ON; + osc.CSICalibrationValue = RCC_CSICALIBRATION_DEFAULT; + osc.PLL.PLLState = RCC_PLL_NONE; + if (HAL_RCC_OscConfig(&osc) != HAL_OK) { + return false; + } + RCC_PeriphCLKInitTypeDef clock = {}; + clock.PeriphClockSelection = RCC_PERIPHCLK_SDMMC1; + clock.Sdmmc1ClockSelection = RCC_SDMMC1CLKSOURCE_PLL2R; + clock.PLL2.PLL2Source = RCC_PLL2_SOURCE_CSI; + clock.PLL2.PLL2M = 2; + clock.PLL2.PLL2N = 192; + clock.PLL2.PLL2P = 2; + clock.PLL2.PLL2Q = 8; + clock.PLL2.PLL2R = 8; + clock.PLL2.PLL2RGE = RCC_PLL2_VCIRANGE_1; + clock.PLL2.PLL2VCOSEL = RCC_PLL2_VCORANGE_WIDE; + clock.PLL2.PLL2FRACN = 0; + clock.PLL2.PLL2ClockOut = RCC_PLL2_DIVR; + // CSI 4 MHz / 2 * 192 / 8 = 48 MHz. Only use this helper when PLL2 is + // available; applications sharing PLL2 should configure it at board level. + return HAL_RCCEx_PeriphCLKConfig(&clock) == HAL_OK; +#else + return true; +#endif +} diff --git a/libraries/SDIO/examples/BoardValidation/BoardValidation.ino b/libraries/SDIO/examples/BoardValidation/BoardValidation.ino new file mode 100644 index 0000000000..a23d512cb4 --- /dev/null +++ b/libraries/SDIO/examples/BoardValidation/BoardValidation.ino @@ -0,0 +1,118 @@ +#include +#include + +// Set to 1 for MMC/eMMC 8-bit validation. H562 in LQFP64 can only use +// MMC 1/4-bit: change VALIDATION_WIDTH accordingly on that package. +#ifndef SDIO_VALIDATION_MMC +#define SDIO_VALIDATION_MMC 0 +#endif + +#if defined(STM32_SDIO_ENABLED) && \ + ((!SDIO_VALIDATION_MMC && defined(HAL_SD_MODULE_ENABLED)) || \ + (SDIO_VALIDATION_MMC && defined(HAL_MMC_MODULE_ENABLED))) +#include + +#ifndef SDIO_VALIDATION_WIDTH +#define SDIO_VALIDATION_WIDTH (SDIO_VALIDATION_MMC ? SDIO_MODE_8B : SDIO_MODE_4B) +#endif +#ifndef SDIO_VALIDATION_CLOCK +#define SDIO_VALIDATION_CLOCK 15000000U +#endif + +alignas(32) static uint8_t reference[1024]; +alignas(32) static uint8_t received[1024]; + +static bool startCard(bool dma) +{ +#if SDIO_VALIDATION_MMC + return SDCard.beginMMC(dma); +#else + return SDCard.begin(dma); +#endif +} + +static void dumpLog() +{ + sd_log_entry_t entry; + for (uint32_t i = 0; i < SDCard.getLogCount(); ++i) { + if (!SDCard.getLog(i, entry)) { break; } + Serial.print("t="); Serial.print(entry.timestamp); + Serial.print(" op="); Serial.print((unsigned)entry.operation); + Serial.print(" phase="); Serial.print((unsigned)entry.phase); + Serial.print(" sector="); Serial.print(entry.address); + Serial.print(" blocks="); Serial.print(entry.blocks); + Serial.print(" status="); Serial.print((unsigned)entry.status); + Serial.print(" error=0x"); Serial.print(entry.error, HEX); + if (entry.registers_valid) { + Serial.print(" CMD=0x"); Serial.print(entry.command, HEX); + Serial.print(" ARG=0x"); Serial.print(entry.argument, HEX); + Serial.print(" RESP1=0x"); Serial.print(entry.response[0], HEX); + } + Serial.println(); + } +} + +static void fail(const char *step) +{ + Serial.print("FAIL: "); + Serial.print(step); + Serial.print(" HAL error=0x"); + Serial.println(SDCard.getError(), HEX); + dumpLog(); + SDCard.end(); +} + +void setup() +{ + Serial.begin(115200); + SDCard.setLogging(); + if (!SDCard.setClock(SDIO_VALIDATION_CLOCK)) { fail("requested clock"); return; } + if (SDCard.setClock(0) || SDCard.setClock(SDIO_SPEED_CLOCK_MAX + 1U) || + SDCard.getClock() != SDIO_VALIDATION_CLOCK) { + fail("clock validation"); return; + } + if (!SDIOExampleConfigureClock()) { fail("kernel clock"); return; } + SDCard.setD0(PC_8); + SDCard.setD1(PC_9); + SDCard.setD2(PC_10); + SDCard.setD3(PC_11); + SDCard.setD4(PB_8); + SDCard.setD5(PB_9); + SDCard.setD6(PC_6); + SDCard.setD7(PC_7); + SDCard.setCMD(PD_2); + SDCard.setSCK(PC_12); + SDCard.setDataMode(SDIO_VALIDATION_WIDTH); + if (!startCard(false)) { fail("polling init / pins"); return; } + if (!SDCard.getActualClock() || SDCard.getActualClock() > SDCard.getClock() || SDCard.setClock(1000000U)) { + fail("active clock validation"); return; + } + Serial.print("SD data clock (Hz): requested="); Serial.print(SDCard.getClock()); + Serial.print(" actual="); Serial.println(SDCard.getActualClock()); + if (!SDCard.read(reference, 0, 2)) { fail("polling read"); return; } + SDCard.end(); + if (!startCard(true)) { fail("DMA init"); return; } + for (unsigned i = 0; i < 100; ++i) { + if (!SDCard.read(received, 0, 2) || !SDCard.wait(2000)) { fail("DMA read/wait"); return; } + if (memcmp(reference, received, sizeof(reference)) != 0) { fail("DMA data comparison"); return; } + } +#if SDIO_LOG_CAPACITY > 0 + sd_log_entry_t last; + uint32_t count = SDCard.getLogCount(); + if (!count || count > SDIO_LOG_CAPACITY || !SDCard.getLog(count - 1U, last) || + last.operation != SD_LOG_READ || last.phase != SD_LOG_COMPLETE || last.status != SD_OK || + last.address != 0 || last.blocks != 2 || SDCard.getLog(count, last)) { + fail("diagnostic history validation"); return; + } +#endif + Serial.println("PASS: polling and 100 DMA reads agree (sectors 0-1 unchanged)"); + SDCard.end(); + dumpLog(); +} + +#else +// The selected SD/MMC test requires a supported controller and HAL module. +void setup() {} +#endif + +void loop() {} diff --git a/libraries/SDIO/examples/BoardValidation/build_opt.h b/libraries/SDIO/examples/BoardValidation/build_opt.h new file mode 100644 index 0000000000..3b4b784eeb --- /dev/null +++ b/libraries/SDIO/examples/BoardValidation/build_opt.h @@ -0,0 +1,3 @@ +-DHAL_SD_MODULE_ENABLED = + -DHAL_MMC_MODULE_ENABLED = + -DHAL_UART_MODULE_ENABLED = diff --git a/libraries/SDIO/examples/ReadDMA/ReadDMA.ino b/libraries/SDIO/examples/ReadDMA/ReadDMA.ino new file mode 100644 index 0000000000..4af0eb29c7 --- /dev/null +++ b/libraries/SDIO/examples/ReadDMA/ReadDMA.ino @@ -0,0 +1,55 @@ +#include +#include + +#if defined(STM32_SDIO_ENABLED) && defined(HAL_SD_MODULE_ENABLED) +#include + +// Keep the buffer in DMA-accessible SRAM, aligned to a 32-bit word. +alignas(32) uint8_t sector[512]; +bool cardReady; + +void setup() +{ + Serial.begin(115200); + if (!SDIOExampleConfigureClock()) { + Serial.println("SDMMC kernel clock configuration failed"); + return; + } +#if defined(STM32F446xx) || defined(STM32F407xx) + SDCard.setD0(PC_8); + SDCard.setD1(PC_9); + SDCard.setD2(PC_10); + SDCard.setD3(PC_11); + SDCard.setSCK(PC_12); + SDCard.setCMD(PD_2); +#endif + SDCard.setDataMode(SDIO_MODE_4B); + cardReady = SDCard.begin(true); + if (!cardReady) { + Serial.print("SD initialization failed: "); + Serial.println(SDCard.getError(), HEX); + return; + } + + // Addresses are logical 512-byte sectors, including on SDSC cards. + // DMA read/write return when the transfer starts. Wait before using data. + if (!SDCard.read(sector, 0, 1) || !SDCard.wait(1000)) { + Serial.print("SD read failed: "); + Serial.println(SDCard.getError(), HEX); + } else { + Serial.println("Sector 0 read successfully"); + for (unsigned i = 0; i < 32; ++i) { + Serial.print(sector[i], HEX); + Serial.print(' '); + } + Serial.println(); + } + SDCard.end(); +} + +#else +// Keep the sketch buildable on targets without SDIO/SDMMC or HAL SD support. +void setup() {} +#endif + +void loop() {} diff --git a/libraries/SDIO/examples/ReadDMA/build_opt.h b/libraries/SDIO/examples/ReadDMA/build_opt.h new file mode 100644 index 0000000000..6b5c4e3fb8 --- /dev/null +++ b/libraries/SDIO/examples/ReadDMA/build_opt.h @@ -0,0 +1,2 @@ +-DHAL_SD_MODULE_ENABLED = + -DHAL_UART_MODULE_ENABLED = diff --git a/libraries/SDIO/utility/sdio_com.c b/libraries/SDIO/utility/sdio_com.c new file mode 100644 index 0000000000..073586dd57 --- /dev/null +++ b/libraries/SDIO/utility/sdio_com.c @@ -0,0 +1,1508 @@ +/** + * @brief STM32 SDIO/SDMMC HAL transport, clock negotiation and DMA support. + * @file sdio_com.c + * @note DMA transfers use caller-owned buffers; CPU D-cache maintenance is + * performed where required. No filesystem cache or sector staging is allocated. + */ +/* + * Copyright (c) 2016 Frederic Pillon for + * STMicroelectronics. All right reserved. + * This file is free software; you can redistribute it and/or modify + * it under the terms of either the GNU General Public License version 2 + * or the GNU Lesser General Public License version 2.1, both as + * published by the Free Software Foundation. + */ +#include "sdio_com.h" + +#if defined(STM32_SDIO_ENABLED) + +#include "pinconfig.h" +#include "stm32yyxx_ll_sdmmc.h" + +#if defined(HAL_MMC_MODULE_ENABLED) +#define SD_CALL(obj, name, ...) ((obj)->isMMC ? \ + HAL_MMC_##name(&(obj)->mmc, ##__VA_ARGS__) : HAL_SD_##name(&(obj)->handle, ##__VA_ARGS__)) +#else +#define SD_CALL(obj, name, ...) HAL_SD_##name(&(obj)->handle, ##__VA_ARGS__) +#endif + +/* Ownership is per controller, so SDMMC1 and SDMMC2 can coexist. */ +static sd_t *volatile sd_owner[2]; +static void sd_release(sd_t *obj); + +/* Some packages omit whole signal maps (e.g. H562 LQFP64 has no D5). + * Required D0/CMD/CK references still pull the variant object from archives. + */ +#pragma weak PinMap_SD_DATA1 +#pragma weak PinMap_SD_DATA2 +#pragma weak PinMap_SD_DATA3 +#pragma weak PinMap_SD_DATA4 +#pragma weak PinMap_SD_DATA5 +#pragma weak PinMap_SD_DATA6 +#pragma weak PinMap_SD_DATA7 + +/** + * @brief Map a supported peripheral instance to its controller ownership slot. + */ +static int sd_slot(SD_TypeDef *instance) +{ +#if defined(SDIO) + if (instance == SDIO) { + return 0; + } +#endif +#if defined(SDMMC1) + if (instance == SDMMC1) { + return 0; + } +#endif +#if defined(SDMMC2) + if (instance == SDMMC2) { + return 1; + } +#endif + return -1; +} + +/** + * @brief Access the HAL error field for the selected media type. + */ +static volatile uint32_t *sd_error(sd_t *obj) +{ +#if defined(HAL_MMC_MODULE_ENABLED) + if (obj->isMMC) { + return &obj->mmc.ErrorCode; + } +#endif + return &obj->handle.ErrorCode; +} + +/** + * @brief Return the active SD/MMC HAL error mask, or a parameter error for null. + * @param obj Controller to inspect. + */ +uint32_t sd_getError(const sd_t *obj) +{ + if (!obj) { + return HAL_SD_ERROR_PARAM; + } +#if defined(HAL_MMC_MODULE_ENABLED) + if (obj->isMMC) { + return obj->mmc.ErrorCode; + } +#endif + return obj->handle.ErrorCode; +} + +/** + * @brief Enable or disable recording of bounded operation snapshots. + * @param obj Controller to configure. + * @param enabled Whether recording is enabled. + */ +void sd_setLogging(sd_t *obj, bool enabled) +{ +#if SDIO_LOG_CAPACITY > 0 + if (obj && obj->logging != enabled) { + obj->logging = enabled; + obj->log_pending = false; + } +#else + UNUSED(obj); UNUSED(enabled); +#endif +} + +/** + * @brief Clear retained operation snapshots. + * @param obj Controller whose log is cleared. + */ +void sd_clearLog(sd_t *obj) +{ +#if SDIO_LOG_CAPACITY > 0 + if (obj) { + obj->log_count = 0; + obj->log_next = 0; + } +#else + UNUSED(obj); +#endif +} + +/** + * @brief Return the retained entry count, or zero when storage is disabled. + * @param obj Controller to inspect. + */ +uint32_t sd_getLogCount(const sd_t *obj) +{ +#if SDIO_LOG_CAPACITY > 0 + return obj ? obj->log_count : 0; +#else + UNUSED(obj); return 0; +#endif +} + +/** + * @brief Copy a retained operation snapshot. + * @param obj Controller to inspect. + * @param index Zero-based index, oldest first. + * @param[out] entry Destination snapshot. + * @return True if an entry was copied. + */ +bool sd_getLog(const sd_t *obj, uint32_t index, sd_log_entry_t *entry) +{ +#if SDIO_LOG_CAPACITY > 0 + if (!obj || !entry || index >= obj->log_count) { + return false; + } + *entry = obj->log[(obj->log_next + SDIO_LOG_CAPACITY - obj->log_count + index) % SDIO_LOG_CAPACITY]; + return true; +#else + UNUSED(obj); UNUSED(index); UNUSED(entry); return false; +#endif +} + +/* Called only from the foreground API, never from an IRQ. In particular, + * DMA completion is observed by wait()/isBusy() before reading card status. + * A rejected request must not inspect another object's controller registers. + */ +/** + * @brief Append an operation snapshot, reading registers only when available. + */ +static void sd_log_record(sd_t *obj, sd_log_operation_e operation, sd_log_phase_e phase, + uint32_t address, uint32_t blocks, sd_status_e status) +{ +#if SDIO_LOG_CAPACITY > 0 + if (!obj || !obj->logging) { + return; + } + sd_log_entry_t entry = {0}; + entry.timestamp = HAL_GetTick(); + entry.instance = (uintptr_t)obj->sd; + entry.address = address; + entry.blocks = blocks; + entry.error = sd_getError(obj); + entry.operation = operation; + entry.phase = phase; + entry.status = status; + entry.requested_clock = obj->requested_clock; + entry.actual_clock = obj->actual_clock; + entry.mode = obj->busMode; + entry.mmc = obj->isMMC; + entry.dma = obj->useDMA; + entry.high_speed = obj->high_speed; + int slot = sd_slot(obj->sd); + if (slot >= 0 && sd_owner[slot] == obj) { + entry.command = obj->sd->CMD; + entry.argument = obj->sd->ARG; + entry.response[0] = obj->sd->RESP1; + entry.response[1] = obj->sd->RESP2; + entry.response[2] = obj->sd->RESP3; + entry.response[3] = obj->sd->RESP4; + entry.registers_valid = true; + } + obj->log[obj->log_next] = entry; + obj->log_next = (obj->log_next + 1U) % SDIO_LOG_CAPACITY; + if (obj->log_count < SDIO_LOG_CAPACITY) { + ++obj->log_count; + } +#else + UNUSED(obj); UNUSED(operation); UNUSED(phase); UNUSED(address); UNUSED(blocks); UNUSED(status); +#endif +} + +/** + * @brief Record submission and track a pending operation for later completion. + */ +static void sd_log_submit(sd_t *obj, sd_log_operation_e operation, uint32_t address, + uint32_t blocks, sd_status_e status) +{ + sd_log_record(obj, operation, SD_LOG_SUBMIT, address, blocks, status); +#if SDIO_LOG_CAPACITY > 0 + if (obj && obj->logging && status == SD_OK) { + obj->log_pending = true; + obj->log_operation = operation; + obj->log_address = address; + obj->log_blocks = blocks; + } +#endif +} + +/** + * @brief Record the final status of the pending operation once. + */ +static void sd_log_finish(sd_t *obj, sd_status_e status) +{ +#if SDIO_LOG_CAPACITY > 0 + if (obj && obj->log_pending) { + sd_log_record(obj, obj->log_operation, SD_LOG_COMPLETE, obj->log_address, obj->log_blocks, status); + obj->log_pending = false; + } +#else + UNUSED(obj); UNUSED(status); +#endif +} + +/** + * @brief Test whether the selected SD/MMC HAL handle is transferring. + */ +static bool sd_hal_busy(sd_t *obj) +{ +#if defined(HAL_MMC_MODULE_ENABLED) + if (obj->isMMC) { + return HAL_MMC_GetState(&obj->mmc) != HAL_MMC_STATE_READY; + } +#endif + return HAL_SD_GetState(&obj->handle) != HAL_SD_STATE_READY; +} + +/** + * @brief Query card transfer state through the selected HAL media API. + */ +static bool sd_card_ready(sd_t *obj) +{ +#if defined(HAL_MMC_MODULE_ENABLED) + if (obj->isMMC) { + return HAL_MMC_GetCardState(&obj->mmc) == HAL_MMC_CARD_TRANSFER; + } +#endif + return HAL_SD_GetCardState(&obj->handle) == HAL_SD_CARD_TRANSFER; +} + +/** + * @brief Return media capacity in 512-byte logical sectors. + */ +static uint32_t sd_block_count(sd_t *obj) +{ +#if defined(HAL_MMC_MODULE_ENABLED) + if (obj->isMMC) { + return obj->mmc.MmcCard.LogBlockNbr; + } +#endif + return obj->handle.SdCard.LogBlockNbr; +} + +/** + * @brief Enable/reset or disable the selected peripheral clock. + */ +static void sd_clock(sd_t *obj, bool enable) +{ +#if defined(SDIO) + UNUSED(obj); + if (enable) { + __HAL_RCC_SDIO_CLK_ENABLE(); + } +#if defined(__HAL_RCC_SDIO_FORCE_RESET) + __HAL_RCC_SDIO_FORCE_RESET(); + __HAL_RCC_SDIO_RELEASE_RESET(); +#else + /* F1 has no RCC reset bit for SDIO. Restore its writable registers. */ + SDIO->POWER = 0; + SDIO->CLKCR = 0; + SDIO->ARG = 0; + SDIO->CMD = 0; + SDIO->DTIMER = 0; + SDIO->DLEN = 0; + SDIO->DCTRL = 0; + SDIO->MASK = 0; + SDIO->ICR = 0xFFFFFFFFU; +#endif + if (!enable) { + __HAL_RCC_SDIO_CLK_DISABLE(); + } +#else +#if defined(SDMMC1) + if (obj->sd == SDMMC1) { + if (enable) { + __HAL_RCC_SDMMC1_CLK_ENABLE(); + } + __HAL_RCC_SDMMC1_FORCE_RESET(); + __HAL_RCC_SDMMC1_RELEASE_RESET(); + if (!enable) { + __HAL_RCC_SDMMC1_CLK_DISABLE(); + } + } +#endif +#if defined(SDMMC2) + if (obj->sd == SDMMC2) { + if (enable) { + __HAL_RCC_SDMMC2_CLK_ENABLE(); + } + __HAL_RCC_SDMMC2_FORCE_RESET(); + __HAL_RCC_SDMMC2_RELEASE_RESET(); + if (!enable) { + __HAL_RCC_SDMMC2_CLK_DISABLE(); + } + } +#endif +#endif +} + +/** + * @brief Build the ordered list of configured data, command and clock pins. + */ +static void sd_signal_pins(sd_t *obj, PinName **pins) +{ + pins[0] = &obj->pin_d0; pins[1] = &obj->pin_d1; + pins[2] = &obj->pin_d2; pins[3] = &obj->pin_d3; + pins[4] = &obj->pin_d4; pins[5] = &obj->pin_d5; + pins[6] = &obj->pin_d6; pins[7] = &obj->pin_d7; + pins[8] = &obj->pin_cmd; pins[9] = &obj->pin_sck; +} + +static const PinMap *const sd_maps[] = { + PinMap_SD_DATA0, PinMap_SD_DATA1, PinMap_SD_DATA2, PinMap_SD_DATA3, + PinMap_SD_DATA4, PinMap_SD_DATA5, PinMap_SD_DATA6, PinMap_SD_DATA7, + PinMap_SD_CMD, PinMap_SD_CK +}; + +/** + * @brief Test whether a signal index is needed for the configured bus width. + */ +static bool sd_pin_used(sd_t *obj, unsigned i) +{ + unsigned width = obj->busMode == SDIO_MODE_8B ? 8U : obj->busMode == SDIO_MODE_4B ? 4U : 1U; + return i < width || i >= 8U; +} + +/** + * @brief Weak board hook to configure active signal pins. + * @param obj Controller with resolved pins and bus width. + * @param params Reserved context; unused by the default implementation. + */ +__weak void SDIO_MspInit(sd_t *obj, void *params) +{ + UNUSED(params); + sd_clock(obj, true); + PinName *pins[10]; + sd_signal_pins(obj, pins); + for (unsigned i = 0; i < 10; ++i) { + if (sd_pin_used(obj, i)) { + pinmap_pinout(*pins[i], sd_maps[i]); + } + } +} + +/** + * @brief Weak board hook to release active signal pins. + * @param obj Controller with resolved pins. + * @param params Reserved context; unused by the default implementation. + */ +__weak void SDIO_MspDeInit(sd_t *obj, void *params) +{ + UNUSED(params); + PinName *pins[10]; + sd_signal_pins(obj, pins); + for (unsigned i = 0; i < 10; ++i) { + if (sd_pin_used(obj, i) && *pins[i] != NC) { + HAL_GPIO_DeInit(get_GPIO_Port(STM_PORT(*pins[i])), STM_GPIO_PIN(*pins[i])); + } + } + sd_clock(obj, false); +} + +/* Select from explicit pins before filling defaults. Every default is taken + * from the selected controller, never blindly from entry zero of each map. + */ +/** + * @brief Resolve unspecified PinMap signals and validate a common controller. + */ +static bool sd_select_pins(sd_t *obj) +{ + PinName *pins[10]; + sd_signal_pins(obj, pins); + SD_TypeDef *instance = obj->requested_instance; + for (unsigned i = 0; i < 10; ++i) { + if (!sd_pin_used(obj, i) || *pins[i] == NC) { + continue; + } + if (!sd_maps[i]) { + return false; + } + SD_TypeDef *mapped = pinmap_peripheral(*pins[i], sd_maps[i]); + if (sd_slot(mapped) < 0 || (instance && instance != mapped)) { + return false; + } + instance = mapped; + } + if (!instance) { + instance = sd_maps[0][0].peripheral; + } + if (sd_slot(instance) < 0) { + return false; + } + for (unsigned i = 0; i < 10; ++i) { + if (!sd_pin_used(obj, i)) { + continue; + } + if (!sd_maps[i]) { + return false; + } + if (*pins[i] == NC) { + const PinMap *map = sd_maps[i]; + while (map->pin != NC && map->peripheral != instance) { + ++map; + } + *pins[i] = map->pin; + } + if (*pins[i] == NC || pinmap_peripheral(*pins[i], sd_maps[i]) != instance) { + return false; + } + } + obj->sd = instance; +#if defined(SDIO) + obj->irq = SDIO_IRQn; +#else +#if defined(SDMMC2) + obj->irq = instance == SDMMC2 ? SDMMC2_IRQn : SDMMC1_IRQn; +#else + obj->irq = SDMMC1_IRQn; +#endif +#endif + return true; +} + +/** + * @brief Return the peripheral kernel input clock in Hz, not the divided card clock. + * @param obj Controller used to select the clock source. + */ +uint32_t sd_getClkFreq(sd_t *obj) +{ +#if defined(STM32H5xx) + if (!obj || !obj->sd) { + return 0; + } +#if defined(SDMMC2) + if (obj->sd == SDMMC2) { + return HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SDMMC2); + } +#endif + return HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SDMMC1); +#elif defined(STM32F1xx) + UNUSED(obj); + return HAL_RCC_GetHCLKFreq(); +#else + UNUSED(obj); +#if defined(STM32F7xx) + if (!obj || !obj->sd) { + return 0; + } + if (obj->sd == SDMMC1 && __HAL_RCC_GET_SDMMC1_SOURCE() == RCC_SDMMC1CLKSOURCE_SYSCLK) { + return HAL_RCC_GetSysClockFreq(); + } +#if defined(SDMMC2) + if (obj->sd == SDMMC2 && __HAL_RCC_GET_SDMMC2_SOURCE() == RCC_SDMMC2CLKSOURCE_SYSCLK) { + return HAL_RCC_GetSysClockFreq(); + } +#endif +#endif +#if defined(__HAL_RCC_GET_SDIO_SOURCE) + if (__HAL_RCC_GET_SDIO_SOURCE() == RCC_SDIOCLKSOURCE_SYSCLK) { + return HAL_RCC_GetSysClockFreq(); + } +#endif + uint32_t pll = RCC->PLLCFGR; + uint32_t source = (pll & RCC_PLLCFGR_PLLSRC) ? HSE_VALUE : HSI_VALUE; + uint32_t m = pll & RCC_PLLCFGR_PLLM; + uint32_t n = (pll & RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos; + uint32_t q = (pll & RCC_PLLCFGR_PLLQ) >> RCC_PLLCFGR_PLLQ_Pos; +#if defined(RCC_CLK48CLKSOURCE_PLLSAIP) || defined(RCC_CLK48SOURCE_PLLSAIP) + /* Nonzero CLK48 mux selects PLLSAIP on these F4/F7 devices. */ + if (__HAL_RCC_GET_CLK48_SOURCE() != 0U) { + pll = RCC->PLLSAICFGR; +#if defined(RCC_PLLSAICFGR_PLLSAIM) + m = pll & RCC_PLLSAICFGR_PLLSAIM; +#endif + n = (pll & RCC_PLLSAICFGR_PLLSAIN) >> RCC_PLLSAICFGR_PLLSAIN_Pos; + q = (((pll & RCC_PLLSAICFGR_PLLSAIP) >> RCC_PLLSAICFGR_PLLSAIP_Pos) + 1U) * 2U; + if (!(RCC->CR & RCC_CR_PLLSAIRDY)) { + return 0; + } + } else +#elif defined(RCC_CLK48CLKSOURCE_PLLI2SQ) + if (__HAL_RCC_GET_CLK48_SOURCE() == RCC_CLK48CLKSOURCE_PLLI2SQ) { + pll = RCC->PLLI2SCFGR; + m = pll & RCC_PLLI2SCFGR_PLLI2SM; + n = (pll & RCC_PLLI2SCFGR_PLLI2SN) >> RCC_PLLI2SCFGR_PLLI2SN_Pos; + q = (pll & RCC_PLLI2SCFGR_PLLI2SQ) >> RCC_PLLI2SCFGR_PLLI2SQ_Pos; +#if defined(RCC_PLLI2SCFGR_PLLI2SSRC) + if (pll & RCC_PLLI2SCFGR_PLLI2SSRC) { + source = EXTERNAL_CLOCK_VALUE; + } +#endif + if (!(RCC->CR & RCC_CR_PLLI2SRDY)) { + return 0; + } + } else +#endif + { + if (!(RCC->CR & RCC_CR_PLLRDY)) { + return 0; + } + } + return (m && q) ? (uint32_t)(((uint64_t)source * n) / ((uint64_t)m * q)) : 0; +#endif +} + +/** + * @brief Configure the interrupt priority and enable its NVIC line. + */ +static void sd_irq_enable(IRQn_Type irq) +{ + HAL_NVIC_ClearPendingIRQ(irq); + HAL_NVIC_SetPriority(irq, SDIO_IRQ_PRIORITY, 0); + HAL_NVIC_EnableIRQ(irq); +} + +#if SDIO_USE_EXTERNAL_DMA +/** + * @brief Connect RX/TX DMA handles to the active media HAL handle. + */ +static void sd_link_dma(sd_t *obj) +{ +#if defined(HAL_MMC_MODULE_ENABLED) + if (obj->isMMC) { + __HAL_LINKDMA(&obj->mmc, hdmarx, obj->dma_rx); + __HAL_LINKDMA(&obj->mmc, hdmatx, obj->dma_tx); + return; + } +#endif + __HAL_LINKDMA(&obj->handle, hdmarx, obj->dma_rx); + __HAL_LINKDMA(&obj->handle, hdmatx, obj->dma_tx); +} + +/** + * @brief Test external DMA activity; always false for internal DMA controllers. + */ +static bool sd_dma_busy(sd_t *obj) +{ + return obj->useDMA && (HAL_DMA_GetState(&obj->dma_rx) == HAL_DMA_STATE_BUSY || + HAL_DMA_GetState(&obj->dma_tx) == HAL_DMA_STATE_BUSY); +} + +/** + * @brief Configure the controller-specific external RX/TX DMA resources. + */ +static HAL_StatusTypeDef sd_dma_init(sd_t *obj) +{ + __HAL_RCC_DMA2_CLK_ENABLE(); +#if defined(STM32F1xx) + obj->dma_rx.Instance = DMA2_Channel4; + obj->dma_tx.Instance = DMA2_Channel4; + obj->dma_rx_irq = DMA2_Channel4_IRQn; + obj->dma_tx_irq = DMA2_Channel4_IRQn; +#else + obj->dma_rx.Instance = DMA2_Stream3; + obj->dma_tx.Instance = DMA2_Stream6; + obj->dma_rx.Init.Channel = obj->dma_tx.Init.Channel = DMA_CHANNEL_4; + obj->dma_rx_irq = DMA2_Stream3_IRQn; + obj->dma_tx_irq = DMA2_Stream6_IRQn; +#if defined(STM32F7xx) && defined(SDMMC2) + if (obj->sd == SDMMC2) { + obj->dma_rx.Instance = DMA2_Stream0; + obj->dma_tx.Instance = DMA2_Stream5; + obj->dma_rx.Init.Channel = obj->dma_tx.Init.Channel = DMA_CHANNEL_11; + obj->dma_rx_irq = DMA2_Stream0_IRQn; + obj->dma_tx_irq = DMA2_Stream5_IRQn; + } +#endif +#endif + DMA_HandleTypeDef *handles[] = {&obj->dma_rx, &obj->dma_tx}; + for (unsigned i = 0; i < 2; ++i) { + DMA_HandleTypeDef *dma = handles[i]; + dma->Init.Direction = i == 0 ? DMA_PERIPH_TO_MEMORY : DMA_MEMORY_TO_PERIPH; + dma->Init.PeriphInc = DMA_PINC_DISABLE; + dma->Init.MemInc = DMA_MINC_ENABLE; + dma->Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD; + dma->Init.MemDataAlignment = DMA_MDATAALIGN_WORD; + dma->Init.Priority = DMA_PRIORITY_VERY_HIGH; +#if defined(STM32F1xx) + dma->Init.Mode = DMA_NORMAL; +#else + dma->Init.Mode = DMA_PFCTRL; + dma->Init.FIFOMode = DMA_FIFOMODE_ENABLE; + dma->Init.FIFOThreshold = DMA_FIFO_THRESHOLD_FULL; + dma->Init.MemBurst = DMA_MBURST_INC4; + dma->Init.PeriphBurst = DMA_PBURST_INC4; +#endif + if (HAL_DMA_Init(dma) != HAL_OK) { + return HAL_ERROR; + } + } + sd_link_dma(obj); + sd_irq_enable(obj->dma_rx_irq); + sd_irq_enable(obj->dma_tx_irq); + return HAL_OK; +} +#else +/** @brief No external DMA state is needed for polling or internal DMA. */ +static bool sd_dma_busy(sd_t *obj) +{ + UNUSED(obj); + return false; +} +#endif + +/* F7 DMA is not cache coherent. DMA buffers cover whole cache lines so + * maintenance cannot corrupt adjacent objects. Track RX until it is idle. + */ +/** + * @brief Invalidate completed RX CPU D-cache lines and release RX tracking. + * @note This maintains CPU cache coherency; it does not manage filesystem pages. + */ +static void sd_cache_finish(sd_t *obj) +{ + if (obj->rx_buffer) { +#if defined(__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U) + if (SCB->CCR & SCB_CCR_DC_Msk) { + SCB_InvalidateDCache_by_Addr((uint32_t *)obj->rx_buffer, (int32_t)obj->rx_bytes); + } +#endif + obj->rx_buffer = NULL; + obj->rx_bytes = 0; + } +} + +/** + * @brief Stop peripheral/DMA activity before releasing buffers and preserve HAL errors. + */ +static void sd_abort_transfer(sd_t *obj) +{ + uint32_t error = sd_getError(obj); + HAL_NVIC_DisableIRQ(obj->irq); +#if SDIO_USE_EXTERNAL_DMA + if (obj->dma_rx.Instance) { + HAL_NVIC_DisableIRQ(obj->dma_rx_irq); + } + if (obj->dma_tx.Instance) { + HAL_NVIC_DisableIRQ(obj->dma_tx_irq); + } + sd_link_dma(obj); +#endif + SD_CALL(obj, Abort); +#if SDIO_USE_EXTERNAL_DMA + if (obj->dma_rx.Instance && HAL_DMA_GetState(&obj->dma_rx) == HAL_DMA_STATE_BUSY) { + HAL_DMA_Abort(&obj->dma_rx); + } + if (obj->dma_tx.Instance && HAL_DMA_GetState(&obj->dma_tx) == HAL_DMA_STATE_BUSY) { + HAL_DMA_Abort(&obj->dma_tx); + } + if (obj->dma_rx.Instance) { + HAL_NVIC_ClearPendingIRQ(obj->dma_rx_irq); + } + if (obj->dma_tx.Instance) { + HAL_NVIC_ClearPendingIRQ(obj->dma_tx_irq); + } + if (obj->initialized) { + HAL_NVIC_EnableIRQ(obj->dma_rx_irq); + HAL_NVIC_EnableIRQ(obj->dma_tx_irq); + } +#endif + *sd_error(obj) |= error; + HAL_NVIC_ClearPendingIRQ(obj->irq); + sd_cache_finish(obj); +#if SDIO_LOG_CAPACITY > 0 + if (obj->log_pending) { + sd_log_record(obj, obj->log_operation, SD_LOG_ABORT, obj->log_address, obj->log_blocks, SD_ERROR); + } +#endif + if (obj->initialized) { + HAL_NVIC_EnableIRQ(obj->irq); + } +} + +#if !SDIO_USE_IDMA +#if defined(SDIO) + #define SD_LL(name) SDIO_##name + #define SD_LL_RX SDIO_TRANSFER_DIR_TO_SDIO +#else + #define SD_LL(name) SDMMC_##name + #define SD_LL_RX SDMMC_TRANSFER_DIR_TO_SDMMC +#endif + +/* Legacy F1/F2/F4/F7 HALs do not expose SD High Speed negotiation. Read + * CMD6's fixed 64-byte switch status in polling mode at the safe clock. + * No CMD16 is needed: CMD6 has a fixed data length independent of blocks. + */ +/** + * @brief Read the fixed 64-byte SD CMD6 switch status at the safe clock. + */ +static uint32_t sd_switch_status(sd_t *obj, uint32_t argument, uint32_t words[16]) +{ + SD_LL(DataInitTypeDef) data = {0}; + obj->sd->DCTRL = 0; + obj->sd->ICR = SD_LL(STATIC_FLAGS); + data.DataTimeOut = SDMMC_DATATIMEOUT; + data.DataLength = 64; + data.DataBlockSize = SD_LL(DATABLOCK_SIZE_64B); + data.TransferDir = SD_LL_RX; + data.TransferMode = SD_LL(TRANSFER_MODE_BLOCK); + data.DPSM = SD_LL(DPSM_ENABLE); + if (SD_LL(ConfigData)(obj->sd, &data) != HAL_OK) { + return HAL_SD_ERROR_PARAM; + } + uint32_t error = SDMMC_CmdSwitch(obj->sd, argument); + uint32_t start = HAL_GetTick(); + unsigned count = 0; + while (error == HAL_SD_ERROR_NONE) { + uint32_t flags = obj->sd->STA; + if (flags & SD_LL(FLAG_DTIMEOUT)) { + error = HAL_SD_ERROR_DATA_TIMEOUT; + break; + } + if (flags & SD_LL(FLAG_DCRCFAIL)) { + error = HAL_SD_ERROR_DATA_CRC_FAIL; + break; + } + if (flags & SD_LL(FLAG_RXOVERR)) { + error = HAL_SD_ERROR_RX_OVERRUN; + break; + } + if (flags & SD_LL(FLAG_RXDAVL)) { + if (count >= 16U) { + error = HAL_SD_ERROR_RX_OVERRUN; + break; + } + words[count++] = SD_LL(ReadFIFO)(obj->sd); + } else if (flags & SD_LL(FLAG_DATAEND)) { + if (count != 16U) { + error = HAL_SD_ERROR_DATA_TIMEOUT; + } + break; + } + if ((HAL_GetTick() - start) >= SD_TRANSFER_TIMEOUT) { + error = HAL_SD_ERROR_TIMEOUT; + break; + } + } + obj->sd->DCTRL = 0; + obj->sd->ICR = SD_LL(STATIC_FLAGS); + return error; +} + +/** + * @brief Extract one protocol-order byte from the CMD6 response words. + */ +static uint8_t sd_status_byte(const uint32_t words[16], unsigned byte) +{ + return (uint8_t)(words[byte / 4U] >> ((byte % 4U) * 8U)); +} + +/** + * @brief Query and select SD High Speed through CMD6. + */ +static uint32_t sd_high_speed(sd_t *obj) +{ + uint32_t words[16]; + if (!(obj->handle.SdCard.Class & (1U << 10U))) { + return HAL_SD_ERROR_UNSUPPORTED_FEATURE; + } + uint32_t start = HAL_GetTick(); + uint32_t error; + do { + error = sd_switch_status(obj, 0x00FFFFF1U, words); // check function group 1, High Speed + if (error) { + return error; + } + if (!(sd_status_byte(words, 13) & 2U)) { + return HAL_SD_ERROR_UNSUPPORTED_FEATURE; + } + if (sd_status_byte(words, 17) < 1U || !(sd_status_byte(words, 29) & 2U)) { + break; + } + if ((HAL_GetTick() - start) >= SD_TRANSFER_TIMEOUT) { + return HAL_SD_ERROR_TIMEOUT; + } + } while (true); + error = sd_switch_status(obj, 0x80FFFFF1U, words); // select High Speed + if (error) { + return error; + } + if ((sd_status_byte(words, 16) & 0x0FU) != 1U) { + return HAL_SD_ERROR_UNSUPPORTED_FEATURE; + } + start = HAL_GetTick(); + while (!sd_card_ready(obj)) { + if (sd_getError(obj)) { + return sd_getError(obj); + } + if ((HAL_GetTick() - start) >= SD_TRANSFER_TIMEOUT) { + return HAL_SD_ERROR_TIMEOUT; + } + } + return HAL_SD_ERROR_NONE; +} +#endif + +/** + * @brief Negotiate SD or MMC high-speed timing before raising the data clock. + */ +static uint32_t sd_negotiate_high_speed(sd_t *obj, uint32_t actual) +{ +#if defined(HAL_MMC_MODULE_ENABLED) + if (obj->isMMC) { + // EXT_CSD DEVICE_TYPE byte 196 advertises SDR 26 MHz (bit0) and + // SDR 52 MHz (bit1). HS_TIMING byte 185 must be switched before raising CK. + if (HAL_MMC_GetCardExtCSD(&obj->mmc, obj->mmc.Ext_CSD, SD_TRANSFER_TIMEOUT) != HAL_OK) { + return sd_getError(obj) ? sd_getError(obj) : HAL_SD_ERROR_UNSUPPORTED_FEATURE; + } + uint32_t type = obj->mmc.Ext_CSD[49] & 0xFFU; + if (!(type & 2U) && (!(type & 1U) || actual > 26000000U)) { + return HAL_SD_ERROR_UNSUPPORTED_FEATURE; + } + uint32_t error = SDMMC_CmdSwitch(obj->sd, 0x03B90100U); + uint32_t start = HAL_GetTick(); + while (!error) { + error = SDMMC_CmdSendStatus(obj->sd, obj->mmc.MmcCard.RelCardAdd << 16U); + if (error) { + break; + } + uint32_t response = obj->sd->RESP1; + if (response & 0x80U) { + return HAL_SD_ERROR_UNSUPPORTED_FEATURE; + } + if ((response & 0x100U) && ((response >> 9U) & 0x0FU) == 4U) { + return HAL_SD_ERROR_NONE; + } + if ((HAL_GetTick() - start) >= SD_TRANSFER_TIMEOUT) { + return HAL_SD_ERROR_TIMEOUT; + } + } + return error; + } +#else + UNUSED(actual); +#endif +#if SDIO_USE_IDMA + return HAL_SD_ConfigSpeedBusOperation(&obj->handle, SDMMC_SPEED_MODE_HIGH) == HAL_OK ? + HAL_SD_ERROR_NONE : (sd_getError(obj) ? sd_getError(obj) : HAL_SD_ERROR_UNSUPPORTED_FEATURE); +#else + return sd_high_speed(obj); +#endif +} + +/** + * @brief Resolve resources, initialize media safely and apply the negotiated clock. + */ +static sd_status_e sd_init_media(sd_t *obj, uint32_t speed, SDIOMode mode, uint8_t dmaEnabled, bool mmc) +{ + if (!obj) { + return SD_ERROR; + } + sd_release(obj); + obj->isMMC = false; +#if defined(HAL_MMC_MODULE_ENABLED) + obj->isMMC = mmc; +#else + if (mmc) { + obj->handle.ErrorCode = HAL_SD_ERROR_UNSUPPORTED_FEATURE; + return SD_ERROR; + } +#endif + if (!speed || speed > (mmc ? SDIO_SPEED_CLOCK_MMC_HIGH : SDIO_SPEED_CLOCK_SD_HIGH) || + (mode == SDIO_MODE_1B && speed > 25000000U) || + (mode != SDIO_MODE_1B && mode != SDIO_MODE_4B && mode != SDIO_MODE_8B) || + (mode == SDIO_MODE_8B && !mmc)) { + *sd_error(obj) = HAL_SD_ERROR_PARAM; + return SD_ERROR; + } + obj->busMode = mode; + obj->useDMA = SDIO_DMA_ENABLED && dmaEnabled != 0; + obj->requested_clock = speed; + if (!sd_select_pins(obj)) { + *sd_error(obj) = HAL_SD_ERROR_PARAM; + return SD_ERROR; + } + int slot = sd_slot(obj->sd); + if (sd_owner[slot] && sd_owner[slot] != obj) { + *sd_error(obj) = HAL_SD_ERROR_BUSY; + return SD_ERROR; + } + + // Check if a card detection is defined and card is inserted + if (obj->SD_detect_gpio_port && !sd_isDetected(obj)) { + *sd_error(obj) = HAL_SD_ERROR_TIMEOUT; + return SD_ERROR; + } + + uint32_t clock = sd_getClkFreq(obj); + // Identify and configure width at <=25 MHz. Keep the target divider + // separate until the medium confirms High Speed mode. + uint32_t safe_speed = speed < 25000000U ? speed : 25000000U; + SD_InitTypeDef init = {0}; +#if defined(SDIO) + init.ClockEdge = SDIO_CLOCK_EDGE_RISING; + init.ClockBypass = SDIO_CLOCK_BYPASS_DISABLE; + init.ClockPowerSave = SDIO_CLOCK_POWER_SAVE_DISABLE; + init.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE; +#else + init.ClockEdge = SDMMC_CLOCK_EDGE_RISING; +#if defined(SDMMC_CLOCK_BYPASS_DISABLE) + init.ClockBypass = SDMMC_CLOCK_BYPASS_DISABLE; +#endif + init.ClockPowerSave = SDMMC_CLOCK_POWER_SAVE_DISABLE; + init.HardwareFlowControl = SDMMC_HARDWARE_FLOW_CONTROL_DISABLE; +#endif + init.BusWide = SD_BUS_WIDE_1B; +#if SDIO_USE_IDMA + uint32_t divisor = clock <= safe_speed ? 0U : clock / (2U * safe_speed) + ((clock % (2U * safe_speed)) != 0U); + if (!clock || divisor > 1023U) { + *sd_error(obj) = HAL_SD_ERROR_PARAM; + return SD_ERROR; + } + init.ClockDiv = divisor; +#if (USE_SD_TRANSCEIVER != 0U) || (USE_SDIO_TRANSCEIVER != 0U) + init.TranceiverPresent = SDMMC_TRANSCEIVER_NOT_PRESENT; +#endif +#else + uint32_t divisor = clock / safe_speed + ((clock % safe_speed) != 0U); +#if defined(STM32F1xx) + /* The F1 HAL in this core derives its identification divider from HCLK. */ + bool init_clock_ok = clock <= 72000000U; +#else + /* The legacy HAL uses a fixed 118 divider for card identification. */ + bool init_clock_ok = clock <= 48000000U; +#endif + if (!clock || !init_clock_ok || divisor > 257U) { + *sd_error(obj) = HAL_SD_ERROR_PARAM; + return SD_ERROR; + } + init.ClockDiv = divisor > 2U ? divisor - 2U : 0U; +#endif + obj->handle.Instance = obj->sd; + obj->handle.Init = init; +#if defined(HAL_MMC_MODULE_ENABLED) + obj->mmc.Instance = obj->sd; + obj->mmc.Init = init; +#endif + sd_owner[slot] = obj; + SDIO_MspInit(obj, NULL); + if (SD_CALL(obj, Init) != HAL_OK) { + goto fail; + } + if (mode != SDIO_MODE_1B && SD_CALL(obj, ConfigWideBusOperation, + mode == SDIO_MODE_8B ? SD_BUS_WIDE_8B : SD_BUS_WIDE_4B) != HAL_OK) { + goto fail; + } + SD_InitTypeDef target = init; + target.BusWide = mode == SDIO_MODE_8B ? SD_BUS_WIDE_8B : mode == SDIO_MODE_4B ? SD_BUS_WIDE_4B : SD_BUS_WIDE_1B; +#if SDIO_USE_IDMA + target.ClockDiv = clock <= speed ? 0U : clock / (2U * speed) + ((clock % (2U * speed)) != 0U); + uint32_t actual = target.ClockDiv ? clock / (2U * target.ClockDiv) : clock; +#else + // Legacy SDIO/SDMMC can bypass the divider, up to the host's 48 MHz + // SDR limit. Otherwise the minimum divisor is two. + if (clock <= speed && clock <= 48000000U) { +#if defined(SDIO) + target.ClockBypass = SDIO_CLOCK_BYPASS_ENABLE; +#else + target.ClockBypass = SDMMC_CLOCK_BYPASS_ENABLE; +#endif + target.ClockDiv = 0; + } else { + uint32_t target_divisor = clock / speed + ((clock % speed) != 0U); + target.ClockDiv = target_divisor > 2U ? target_divisor - 2U : 0U; + } + uint32_t actual = target.ClockBypass ? clock : clock / (target.ClockDiv + 2U); +#endif + if (actual > 25000000U) { + uint32_t error = sd_negotiate_high_speed(obj, actual); + if (error) { + *sd_error(obj) |= error; + goto fail; + } + obj->high_speed = true; + } + obj->handle.Init = target; +#if defined(HAL_MMC_MODULE_ENABLED) + obj->mmc.Init = target; +#endif +#if defined(SDIO) + if (SDIO_Init(obj->sd, target) != HAL_OK) { + *sd_error(obj) |= HAL_SD_ERROR_PARAM; + goto fail; + } +#else + if (SDMMC_Init(obj->sd, target) != HAL_OK) { + *sd_error(obj) |= HAL_SD_ERROR_PARAM; + goto fail; + } +#if SDIO_USE_IDMA + if (obj->high_speed) { + SET_BIT(obj->sd->CLKCR, SDMMC_CLKCR_BUSSPEED); + } +#endif +#endif + if (obj->useDMA) { +#if SDIO_USE_EXTERNAL_DMA + if (sd_dma_init(obj) != HAL_OK) { + *sd_error(obj) |= HAL_SD_ERROR_DMA; + goto fail; + } +#endif + sd_irq_enable(obj->irq); + } + obj->initialized = true; + // Read back the controller configuration: some HALs adjust it while + // negotiating the bus width or the medium's operating speed. +#if defined(SDIO) + uint32_t active_div = obj->sd->CLKCR & SDIO_CLKCR_CLKDIV; +#else + uint32_t active_div = obj->sd->CLKCR & SDMMC_CLKCR_CLKDIV; +#endif +#if SDIO_USE_IDMA + obj->actual_clock = active_div ? clock / (2U * active_div) : clock; +#else +#if defined(SDIO) + obj->actual_clock = (obj->sd->CLKCR & SDIO_CLKCR_BYPASS) ? clock : clock / (active_div + 2U); +#else + obj->actual_clock = (obj->sd->CLKCR & SDMMC_CLKCR_BYPASS) ? clock : clock / (active_div + 2U); +#endif +#endif + return SD_OK; +fail: { + uint32_t error = sd_getError(obj); + sd_log_record(obj, SD_LOG_INIT, SD_LOG_FAILURE, 0, 0, SD_ERROR); + sd_release(obj); + *sd_error(obj) = error; + return SD_ERROR; + } +} + +/** + * @brief Initialize SD media; eight-bit mode selects MMC initialization. + * @param obj Controller configuration and runtime state. + * @param speed Requested maximum data clock in Hz. + * @param mode Bus width. + * @param dmaEnabled Nonzero requests DMA; ignored if HAL DMA is disabled. + * @return SD_OK on success, SD_ERROR on initialization failure. + */ +sd_status_e sd_init(sd_t *obj, uint32_t speed, SDIOMode mode, uint8_t dmaEnabled) +{ + sd_status_e status = sd_init_media(obj, speed, mode, dmaEnabled, mode == SDIO_MODE_8B); + sd_log_record(obj, SD_LOG_INIT, SD_LOG_COMPLETE, 0, 0, status); + return status; +} + +/** + * @brief Initialize MMC/eMMC explicitly. + * @param obj Controller configuration and runtime state. + * @param speed Requested maximum data clock in Hz. + * @param mode One-, four- or eight-bit bus mode. + * @param dmaEnabled Nonzero requests DMA; ignored if HAL DMA is disabled. + * @return SD_OK on success, SD_ERROR on failure, including missing HAL MMC support. + */ +sd_status_e sd_init_mmc(sd_t *obj, uint32_t speed, SDIOMode mode, uint8_t dmaEnabled) +{ + sd_status_e status = sd_init_media(obj, speed, mode, dmaEnabled, true); + sd_log_record(obj, SD_LOG_INIT, SD_LOG_COMPLETE, 0, 0, status); + return status; +} + +/** + * @brief Release owned hardware and interrupts, including partial initialization. + */ +static void sd_release(sd_t *obj) +{ + if (!obj) { + return; + } + int slot = sd_slot(obj->sd); + if (slot >= 0 && sd_owner[slot] == obj) { + obj->initialized = false; + if (obj->useDMA) { + HAL_NVIC_DisableIRQ(obj->irq); + if (sd_hal_busy(obj) || sd_dma_busy(obj)) { + sd_abort_transfer(obj); + } +#if SDIO_USE_EXTERNAL_DMA + if (obj->dma_rx.Instance) { + HAL_NVIC_DisableIRQ(obj->dma_rx_irq); + HAL_DMA_DeInit(&obj->dma_rx); + HAL_NVIC_ClearPendingIRQ(obj->dma_rx_irq); + } + if (obj->dma_tx.Instance) { + HAL_NVIC_DisableIRQ(obj->dma_tx_irq); + HAL_DMA_DeInit(&obj->dma_tx); + HAL_NVIC_ClearPendingIRQ(obj->dma_tx_irq); + } +#endif + HAL_NVIC_ClearPendingIRQ(obj->irq); + } + sd_log_finish(obj, SD_ERROR); + HAL_StatusTypeDef status = SD_CALL(obj, DeInit); + sd_log_record(obj, SD_LOG_END, SD_LOG_COMPLETE, 0, 0, status == HAL_OK ? SD_OK : SD_ERROR); + sd_cache_finish(obj); + SDIO_MspDeInit(obj, NULL); + sd_owner[slot] = NULL; + } +#if SDIO_USE_EXTERNAL_DMA + obj->handle.hdmarx = obj->handle.hdmatx = NULL; +#if defined(HAL_MMC_MODULE_ENABLED) + obj->mmc.hdmarx = obj->mmc.hdmatx = NULL; +#endif +#endif + obj->handle.State = HAL_SD_STATE_RESET; +#if defined(HAL_MMC_MODULE_ENABLED) + obj->mmc.State = HAL_MMC_STATE_RESET; +#endif + obj->initialized = false; + obj->sd = NULL; + obj->actual_clock = 0; + obj->high_speed = false; +} + +/** + * @brief Abort activity and release peripheral, DMA, pins and controller ownership. + * @param obj Controller to release; null is allowed. + */ +void sd_deinit(sd_t *obj) +{ + sd_release(obj); + sd_detachDetectionInterrupt(obj); +} + +/** + * @brief Poll HAL, DMA and card readiness, finishing RX cache maintenance and logging. + * @param obj Controller to poll. + * @return True while busy; false also on error or an uninitialized controller. + * @note Inspect sd_getError() to distinguish completion from failure. + */ +bool sd_isBusy(sd_t *obj) +{ + if (!obj || !obj->initialized) { + return false; + } + if (sd_hal_busy(obj) || sd_dma_busy(obj)) { + return true; + } + sd_cache_finish(obj); + if (sd_getError(obj) != HAL_SD_ERROR_NONE) { + sd_log_finish(obj, SD_ERROR); + return false; + } + bool ready = sd_card_ready(obj); + if (ready || sd_getError(obj) != HAL_SD_ERROR_NONE) { + sd_log_finish(obj, sd_getError(obj) == HAL_SD_ERROR_NONE ? SD_OK : SD_ERROR); + } + return sd_getError(obj) == HAL_SD_ERROR_NONE && !ready; +} + +/** + * @brief Wait for transfer completion and card readiness; abort DMA on timeout. + * @param obj Initialized controller. + * @param timeout Maximum wait in milliseconds. + * @return SD_OK, SD_TIMEOUT or SD_ERROR. + */ +sd_status_e sd_wait(sd_t *obj, uint32_t timeout) +{ + if (!obj || !obj->initialized) { + return SD_ERROR; + } + uint32_t start = HAL_GetTick(); + while (sd_isBusy(obj)) { + if ((HAL_GetTick() - start) >= timeout) { + if (obj->useDMA) { + sd_abort_transfer(obj); + } + *sd_error(obj) |= HAL_SD_ERROR_TIMEOUT; + sd_log_finish(obj, SD_TIMEOUT); + return SD_TIMEOUT; + } + } + return sd_getError(obj) == HAL_SD_ERROR_NONE ? SD_OK : SD_ERROR; +} + +/** + * @brief Validate range, alignment, DMA limits and readiness before submission. + */ +static bool sd_valid_transfer(sd_t *obj, const void *buffer, uint32_t address, uint32_t blocks) +{ + if (!obj || !obj->initialized || sd_hal_busy(obj) || sd_dma_busy(obj)) { + return false; + } + sd_cache_finish(obj); + if (!buffer || ((uintptr_t)buffer & 3U) || !blocks || blocks > 65535U || + (!SDIO_USE_IDMA && obj->useDMA && blocks > 511U)) { + *sd_error(obj) = HAL_SD_ERROR_PARAM; return false; + } +#if defined(__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U) + if (obj->useDMA && ((uintptr_t)buffer & 31U)) { + *sd_error(obj) = HAL_SD_ERROR_PARAM; + return false; + } +#endif + uint32_t count = sd_block_count(obj); + if (address >= count || blocks > count - address) { + *sd_error(obj) = HAL_SD_ERROR_ADDR_OUT_OF_RANGE; + return false; + } +#if defined(STM32F4xx) + if (obj->useDMA && (uintptr_t)buffer >= 0x10000000U && (uintptr_t)buffer < 0x10010000U) { + *sd_error(obj) = HAL_SD_ERROR_PARAM; return false; + } +#endif +#if SDIO_USE_EXTERNAL_DMA + if (obj->useDMA) { + if (HAL_DMA_GetState(&obj->dma_rx) != HAL_DMA_STATE_READY || HAL_DMA_GetState(&obj->dma_tx) != HAL_DMA_STATE_READY) { + return false; + } + sd_link_dma(obj); + } +#endif + bool ready = sd_card_ready(obj); + if (ready) { + sd_log_finish(obj, sd_getError(obj) == HAL_SD_ERROR_NONE ? SD_OK : SD_ERROR); + } + return ready; +} + +/** + * @brief Read consecutive 512-byte logical sectors. + * @param obj Initialized controller. + * @param[out] buffer Destination of at least blocks * 512 bytes. + * @param address First logical sector. + * @param blocks Sector count; 1..511 for external DMA, otherwise 1..65535. + * @return SD_OK on DMA acceptance or blocking completion; otherwise an error status. + * @note Buffers must be four-byte aligned (32 for Cortex-M7 DMA) and DMA-accessible. + * Keep DMA buffers untouched until sd_wait() completes successfully. + */ +sd_status_e sd_read(sd_t *obj, uint8_t *buffer, uint32_t address, uint32_t blocks) +{ + if (!sd_valid_transfer(obj, buffer, address, blocks)) { + sd_log_record(obj, SD_LOG_READ, SD_LOG_FAILURE, address, blocks, SD_ERROR); return SD_ERROR; + } + if (obj->useDMA) { + obj->rx_buffer = buffer; + obj->rx_bytes = blocks * 512U; +#if defined(__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U) + if (SCB->CCR & SCB_CCR_DC_Msk) { + SCB_CleanInvalidateDCache_by_Addr((uint32_t *)buffer, (int32_t)obj->rx_bytes); + } +#endif + } + HAL_StatusTypeDef status = +#if SDIO_DMA_ENABLED + obj->useDMA ? SD_CALL(obj, ReadBlocks_DMA, buffer, address, blocks) : +#endif + SD_CALL(obj, ReadBlocks, buffer, address, blocks, SD_TRANSFER_TIMEOUT); + sd_log_submit(obj, SD_LOG_READ, address, blocks, status == HAL_OK ? SD_OK : SD_ERROR); + if (status != HAL_OK) { + if (obj->useDMA) { + sd_abort_transfer(obj); + } + return SD_ERROR; + } + return obj->useDMA ? SD_OK : sd_wait(obj, SD_TRANSFER_TIMEOUT); +} + +/** + * @brief Write consecutive 512-byte logical sectors. + * @param obj Initialized controller. + * @param[in] buffer Source of at least blocks * 512 bytes. + * @param address First logical sector. + * @param blocks Sector count; 1..511 for external DMA, otherwise 1..65535. + * @return SD_OK on DMA acceptance or blocking completion; otherwise an error status. + * @note Alignment and lifetime requirements match sd_read(). Keep the source + * unchanged until transfer and card programming complete. + */ +sd_status_e sd_write(sd_t *obj, const uint8_t *buffer, uint32_t address, uint32_t blocks) +{ + if (!sd_valid_transfer(obj, buffer, address, blocks)) { + sd_log_record(obj, SD_LOG_WRITE, SD_LOG_FAILURE, address, blocks, SD_ERROR); return SD_ERROR; + } +#if defined(__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U) + if (obj->useDMA && (SCB->CCR & SCB_CCR_DC_Msk)) { + SCB_CleanDCache_by_Addr((uint32_t *)buffer, (int32_t)(blocks * 512U)); + } +#endif + HAL_StatusTypeDef status = +#if SDIO_DMA_ENABLED + obj->useDMA ? SD_CALL(obj, WriteBlocks_DMA, (uint8_t *)buffer, address, blocks) : +#endif + SD_CALL(obj, WriteBlocks, (uint8_t *)buffer, address, blocks, SD_TRANSFER_TIMEOUT); + sd_log_submit(obj, SD_LOG_WRITE, address, blocks, status == HAL_OK ? SD_OK : SD_ERROR); + if (status != HAL_OK) { + if (obj->useDMA) { + sd_abort_transfer(obj); + } + return SD_ERROR; + } + return obj->useDMA ? SD_OK : sd_wait(obj, SD_TRANSFER_TIMEOUT); +} + +/** + * @brief Erase an inclusive range and wait for card readiness. + * @param obj Initialized controller. + * @param start_address First logical sector. + * @param end_address Last logical sector. + * @return SD_OK, SD_TIMEOUT or SD_ERROR. + */ +sd_status_e sd_erase(sd_t *obj, uint32_t start_address, uint32_t end_address) +{ + if (!obj || !obj->initialized || sd_hal_busy(obj) || sd_dma_busy(obj)) { + sd_log_record(obj, SD_LOG_ERASE, SD_LOG_FAILURE, start_address, 0, SD_ERROR); return SD_ERROR; + } + if (start_address > end_address || end_address >= sd_block_count(obj)) { + *sd_error(obj) = HAL_SD_ERROR_ADDR_OUT_OF_RANGE; + sd_log_record(obj, SD_LOG_ERASE, SD_LOG_FAILURE, start_address, 0, SD_ERROR); return SD_ERROR; + } + if (!sd_card_ready(obj)) { + sd_log_record(obj, SD_LOG_ERASE, SD_LOG_FAILURE, start_address, end_address - start_address + 1U, SD_ERROR); return SD_ERROR; + } + sd_log_finish(obj, sd_getError(obj) == HAL_SD_ERROR_NONE ? SD_OK : SD_ERROR); + HAL_StatusTypeDef status = SD_CALL(obj, Erase, start_address, end_address); + sd_log_submit(obj, SD_LOG_ERASE, start_address, end_address - start_address + 1U, status == HAL_OK ? SD_OK : SD_ERROR); + if (status != HAL_OK) { + return SD_ERROR; + } + return sd_wait(obj, SD_TRANSFER_TIMEOUT); +} + +/** + * @brief Configure a pull-up input for card detection and detach its previous EXTI. + * @param obj Controller to configure. + * @param pin Detection pin. + * @param level Active level: zero for low, nonzero for high. + * @return True if configuration succeeds. + */ +bool sd_setDetectionInput(sd_t *obj, PinName pin, uint32_t level) +{ + if (!obj || pin == NC) { + return false; + } + GPIO_TypeDef *port = set_GPIO_Port_Clock(STM_PORT(pin)); + if (!port) { + return false; + } + sd_detachDetectionInterrupt(obj); + obj->pin_detect = pin; + obj->SD_detect_gpio_port = port; + obj->SD_detect_ll_gpio_pin = STM_LL_GPIO_PIN(pin); + obj->SD_detect_level = level != 0; +#if defined(STM32F1xx) + LL_GPIO_SetPinPull(port, obj->SD_detect_ll_gpio_pin, LL_GPIO_PULL_UP); + LL_GPIO_SetPinMode(port, obj->SD_detect_ll_gpio_pin, LL_GPIO_MODE_INPUT); +#else + LL_GPIO_SetPinMode(port, obj->SD_detect_ll_gpio_pin, LL_GPIO_MODE_INPUT); + LL_GPIO_SetPinPull(port, obj->SD_detect_ll_gpio_pin, LL_GPIO_PULL_UP); +#endif + return true; +} + +/** + * @brief Return whether the detection pin matches its configured active level. + * @param obj Controller to inspect. + * @return False when detection is unconfigured. + */ +bool sd_isDetected(sd_t *obj) +{ + return obj && obj->SD_detect_gpio_port && + (LL_GPIO_IsInputPinSet(obj->SD_detect_gpio_port, obj->SD_detect_ll_gpio_pin) != 0) == obj->SD_detect_level; +} + +/** + * @brief Dispatch a peripheral interrupt to its registered SD/MMC owner. + */ +static void sd_irq(unsigned slot) +{ + sd_t *obj = sd_owner[slot]; + if (obj && obj->useDMA) { + SD_CALL(obj, IRQHandler); + } +} + +#if defined(SDIO) +/** + * @brief Service the SDIO interrupt for its active owner. + */ +void SDIO_IRQHandler(void) +{ + sd_irq(0); +} +#endif +#if defined(SDMMC1) +/** + * @brief Service the SDMMC1 interrupt for its active owner. + */ +void SDMMC1_IRQHandler(void) +{ + sd_irq(0); +} +#endif +#if defined(SDMMC2) +/** + * @brief Service the SDMMC2 interrupt for its active owner. + */ +void SDMMC2_IRQHandler(void) +{ + sd_irq(1); +} +#endif + +#if SDIO_USE_EXTERNAL_DMA +#define sd_dma_irq(object, dmaHandle, writing) HAL_DMA_IRQHandler(dmaHandle) + +#if defined(STM32F1xx) +/* CMSIS maps this name to Channel4_5 on high-density F103 devices. The + * shared vector is reserved while SDIO DMA is enabled (including channel5). + */ +/** + * @brief Service the DMA2_Channel4 interrupt for its active owner. + */ +void DMA2_Channel4_IRQHandler(void) +{ + sd_t *obj = sd_owner[0]; + if (obj && obj->useDMA) { + if (HAL_DMA_GetState(&obj->dma_rx) == HAL_DMA_STATE_BUSY) { + sd_dma_irq(obj, &obj->dma_rx, false); + } else if (HAL_DMA_GetState(&obj->dma_tx) == HAL_DMA_STATE_BUSY) { + sd_dma_irq(obj, &obj->dma_tx, true); + } + } +} +#else +/** + * @brief Service the DMA2_Stream3 interrupt for its active owner. + */ +void DMA2_Stream3_IRQHandler(void) +{ + sd_t *obj = sd_owner[0]; + if (obj && obj->useDMA) { + sd_dma_irq(obj, &obj->dma_rx, false); + } +} +/** + * @brief Service the DMA2_Stream6 interrupt for its active owner. + */ +void DMA2_Stream6_IRQHandler(void) +{ + sd_t *obj = sd_owner[0]; + if (obj && obj->useDMA) { + sd_dma_irq(obj, &obj->dma_tx, true); + } +} +#if defined(STM32F7xx) && defined(SDMMC2) +/** + * @brief Service the DMA2_Stream0 interrupt for its active owner. + */ +void DMA2_Stream0_IRQHandler(void) +{ + sd_t *obj = sd_owner[1]; + if (obj && obj->useDMA) { + sd_dma_irq(obj, &obj->dma_rx, false); + } +} +/** + * @brief Service the DMA2_Stream5 interrupt for its active owner. + */ +void DMA2_Stream5_IRQHandler(void) +{ + sd_t *obj = sd_owner[1]; + if (obj && obj->useDMA) { + sd_dma_irq(obj, &obj->dma_tx, true); + } +} +#endif +#endif +#endif + +#endif // STM32_SDIO_ENABLED diff --git a/libraries/SDIO/utility/sdio_com.h b/libraries/SDIO/utility/sdio_com.h new file mode 100644 index 0000000000..92a2e6e54c --- /dev/null +++ b/libraries/SDIO/utility/sdio_com.h @@ -0,0 +1,331 @@ +/** + * @brief C HAL bridge for SDIO/SDMMC, SD and MMC/eMMC transfers. + * @file sdio_com.h + * @note Logical addresses and counts use 512-byte sectors. Configuration and I/O + * must be serialized by the caller; one owner is allowed per controller. + */ +/* + * Copyright (c) 2016 Frederic Pillon for + * STMicroelectronics. All right reserved. + * This file is free software; you can redistribute it and/or modify + * it under the terms of either the GNU General Public License version 2 + * or the GNU Lesser General Public License version 2.1, both as + * published by the Free Software Foundation. + */ +#ifndef SDIO_COM_H +#define SDIO_COM_H + +#include +#include "stm32_def.h" +#if (defined(STM32F1xx) || defined(STM32F2xx) || defined(STM32F4xx) || defined(STM32F7xx) || defined(STM32H5xx)) && \ + (defined(SDIO) || defined(SDMMC1) || defined(SDMMC2)) && defined(HAL_SD_MODULE_ENABLED) + /** @brief SDIO API is available for this target and HAL configuration. */ + #define STM32_SDIO_ENABLED +#endif + +#if defined(STM32_SDIO_ENABLED) +#include "PeripheralPins.h" + +#if defined(STM32H5xx) + #define SDIO_USE_IDMA 1 +#else + #define SDIO_USE_IDMA 0 +#endif + +/** @brief DMA is optional; disabled builds use blocking transfers. */ +#if defined(HAL_DMA_MODULE_ENABLED) + #define SDIO_DMA_ENABLED 1 +#else + #define SDIO_DMA_ENABLED 0 +#endif +#define SDIO_USE_EXTERNAL_DMA (SDIO_DMA_ENABLED && !SDIO_USE_IDMA) + +#if defined(SDMMC1) || defined(SDMMC2) + #define SD_BUS_WIDE_1B SDMMC_BUS_WIDE_1B + #define SD_BUS_WIDE_4B SDMMC_BUS_WIDE_4B + #define SD_BUS_WIDE_8B SDMMC_BUS_WIDE_8B +#else + #define SD_BUS_WIDE_1B SDIO_BUS_WIDE_1B + #define SD_BUS_WIDE_4B SDIO_BUS_WIDE_4B + #define SD_BUS_WIDE_8B SDIO_BUS_WIDE_8B +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#define SDIO_SPEED_CLOCK_DEFAULT 25000000U +#define SDIO_SPEED_CLOCK_SD_HIGH 50000000U +#define SDIO_SPEED_CLOCK_MMC_HIGH 52000000U +#define SDIO_SPEED_CLOCK_MAX SDIO_SPEED_CLOCK_MMC_HIGH +#ifndef SDIO_LOG_CAPACITY +#define SDIO_LOG_CAPACITY 10 +#elif SDIO_LOG_CAPACITY < 0 +#error "SDIO_LOG_CAPACITY cannot be negative" +#endif +#ifndef SD_TRANSFER_TIMEOUT +#define SD_TRANSFER_TIMEOUT 1000U +#elif SD_TRANSFER_TIMEOUT <= 0 +#error "SD_TRANSFER_TIMEOUT must be positive" +#endif +#ifndef SDIO_IRQ_PRIORITY +#define SDIO_IRQ_PRIORITY 5U +#endif + +/** + * @brief Supported bus widths; eight-bit mode is reserved for MMC/eMMC. + */ +typedef enum { + SDIO_MODE_1B = 0, + SDIO_MODE_4B = 1, + SDIO_MODE_8B = 2 +} SDIOMode; + +/** + * @brief Transfer and initialization result codes. + */ +typedef enum { + SD_OK = 0, + SD_TIMEOUT = 1, + SD_ERROR = 2 +} sd_status_e; + +/** + * @brief Operation represented by a diagnostic snapshot. + */ +typedef enum { + SD_LOG_INIT, SD_LOG_READ, SD_LOG_WRITE, SD_LOG_ERASE, SD_LOG_END +} sd_log_operation_e; + +/** + * @brief Lifecycle phase represented by a diagnostic snapshot. + */ +typedef enum { + SD_LOG_SUBMIT, SD_LOG_COMPLETE, SD_LOG_ABORT, SD_LOG_FAILURE +} sd_log_phase_e; + +/* Operation snapshots, not a trace of every command sent inside the HAL. */ +/** + * @brief Bounded operation snapshot, not a trace of every command inside HAL. + * @note timestamp is in milliseconds; addresses/counts are sectors and clocks are Hz. + * Register values are meaningful only when registers_valid is true. + */ +typedef struct { + uint32_t timestamp; + uintptr_t instance; + uint32_t address; + uint32_t blocks; + uint32_t error; + uint32_t command; + uint32_t argument; + uint32_t response[4]; + uint32_t requested_clock; + uint32_t actual_clock; + sd_log_operation_e operation; + sd_log_phase_e phase; + sd_status_e status; + SDIOMode mode; + bool mmc: 1; + bool dma: 1; + bool registers_valid: 1; + bool high_speed: 1; +} sd_log_entry_t; + +/** + * @brief Controller configuration, HAL handles, DMA ownership and diagnostic state. + * @note Initialize storage before use. Do not copy an active controller or modify + * its buffers and handles during transfers. + */ +typedef struct sd_s { + SD_HandleTypeDef handle; +#if defined(HAL_MMC_MODULE_ENABLED) + MMC_HandleTypeDef mmc; +#endif +#if SDIO_USE_EXTERNAL_DMA + DMA_HandleTypeDef dma_rx; + DMA_HandleTypeDef dma_tx; +#endif + SD_TypeDef *sd; + SD_TypeDef *requested_instance; + IRQn_Type irq; +#if SDIO_USE_EXTERNAL_DMA + IRQn_Type dma_rx_irq; + IRQn_Type dma_tx_irq; +#endif + PinName pin_d0; + PinName pin_d1; + PinName pin_d2; + PinName pin_d3; + PinName pin_d4; + PinName pin_d5; + PinName pin_d6; + PinName pin_d7; + PinName pin_cmd; + PinName pin_sck; + PinName pin_detect; + GPIO_TypeDef *SD_detect_gpio_port; + uint32_t SD_detect_ll_gpio_pin; + uint32_t SD_detect_level; + SDIOMode busMode; + uint8_t *rx_buffer; + uint32_t rx_bytes; + uint32_t requested_clock; + uint32_t actual_clock; +#if SDIO_LOG_CAPACITY > 0 + sd_log_entry_t log[SDIO_LOG_CAPACITY]; + uint32_t log_next; + uint32_t log_count; + sd_log_operation_e log_operation; + uint32_t log_address; + uint32_t log_blocks; + bool logging: 1; + bool log_pending: 1; +#endif + bool high_speed: 1; + bool useDMA: 1; + bool isMMC: 1; + bool initialized: 1; + bool detection_interrupt: 1; +} sd_t; + +/** + * @brief Initialize SD media; eight-bit mode selects MMC initialization. + * @param obj Controller configuration and runtime state. + * @param speed Requested maximum data clock in Hz. + * @param mode Bus width. + * @param dmaEnabled Nonzero requests DMA; ignored if HAL DMA is disabled. + * @return SD_OK on success, SD_ERROR on initialization failure. + */ +sd_status_e sd_init(sd_t *obj, uint32_t speed, SDIOMode mode, uint8_t dmaEnabled); +/** + * @brief Initialize MMC/eMMC explicitly. + * @param obj Controller configuration and runtime state. + * @param speed Requested maximum data clock in Hz. + * @param mode One-, four- or eight-bit bus mode. + * @param dmaEnabled Nonzero requests DMA; ignored if HAL DMA is disabled. + * @return SD_OK on success, SD_ERROR on failure, including missing HAL MMC support. + */ +sd_status_e sd_init_mmc(sd_t *obj, uint32_t speed, SDIOMode mode, uint8_t dmaEnabled); +/** + * @brief Abort activity and release peripheral, DMA, pins and controller ownership. + * @param obj Controller to release; null is allowed. + */ +void sd_deinit(sd_t *obj); +/** + * @brief Read consecutive 512-byte logical sectors. + * @param obj Initialized controller. + * @param[out] buffer Destination of at least blocks * 512 bytes. + * @param address First logical sector. + * @param blocks Sector count; 1..511 for external DMA, otherwise 1..65535. + * @return SD_OK on DMA acceptance or blocking completion; otherwise an error status. + * @note Buffers must be four-byte aligned (32 for Cortex-M7 DMA) and DMA-accessible. + * Keep DMA buffers untouched until sd_wait() completes successfully. + */ +sd_status_e sd_read(sd_t *obj, uint8_t *buffer, uint32_t address, uint32_t blocks); +/** + * @brief Write consecutive 512-byte logical sectors. + * @param obj Initialized controller. + * @param[in] buffer Source of at least blocks * 512 bytes. + * @param address First logical sector. + * @param blocks Sector count; 1..511 for external DMA, otherwise 1..65535. + * @return SD_OK on DMA acceptance or blocking completion; otherwise an error status. + * @note Alignment and lifetime requirements match sd_read(). Keep the source + * unchanged until transfer and card programming complete. + */ +sd_status_e sd_write(sd_t *obj, const uint8_t *buffer, uint32_t address, uint32_t blocks); +/** + * @brief Erase an inclusive range and wait for card readiness. + * @param obj Initialized controller. + * @param start_address First logical sector. + * @param end_address Last logical sector. + * @return SD_OK, SD_TIMEOUT or SD_ERROR. + */ +sd_status_e sd_erase(sd_t *obj, uint32_t start_address, uint32_t end_address); +/** + * @brief Return the peripheral kernel input clock in Hz, not the divided card clock. + * @param obj Controller used to select the clock source. + */ +uint32_t sd_getClkFreq(sd_t *obj); +/** + * @brief Return the active SD/MMC HAL error mask, or a parameter error for null. + * @param obj Controller to inspect. + */ +uint32_t sd_getError(const sd_t *obj); +/** + * @brief Enable or disable recording of bounded operation snapshots. + * @param obj Controller to configure. + * @param enabled Whether recording is enabled. + */ +void sd_setLogging(sd_t *obj, bool enabled); +/** + * @brief Clear retained operation snapshots. + * @param obj Controller whose log is cleared. + */ +void sd_clearLog(sd_t *obj); +/** + * @brief Return the retained entry count, or zero when storage is disabled. + * @param obj Controller to inspect. + */ +uint32_t sd_getLogCount(const sd_t *obj); +/** + * @brief Copy a retained operation snapshot. + * @param obj Controller to inspect. + * @param index Zero-based index, oldest first. + * @param[out] entry Destination snapshot. + * @return True if an entry was copied. + */ +bool sd_getLog(const sd_t *obj, uint32_t index, sd_log_entry_t *entry); +/** + * @brief Configure a pull-up input for card detection and detach its previous EXTI. + * Call it before sd_init + * @param obj Controller to configure. + * @param pin Detection pin. + * @param level Active level: zero for low, nonzero for high. + * @return True if configuration succeeds. + */ +bool sd_setDetectionInput(sd_t *obj, PinName pin, uint32_t level); +/** + * @brief Disable the controller-owned detection EXTI registration. + * @param obj Controller to update. + */ +void sd_detachDetectionInterrupt(sd_t *obj); +/** + * @brief Return whether the detection pin matches its configured active level. + * @param obj Controller to inspect. + * @return False when detection is unconfigured. + */ +bool sd_isDetected(sd_t *obj); +/** + * @brief Poll HAL, DMA and card readiness, finishing RX cache maintenance and logging. + * @param obj Controller to poll. + * @return True while busy; false also on error or an uninitialized controller. + * @note Inspect sd_getError() to distinguish completion from failure. + */ +bool sd_isBusy(sd_t *obj); +/** + * @brief Wait for transfer completion and card readiness; abort DMA on timeout. + * @param obj Initialized controller. + * @param timeout Maximum wait in milliseconds. + * @return SD_OK, SD_TIMEOUT or SD_ERROR. + */ +sd_status_e sd_wait(sd_t *obj, uint32_t timeout); + +/* Optional board overrides for SD signal setup/teardown. */ +/** + * @brief Weak board hook to configure active signal pins. + * @param obj Controller with resolved pins and bus width. + * @param params Reserved context; unused by the default implementation. + */ +void SDIO_MspInit(sd_t *obj, void *params); +/** + * @brief Weak board hook to release active signal pins. + * @param obj Controller with resolved pins. + * @param params Reserved context; unused by the default implementation. + */ +void SDIO_MspDeInit(sd_t *obj, void *params); + +#ifdef __cplusplus +} +#endif +#endif // STM32_SDIO_ENABLED +#endif