SPI Flash API

Overview

The spi_flash component contains API functions related to reading, writing, erasing, memory mapping for data in the external flash. The spi_flash component also has higher-level API functions which work with partitions defined in the partition table.

Different from the API before IDF v4.0, the functionality is not limited to the “main” SPI flash chip (the same SPI flash chip from which program runs). With different chip pointers, you can access to external flashes chips on not only SPI0/1 but also HSPI/VSPI buses.

注解

Flash APIs after IDF v4.0 are no longer atomic. A writing operation during another on-going read operation, on the overlapped flash address, may cause the return data from the read operation to be partly same as before, and partly updated as new written.

Kconfig option CONFIG_SPI_FLASH_USE_LEGACY_IMPL can be used to switch spi_flash_* functions back to the implementation before IDF v4.0. However, the code size may get bigger if you use the new API and the old API the same time.

Encrypted reads and writes use the old implementation, even if CONFIG_SPI_FLASH_USE_LEGACY_IMPL is not enabled. As such, encrypted flash operations are only supported with the main flash chip (and not with other flash chips on SPI1 with different CS).

Initializing a flash device

To use esp_flash_* APIs, you need to have a chip initialized on a certain SPI bus.

  1. Call spi_bus_initialize() to properly initialize an SPI bus. This functions initialize the resources (I/O, DMA, interrupts) shared among devices attached to this bus.
  2. Call spi_bus_add_flash_device() to attach the flash device onto the bus. This allocates memory, and fill the members for the esp_flash_t structure. The CS I/O is also initialized here.
  3. Call esp_flash_init() to actually communicate with the chip. This will also detect the chip type, and influence the following operations.

注解

Multiple flash chips can be attached to the same bus now. However, using esp_flash_* devices and spi_device_* devices on the same SPI bus is not supported yet.

SPI flash access API

This is the set of API functions for working with data in flash:

Generally, try to avoid using the raw SPI flash functions to the “main” SPI flash chip in favour of partition-specific functions.

SPI Flash Size

The SPI flash size is configured by writing a field in the software bootloader image header, flashed at offset 0x1000.

By default, the SPI flash size is detected by esptool.py when this bootloader is written to flash, and the header is updated with the correct size. Alternatively, it is possible to generate a fixed flash size by setting CONFIG_ESPTOOLPY_FLASHSIZE in project configuration.

If it is necessary to override the configured flash size at runtime, it is possible to set the chip_size member of the g_rom_flashchip structure. This size is used by esp_flash_* functions (in both software & ROM) to check the bounds.

Concurrency Constraints for flash on SPI1

Because the SPI1 flash is also used for firmware execution via the instruction & data caches, these caches must be disabled while reading/writing/erasing. This means that both CPUs must be running code from IRAM and must only be reading data from DRAM while flash write operations occur.

If you use the API functions documented here, then these constraints are applied automatically and transparently. However, note that it will have some performance impact on other tasks in the system.

There are no such constraints and impacts for flash chips on other SPI buses than SPI0/1.

For differences between IRAM, DRAM, and flash cache, please refer to the application memory layout documentation.

To avoid reading flash cache accidentally, when one CPU initiates a flash write or erase operation, the other CPU is put into a blocked state, and all non-IRAM-safe interrupts are disabled on both CPUs until the flash operation completes.

If one CPU initiates a flash write or erase operation, the other CPU is put into a blocked state to avoid reading flash cache accidentally. All interrupts not safe for IRAM are disabled on both CPUs until the flash operation completes.

IRAM-Safe Interrupt Handlers

If you have an interrupt handler that you want to execute while a flash operation is in progress (for example, for low latency operations), set the ESP_INTR_FLAG_IRAM flag when the interrupt handler is registered.

You must ensure that all data and functions accessed by these interrupt handlers, including the ones that handlers call, are located in IRAM or DRAM.

Use the IRAM_ATTR attribute for functions:

#include "esp_attr.h"

void IRAM_ATTR gpio_isr_handler(void* arg)
{
    // ...
}

Use the DRAM_ATTR and DRAM_STR attributes for constant data:

void IRAM_ATTR gpio_isr_handler(void* arg)
{
   const static DRAM_ATTR uint8_t INDEX_DATA[] = { 45, 33, 12, 0 };
   const static char *MSG = DRAM_STR("I am a string stored in RAM");
}

Note that knowing which data should be marked with DRAM_ATTR can be hard, the compiler will sometimes recognize that a variable or expression is constant (even if it is not marked const) and optimize it into flash, unless it is marked with DRAM_ATTR.

If a function or symbol is not correctly put into IRAM/DRAM, and the interrupt handler reads from the flash cache during a flash operation, it will cause a crash due to Illegal Instruction exception (for code which should be in IRAM) or garbage data to be read (for constant data which should be in DRAM).

Partition table API

ESP-IDF projects use a partition table to maintain information about various regions of SPI flash memory (bootloader, various application binaries, data, filesystems). More information on partition tables can be found here.

This component provides API functions to enumerate partitions found in the partition table and perform operations on them. These functions are declared in esp_partition.h:

注解

Application code should mostly use these esp_partition_* API functions instead of lower level spi_flash_* API functions. Partition table API functions do bounds checking and calculate correct offsets in flash, based on data stored in a partition table.

SPI Flash Encryption

It is possible to encrypt the contents of SPI flash and have it transparently decrypted by hardware.

Refer to the Flash Encryption documentation for more details.

Memory mapping API

ESP32 features memory hardware which allows regions of flash memory to be mapped into instruction and data address spaces. This mapping works only for read operations. It is not possible to modify contents of flash memory by writing to a mapped memory region.

Mapping happens in 64KB pages. Memory mapping hardware can map up to four megabytes of flash into data address space and up to 16 megabytes of flash into instruction address space. See the technical reference manual for more details about memory mapping hardware.

Note that some 64KB pages are used to map the application itself into memory, so the actual number of available 64KB pages may be less.

Reading data from flash using a memory mapped region is the only way to decrypt contents of flash when flash encryption is enabled. Decryption is performed at the hardware level.

Memory mapping API are declared in esp_spi_flash.h and esp_partition.h:

  • spi_flash_mmap() maps a region of physical flash addresses into instruction space or data space of the CPU.
  • spi_flash_munmap() unmaps previously mapped region.
  • esp_partition_mmap() maps part of a partition into the instruction space or data space of the CPU.

Differences between spi_flash_mmap() and esp_partition_mmap() are as follows:

  • spi_flash_mmap() must be given a 64KB aligned physical address.
  • esp_partition_mmap() may be given any arbitrary offset within the partition, it will adjust the returned pointer to mapped memory as necessary

Note that since memory mapping happens in 64KB blocks, it may be possible to read data outside of the partition provided to esp_partition_mmap.

Implementation

The esp_flash_t structure holds chip data as well as three important parts of this API:

  1. The host driver, which provides the hardware support to access the chip;
  2. The chip driver, which provides compatibility service to different chips;
  3. The OS functions, provides support of some OS functions (e.g. lock, delay) in different stages (1st/2st boot, or the app).

Host driver

The host driver relies on an interface (spi_flash_host_driver_t) defined in the spi_flash_host_drv.h (in the soc/include/hal folder). This interface provides some common functions to communicate with the chip.

In other files of the SPI HAL, some of these functions are implemented with existing ESP32 memory-spi functionalities. However due to the speed limitations of ESP32, the HAL layer can’t provide high-speed implementations to some reading commands (So we didn’t do it at all). The files (memspi_host_driver.h and .c) implement the high-speed version of these commands with the common_command function provided in the HAL, and wrap these functions as spi_flash_host_driver_t for upper layer to use.

You can also implement your own host driver, even with the GPIO. As long as all the functions in the spi_flash_host_driver_t are implemented, the esp_flash API can access to the flash regardless of the low-level hardware.

Chip driver

The chip driver, defined in spi_flash_chip_driver.h, wraps basic functions provided by the host driver for the API layer to use.

Some operations need some commands to be sent first, or read some status after. Some chips need different command or value, or need special communication ways.

There is a type of chip called generic chip which stands for common chips. Other special chip drivers can be developed on the base of the generic chip.

The chip driver relies on the host driver.

OS functions

Currently the OS function layer provides a lock and a delay entries.

The lock is used to resolve the conflicts between the SPI chip access and other functions. E.g. the cache (used for the code and PSRAM data fetch) should be disabled when the flash chip on the SPI0/1 is being accessed. Also, some devices which don’t have CS wire, or the wire is controlled by the software (e.g. SD card via SPI interface), requires the bus to be monopolized during a period.

The delay is used by some long operations which requires the master to wait or polling periodically.

The top API wraps these the chip driver and OS functions into an entire component, and also provides some argument checking.

See also

Implementation details

In order to perform some flash operations, it is necessary to make sure that both CPUs are not running any code from flash for the duration of the flash operation: - In a single-core setup, the SDK does it by disabling interrupts/scheduler before performing the flash operation. - In a dual-core setup, this is slightly more complicated as the SDK needs to make sure that the other CPU is not running any code from flash.

When SPI flash API is called on CPU A (can be PRO or APP), start the spi_flash_op_block_func function on CPU B using the esp_ipc_call API. This API wakes up a high priority task on CPU B and tells it to execute a given function, in this case, spi_flash_op_block_func. This function disables cache on CPU B and signals that the cache is disabled by setting the s_flash_op_can_start flag. Then the task on CPU A disables cache as well and proceeds to execute flash operation.

While a flash operation is running, interrupts can still run on CPUs A and B. It is assumed that all interrupt code is placed into RAM. Once the interrupt allocation API is added, a flag should be added to request the interrupt to be disabled for the duration of a flash operations.

Once the flash operation is complete, the function on CPU A sets another flag, s_flash_op_complete, to let the task on CPU B know that it can re-enable cache and release the CPU. Then the function on CPU A re-enables the cache on CPU A as well and returns control to the calling code.

Additionally, all API functions are protected with a mutex (s_flash_op_mutex).

In a single core environment (CONFIG_FREERTOS_UNICORE enabled), you need to disable both caches, so that no inter-CPU communication can take place.

API Reference - SPI Flash

Functions

esp_err_t spi_bus_add_flash_device(esp_flash_t **out_chip, const esp_flash_spi_device_config_t *config)

Add a SPI Flash device onto the SPI bus.

The bus should be already initialized by spi_bus_initialization.

Return
  • ESP_ERR_INVALID_ARG: out_chip is NULL, or some field in the config is invalid.
  • ESP_ERR_NO_MEM: failed to allocate memory for the chip structures.
  • ESP_OK: success.
Parameters
  • out_chip: Pointer to hold the initialized chip.
  • config: Configuration of the chips to initialize.

esp_err_t spi_bus_remove_flash_device(esp_flash_t *chip)

Remove a SPI Flash device from the SPI bus.

Return
  • ESP_ERR_INVALID_ARG: The chip is invalid.
  • ESP_OK: success.
Parameters
  • chip: The flash device to remove.

Structures

struct esp_flash_spi_device_config_t

Configurations for the SPI Flash to init.

Public Members

spi_host_device_t host_id

Bus to use.

int cs_id

CS pin (signal) to use.

int cs_io_num

GPIO pin to output the CS signal.

esp_flash_read_mode_t io_mode

IO mode to read from the Flash.

esp_flash_speed_t speed

Speed of the Flash clock.

int input_delay_ns

Input delay of the data pins, in ns. Set to 0 if unknown.

Functions

esp_err_t esp_flash_init(esp_flash_t *chip)

Initialise SPI flash chip interface.

This function must be called before any other API functions are called for this chip.

Note
Only the host and read_mode fields of the chip structure must be initialised before this function is called. Other fields may be auto-detected if left set to zero or NULL.
Note
If the chip->drv pointer is NULL, chip chip_drv will be auto-detected based on its manufacturer & product IDs. See esp_flash_registered_flash_drivers pointer for details of this process.
Return
ESP_OK on success, or a flash error code if initialisation fails.
Parameters
  • chip: Pointer to SPI flash chip to use. If NULL, esp_flash_default_chip is substituted.

bool esp_flash_chip_driver_initialized(const esp_flash_t *chip)

Check if appropriate chip driver is set.

Return
true if set, otherwise false.
Parameters
  • chip: Pointer to SPI flash chip to use. If NULL, esp_flash_default_chip is substituted.

esp_err_t esp_flash_read_id(esp_flash_t *chip, uint32_t *out_id)

Read flash ID via the common “RDID” SPI flash command.

ID is a 24-bit value. Lower 16 bits of ‘id’ are the chip ID, upper 8 bits are the manufacturer ID.

Parameters
  • chip: Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
  • out_id: Pointer to receive ID value.

Return
ESP_OK on success, or a flash error code if operation failed.

esp_err_t esp_flash_get_size(esp_flash_t *chip, uint32_t *out_size)

Detect flash size based on flash ID.

Note
Most flash chips use a common format for flash ID, where the lower 4 bits specify the size as a power of 2. If the manufacturer doesn’t follow this convention, the size may be incorrectly detected.
Return
ESP_OK on success, or a flash error code if operation failed.
Parameters
  • chip: Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
  • out_size: Detected size in bytes.

esp_err_t esp_flash_erase_chip(esp_flash_t *chip)

Erase flash chip contents.

Return
ESP_OK on success, or a flash error code if operation failed.
Parameters
  • chip: Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()

esp_err_t esp_flash_erase_region(esp_flash_t *chip, uint32_t start, uint32_t len)

Erase a region of the flash chip.

Sector size is specifyed in chip->drv->sector_size field (typically 4096 bytes.) ESP_ERR_INVALID_ARG will be returned if the start & length are not a multiple of this size.

Parameters
  • chip: Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
  • start: Address to start erasing flash. Must be sector aligned.
  • len: Length of region to erase. Must also be sector aligned.

Erase is performed using block (multi-sector) erases where possible (block size is specified in chip->drv->block_erase_size field, typically 65536 bytes). Remaining sectors are erased using individual sector erase commands.

Return
ESP_OK on success, or a flash error code if operation failed.

esp_err_t esp_flash_get_chip_write_protect(esp_flash_t *chip, bool *write_protected)

Read if the entire chip is write protected.

Note
A correct result for this flag depends on the SPI flash chip model and chip_drv in use (via the ‘chip->drv’ field).
Return
ESP_OK on success, or a flash error code if operation failed.
Parameters
  • chip: Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
  • write_protected: Pointer to boolean, set to the value of the write protect flag.

esp_err_t esp_flash_set_chip_write_protect(esp_flash_t *chip, bool write_protect)

Set write protection for the SPI flash chip.

If write protection is enabled, destructive operations will fail with ESP_ERR_FLASH_PROTECTED.

Note
Correct behaviour of this function depends on the SPI flash chip model and chip_drv in use (via the ‘chip->drv’ field).
Parameters
  • chip: Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
  • write_protect: Boolean value for the write protect flag

Some SPI flash chips may require a power cycle before write protect status can be cleared. Otherwise, write protection can be removed via a follow-up call to this function.

Return
ESP_OK on success, or a flash error code if operation failed.

esp_err_t esp_flash_get_protectable_regions(const esp_flash_t *chip, const esp_flash_region_t **out_regions, uint32_t *out_num_regions)

Read the list of individually protectable regions of this SPI flash chip.

Note
Correct behaviour of this function depends on the SPI flash chip model and chip_drv in use (via the ‘chip->drv’ field).
Return
ESP_OK on success, or a flash error code if operation failed.
Parameters
  • chip: Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
  • out_regions: Pointer to receive a pointer to the array of protectable regions of the chip.
  • out_num_regions: Pointer to an integer receiving the count of protectable regions in the array returned in ‘regions’.

esp_err_t esp_flash_get_protected_region(esp_flash_t *chip, const esp_flash_region_t *region, bool *out_protected)

Detect if a region of the SPI flash chip is protected.

Note
It is possible for this result to be false and write operations to still fail, if protection is enabled for the entire chip.
Note
Correct behaviour of this function depends on the SPI flash chip model and chip_drv in use (via the ‘chip->drv’ field).
Return
ESP_OK on success, or a flash error code if operation failed.
Parameters
  • chip: Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
  • region: Pointer to a struct describing a protected region. This must match one of the regions returned from esp_flash_get_protectable_regions(…).
  • out_protected: Pointer to a flag which is set based on the protected status for this region.

esp_err_t esp_flash_set_protected_region(esp_flash_t *chip, const esp_flash_region_t *region, bool protect)

Update the protected status for a region of the SPI flash chip.

Note
It is possible for the region protection flag to be cleared and write operations to still fail, if protection is enabled for the entire chip.
Note
Correct behaviour of this function depends on the SPI flash chip model and chip_drv in use (via the ‘chip->drv’ field).
Return
ESP_OK on success, or a flash error code if operation failed.
Parameters
  • chip: Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
  • region: Pointer to a struct describing a protected region. This must match one of the regions returned from esp_flash_get_protectable_regions(…).
  • protect: Write protection flag to set.

esp_err_t esp_flash_read(esp_flash_t *chip, void *buffer, uint32_t address, uint32_t length)

Read data from the SPI flash chip.

There are no alignment constraints on buffer, address or length.

Parameters
  • chip: Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
  • buffer: Pointer to a buffer where the data will be read. To get better performance, this should be in the DRAM and word aligned.
  • address: Address on flash to read from. Must be less than chip->size field.
  • length: Length (in bytes) of data to read.

Note
If on-chip flash encryption is used, this function returns raw (ie encrypted) data. Use the flash cache to transparently decrypt data.
Return
  • ESP_OK: success
  • ESP_ERR_NO_MEM: the buffer is not valid, however failed to malloc on the heap.
  • or a flash error code if operation failed.

esp_err_t esp_flash_write(esp_flash_t *chip, const void *buffer, uint32_t address, uint32_t length)

Write data to the SPI flash chip.

There are no alignment constraints on buffer, address or length.

Parameters
  • chip: Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
  • address: Address on flash to write to. Must be previously erased (SPI NOR flash can only write bits 1->0).
  • buffer: Pointer to a buffer with the data to write. To get better performance, this should be in the DRAM and word aligned.
  • length: Length (in bytes) of data to write.

Return
ESP_OK on success, or a flash error code if operation failed.

esp_err_t esp_flash_write_encrypted(esp_flash_t *chip, uint32_t address, const void *buffer, uint32_t length)

Encrypted and write data to the SPI flash chip using on-chip hardware flash encryption.

Note
Both address & length must be 16 byte aligned, as this is the encryption block size
Return
ESP_OK on success, or a flash error code if operation failed.
Parameters
  • chip: Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
  • address: Address on flash to write to. 16 byte aligned. Must be previously erased (SPI NOR flash can only write bits 1->0).
  • buffer: Pointer to a buffer with the data to write.
  • length: Length (in bytes) of data to write. 16 byte aligned.

esp_err_t esp_flash_init_default_chip(void)

Initialise the default SPI flash chip.

Called by OS startup code. You do not need to call this in your own applications.

esp_err_t esp_flash_app_init(void)

Enable OS-level SPI flash protections in IDF

Called by OS startup code. You do not need to call this in your own applications.

Return
ESP_OK if success, otherwise failed. See return value of esp_flash_init_os_functions.

esp_err_t esp_flash_init_os_functions(esp_flash_t *chip, int host_id)

Enable OS-level SPI flash for a specific chip.

Return
  • ESP_OK if success
  • ESP_ERR_INVALID_ARG if host_id is invalid
Parameters
  • chip: The chip to init os functions.
  • host_id: Which SPI host to use, 1 for SPI1, 2 for SPI2 (HSPI), 3 for SPI3 (VSPI)

Structures

struct esp_flash_region_t

Structure for describing a region of flash.

Public Members

uint32_t offset

Start address of this region.

uint32_t size

Size of the region.

struct esp_flash_os_functions_t

OS-level integration hooks for accessing flash chips inside a running OS

Public Members

esp_err_t (*start)(void *arg)

Called before commencing any flash operation. Does not need to be recursive (ie is called at most once for each call to ‘end’).

esp_err_t (*end)(void *arg)

Called after completing any flash operation.

esp_err_t (*delay_ms)(void *arg, unsigned ms)

Delay for at least ‘ms’ milliseconds. Called in between ‘start’ and ‘end’.

struct esp_flash_t

Structure to describe a SPI flash chip connected to the system.

Structure must be initialized before use (passed to esp_flash_init()).

Public Members

spi_flash_host_driver_t *host

Pointer to hardware-specific “host_driver” structure. Must be initialized before used.

const spi_flash_chip_t *chip_drv

Pointer to chip-model-specific “adapter” structure. If NULL, will be detected during initialisation.

const esp_flash_os_functions_t *os_func

Pointer to os-specific hook structure. Call esp_flash_init_os_functions() to setup this field, after the host is properly initialized.

void *os_func_data

Pointer to argument for os-specific hooks. Left NULL and will be initialized with os_func.

esp_flash_read_mode_t read_mode

Configured SPI flash read mode. Set before esp_flash_init is called.

uint32_t size

Size of SPI flash in bytes. If 0, size will be detected during initialisation.

Type Definitions

typedef struct spi_flash_chip_t spi_flash_chip_t
typedef struct esp_flash_t esp_flash_t

Structures

struct spi_flash_trans_t

Definition of a common transaction. Also holds the return value.

Public Members

uint8_t command

Command to send, always 8bits.

uint8_t mosi_len

Output data length, in bits.

uint8_t miso_len

Input data length, in bits.

uint32_t mosi_data

Output data to slave.

uint32_t miso_data[2]

[out] Input data from slave, little endian

struct spi_flash_host_driver_t

Host driver configuration and context structure.

Public Members

void *driver_data

Configuration and static data used by the specific host driver. The type is determined by the host driver.

esp_err_t (*dev_config)(spi_flash_host_driver_t *driver)

Configure the device-related register before transactions. This saves some time to re-configure those registers when we send continuously

esp_err_t (*common_command)(spi_flash_host_driver_t *driver, spi_flash_trans_t *t)

Send an user-defined spi transaction to the device.

esp_err_t (*read_id)(spi_flash_host_driver_t *driver, uint32_t *id)

Read flash ID.

void (*erase_chip)(spi_flash_host_driver_t *driver)

Erase whole flash chip.

void (*erase_sector)(spi_flash_host_driver_t *driver, uint32_t start_address)

Erase a specific sector by its start address.

void (*erase_block)(spi_flash_host_driver_t *driver, uint32_t start_address)

Erase a specific block by its start address.

esp_err_t (*read_status)(spi_flash_host_driver_t *driver, uint8_t *out_sr)

Read the status of the flash chip.

esp_err_t (*set_write_protect)(spi_flash_host_driver_t *driver, bool wp)

Disable write protection.

void (*program_page)(spi_flash_host_driver_t *driver, const void *buffer, uint32_t address, uint32_t length)

Program a page of the flash. Check max_write_bytes for the maximum allowed writing length.

bool (*supports_direct_write)(spi_flash_host_driver_t *driver, const void *p)

Check whether need to allocate new buffer to write

bool (*supports_direct_read)(spi_flash_host_driver_t *driver, const void *p)

Check whether need to allocate new buffer to read

int max_write_bytes

maximum length of program_page

esp_err_t (*read)(spi_flash_host_driver_t *driver, void *buffer, uint32_t address, uint32_t read_len)

Read data from the flash. Check max_read_bytes for the maximum allowed reading length.

int max_read_bytes

maximum length of read

bool (*host_idle)(spi_flash_host_driver_t *driver)

Check whether the host is idle to perform new operations.

esp_err_t (*configure_host_read_mode)(spi_flash_host_driver_t *driver, esp_flash_read_mode_t read_mode, uint32_t addr_bitlen, uint32_t dummy_bitlen_base, uint32_t read_command)

Configure the host to work at different read mode.

void (*poll_cmd_done)(spi_flash_host_driver_t *driver)

Internal use, poll the HW until the last operation is done.

esp_err_t (*flush_cache)(spi_flash_host_driver_t *driver, uint32_t addr, uint32_t size)

For some host (SPI1), they are shared with a cache. When the data is modified, the cache needs to be flushed. Left NULL if not supported.

bool (*region_protected)(spi_flash_host_driver_t *driver, uint32_t addr, uint32_t size)

Check if the given region is protected (e.g. is the bootloader). Left NULL if current host doesn’t need protection.

Macros

ESP_FLASH_SPEED_MIN

Lowest speed supported by the driver, currently 5 MHz.

SPI_FLASH_READ_MODE_MIN

Slowest io mode supported by ESP32, currently SlowRd.

Type Definitions

typedef struct spi_flash_host_driver_t spi_flash_host_driver_t

Enumerations

enum esp_flash_speed_t

SPI flash clock speed values, always refer to them by the enum rather than the actual value (more speed may be appended into the list).

A strategy to select the maximum allowed speed is to enumerate from the ESP_FLSH_SPEED_MAX-1 or highest frequency supported by your flash, and decrease the speed until the probing success.

Values:

ESP_FLASH_5MHZ = 0

The flash runs under 5MHz.

ESP_FLASH_10MHZ

The flash runs under 10MHz.

ESP_FLASH_20MHZ

The flash runs under 20MHz.

ESP_FLASH_26MHZ

The flash runs under 26MHz.

ESP_FLASH_40MHZ

The flash runs under 40MHz.

ESP_FLASH_80MHZ

The flash runs under 80MHz.

ESP_FLASH_SPEED_MAX

The maximum frequency supported by the host is ESP_FLASH_SPEED_MAX-1.

enum esp_flash_read_mode_t

Mode used for reading from SPI flash.

Values:

SPI_FLASH_SLOWRD = 0

Data read using single I/O, some limits on speed.

SPI_FLASH_FASTRD

Data read using single I/O, no limit on speed.

SPI_FLASH_DOUT

Data read using dual I/O.

SPI_FLASH_DIO

Both address & data transferred using dual I/O.

SPI_FLASH_QOUT

Data read using quad I/O.

SPI_FLASH_QIO

Both address & data transferred using quad I/O.

SPI_FLASH_READ_MODE_MAX

The fastest io mode supported by the host is ESP_FLASH_READ_MODE_MAX-1.

API Reference - Partition Table

Functions

esp_partition_iterator_t esp_partition_find(esp_partition_type_t type, esp_partition_subtype_t subtype, const char *label)

Find partition based on one or more parameters.

Return
iterator which can be used to enumerate all the partitions found, or NULL if no partitions were found. Iterator obtained through this function has to be released using esp_partition_iterator_release when not used any more.
Parameters
  • type: Partition type, one of esp_partition_type_t values
  • subtype: Partition subtype, one of esp_partition_subtype_t values. To find all partitions of given type, use ESP_PARTITION_SUBTYPE_ANY.
  • label: (optional) Partition label. Set this value if looking for partition with a specific name. Pass NULL otherwise.

const esp_partition_t *esp_partition_find_first(esp_partition_type_t type, esp_partition_subtype_t subtype, const char *label)

Find first partition based on one or more parameters.

Return
pointer to esp_partition_t structure, or NULL if no partition is found. This pointer is valid for the lifetime of the application.
Parameters
  • type: Partition type, one of esp_partition_type_t values
  • subtype: Partition subtype, one of esp_partition_subtype_t values. To find all partitions of given type, use ESP_PARTITION_SUBTYPE_ANY.
  • label: (optional) Partition label. Set this value if looking for partition with a specific name. Pass NULL otherwise.

const esp_partition_t *esp_partition_get(esp_partition_iterator_t iterator)

Get esp_partition_t structure for given partition.

Return
pointer to esp_partition_t structure. This pointer is valid for the lifetime of the application.
Parameters
  • iterator: Iterator obtained using esp_partition_find. Must be non-NULL.

esp_partition_iterator_t esp_partition_next(esp_partition_iterator_t iterator)

Move partition iterator to the next partition found.

Any copies of the iterator will be invalid after this call.

Return
NULL if no partition was found, valid esp_partition_iterator_t otherwise.
Parameters
  • iterator: Iterator obtained using esp_partition_find. Must be non-NULL.

void esp_partition_iterator_release(esp_partition_iterator_t iterator)

Release partition iterator.

Parameters
  • iterator: Iterator obtained using esp_partition_find. Must be non-NULL.

const esp_partition_t *esp_partition_verify(const esp_partition_t *partition)

Verify partition data.

Given a pointer to partition data, verify this partition exists in the partition table (all fields match.)

This function is also useful to take partition data which may be in a RAM buffer and convert it to a pointer to the permanent partition data stored in flash.

Pointers returned from this function can be compared directly to the address of any pointer returned from esp_partition_get(), as a test for equality.

Return
  • If partition not found, returns NULL.
  • If found, returns a pointer to the esp_partition_t structure in flash. This pointer is always valid for the lifetime of the application.
Parameters
  • partition: Pointer to partition data to verify. Must be non-NULL. All fields of this structure must match the partition table entry in flash for this function to return a successful match.

esp_err_t esp_partition_read(const esp_partition_t *partition, size_t src_offset, void *dst, size_t size)

Read data from the partition.

Return
ESP_OK, if data was read successfully; ESP_ERR_INVALID_ARG, if src_offset exceeds partition size; ESP_ERR_INVALID_SIZE, if read would go out of bounds of the partition; or one of error codes from lower-level flash driver.
Parameters
  • partition: Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL.
  • dst: Pointer to the buffer where data should be stored. Pointer must be non-NULL and buffer must be at least ‘size’ bytes long.
  • src_offset: Address of the data to be read, relative to the beginning of the partition.
  • size: Size of data to be read, in bytes.

esp_err_t esp_partition_write(const esp_partition_t *partition, size_t dst_offset, const void *src, size_t size)

Write data to the partition.

Before writing data to flash, corresponding region of flash needs to be erased. This can be done using esp_partition_erase_range function.

Partitions marked with an encryption flag will automatically be written via the spi_flash_write_encrypted() function. If writing to an encrypted partition, all write offsets and lengths must be multiples of 16 bytes. See the spi_flash_write_encrypted() function for more details. Unencrypted partitions do not have this restriction.

Note
Prior to writing to flash memory, make sure it has been erased with esp_partition_erase_range call.
Return
ESP_OK, if data was written successfully; ESP_ERR_INVALID_ARG, if dst_offset exceeds partition size; ESP_ERR_INVALID_SIZE, if write would go out of bounds of the partition; or one of error codes from lower-level flash driver.
Parameters
  • partition: Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL.
  • dst_offset: Address where the data should be written, relative to the beginning of the partition.
  • src: Pointer to the source buffer. Pointer must be non-NULL and buffer must be at least ‘size’ bytes long.
  • size: Size of data to be written, in bytes.

esp_err_t esp_partition_erase_range(const esp_partition_t *partition, size_t offset, size_t size)

Erase part of the partition.

Return
ESP_OK, if the range was erased successfully; ESP_ERR_INVALID_ARG, if iterator or dst are NULL; ESP_ERR_INVALID_SIZE, if erase would go out of bounds of the partition; or one of error codes from lower-level flash driver.
Parameters
  • partition: Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL.
  • offset: Offset from the beginning of partition where erase operation should start. Must be aligned to 4 kilobytes.
  • size: Size of the range which should be erased, in bytes. Must be divisible by 4 kilobytes.

esp_err_t esp_partition_mmap(const esp_partition_t *partition, size_t offset, size_t size, spi_flash_mmap_memory_t memory, const void **out_ptr, spi_flash_mmap_handle_t *out_handle)

Configure MMU to map partition into data memory.

Unlike spi_flash_mmap function, which requires a 64kB aligned base address, this function doesn’t impose such a requirement. If offset results in a flash address which is not aligned to 64kB boundary, address will be rounded to the lower 64kB boundary, so that mapped region includes requested range. Pointer returned via out_ptr argument will be adjusted to point to the requested offset (not necessarily to the beginning of mmap-ed region).

To release mapped memory, pass handle returned via out_handle argument to spi_flash_munmap function.

Return
ESP_OK, if successful
Parameters
  • partition: Pointer to partition structure obtained using esp_partition_find_first or esp_partition_get. Must be non-NULL.
  • offset: Offset from the beginning of partition where mapping should start.
  • size: Size of the area to be mapped.
  • memory: Memory space where the region should be mapped
  • out_ptr: Output, pointer to the mapped memory region
  • out_handle: Output, handle which should be used for spi_flash_munmap call

esp_err_t esp_partition_get_sha256(const esp_partition_t *partition, uint8_t *sha_256)

Get SHA-256 digest for required partition.

For apps with SHA-256 appended to the app image, the result is the appended SHA-256 value for the app image content. The hash is verified before returning, if app content is invalid then the function returns ESP_ERR_IMAGE_INVALID. For apps without SHA-256 appended to the image, the result is the SHA-256 of all bytes in the app image. For other partition types, the result is the SHA-256 of the entire partition.

Return
  • ESP_OK: In case of successful operation.
  • ESP_ERR_INVALID_ARG: The size was 0 or the sha_256 was NULL.
  • ESP_ERR_NO_MEM: Cannot allocate memory for sha256 operation.
  • ESP_ERR_IMAGE_INVALID: App partition doesn’t contain a valid app image.
  • ESP_FAIL: An allocation error occurred.
Parameters
  • partition: Pointer to info for partition containing app or data. (fields: address, size and type, are required to be filled).
  • sha_256: Returned SHA-256 digest for a given partition.

bool esp_partition_check_identity(const esp_partition_t *partition_1, const esp_partition_t *partition_2)

Check for the identity of two partitions by SHA-256 digest.

Return
  • True: In case of the two firmware is equal.
  • False: Otherwise
Parameters
  • partition_1: Pointer to info for partition 1 containing app or data. (fields: address, size and type, are required to be filled).
  • partition_2: Pointer to info for partition 2 containing app or data. (fields: address, size and type, are required to be filled).

esp_err_t esp_partition_register_external(esp_flash_t *flash_chip, size_t offset, size_t size, const char *label, esp_partition_type_t type, esp_partition_subtype_t subtype, const esp_partition_t **out_partition)

Register a partition on an external flash chip.

This API allows designating certain areas of external flash chips (identified by the esp_flash_t structure) as partitions. This allows using them with components which access SPI flash through the esp_partition API.

Return
  • ESP_OK on success
  • ESP_ERR_NOT_SUPPORTED if CONFIG_CONFIG_SPI_FLASH_USE_LEGACY_IMPL is enabled
  • ESP_ERR_NO_MEM if memory allocation has failed
  • ESP_ERR_INVALID_ARG if the new partition overlaps another partition on the same flash chip
  • ESP_ERR_INVALID_SIZE if the partition doesn’t fit into the flash chip size
Parameters
  • flash_chip: Pointer to the structure identifying the flash chip
  • offset: Address in bytes, where the partition starts
  • size: Size of the partition in bytes
  • label: Partition name
  • type: One of the partition types (ESP_PARTITION_TYPE_*). Note that applications can not be booted from external flash chips, so using ESP_PARTITION_TYPE_APP is not supported.
  • subtype: One of the partition subtypes (ESP_PARTITION_SUBTYPE_*)
  • out_partition: Output, if non-NULL, receives the pointer to the resulting esp_partition_t structure

esp_err_t esp_partition_deregister_external(const esp_partition_t *partition)

Deregister the partition previously registered using esp_partition_register_external.

Return
  • ESP_OK on success
  • ESP_ERR_NOT_FOUND if the partition pointer is not found
  • ESP_ERR_INVALID_ARG if the partition comes from the partition table
  • ESP_ERR_INVALID_ARG if the partition was not registered using esp_partition_register_external function.
Parameters
  • partition: pointer to the partition structure obtained from esp_partition_register_external,

Structures

struct esp_partition_t

partition information structure

This is not the format in flash, that format is esp_partition_info_t.

However, this is the format used by this API.

Public Members

esp_flash_t *flash_chip

SPI flash chip on which the partition resides

esp_partition_type_t type

partition type (app/data)

esp_partition_subtype_t subtype

partition subtype

uint32_t address

starting address of the partition in flash

uint32_t size

size of the partition, in bytes

char label[17]

partition label, zero-terminated ASCII string

bool encrypted

flag is set to true if partition is encrypted

Macros

ESP_PARTITION_SUBTYPE_OTA(i)

Convenience macro to get esp_partition_subtype_t value for the i-th OTA partition.

Type Definitions

typedef struct esp_partition_iterator_opaque_ *esp_partition_iterator_t

Opaque partition iterator type.

Enumerations

enum esp_partition_type_t

Partition type.

Note
Keep this enum in sync with PartitionDefinition class gen_esp32part.py

Values:

ESP_PARTITION_TYPE_APP = 0x00

Application partition type.

ESP_PARTITION_TYPE_DATA = 0x01

Data partition type.

enum esp_partition_subtype_t

Partition subtype.

Note
Keep this enum in sync with PartitionDefinition class gen_esp32part.py

Values:

ESP_PARTITION_SUBTYPE_APP_FACTORY = 0x00

Factory application partition.

ESP_PARTITION_SUBTYPE_APP_OTA_MIN = 0x10

Base for OTA partition subtypes.

ESP_PARTITION_SUBTYPE_APP_OTA_0 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 0

OTA partition 0.

ESP_PARTITION_SUBTYPE_APP_OTA_1 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 1

OTA partition 1.

ESP_PARTITION_SUBTYPE_APP_OTA_2 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 2

OTA partition 2.

ESP_PARTITION_SUBTYPE_APP_OTA_3 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 3

OTA partition 3.

ESP_PARTITION_SUBTYPE_APP_OTA_4 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 4

OTA partition 4.

ESP_PARTITION_SUBTYPE_APP_OTA_5 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 5

OTA partition 5.

ESP_PARTITION_SUBTYPE_APP_OTA_6 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 6

OTA partition 6.

ESP_PARTITION_SUBTYPE_APP_OTA_7 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 7

OTA partition 7.

ESP_PARTITION_SUBTYPE_APP_OTA_8 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 8

OTA partition 8.

ESP_PARTITION_SUBTYPE_APP_OTA_9 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 9

OTA partition 9.

ESP_PARTITION_SUBTYPE_APP_OTA_10 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 10

OTA partition 10.

ESP_PARTITION_SUBTYPE_APP_OTA_11 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 11

OTA partition 11.

ESP_PARTITION_SUBTYPE_APP_OTA_12 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 12

OTA partition 12.

ESP_PARTITION_SUBTYPE_APP_OTA_13 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 13

OTA partition 13.

ESP_PARTITION_SUBTYPE_APP_OTA_14 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 14

OTA partition 14.

ESP_PARTITION_SUBTYPE_APP_OTA_15 = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 15

OTA partition 15.

ESP_PARTITION_SUBTYPE_APP_OTA_MAX = ESP_PARTITION_SUBTYPE_APP_OTA_MIN + 16

Max subtype of OTA partition.

ESP_PARTITION_SUBTYPE_APP_TEST = 0x20

Test application partition.

ESP_PARTITION_SUBTYPE_DATA_OTA = 0x00

OTA selection partition.

ESP_PARTITION_SUBTYPE_DATA_PHY = 0x01

PHY init data partition.

ESP_PARTITION_SUBTYPE_DATA_NVS = 0x02

NVS partition.

ESP_PARTITION_SUBTYPE_DATA_COREDUMP = 0x03

COREDUMP partition.

ESP_PARTITION_SUBTYPE_DATA_NVS_KEYS = 0x04

Partition for NVS keys.

ESP_PARTITION_SUBTYPE_DATA_EFUSE_EM = 0x05

Partition for emulate eFuse bits.

ESP_PARTITION_SUBTYPE_DATA_ESPHTTPD = 0x80

ESPHTTPD partition.

ESP_PARTITION_SUBTYPE_DATA_FAT = 0x81

FAT partition.

ESP_PARTITION_SUBTYPE_DATA_SPIFFS = 0x82

SPIFFS partition.

ESP_PARTITION_SUBTYPE_ANY = 0xff

Used to search for partitions with any subtype.

API Reference - Flash Encrypt

Functions

static bool esp_flash_encryption_enabled(void)

Is flash encryption currently enabled in hardware?

Flash encryption is enabled if the FLASH_CRYPT_CNT efuse has an odd number of bits set.

Return
true if flash encryption is enabled.

esp_err_t esp_flash_encrypt_check_and_update(void)
esp_err_t esp_flash_encrypt_region(uint32_t src_addr, size_t data_length)

Encrypt-in-place a block of flash sectors.

Note
This function resets RTC_WDT between operations with sectors.
Return
ESP_OK if all operations succeeded, ESP_ERR_FLASH_OP_FAIL if SPI flash fails, ESP_ERR_FLASH_OP_TIMEOUT if flash times out.
Parameters
  • src_addr: Source offset in flash. Should be multiple of 4096 bytes.
  • data_length: Length of data to encrypt in bytes. Will be rounded up to next multiple of 4096 bytes.

void esp_flash_write_protect_crypt_cnt(void)

Write protect FLASH_CRYPT_CNT.

Intended to be called as a part of boot process if flash encryption is enabled but secure boot is not used. This should protect against serial re-flashing of an unauthorised code in absence of secure boot.

esp_flash_enc_mode_t esp_get_flash_encryption_mode(void)

Return the flash encryption mode.

The API is called during boot process but can also be called by application to check the current flash encryption mode of ESP32

Return

Enumerations

enum esp_flash_enc_mode_t

Values:

ESP_FLASH_ENC_MODE_DISABLED
ESP_FLASH_ENC_MODE_DEVELOPMENT
ESP_FLASH_ENC_MODE_RELEASE