Skip to main content

OSPI MCAL Module

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

This module provides an abstraction layer for the Octo-SPI interface (OCTOSPIx, in the newest devices called Extended-SPI) of STM32 MCUs: the connection of the external flash and RAM memories over 1, 2, 4 or 8 data lines in the single and the double transfer rate, including the HyperBus memories. It offers the three functional modes of the hardware - the indirect commands with the data transfer in DMA, interrupt or polling mode, the automatic status polling and the memory-mapped mode in which the external memory appears in the address space of the CPU (read, execute in place and write). It is a low-level MCAL module: it owns the OCTOSPI hardware, the application and the other modules never touch the registers.

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

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

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


Intent and purpose​

  • Typical users are the external NOR flash (code executed in place, graphics and audio assets, the file system, the firmware update image), the external PSRAM / HyperRAM (frame buffers, the heap, the audio buffers) and the serial NAND. The memory-mapped mode makes the external memory look like the internal one; the indirect mode is used for everything that the address space cannot express: the commands (read ID, write enable, erase, write status), the programming and the status polling.
  • The interface is a protocol engine with a programmable frame: instruction, address, alternate bytes, dummy cycles and data, every phase with its own number of lines, size and rate. The user describes the command of the memory (ospi_Command_t) exactly as the datasheet of the memory does; the module sets the registers, starts the command, moves the data and reports the end. The knowledge of the memory commands (the sequences of an erase or a write) belongs to a memory driver on the top of this module, which is written once per memory type and works on all families.
  • The user thinks in hertz: the module calculates the clock prescaler from the kernel clock for the required memory clock, sets the sampling shift, the chip-select high time and the data strobe, and reports the achieved frequency. The high speed double-rate modes need the tuning of the sampling with the delay block (the Dlyb module).
  • The module hides the differences between the families: the number of instances, the I/O manager that connects the instances to the pins, the memory types, the address windows, the DMA and the kernel clock selection differ, the interface stays the same.

What the module is not: it does not know the commands of any particular memory, it does not implement a file system or a flash translation layer, it does not configure the MPU attributes of the memory-mapped window (the memory is cacheable, device or normal according to the use - the application / the Cache module decides) and it does not serve the QUADSPI peripheral of the older families (the Qspi module does).


Concept​

An instance is identified by ospi_PeriphId_t. The module has three working modes of the interface (ospi_Mode_t):

ModeFunctionsMeaning
IndirectOspi_Set_Command, Ospi_Set_Read, Ospi_Set_WriteA command with an optional data phase is executed on request; the data are moved by the CPU, the interrupt or the DMA.
Automatic pollingOspi_Set_AutoPollingThe interface repeats a status read command and compares the answer with a mask and a match value; the callback comes when the memory is ready (the end of an erase or a write) or on the timeout.
Memory-mappedOspi_Set_MemoryMapped, Ospi_Set_MemoryMappedStopThe external memory is read (and written, where the memory allows it) by normal CPU and DMA accesses in an address window; the interface generates the commands by itself from a read command and a write command.

The memory and the bus are described by ospi_MemoryConfig_t:

ItemMeaning
Memory typeOSPI_MEMORY_STANDARD, OSPI_MEMORY_MICRON, OSPI_MEMORY_MACRONIX, OSPI_MEMORY_MACRONIX_RAM, OSPI_MEMORY_APMEMORY, OSPI_MEMORY_HYPERBUS_MEMORY, OSPI_MEMORY_HYPERBUS_RAM - selects the protocol details of the hardware (the data strobe and the byte order, the HyperBus latency).
SizeThe size of the memory in bytes (a power of two), the address range of the instance.
ClockThe memory clock in Hz, the clock mode (idle low / idle high), the free running clock, the sampling shift and the hold delay.
Chip selectThe high time between the commands in clock cycles, the maximum transfer length for the memories with a limited chip-select time (PSRAM, HyperRAM).
Data strobeThe use of the DQS signal and the double transfer rate (DTR) per phase.
Dual-quadTwo quad memories in parallel as one octal memory.
PinsThe clock, the chip select, the data strobe and the data lines from the lists of the device.

A command (ospi_Command_t) has the phases:

PhaseItems
InstructionValue, lines (none / 1 / 2 / 4 / 8), size (8 ... 32 bits), DTR.
AddressValue, lines, size (8 ... 32 bits), DTR.
Alternate bytesValue, lines, size, DTR (the mode bits of the quad read).
Dummy cyclesThe number of the clock cycles before the data.
DataLines, the number of bytes, DTR, the data strobe on / off.
OptionsSend the instruction only once (the continuous read), the HyperBus latency mode.

Rules:

  1. Ospi_Init configures the instance (the clock, the memory description, the pins, the interrupt, the DMA) and leaves the interface idle; one memory per instance is connected.
  2. Only one mode is active at a time. The indirect commands and the polling are refused while the memory-mapped mode runs (Ospi_Set_MemoryMappedStop first); the module does not abort a running transfer silently. Ospi_Set_Abort aborts the current command of any mode.
  3. A command is a request: Ospi_Set_Read and Ospi_Set_Write return at once, the data move in the DMA or the ISR mode (or are served by Ospi_Task in the POLL mode) and the complete callback reports the end; the same request and the same callbacks are used in all modes. The data phase longer than the hardware counter is split by the module.
  4. The module checks the command before the first register write: the number of lines against the instance and the mode, the sizes, the DTR against the memory type, the address inside the size of the memory, the data buffer and the length.
  5. The automatic polling ends with the callback OSPI_POLL_MATCH or OSPI_POLL_TIMEOUT (the timeout in cycles in the request); the polling can be stopped by Ospi_Set_Abort.
  6. The memory-mapped mode needs a read command (and a write command for a writable memory, for example the PSRAM); an optional timeout deactivates the clock and the chip select after the period of the inactivity (the saving of the power). The base address of the window is given by Ospi_Get_MappedBaseAddress.
  7. The errors (transfer error - an access beyond the size, a timeout, an invalid command, the FIFO error, the DMA error) are reported by the error callback with the error mask; the interface is brought back to the idle state.

Supported families​

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

FamilyBranchInterfaceStatus
STM32H5Dev/STM32H5OCTOSPI1 on STM32H523, H533, H562, H563, H573; OCTOSPI1, OCTOSPI2 and the I/O manager OCTOSPIM on STM32H5E / H5F; indirect, polling and memory-mapped mode with the read and the write, single / dual / quad / octal lines, SDR and DTR, data strobe, HyperBus, Xccela and XSPI memories, dual-quad configuration; not on STM32H503 / H543 / H553planned (first)
STM32U5Dev/STM32U5OCTOSPI1, OCTOSPI2 and the I/O manager (the hexadeca-SPI HSPI1 of some lines is not covered)planned
STM32H7Dev/STM32H7OCTOSPI1, OCTOSPI2 and the I/O manager on the lines that have them (the other lines have the QUADSPI - Qspi module)planned
STM32L4Dev/STM32L4OCTOSPI1, OCTOSPI2 on the L4+ lines that have them (the other lines have the QUADSPI - Qspi module)planned
STM32F4, STM32F7, STM32G4Dev/STM32F4 ...the QUADSPI of these families is served by the Qspi module - this module is a stub that returns OSPI_REQUEST_ERRORplanned
STM32U3Dev/STM32U3device dependentplanned

A function without a meaning in a family stays in the interface, returns OSPI_REQUEST_ERROR and suppresses the unused parameters (for example the octal lines on an interface with quad lines only, the HyperBus on an instance without it, the second instance of a device that has one).


Public interface in short (proposal)​

GroupFunctions
Module managementOspi_Get_ModuleVersion, Ospi_Init, Ospi_Deinit, Ospi_Task, Ospi_Get_DefaultConfig
Memory and clockOspi_Set_ClkFreq / Get, Ospi_Set_MemoryConfig / Get, Ospi_Set_Tuning
Indirect modeOspi_Set_Command, Ospi_Set_Read, Ospi_Set_Write
Automatic pollingOspi_Set_AutoPolling
Memory-mapped modeOspi_Set_MemoryMapped, Ospi_Set_MemoryMappedStop, Ospi_Get_MappedBaseAddress
Control and stateOspi_Set_Abort, Ospi_Get_State, Ospi_Get_XferError
InterruptsOspi_Set_IrqPriority / Get, the callbacks are a part of the configuration
PinsOspi_InitClkGpio, Ospi_InitNcsGpio, Ospi_InitDqsGpio, Ospi_InitDataGpio, Ospi_InitIoManager
ospi_ModuleVersion_t Ospi_Get_ModuleVersion ( void );

ospi_RequestState_t Ospi_Init ( const ospi_Config_t * const ospiConfig );
ospi_RequestState_t Ospi_Deinit ( ospi_PeriphId_t periphId );
void Ospi_Task ( void );
ospi_RequestState_t Ospi_Get_DefaultConfig ( ospi_Config_t * const ospiConfig );

ospi_RequestState_t Ospi_Set_ClkFreq ( ospi_PeriphId_t periphId, ospi_Frequency_Hz_t clkFreq );
ospi_RequestState_t Ospi_Get_ClkFreq ( ospi_PeriphId_t periphId, ospi_Frequency_Hz_t * const clkFreq );
ospi_RequestState_t Ospi_Set_Tuning ( ospi_PeriphId_t periphId );

ospi_RequestState_t Ospi_Set_Command ( ospi_PeriphId_t periphId, const ospi_Command_t * const command );
ospi_RequestState_t Ospi_Set_Read ( ospi_PeriphId_t periphId, const ospi_Command_t * const command, ospi_Data_t * const buffer );
ospi_RequestState_t Ospi_Set_Write ( ospi_PeriphId_t periphId, const ospi_Command_t * const command, const ospi_Data_t * const buffer );

ospi_RequestState_t Ospi_Set_AutoPolling ( ospi_PeriphId_t periphId, const ospi_Command_t * const command, const ospi_PollConfig_t * const pollConfig );

ospi_RequestState_t Ospi_Set_MemoryMapped ( ospi_PeriphId_t periphId, const ospi_MappedConfig_t * const mappedConfig );
ospi_RequestState_t Ospi_Set_MemoryMappedStop ( ospi_PeriphId_t periphId );
ospi_RequestState_t Ospi_Get_MappedBaseAddress ( ospi_PeriphId_t periphId, ospi_Address_t * const baseAddress );

ospi_RequestState_t Ospi_Set_Abort ( ospi_PeriphId_t periphId );
ospi_RequestState_t Ospi_Get_State ( ospi_PeriphId_t periphId, ospi_State_t * const ospiState );
ospi_RequestState_t Ospi_Get_XferError ( ospi_PeriphId_t periphId, ospi_XferError_t * const xferError );

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

TypeMeaning
ospi_Config_tInstance, kernel clock source, memory description and clock, transfer mode (OSPI_XFER_MODE_POLL / ISR / DMA), DMA channel and priority, pins, callbacks, interrupt priority
ospi_Command_tThe phases of a command (see above) and the data length
ospi_PollConfig_tMatch value, mask, match mode (AND / OR), the polling interval in clock cycles, the automatic stop, the timeout
ospi_MappedConfig_tRead command, write command, the timeout of the inactivity
ospi_State_tOSPI_STATE_IDLE, OSPI_STATE_BUSY, OSPI_STATE_POLLING, OSPI_STATE_MEMORY_MAPPED, OSPI_STATE_ERROR
ospi_XferError_tBit mask: transfer error, timeout, invalid command, FIFO error, DMA error
CallbacksXferCompleteCallback, PollCallback( result ), ErrorCallback

Usage​

Reading the identification of a NOR flash and switching to the memory-mapped quad read​

#include "Ospi_Port.h"

static ospi_Data_t jedecId[ 3u ];

ospi_Config_t ospiConfig;

(void)Ospi_Get_DefaultConfig( &ospiConfig );

ospiConfig.PeriphId = OSPI_PERIPH_1;
ospiConfig.Memory.Type = OSPI_MEMORY_STANDARD;
ospiConfig.Memory.SizeBytes = 16u * 1024u * 1024u; /* 128 Mbit */
ospiConfig.Memory.ClkFreq = 50000000u;
ospiConfig.XferMode = OSPI_XFER_MODE_DMA;
(void)Ospi_Init( &ospiConfig );

ospi_Address_t baseAddress = 0u;

const ospi_Command_t readId =
{
.Instruction = 0x9Fu, .InstructionMode = OSPI_LINES_1, .InstructionSize = OSPI_SIZE_8_BIT,
.DataMode = OSPI_LINES_1, .DataLength = 3u,
};

(void)Ospi_Set_Read( OSPI_PERIPH_1, &readId, jedecId ); /* the complete callback reports the end */

const ospi_MappedConfig_t mapped =
{
.ReadCommand = { .Instruction = 0xEBu, .InstructionMode = OSPI_LINES_1, .InstructionSize = OSPI_SIZE_8_BIT,
.AddressMode = OSPI_LINES_4, .AddressSize = OSPI_SIZE_24_BIT,
.DummyCycles = 6u, .DataMode = OSPI_LINES_4 },
};

(void)Ospi_Set_MemoryMapped( OSPI_PERIPH_1, &mapped );
(void)Ospi_Get_MappedBaseAddress( OSPI_PERIPH_1, &baseAddress ); /* the flash is read as the memory from baseAddress */

Waiting for the end of a programming by the automatic polling​

const ospi_Command_t readStatus =
{
.Instruction = 0x05u, .InstructionMode = OSPI_LINES_1, .InstructionSize = OSPI_SIZE_8_BIT,
.DataMode = OSPI_LINES_1, .DataLength = 1u,
};

const ospi_PollConfig_t waitReady =
{
.Match = 0x00u, .Mask = 0x01u, /* the WIP bit is cleared */
.MatchMode = OSPI_MATCH_AND, .Interval = 0x10u,
.TimeoutCycles = 500000u,
};

(void)Ospi_Set_AutoPolling( OSPI_PERIPH_1, &readStatus, &waitReady ); /* PollCallback( OSPI_POLL_MATCH ) */

Behaviour and limits​

  • Execute in place and writes. A flash cannot be read while it is being programmed or erased. The programming and the erase need the indirect mode, so the memory-mapped mode is stopped first and the code that runs from this flash must be running from the RAM or from another memory meanwhile. The memory driver on the top of the module takes care of it.
  • Clock and tuning. The memory clock is the kernel clock divided by the prescaler; the achieved frequency is read back. The double-rate and the high-frequency modes need the data strobe and the tuning of the sampling with the delay block (the Dlyb module); the module offers the modes that need the tuning only when it is available.
  • Memory-mapped writes and the chip select. The PSRAM / HyperRAM limit the time of a transaction (the chip-select low time); the maximum transfer in the configuration splits the long accesses. The refresh rate parameter applies to these memories.
  • Cache and the MPU. The window can be cacheable; the coherency of the data cache with the writes and the DMA, and the attributes of the region (the speculative accesses of the Cortex-M7 into the PSRAM window), are the task of the application (the Cache module, the MPU configuration).
  • Power. The clock of the interface and the memory are stopped when the interface is idle (the free running clock off); the timeout of the memory-mapped mode saves the power of the memory.
  • Not part of the first version: the commands of particular memories, the HSPI of STM32U5, the second memory on one instance beyond the dual-quad, the prefetch of the memory-mapped reads, the secure aliases of the registers.

Dependencies​

  • Rcc - peripheral clock, kernel clock source selection and frequency, reset
  • Nvic - interrupt of the instance
  • Gpio - clock, chip select, data strobe and data pins (the I/O manager mapping where the device has it)
  • Gpdma - DMA transfers of the indirect mode
  • Dlyb - the delay block for the sampling tuning of the high speed modes (a module of its own, planned)
  • RAL (Register Abstraction Layer) - used internally to access the registers

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


Testing​

  • Unit tests (host, Unity + CMock + RegMem): the clock prescaler calculation, the validation of the commands (lines, sizes, DTR, address range), the mapping of the command to the registers for every phase combination, the transfer flow in the POLL / ISR / DMA mode, the splitting of a long data phase, the automatic polling (match, timeout, abort), the memory-mapped start / stop and the rejected calls in the wrong mode, the error mapping.
  • Integration tests (target, probe-rs): the read of the identification, the erase - program - read back of a sector with the polling, the memory-mapped read compared with the indirect read, the execute-in-place of a test function, a PSRAM write / read pattern in the memory-mapped mode, the throughput measurement in every supported mode.

Interface conventions​

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

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

Repository layout and branches​

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

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

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


CMake integration​

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

License​

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

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

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


Authors​

Contributions are welcome! Please open a pull request.