From ce4de867d61c042fd08137088218ff54dcc4809d Mon Sep 17 00:00:00 2001 From: Angus Gratton Date: Wed, 24 May 2017 12:35:12 +1000 Subject: [PATCH] spi_flash: New low-level flash API --- components/esp32/cpu_start.c | 5 +- .../spi_flash/include/spi_flash_lowlevel.h | 265 +++++++++ .../include/spi_flash_lowlevel_driver.h | 176 ++++++ .../include/spi_flash_lowlevel_generic.h | 151 +++++ components/spi_flash/linker.lf | 7 +- components/spi_flash/spi_flash_lowlevel_api.c | 552 ++++++++++++++++++ .../spi_flash/spi_flash_lowlevel_driver.c | 34 ++ .../spi_flash/spi_flash_lowlevel_generic.c | 498 ++++++++++++++++ .../spi_flash/spi_flash_lowlevel_idf_app.c | 60 ++ .../spi_flash/spi_flash_lowlevel_issi.c | 74 +++ .../spi_flash/spi_flash_lowlevel_noos.c | 51 ++ components/spi_flash/test/test_low_level.c | 181 ++++++ 12 files changed, 2052 insertions(+), 2 deletions(-) create mode 100644 components/spi_flash/include/spi_flash_lowlevel.h create mode 100644 components/spi_flash/include/spi_flash_lowlevel_driver.h create mode 100644 components/spi_flash/include/spi_flash_lowlevel_generic.h create mode 100644 components/spi_flash/spi_flash_lowlevel_api.c create mode 100644 components/spi_flash/spi_flash_lowlevel_driver.c create mode 100644 components/spi_flash/spi_flash_lowlevel_generic.c create mode 100644 components/spi_flash/spi_flash_lowlevel_idf_app.c create mode 100644 components/spi_flash/spi_flash_lowlevel_issi.c create mode 100644 components/spi_flash/spi_flash_lowlevel_noos.c create mode 100644 components/spi_flash/test/test_low_level.c diff --git a/components/esp32/cpu_start.c b/components/esp32/cpu_start.c index e8e1100993..266c7f5e30 100644 --- a/components/esp32/cpu_start.c +++ b/components/esp32/cpu_start.c @@ -43,6 +43,7 @@ #include "sdkconfig.h" #include "esp_system.h" #include "esp_spi_flash.h" +#include "spi_flash_lowlevel.h" #include "nvs_flash.h" #include "esp_event.h" #include "esp_spi_flash.h" @@ -388,6 +389,9 @@ void start_cpu0_default(void) spi_flash_init(); /* init default OS-aware flash access critical section */ spi_flash_guard_set(&g_flash_guard_default_ops); + /* Todo the following needs to be properly integrated */ + esp_flash_low_level_app_init(); + esp_flash_init_default_chip(); #ifdef CONFIG_PM_ENABLE esp_pm_impl_init(); #ifdef CONFIG_PM_DFS_INIT_AUTO @@ -399,7 +403,6 @@ void start_cpu0_default(void) esp_pm_configure(&cfg); #endif //CONFIG_PM_DFS_INIT_AUTO #endif //CONFIG_PM_ENABLE - #if CONFIG_ESP32_ENABLE_COREDUMP esp_core_dump_init(); size_t core_data_sz = 0; diff --git a/components/spi_flash/include/spi_flash_lowlevel.h b/components/spi_flash/include/spi_flash_lowlevel.h new file mode 100644 index 0000000000..0b4ebf9a31 --- /dev/null +++ b/components/spi_flash/include/spi_flash_lowlevel.h @@ -0,0 +1,265 @@ +#pragma once +#include +#include + +#include "soc/spi_struct.h" + +struct esp_flash_driver; + +/** @brief Mode used for reading from SPI flash */ +typedef enum { + ESP_FLASH_QIO, ///< Both address & data transferred using quad I/O + ESP_FLASH_QOUT, ///< Data read using quad I/O + ESP_FLASH_DIO, ///< Both address & data transferred using dual I/O + ESP_FLASH_DOUT, ///< Data read using dual I/O + ESP_FLASH_FASTRD, ///< Data read using single I/O, no limit on speed + ESP_FLASH_SLOWRD, ///< Data read using single I/O, some limits on speed + + ESP_FLASH_READ_MODE_MAX, +} esp_flash_read_mode_t; + +/** @brief Configured SPI flash clock speed */ +typedef enum { + ESP_FLASH_80MHZ, + ESP_FLASH_40MHZ, + ESP_FLASH_26MHZ, + ESP_FLASH_20MHZ, + ESP_FLASH_SPEED_MAX, +} esp_flash_speed_t; + +/** @brief Structure for describing a region of flash */ +typedef struct { + uint32_t offset; + uint32_t size; +} esp_flash_region_t; + +// TODO this is copied from SPI driver, should be unified somehow +typedef struct { + int mosi_io_num; ///< GPIO pin for Master Out Slave In (=spi_d) signal + int miso_io_num; ///< GPIO pin for Master In Slave Out (=spi_q) signal + int sclk_io_num; ///< GPIO pin for Spi CLocK signal + int quadwp_io_num; ///< GPIO pin for WP (Write Protect) signal which is used as D2 in 4-bit communication modes, or -1 if not used. + int quadhd_io_num; ///< GPIO pin for HD (HolD) signal which is used as D3 in 4-bit communication modes, or -1 if not used. +} esp_flash_pin_cfg_t; + +/** @brief Structure to describe a SPI flash chip connected to the system. + + Structure must be passed to esp_flash_init() before use. +*/ +typedef struct { + spi_dev_t *spi; ///< Pointer to hardware SPI bus registers used for connection (SP1, SPI2 or SPI3). Set before initialisation. + esp_flash_speed_t speed; ///< Configured SPI flash clock speed. Set before initialisation. + esp_flash_read_mode_t read_mode; ///< Configured SPI flash read mode. Set before initialisation. + uint32_t size; ///< Size of SPI flash in bytes. If 0, size will be detected during initialisation. + const struct esp_flash_driver *drv; ///< Pointer to chip-model-specific "driver" structure. If NULL, will be detected during initialisatiopn. + const esp_flash_pin_cfg_t *pins; ///< Pin configuration for the chip + + void *driver_data; ///< Currently unused, allows drivers to store driver-implementation-specific data on initialisation +} esp_flash_chip_t; + +/** @brief Possible errors returned from SPI flash low-level API */ +typedef enum { + FLASH_OK = 0, ///< Success + FLASH_ERR_NOT_INITIALISED, ///< esp_flash_chip_t structure not correctly initialised by esp_flash_init(). + FLASH_ERR_INVALID_ARG, ///< A supplied argument was invalid. + FLASH_ERR_NOT_FOUND, ///< A requested value is not found. + FLASH_ERR_NO_RESPONSE, ///< Chip did not respond to the command, or timed out. + FLASH_ERR_UNSUPPORTED_HOST, ///< Requested operation isn't supported via this host SPI bus (chip->spi field). + FLASH_ERR_UNSUPPORTED_CHIP, ///< Requested operation isn't supported by this model of SPI flash chip. + FLASH_ERR_PROTECTED, ///< Write operation failed due to chip's write protection being enabled. +} esp_flash_err_t; + +/** @brief Initialise SPI flash chip interface. + * + * This function must be called before any other API functions are called for this chip. + * + * @note Only the spi, speed & read_mode fields of the chip structure need to be initialised. Other fields will be auto-detected + * if left set to zero or NULL. + * + * @note If the chip->drv pointer is NULL, chip driver will be autodetected based on its manufacturer & product IDs. See + * esp_flash_registered_flash_drivers pointer for details of this process. + * + * @param chip Pointer to SPI flash chip to use. If NULL, esp_flash_default_chip is substituted. + * @return FLASH_OK on success, or a flash error code if initialisation fails. + */ +esp_flash_err_t esp_flash_init(esp_flash_chip_t *chip); + +/** @brief Read flash ID via the common "RDID" SPI flash command. + * + * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() + * @param[out] Pointer to receive ID value. + * + * ID is a 24-bit value. Lower 16 bits of 'id' are the chip ID, upper 8 bits are the manufacturer ID. + * + * @return FLASH_OK on success, or a flash error code if operation failed. + */ +esp_flash_err_t esp_flash_read_id(const esp_flash_chip_t *chip, uint32_t *id); + +/** @brief Detect flash size based on flash ID. + * + * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() + * @param[out] Detected size in bytes. + * + * @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 FLASH_OK on success, or a flash error code if operation failed. + */ +esp_flash_err_t esp_flash_detect_size(const esp_flash_chip_t *chip, uint32_t *size); + +/** @brief Erase flash chip contents + * + * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() + * + * + * @return FLASH_OK on success, or a flash error code if operation failed. + */ +esp_flash_err_t esp_flash_erase_chip(const esp_flash_chip_t *chip); + +/** @brief Erase a region of the flash chip + * + * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() + * @param start Address to start erasing flash. Must be sector aligned. + * @param len Length of region to erase. Must also be sector aligned. + * + * Sector size is specifyed in chip->drv->sector_size field (typically 4096 bytes.) FLASH_ERR_INVALID_ARG will be + * returned if the start & length are not a multiple of this size. + * + * 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 FLASH_OK on success, or a flash error code if operation failed. + */ +esp_flash_err_t esp_flash_erase_region(const esp_flash_chip_t *chip, uint32_t start, uint32_t len); + +/** @brief Read if the entire chip is write protected + * + * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() + * @param[out] write_protected Pointer to boolean, set to the value of the write protect flag. + * + * @note A correct result for this flag depends on the SPI flash chip model and driver in use (via the 'chip->drv' + * field). + * + * @return FLASH_OK on success, or a flash error code if operation failed. + */ +esp_flash_err_t esp_flash_get_chip_write_protect(const esp_flash_chip_t *chip, bool *write_protected); + +/** @brief Set write protection for the SPI flash chip + * + * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() + * @param write_protected Boolean value for the write protect flag + * + * @note Correct behaviour of this function depends on the SPI flash chip model and driver in use (via the 'chip->drv' + * field). + * + * If write protection is enabled, destructive operations will fail with FLASH_ERR_PROTECTED. + * + * 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 FLASH_OK on success, or a flash error code if operation failed. + */ +esp_flash_err_t esp_flash_set_chip_write_protect(const esp_flash_chip_t *chip, bool write_protect_chip); + + +/** @brief Read the list of individually protectable regions of this SPI flash chip. + * + * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() + * @param regions[out] Pointer to receive a pointer to the array of protectable regions of the chip. + * @param[out] Pointer to an integer receiving the count of protectable regions in the array returned in 'regions'. + * + * @note Correct behaviour of this function depends on the SPI flash chip model and driver in use (via the 'chip->drv' + * field). + * + * @return FLASH_OK on success, or a flash error code if operation failed. + */ +esp_flash_err_t esp_flash_get_protectable_regions(const esp_flash_chip_t *chip, const esp_flash_region_t **regions, uint32_t *num_regions); + + +/** @brief Detect if a region of the SPI flash chip is protected + * + * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() + * @param region Pointer to a struct describing a protected region. This must match one of the regions returned from esp_flash_get_protectable_regions(...). + * @param[out] protected Pointer to a flag which is set based on the protected status for this region. + * + * @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 driver in use (via the 'chip->drv' + * field). + * + * @return FLASH_OK on success, or a flash error code if operation failed. + */ +esp_flash_err_t esp_flash_get_protected_region(const esp_flash_chip_t *chip, const esp_flash_region_t *region, bool *protected); + +/** @brief Update the protected status for a region of the SPI flash chip + * + * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() + * @param region Pointer to a struct describing a protected region. This must match one of the regions returned from esp_flash_get_protectable_regions(...). + * @param protected Write protection flag to set. + * + * @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 driver in use (via the 'chip->drv' + * field). + * + * @return FLASH_OK on success, or a flash error code if operation failed. + */ +esp_flash_err_t esp_flash_set_protected_region(const esp_flash_chip_t *chip, const esp_flash_region_t *region, bool protected); + +/** @brief Read data from the SPI flash chip + * + * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() + * @param buffer Pointer to a buffer where the data will be read. + * @param address Address on flash to read from. Must be less than chip->size field. + * @param length Length (in bytes) of data to read. + * + * There are no alignment constraints on buffer, address or length. + * + * @note If on-chip flash encryption is used, this function returns raw (ie encrypted) data. Use the flash cache + * to transparently decrypt data. + * + * @return FLASH_OK on success, or a flash error code if operation failed. + */ +esp_flash_err_t esp_flash_read(const esp_flash_chip_t *chip, void *buffer, uint32_t address, uint32_t length); + +/** @brief Write data to the SPI flash chip + * + * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() + * @param address Address on flash to write to. Must be previously erased (SPI NOR flash can only write bits 1->0). + * @param buffer Pointer to a buffer with the data to write. + * @param length Length (in bytes) of data to write. + * + * There are no alignment constraints on buffer, address or length. + * + * @return FLASH_OK on success, or a flash error code if operation failed. + */ +esp_flash_err_t esp_flash_write(const esp_flash_chip_t *chip, uint32_t address, const void *buffer, uint32_t length); + +/** @brief Encrypted and write data to the SPI flash chip using on-chip hardware flash encryption + * + * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init() + * @param address Address on flash to write to. 16 byte aligned. Must be previously erased (SPI NOR flash can only write bits 1->0). + * @param buffer Pointer to a buffer with the data to write. + * @param length Length (in bytes) of data to write. 16 byte aligned. + * + * @note Both address & length must be 16 byte aligned, as this is the encryption block size + * + * @return FLASH_OK on success, or a flash error code if operation failed. + */ +esp_flash_err_t esp_flash_write_encrypted(const esp_flash_chip_t *chip, uint32_t address, const void *buffer, uint32_t length); + +/** @brief Pointer to the "default" SPI flash chip, ie the main chip attached to the MCU. + + This chip is used if the 'chip' argument pass to esp_flash_xxx API functions is ever NULL. +*/ +extern const esp_flash_chip_t *esp_flash_default_chip; + +/** @brief Initialise the default SPI flash chip + * + * Called by OS startup code. You do not need to call this in your own applications. + */ +esp_flash_err_t esp_flash_init_default_chip(); + +/** Enable OS-level SPI flash protections in IDF */ +void esp_flash_low_level_app_init(); /* ROM TODO move this to IDF */ diff --git a/components/spi_flash/include/spi_flash_lowlevel_driver.h b/components/spi_flash/include/spi_flash_lowlevel_driver.h new file mode 100644 index 0000000000..0343cc7cb4 --- /dev/null +++ b/components/spi_flash/include/spi_flash_lowlevel_driver.h @@ -0,0 +1,176 @@ +#pragma once +#include "spi_flash_lowlevel.h" + +/** @brief SPI flash driver definition structure. + * + * The driver structure contains chip-specific pointers to functions to perform SPI flash operations, and some + * chip-specific numeric values. + * + * @note This is not a public API. Driver-specific functions are called from the public API (declared in + * spi_flash_lowlevel.h). They assume the caller has already validated arguments and enabled relevant protections + * (disabling flash cache, prevent concurrent SPI access, etc.) + * + * Do not call driver functions directly in other contexts. + * + * A generic driver and it's related operations are defined in spi_flash_lowlevel_generic.h which can be used as + * building blocks for written new/specific SPI flash chip drivers. + * + * @note All of these functions may be called with SPI flash cache disabled, so must only ever access IRAM/DRAM/ROM. + */ +typedef struct esp_flash_driver { + /* Probe to detect if a supported SPI flash chip is found. + * + * Attempts to configure 'chip' with these operations and probes for a matching SPI flash chip. + * + * Auto-detection of a SPI flash chip calls this function in turn on each registered driver (see esp_flash_registered_flash_drivers). + * + * ID - as read by spi_flash_generic_read_id() - is supplied so each probe + * function doesn't need to unnecessarily read ID, but probe is permitted + * to interrogate flash in any non-destructive way. + * + * It is permissible for the driver to modify the 'chip' structure if probing succeeds (specifically, to assign something to the + * driver_data pointer if that is useful for the driver.) + * + * @return FLASH_OK if probing was successful, an error otherwise. Driver may + * assume that returning FLASH_OK means it has claimed this chip. + */ + esp_flash_err_t (*probe)(esp_flash_chip_t *chip, uint32_t flash_id); + + /* Read SPI flash ID + * + * Sends RDID (or an equivalent command) to the device. + */ + esp_flash_err_t (*read_id)(const esp_flash_chip_t *chip, uint32_t *id); + + /* Detect SPI flash size + * + * Interrogate the chip to detect it's size. + */ + esp_flash_err_t (*detect_size)(const esp_flash_chip_t *chip, uint32_t *size); + + /* Erase the entire chip + + Caller has verified the chip is not write protected. + */ + esp_flash_err_t (*erase_chip)(const esp_flash_chip_t *chip); + + /* Erase a sector of the chip. Sector size is specified in the 'sector_size' field. + + sector_address is an offset in bytes. + + Caller has verified that this sector should be non-write-protected. + */ + esp_flash_err_t (*erase_sector)(const esp_flash_chip_t *chip, uint32_t sector_address); + + /* Erase a multi-sector block of the chip. Block size is specified in the 'block_erase_size' field. + sector_address is an offset in bytes. + + Caller has verified that this block should be non-write-protected. + */ + esp_flash_err_t (*erase_block)(const esp_flash_chip_t *chip, uint32_t block_address); + + uint32_t sector_size; /* Sector is minimum erase size */ + uint32_t block_erase_size; /* Optimal (fastest) block size for multi-sector erases on this chip */ + + /* Read the write protect status of the entire chip. */ + esp_flash_err_t (*get_chip_write_protect)(const esp_flash_chip_t *chip, bool *write_protected); + + /* Set the write protect status of the entire chip. */ + esp_flash_err_t (*set_chip_write_protect)(const esp_flash_chip_t *chip, bool write_protect_chip); + + /* Number of individually write protectable regions on this chip. Range 0-63. */ + uint8_t num_protectable_regions; + /* Pointer to an array describing each protectable region. Should have num_protectable_regions elements. */ + const esp_flash_region_t *protectable_regions; + /* Get a bitmask describing all protectable regions on the chip. Each bit represents one entry in the + protectable_regions array, ie bit (1<drv->set_read_mode(chip) in order to configure the chip's read mode correctly. + */ + esp_flash_err_t (*read)(const esp_flash_chip_t *chip, void *buffer, uint32_t address, uint32_t length); + + /* Write any amount of data to the chip. + */ + esp_flash_err_t (*write)(const esp_flash_chip_t *chip, uint32_t address, const void *buffer, uint32_t length); + + + /* Use the page program command to write data to the chip. + * + * This function is expected to be called by chip->drv->write (if the + * chip->drv->write implementation doesn't call it then it can be left as NULL.) + * + * - The length argument supplied to this function is at most 'page_size' bytes. + * + * - The region between 'address' and 'address + length' will not cross a page_size aligned boundary (the write + * implementation is expected to split such a write into two before calling page_program.) + */ + esp_flash_err_t (*page_program)(const esp_flash_chip_t *chip, uint32_t address, const void *buffer, uint32_t length); + + /* Page size as written by the page_program function. Usually 256 bytes. */ + uint32_t page_size; + + /* Perform an encrypted write to the chip, using internal flash encryption hardware. */ + esp_flash_err_t (*write_encrypted)(const esp_flash_chip_t *chip, uint32_t address, const void *buffer, uint32_t length); + + /* Set the write enable flag. This function is called internally by other functions in this structure, before a destructive + operation takes place. */ + esp_flash_err_t (*write_enable)(const esp_flash_chip_t *chip); + + /* Wait for the SPI flash chip to be idle (any write operation to be complete.) This function is both called from the higher-level API functions, and from other functions in this structure. + + timeout_ms should be a timeout (in milliseconds) before the function returns FLASH_ERR_NO_RESPONSE. This is useful to avoid hanging + if the chip is otherwise unresponsive (ie returns all 0xFF or similar.) + */ + esp_flash_err_t (*wait_idle)(const esp_flash_chip_t *chip, unsigned timeout_ms); + + /* Configure both the SPI host and the chip for the read mode specified in chip->read_mode. + * + * This function is called by the higher-level API before the 'read' function is called. + * + * Can return FLASH_ERR_UNSUPPORTED_HOST or FLASH_ERR_UNSUPPORTED_CHIP if the specified mode is unsupported. + */ + esp_flash_err_t (*set_read_mode)(const esp_flash_chip_t *chip); +} esp_flash_driver_t; + +/* Pointer to an array of pointers to all known drivers for flash chips. This array is used + by esp_flash_init() to detect the flash chip driver, if none is supplied by the caller. + + Array is terminated with a NULL pointer. + + This pointer can be overwritten with a pointer to a new array, to update the list of known flash chips. + */ +extern const esp_flash_driver_t **esp_flash_registered_flash_drivers; + +/* Provide OS-level integration hooks for accessing flash chips + inside a running OS */ +typedef struct +{ + /* Call this function before commencing any flash operation. + + Does not need to be recursive (ie is called at most once for each call to 'end'. + */ + esp_flash_err_t (*start)(const esp_flash_chip_t *chip); + + /* Call this function after completing any flash operation. */ + esp_flash_err_t (*end)(const esp_flash_chip_t *chip); + + /* Delay for at least 'ms' milliseconds. + + This function will be called in between 'start' and 'end'. + */ + esp_flash_err_t (*delay_ms)(unsigned ms); +} esp_flash_os_functions_t; + +/* The default (ie initial boot) no-OS ROM esp_flash_os_functions_t */ +const esp_flash_os_functions_t esp_flash_noos_functions; + +/* Pointer to the current esp_flash_os_functions_t structure in use. + Can be changed at runtime to reflect different running conditions. + */ +extern const esp_flash_os_functions_t *esp_flash_os_functions; diff --git a/components/spi_flash/include/spi_flash_lowlevel_generic.h b/components/spi_flash/include/spi_flash_lowlevel_generic.h new file mode 100644 index 0000000000..75866c721e --- /dev/null +++ b/components/spi_flash/include/spi_flash_lowlevel_generic.h @@ -0,0 +1,151 @@ +#pragma once +#include "spi_flash_lowlevel_driver.h" +/* The 'generic' SPI flash operations are a lowest common subset of SPI flash commands, that work across most chips. + * + * These can be used as-is vai the esp_flash_common_chip_driver driver, or they can be used as "base driver" functions when + * creating a new esp_flash_driver_t driver structure. + * + * + * All of the functions in this header are internal functions, not part of a public API. See spi_flash_lowlevel.h for + * the public API. + */ + +/* SPI commands (actual on-wire commands not SPI controller bitmasks) + Suitable for use with spi_flash_common_command static function. +*/ +#define CMD_RDID 0x9F +#define CMD_WRSR 0x01 +#define CMD_WRSR2 0x31 /* Not all SPI flash uses this command */ +#define CMD_WREN 0x06 +#define CMD_WRDI 0x04 +#define CMD_RDSR 0x05 +#define CMD_RDSR2 0x35 /* Not all SPI flash uses this command */ + +#define CMD_FASTRD_QIO 0xEB +#define CMD_FASTRD_QUAD 0x6B +#define CMD_FASTRD_DIO 0xBB +#define CMD_FASTRD_DUAL 0x3B +#define CMD_FASTRD 0x0B +#define CMD_READ 0x03 /* Speed limited */ + +#define CMD_CHIP_ERASE 0xC7 +#define CMD_SECTOR_ERASE 0x20 +#define CMD_LARGE_BLOCK_ERASE 0xD8 /* 64KB block erase command */ + +#define SR_WIP (1<<0) /* Status register write-in-progress bit */ +#define SR_WREN (1<<1) /* Status register write enable bit */ + + +/** @brief Execute a simple SPI flash command against the chip. + * + * @param chip Pointer to the chip to use. + * @param command Command to execute (an on-wire hex command.) + * @param mosi_data Up to 32 bits of MOSI data to write after the command. + * @param mosi_len Length of MOSI data (in bits.) + * @param miso_len Length of MISO data (in bits.) + * @return MISO value read back, if any (depending on miso_len value.) + */ +uint32_t spi_flash_common_command(const esp_flash_chip_t *chip, uint8_t command, uint32_t mosi_data, uint8_t mosi_len, uint8_t miso_len); + +/** @brief Returns true if the pin configuration for this chip uses the GPIO matrix for any signals. */ +bool spi_flash_uses_gpio_matrix(const esp_flash_chip_t *chip); + +/** @brief Generic probe function + * + * If chip->drv_read_id succeeds, the probe succeeds. + */ +esp_flash_err_t spi_flash_generic_probe(esp_flash_chip_t *chip, uint32_t flash_id); + +/** @brief Generic implementation of esp_flash_driver_t->read_id + * + * Uses the RDID command (9Fh) supported by most SPI flash chips. + * + * Results of all-zeroes or all-ones are considered failures (probably no chip attached.) + */ +esp_flash_err_t spi_flash_generic_read_id(const esp_flash_chip_t *chip, uint32_t *id); + +/** @brief Generic size detection function + * + * Tries to detect the size of chip by using the lower 4 bits of the chip->drv->read_id result = N, and assuming size is 2 ^ N. + */ +esp_flash_err_t spi_flash_generic_detect_size(const esp_flash_chip_t *chip, uint32_t *size); + +/** @brief Erase chip by using the generic erase chip (C7h) command. */ +esp_flash_err_t spi_flash_generic_erase_chip(const esp_flash_chip_t *chip); + +/** @brief Erase sector by using the generic sector erase (20h) command. */ +esp_flash_err_t spi_flash_generic_erase_sector(const esp_flash_chip_t *chip, uint32_t start_address); + +/** @brief Erase block by using the generic 64KB block erase (D8h) command */ +esp_flash_err_t spi_flash_generic_erase_block(const esp_flash_chip_t *chip, uint32_t start_address); + +/** @brief Read from flash by using a read command that matches the programmed read mode. */ +esp_flash_err_t spi_flash_generic_read(const esp_flash_chip_t *chip, void *buffer, uint32_t address, uint32_t length); + +/** @brief Perform a page program using the page program (02h) command. */ +esp_flash_err_t spi_flash_generic_page_program(const esp_flash_chip_t *chip, uint32_t address, const void *buffer, uint32_t length); + +/** @brief Perform a generic write. Split the write buffer into + one page operations, and call chip->drv->page-program() for each. +*/ +esp_flash_err_t spi_flash_generic_write(const esp_flash_chip_t *chip, uint32_t address, const void *buffer, uint32_t length); + +/** @brief Perform a write using on-chip flash encryption */ +esp_flash_err_t spi_flash_generic_write_encrypted(const esp_flash_chip_t *chip, uint32_t address, const void *buffer, uint32_t length); + +/** @brief Send the write enable (06h) command and verify the expected bit (1) in the status register is set. */ +esp_flash_err_t spi_flash_generic_write_enable(const esp_flash_chip_t *chip); + +/** @brief Wait for the SPI host hardware state machine to be idle. + + This isn't a flash driver operation, but it's called by spi_flash_generic_wait_idle() and may be useful when implementing alternative drivers. + + timeout_ms will be decremented if the function needs to wait until the host hardware is idle. +*/ +esp_flash_err_t spi_flash_generic_wait_host_idle(const esp_flash_chip_t *chip, uint32_t *timeout_ms); + +/** @brief Read flash status via the RDSR command (05h) and wait for bit 0 (write in progress bit) to be cleared. */ +esp_flash_err_t spi_flash_generic_wait_idle(const esp_flash_chip_t *chip, uint32_t timeout_ms); + +/** @brief Utility function to configure the SPI host hardware registers for the specified read mode. + + Called by spi_flash_generic_set_read_mode() but may also be useful + when implementing other SPI flash drivers. + + Note that calling this configures SPI host registers, so if running any other commands as part of set_read_mode() then these must be run before calling this function. + */ +esp_flash_err_t spi_flash_common_configure_host_read_mode(const esp_flash_chip_t *chip); + +/** @brief Utility function for set_read_mode driver function + * + * Most setting of read mode follows a common pattern, except for how to enable Quad I/O modes (QIO/QOUT). + * These use different commands to read/write the status register, and a different bit is set/cleared. + * + * This is a generic utility function to implement set_read_mode() for this pattern. Also configures host + * registers via spi_flash_common_configure_host_read_mode(). + * + * @param qe_rdsr_command SPI flash command to read status register + * @param qe_wrsr_command SPI flash command to write status register + * @param qe_sr_bitwidth Width of the status register these commands operate on, in bits. + * @param qe_sr_bit Bit mask for enabling Quad Enable functions on this chio. + */ +esp_flash_err_t spi_flash_common_set_read_mode(const esp_flash_chip_t *chip, uint8_t qe_rdsr_command, uint8_t qe_wrsr_command, uint8_t qe_sr_bitwidth, unsigned qe_sr_bit); + +/** @brief Set the specified SPI read mode. + * + * Includes setting SPI host hardware registers, but also setting quad enable status register bit if needed. + */ +esp_flash_err_t spi_flash_generic_set_read_mode(const esp_flash_chip_t *chip); + +/** @brief Returns true if chip is configured for Quad I/O or + Quad Fast Read */ +inline static bool spi_flash_is_quad_mode(const esp_flash_chip_t *chip) +{ + return chip->read_mode == ESP_FLASH_QIO || chip->read_mode == ESP_FLASH_QOUT; +} + +/* Generic SPI flash driver, uses all the above functions for its operations. In default autodetection, this is used as + a catchall if a more specific driver is not found. +*/ +extern const esp_flash_driver_t esp_flash_generic_chip_driver; + diff --git a/components/spi_flash/linker.lf b/components/spi_flash/linker.lf index fbbb64ea74..e466c85a2b 100644 --- a/components/spi_flash/linker.lf +++ b/components/spi_flash/linker.lf @@ -1,5 +1,10 @@ [mapping:spi_flash] archive: libspi_flash.a -entries: +entries: spi_flash_rom_patch (noflash_text) + spi_flash_lowlevel_api (noflash) + spi_flash_lowlevel_generic (noflash) + spi_flash_lowlevel_issi (noflash) + spi_flash_lowlevel_idf_app (noflash) + spi_flash_driver_hs (noflash) diff --git a/components/spi_flash/spi_flash_lowlevel_api.c b/components/spi_flash/spi_flash_lowlevel_api.c new file mode 100644 index 0000000000..0a3d6f29a5 --- /dev/null +++ b/components/spi_flash/spi_flash_lowlevel_api.c @@ -0,0 +1,552 @@ +// Copyright 2017 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#include +#include +#include +#include + +#include "spi_flash_lowlevel_driver.h" +#include "spi_flash_lowlevel_generic.h" +#include "soc/spi_reg.h" + +#define MAX_WRITE_CHUNK 8192 /* write in chunks */ + +/* Static function to notify OS of a new SPI flash operation. + + If returns an error result, caller must abort. If returns FLASH_OK, caller must + call spiflash_end() before returning. +*/ +static esp_flash_err_t spiflash_start(const esp_flash_chip_t *chip) +{ + if (esp_flash_os_functions != NULL + && esp_flash_os_functions->start != NULL) { + esp_flash_err_t err = esp_flash_os_functions->start(chip); + if (err != FLASH_OK) { + return err; + } + } + return FLASH_OK; +} + +/* Static function to notify OS that SPI flash operation is complete. + */ +static esp_flash_err_t spiflash_end(const esp_flash_chip_t *chip, esp_flash_err_t err) +{ + if (esp_flash_os_functions != NULL + && esp_flash_os_functions->end != NULL) { + esp_flash_err_t end_err = esp_flash_os_functions->end(chip); + if (err == FLASH_OK) { + err = end_err; // Only return the 'end' error if we haven't already failed + } + } + return err; +} + +/* Return true if regions 'a' and 'b' overlap at all, based on their start offsets and lengths. */ +inline static bool regions_overlap(uint32_t a_start, uint32_t a_len,uint32_t b_start, uint32_t b_len); + +/* Top-level API functions, calling into driver functions via chip->drv */ + +static esp_flash_err_t detect_spi_flash_chip(esp_flash_chip_t *chip); + +esp_flash_err_t esp_flash_init(esp_flash_chip_t *chip) +{ + if (chip->spi == NULL) { + return FLASH_ERR_INVALID_ARG; + } + + // TODO: configure SPI host clock speed, pin configuration + + if (chip->drv == NULL) { + // Detect driver + esp_flash_err_t err = detect_spi_flash_chip(chip); + if (err != FLASH_OK) { + return err; + } + } + + esp_flash_err_t err = spiflash_start(chip); + if (err != FLASH_OK) { + return err; + } + + if (chip->size == 0) { + // Detect flash size + err = chip->drv->detect_size(chip, &chip->size); + } + + if (err == FLASH_OK) { + // Try to set the flash mode to whatever default mode was chosen + // (this isn't necessary at this point for functionality, but init will fail + // if this mode can't be set on this chip.) + err = chip->drv->set_read_mode(chip); + } + + // Done: all fields on 'chip' are initialised + return spiflash_end(chip, err); +} + +static esp_flash_err_t detect_spi_flash_chip(esp_flash_chip_t *chip) +{ + esp_flash_err_t err; + uint32_t flash_id; + int retries = 10; + do { + err = spiflash_start(chip); + if (err != FLASH_OK) { + return err; + } + + // Send generic RDID command twice, check for a matching result and retry in case we just powered on (inner + // function fails if it sees all-ones or all-zeroes.) + err = spi_flash_generic_read_id(chip, &flash_id); + + if (err == FLASH_OK) { // check we see the same ID twice, in case of transient power-on errors + uint32_t new_id; + err = spi_flash_generic_read_id(chip, &new_id); + if (err == FLASH_OK && (new_id != flash_id)) { + err = FLASH_ERR_NOT_INITIALISED; + } + } + + err = spiflash_end(chip, err); + } while (err != FLASH_OK && retries-- > 0); + + // Detect the chip and set the driver structure for it + const esp_flash_driver_t **drivers = esp_flash_registered_flash_drivers; + while (*drivers != NULL && chip->drv == NULL) { + chip->drv = *drivers; + + // start/end SPI operation each time, for multitasking + // and also so esp_flash_registered_flash_drivers can live in flash + err = spiflash_start(chip); + if (err != FLASH_OK) { + return err; + } + + if (chip->drv->probe(chip, flash_id) != FLASH_OK) { + chip->drv = NULL; + } + // if probe succeeded, chip->drv stays set + drivers++; + + err = spiflash_end(chip, err); + if (err != FLASH_OK) { + return err; + } + } + + return (chip->drv == NULL) ? FLASH_ERR_NOT_FOUND : FLASH_OK; +} + +// Convenience macro for beginning of all API functions, +// check that the 'chip' parameter is properly initialised +// and supports the operation in question +#define VERIFY_OP(OP) do { \ + if (chip == NULL) { \ + chip = esp_flash_default_chip; \ + } \ + if (chip == NULL || chip->drv == NULL) { \ + return FLASH_ERR_NOT_INITIALISED; \ + } \ + if (chip->drv->OP == NULL) { \ + return FLASH_ERR_UNSUPPORTED_CHIP; \ + } \ + } while (0) + +esp_flash_err_t esp_flash_read_id(const esp_flash_chip_t *chip, uint32_t *id) +{ + printf("chip %p esp_flash_default_chip %p\n", + chip, esp_flash_default_chip); + VERIFY_OP(read_id); + if (id == NULL) { + return FLASH_ERR_INVALID_ARG; + } + esp_flash_err_t err = spiflash_start(chip); + if (err != FLASH_OK) { + return err; + } + + err = chip->drv->read_id(chip, id); + + return spiflash_end(chip, err); +} + +esp_flash_err_t esp_flash_detect_size(const esp_flash_chip_t *chip, uint32_t *size) +{ + VERIFY_OP(detect_size); + if (size == NULL) { + return FLASH_ERR_INVALID_ARG; + } + *size = 0; + + esp_flash_err_t err = spiflash_start(chip); + if (err != FLASH_OK) { + return err; + } + + err = chip->drv->detect_size(chip, size); + + return spiflash_end(chip, err); +} + +esp_flash_err_t esp_flash_erase_chip(const esp_flash_chip_t *chip) +{ + VERIFY_OP(erase_chip); + bool write_protect = false; + + esp_flash_err_t err = spiflash_start(chip); + if (err != FLASH_OK) { + return err; + } + + err = esp_flash_get_chip_write_protect(chip, &write_protect); + + if (err == FLASH_OK && write_protect) { + err = FLASH_ERR_PROTECTED; + } + + if (err == FLASH_OK) { + err = chip->drv->erase_chip(chip); + } + + return spiflash_end(chip, err); +} + +esp_flash_err_t esp_flash_erase_region(const esp_flash_chip_t *chip, uint32_t start, uint32_t len) +{ + VERIFY_OP(erase_sector); + uint32_t block_erase_size = chip->drv->erase_block == NULL ? 0 : chip->drv->block_erase_size; + uint32_t sector_size = chip->drv->sector_size; + bool write_protect = false; + + if (sector_size == 0 || (block_erase_size % sector_size) != 0) { + return FLASH_ERR_NOT_INITIALISED; + } + if (start > chip->size || start + len > chip->size) { + return FLASH_ERR_INVALID_ARG; + } + if ((start % chip->drv->sector_size) != 0 || (len % chip->drv->sector_size) != 0) { + // Can only erase multiples of the sector size, starting at sector boundary + return FLASH_ERR_INVALID_ARG; + } + + esp_flash_err_t err = spiflash_start(chip); + if (err != FLASH_OK) { + return err; + } + + // Check for write protection on whole chip + if (chip->drv->get_chip_write_protect != NULL) { + err = chip->drv->get_chip_write_protect(chip, &write_protect); + if (err == FLASH_OK && write_protect) { + err = FLASH_ERR_PROTECTED; + } + } + + // Check for write protected regions overlapping the erase region + if (err == FLASH_OK && chip->drv->get_protected_regions != NULL && chip->drv->num_protectable_regions > 0) { + uint64_t protected = 0; + err = chip->drv->get_protected_regions(chip, &protected); + if (protected != 0) { + for (int i = 0; i < chip->drv->num_protectable_regions && err == FLASH_OK; i++) { + const esp_flash_region_t *region = &chip->drv->protectable_regions[i]; + if ((protected & (1LL << i)) + && regions_overlap(start, len, region->offset, region->size)) { + err = FLASH_ERR_PROTECTED; + } + } + } + } + + // Don't lock the SPI flash for the entire erase, as this may be very long + err = spiflash_end(chip, err); + + while (err == FLASH_OK && len >= sector_size) { + esp_flash_err_t err = spiflash_start(chip); + if (err != FLASH_OK) { + return err; + } + + // If possible erase an entire multi-sector block + if (block_erase_size > 0 && len >= block_erase_size && (start % block_erase_size) == 0) { + err = chip->drv->erase_block(chip, start); + start += block_erase_size; + len -= block_erase_size; + } + else { + // Otherwise erase individual sector only + err = chip->drv->erase_sector(chip, start); + start += sector_size; + len -= sector_size; + } + + err = spiflash_end(chip, err); + } + + return err; +} + +esp_flash_err_t esp_flash_get_chip_write_protect(const esp_flash_chip_t *chip, bool *write_protected) +{ + VERIFY_OP(get_chip_write_protect); + if (write_protected == NULL) { + return FLASH_ERR_INVALID_ARG; + } + + esp_flash_err_t err = spiflash_start(chip); + if (err != FLASH_OK) { + return err; + } + + err = chip->drv->get_chip_write_protect(chip, write_protected); + + return spiflash_end(chip, err); +} + +esp_flash_err_t esp_flash_set_chip_write_protect(const esp_flash_chip_t *chip, bool write_protect_chip) +{ + VERIFY_OP(set_chip_write_protect); + + esp_flash_err_t err = spiflash_start(chip); + if (err != FLASH_OK) { + return err; + } + + err = chip->drv->set_chip_write_protect(chip, write_protect_chip); + + return spiflash_end(chip, err); +} + +esp_flash_err_t esp_flash_get_protectable_regions(const esp_flash_chip_t *chip, const esp_flash_region_t **regions, uint32_t *num_regions) +{ + if(num_regions != NULL) { + *num_regions = 0; // In case caller doesn't check result + } + VERIFY_OP(get_protected_regions); + + if(regions == NULL || num_regions == NULL) { + return FLASH_ERR_INVALID_ARG; + } + + *num_regions = chip->drv->num_protectable_regions; + *regions = chip->drv->protectable_regions; + return FLASH_OK; +} + +static esp_flash_err_t find_region(const esp_flash_chip_t *chip, const esp_flash_region_t *region, uint8_t *index) +{ + if (region == NULL) { + return FLASH_ERR_INVALID_ARG; + } + + for(*index = 0; *index < chip->drv->num_protectable_regions; (*index)++) { + if (memcmp(&chip->drv->protectable_regions[*index], + region, sizeof(esp_flash_region_t)) == 0) { + return FLASH_OK; + } + } + + return FLASH_ERR_NOT_FOUND; +} + +esp_flash_err_t esp_flash_get_protected_region(const esp_flash_chip_t *chip, const esp_flash_region_t *region, bool *protected) +{ + VERIFY_OP(get_protected_regions); + + if (protected == NULL) { + return FLASH_ERR_INVALID_ARG; + } + + uint8_t index; + esp_flash_err_t err = find_region(chip, region, &index); + if (err != FLASH_OK) { + return err; + } + + uint64_t protection_mask = 0; + err = spiflash_start(chip); + if (err != FLASH_OK) { + return err; + } + + err = chip->drv->get_protected_regions(chip, &protection_mask); + if (err == FLASH_OK) { + *protected = protection_mask & (1LL << index); + } + + return spiflash_end(chip, err); +} + +esp_flash_err_t esp_flash_set_protected_region(const esp_flash_chip_t *chip, const esp_flash_region_t *region, bool protected) +{ + VERIFY_OP(set_protected_regions); + + uint8_t index; + esp_flash_err_t err = find_region(chip, region, &index); + if (err != FLASH_OK) { + return err; + } + + uint64_t protection_mask = 0; + err = spiflash_start(chip); + if (err != FLASH_OK) { + return err; + } + + err = chip->drv->get_protected_regions(chip, &protection_mask); + if (err == FLASH_OK) { + if (protected) { + protection_mask |= (1LL << index); + } else { + protection_mask &= ~(1LL << index); + } + err = chip->drv->set_protected_regions(chip, protection_mask); + } + + return spiflash_end(chip, err); +} + +esp_flash_err_t esp_flash_read(const esp_flash_chip_t *chip, void *buffer, uint32_t address, uint32_t length) +{ + VERIFY_OP(read); + if (buffer == NULL || address > chip->size || address+length > chip->size) { + return FLASH_ERR_INVALID_ARG; + } + + esp_flash_err_t err = spiflash_start(chip); + if (err != FLASH_OK) { + return err; + } + + if (err == FLASH_OK) { + err = chip->drv->set_read_mode(chip); + } + + if (err == FLASH_OK) { + err = chip->drv->read(chip, buffer, address, length); + } + + return spiflash_end(chip, err); +} + +esp_flash_err_t esp_flash_write(const esp_flash_chip_t *chip, uint32_t address, const void *buffer, uint32_t length) +{ + VERIFY_OP(write); + if (buffer == NULL || address > chip->size || address+length > chip->size) { + return FLASH_ERR_INVALID_ARG; + } + + /* If 'chip' is connected to the main SPI bus, we can only write directly from regions that are accessible + with cache disabled. */ +#ifdef ESP_PLATFORM + bool direct_write = ( chip->spi != &SPI1 + || ( (uintptr_t) address >= 0x3FFAE000 + && (uintptr_t) address < 0x40000000 ) ); +#else + bool direct_write = true; +#endif + + esp_flash_err_t err = FLASH_OK; + + /* Write output in chunks, either by buffering on stack or + by artificially cutting into MAX_WRITE_CHUNK parts (in an OS + environment, this prevents writing from causing interrupt or higher priority task + starvation.) */ + while(err == FLASH_OK && length > 0) { + uint32_t write_len; + const void *write_buf; + if (direct_write) { + write_len = MIN(length, MAX_WRITE_CHUNK); + write_buf = buffer; + } else { + uint32_t buf[8]; + write_len = MIN(length, sizeof(buf)); + memcpy(buf, buffer, write_len); + write_buf = buf; + } + + err = spiflash_start(chip); + if (err != FLASH_OK) { + return err; + } + + err = chip->drv->write(chip, address, write_buf, write_len); + + address += write_len; + buffer = (void *)((intptr_t)buffer + write_len); + length -= write_len; + + err = spiflash_end(chip, err); + } + return err; +} + +esp_flash_err_t esp_flash_write_encrypted(const esp_flash_chip_t *chip, uint32_t address, const void *buffer, uint32_t length) +{ + VERIFY_OP(write_encrypted); + if (chip->spi != 0) { + // Encrypted operations have to use SPI0 + return FLASH_ERR_UNSUPPORTED_HOST; + } + if (buffer == NULL || address > chip->size || address+length > chip->size) { + return FLASH_ERR_INVALID_ARG; + } + + esp_flash_err_t err = spiflash_start(chip); + if (err != FLASH_OK) { + return err; + } + + err = chip->drv->write_encrypted(chip, address, buffer, length); + + return spiflash_end(chip, err); +} + + +inline static bool regions_overlap(uint32_t a_start, uint32_t a_len,uint32_t b_start, uint32_t b_len) +{ + uint32_t a_end = a_start + a_len; + uint32_t b_end = b_start + b_len; + + return ((a_start >= b_start && a_start <= b_end) + || (a_end >= b_start && a_end <= b_end) + || (b_start >= a_start && b_start <= a_end) + || (b_end >= a_start && b_end <= a_end)); +} + +const esp_flash_chip_t *esp_flash_default_chip; + +static esp_flash_chip_t default_chip; + +esp_flash_err_t esp_flash_init_default_chip() +{ + default_chip.spi = &SPI1; + default_chip.read_mode = ESP_FLASH_FASTRD; // TODO: initialise properly + default_chip.speed = ESP_FLASH_20MHZ; // TODO: initialise properly + + // ROM TODO: account for non-standard default pins in efuse + + // ROM TODO: to account for chips which are slow to power on, maybe keep probing in a loop here + + esp_flash_err_t err = esp_flash_init(&default_chip); + if (err != FLASH_OK) { + return err; + } + + esp_flash_default_chip = &default_chip; + return FLASH_OK; +} + +const esp_flash_os_functions_t *esp_flash_os_functions = &esp_flash_noos_functions; diff --git a/components/spi_flash/spi_flash_lowlevel_driver.c b/components/spi_flash/spi_flash_lowlevel_driver.c new file mode 100644 index 0000000000..e901ef1e21 --- /dev/null +++ b/components/spi_flash/spi_flash_lowlevel_driver.c @@ -0,0 +1,34 @@ +// Copyright 2017 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#include +#include "spi_flash_lowlevel_driver.h" + +extern const esp_flash_driver_t esp_flash_generic_chip_driver; +extern const esp_flash_driver_t esp_flash_issi_chip_driver; + +/* Default registered chip drivers. + + Note these are tested in order and first match is taken, so generic/catchall entries + should go last. + + Note that the esp_flash_registered_flash_ops pointer can be + changed to point to a different array of registered ops, if desired. +*/ +static const esp_flash_driver_t *default_registered_flash_drivers[] = { + &esp_flash_issi_chip_driver, + &esp_flash_generic_chip_driver, + NULL, +}; + +const esp_flash_driver_t **esp_flash_registered_flash_drivers = default_registered_flash_drivers; diff --git a/components/spi_flash/spi_flash_lowlevel_generic.c b/components/spi_flash/spi_flash_lowlevel_generic.c new file mode 100644 index 0000000000..aef068e30f --- /dev/null +++ b/components/spi_flash/spi_flash_lowlevel_generic.c @@ -0,0 +1,498 @@ +// Copyright 2017 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#include +#include // For MIN/MAX +#include + +#include "spi_flash_lowlevel_driver.h" +#include "spi_flash_lowlevel_generic.h" + +#define SPI_FLASH_GENERIC_CHIP_ERASE_TIMEOUT 4000 +#define SPI_FLASH_GENERIC_SECTOR_ERASE_TIMEOUT 500 +#define SPI_FLASH_GENERIC_BLOCK_ERASE_TIMEOUT 1000 + +#define DEFAULT_IDLE_TIMEOUT 200 +#define DEFAULT_PAGE_PROGRAM_TIMEOUT 500 + +/* Hardware host-specific constants */ +#define MAX_WRITE_BYTES 32 +#define MAX_READ_BYTES 64 + +#define ADDRESS_MASK_24BIT 0xFFFFFF + +uint32_t spi_flash_common_command(const esp_flash_chip_t *chip, uint8_t command, uint32_t mosi_data, uint8_t mosi_len, uint8_t miso_len) +{ + typeof(chip->spi->user2) user2 = { + .usr_command_value = command, + .usr_command_bitlen = (8 -1), + }; + chip->spi->user2 = user2; + + typeof(chip->spi->user) user = { + .usr_miso = miso_len > 0, + .usr_mosi = mosi_len > 0, + .usr_dummy = 0, + .usr_command = 1, + }; + chip->spi->user = user; + + chip->spi->ctrl.val = 0; + chip->spi->miso_dlen.usr_miso_dbitlen = miso_len ? (miso_len - 1) : 0; + chip->spi->mosi_dlen.usr_mosi_dbitlen = mosi_len ? (mosi_len - 1) : 0; + + // TODO: there's a bug(?) here where if multiple bytes are written + // with each byte MSB-first (correct), but the bytes are + // written out LSB first... + // + // May be easier to just document this in the function interface... + chip->spi->data_buf[0] = mosi_data; + + if (spi_flash_uses_gpio_matrix(chip)) { + /* When flash pins are mapped via GPIO matrix, need a dummy cycle before reading via MISO */ + if (chip->speed == ESP_FLASH_80MHZ) { + chip->spi->user.usr_dummy = 1; + chip->spi->user1.usr_dummy_cyclelen = 1; + } else { + chip->spi->user.usr_dummy = 1; + chip->spi->user1.usr_dummy_cyclelen = 0; + } + } + + chip->spi->cmd.usr = 1; + while(chip->spi->cmd.usr != 0) + { } + + uint32_t miso = chip->spi->data_buf[0]; + + return miso; +} + +esp_flash_err_t spi_flash_generic_probe(esp_flash_chip_t *chip, uint32_t flash_id) +{ + // This is the catch-all probe function, claim the chip always if nothing + // else has claimed it yet. + return FLASH_OK; +} + +esp_flash_err_t spi_flash_generic_read_id(const esp_flash_chip_t *chip, uint32_t *id) +{ + uint32_t raw_flash_id = spi_flash_common_command(chip, CMD_RDID, 0, 0, 24); + if (raw_flash_id == 0xFFFFFF || raw_flash_id == 0) { + return FLASH_ERR_NO_RESPONSE; + } + + // Byte swap the flash id as it's usually written the other way around + uint8_t mfg_id = raw_flash_id & 0xFF; + uint16_t flash_id = (raw_flash_id >> 16) | (raw_flash_id & 0xFF00); + + *id = ((uint32_t)mfg_id << 16) | flash_id; + return FLASH_OK; +} + + +esp_flash_err_t spi_flash_generic_detect_size(const esp_flash_chip_t *chip, uint32_t *size) +{ + uint32_t id = 0; + *size = 0; + esp_flash_err_t err = chip->drv->read_id(chip, &id); + if (err != FLASH_OK) { + return err; + } + + /* Can't detect size unless the high byte of the product ID matches the same convention, which is usually 0x40 or + * 0xC0 or similar. */ + if ((id & 0x0F00) != 0) { + return FLASH_ERR_UNSUPPORTED_CHIP; + } + + *size = 1 << (id & 0xFF); + + return FLASH_OK; +} + + +esp_flash_err_t spi_flash_generic_erase_chip(const esp_flash_chip_t *chip) +{ + esp_flash_err_t err; + + err = chip->drv->write_enable(chip); + if (err == FLASH_OK) { + err = chip->drv->wait_idle(chip, DEFAULT_IDLE_TIMEOUT); + } + if (err == FLASH_OK) { + chip->spi->ctrl.val = 0; + chip->spi->cmd.flash_ce = 1; + while(chip->spi->cmd.val != 0) { } + err = chip->drv->wait_idle(chip, SPI_FLASH_GENERIC_CHIP_ERASE_TIMEOUT); + } + + return err; +} + +esp_flash_err_t spi_flash_generic_erase_sector(const esp_flash_chip_t *chip, uint32_t start_address) +{ + esp_flash_err_t err = chip->drv->write_enable(chip); + if (err == FLASH_OK) { + err = chip->drv->wait_idle(chip, DEFAULT_IDLE_TIMEOUT); + } + if (err == FLASH_OK) { + chip->spi->user1.usr_addr_bitlen = (24 - 1); + chip->spi->addr = start_address & ADDRESS_MASK_24BIT; + chip->spi->ctrl.val = 0; + chip->spi->cmd.flash_se = 1; + while(chip->spi->cmd.val != 0) { } + err = chip->drv->wait_idle(chip, SPI_FLASH_GENERIC_SECTOR_ERASE_TIMEOUT); + } + return err; +} + +esp_flash_err_t spi_flash_generic_erase_block(const esp_flash_chip_t *chip, uint32_t start_address) +{ + esp_flash_err_t err = chip->drv->write_enable(chip); + if (err == FLASH_OK) { + err = chip->drv->wait_idle(chip, DEFAULT_IDLE_TIMEOUT); + } + if (err == FLASH_OK) { + chip->spi->user1.usr_addr_bitlen = (24 - 1); + chip->spi->addr = start_address & ADDRESS_MASK_24BIT; + chip->spi->cmd.flash_be = 1; + while(chip->spi->cmd.val != 0) { } + err = chip->drv->wait_idle(chip, SPI_FLASH_GENERIC_BLOCK_ERASE_TIMEOUT); + } + return err; +} + +esp_flash_err_t spi_flash_generic_read(const esp_flash_chip_t *chip, void *buffer, uint32_t address, uint32_t length) +{ + esp_flash_err_t err = FLASH_OK; + + while (err == FLASH_OK && length > 0) { + uint32_t read_len = MIN(length, MAX_READ_BYTES); + chip->spi->miso_dlen.usr_miso_dbitlen = (read_len * 8) - 1; + chip->spi->addr = address << 8; + + chip->spi->cmd.usr = 1; + while(chip->spi->cmd.val != 0) {} + + if(((intptr_t)buffer % 4 == 0) && (read_len % 4 == 0)) { + // If everything is word-aligned, do a faster memcpy + xthal_memcpy(buffer, (void *)chip->spi->data_buf, read_len); + length -= read_len; + buffer = (void *)((intptr_t)buffer + read_len); + address += read_len; + } else { + // Otherwise, slow(er) path copies word by word + for (int i = 0; i < (read_len+3)/4; i++) { + int word_len = MIN(sizeof(uint32_t), length); + uint32_t word = chip->spi->data_buf[i]; + xthal_memcpy(buffer, &word, word_len); + length -= word_len; + buffer = (void *)((intptr_t)buffer + word_len); + address += word_len; + } + } + } + + + return err; +} + +esp_flash_err_t spi_flash_generic_page_program(const esp_flash_chip_t *chip, uint32_t address, const void *buffer, uint32_t length) +{ + esp_flash_err_t err; + + err = chip->drv->wait_idle(chip, DEFAULT_IDLE_TIMEOUT); + + if (err == FLASH_OK) { + err = chip->drv->write_enable(chip); + } + + if (err == FLASH_OK) { + // Perform the actual Page Program command + chip->spi->user.usr_dummy = 0; + chip->spi->user1.usr_addr_bitlen = (24 - 1); + chip->spi->addr = (address & ADDRESS_MASK_24BIT) | (length << 24); + + // Load data registers, word at a time + int num_words = (length+3) / 4; + for (int i = 0; i < num_words; i++) { + uint32_t word = 0; + uint32_t word_len = MIN(length, sizeof(word)); + xthal_memcpy(&word, buffer, word_len); + chip->spi->data_buf[i] = word; + length -= word_len; + buffer = (void *)((intptr_t)buffer + word_len); + } + + chip->spi->cmd.flash_pp = 1; + while (chip->spi->cmd.val != 0) { } + + err = chip->drv->wait_idle(chip, DEFAULT_PAGE_PROGRAM_TIMEOUT); + } + + + return err; +} + +esp_flash_err_t spi_flash_generic_write(const esp_flash_chip_t *chip, uint32_t address, const void *buffer, uint32_t length) +{ + esp_flash_err_t err = FLASH_OK; + const uint32_t page_size = chip->drv->page_size; + + while (err == FLASH_OK && length > 0) { + uint32_t page_len = MIN(MAX_WRITE_BYTES, MIN(page_size, length)); + if ((address + page_len) / page_size != address / page_size) { + // Most flash chips can't page write across a page boundary + page_len = page_size - (address % page_size); + } + err = chip->drv->page_program(chip, address, buffer, page_len); + address += page_len; + buffer = (void *)((intptr_t)buffer + page_len); + length -= page_len; + } + + + return err; +} + +esp_flash_err_t spi_flash_generic_write_encrypted(const esp_flash_chip_t *chip, uint32_t address, const void *buffer, uint32_t length) +{ + return FLASH_ERR_UNSUPPORTED_HOST; // TODO +} + +esp_flash_err_t spi_flash_generic_write_enable(const esp_flash_chip_t *chip) +{ + esp_flash_err_t err = FLASH_OK; + + err = chip->drv->wait_idle(chip, DEFAULT_IDLE_TIMEOUT); + + if (err == FLASH_OK) { + chip->spi->cmd.flash_wren = 1; + while(chip->spi->cmd.val != 0) { } + } + + uint8_t status = spi_flash_common_command(chip, CMD_RDSR, 0, 0, 8); + if ((status & SR_WREN) == 0) { + // WREN flag has not been set! + err = FLASH_ERR_NOT_FOUND; + } + + + return err; +} + +esp_flash_err_t spi_flash_generic_wait_host_idle(const esp_flash_chip_t *chip, uint32_t *timeout_ms) +{ + while(chip->spi->ext2.st != 0 && *timeout_ms > 0) { + if (*timeout_ms > 1) { + esp_flash_os_functions->delay_ms(1); + } + (*timeout_ms)--; + } + + // Not clear if this is necessary, or only necessary if + // chip->spi == SPI1. But probably doesn't hurt... + while(SPI0.ext2.st != 0 && *timeout_ms > 0) { + if (*timeout_ms > 1) { + esp_flash_os_functions->delay_ms(1); + } + (*timeout_ms)--; + } + + return (*timeout_ms > 0) ? FLASH_OK : FLASH_ERR_NO_RESPONSE; +} + +esp_flash_err_t spi_flash_generic_wait_idle(const esp_flash_chip_t *chip, uint32_t timeout_ms) +{ + timeout_ms++; // allow at least one pass before timeout, last one has no sleep cycle + + uint8_t status = 0; + while(timeout_ms > 0) { + + esp_flash_err_t err = spi_flash_generic_wait_host_idle(chip, &timeout_ms); + if (err != FLASH_OK) { + return err; + } + + status = spi_flash_common_command(chip, CMD_RDSR, 0, 0, 8); + if ((status & SR_WIP) == 0) { + break; // Write in progress is complete + } + if (timeout_ms > 1) { + esp_flash_os_functions->delay_ms(1); + } + timeout_ms--; + } + + return (timeout_ms > 0) ? FLASH_OK : FLASH_ERR_NO_RESPONSE; +} + +esp_flash_err_t spi_flash_common_configure_host_read_mode(const esp_flash_chip_t *chip) +{ + int dummy_cyclelen, addr_bitlen, read_command; + switch(chip->read_mode) { + case ESP_FLASH_QIO: + addr_bitlen = 32; + dummy_cyclelen = 4; // TODO check this works + read_command = CMD_FASTRD_QIO; + break; + case ESP_FLASH_QOUT: + addr_bitlen = 24; + dummy_cyclelen = 8; // TODO check this works + read_command = CMD_FASTRD_QUAD; + break; + case ESP_FLASH_DIO: + addr_bitlen = 32; + dummy_cyclelen = 0; + read_command = CMD_FASTRD_DIO; + break; + case ESP_FLASH_DOUT: + addr_bitlen = 24; + dummy_cyclelen = 8; + read_command = CMD_FASTRD_DUAL; + break; + case ESP_FLASH_FASTRD: + addr_bitlen = 24; + dummy_cyclelen = 8; + read_command = CMD_FASTRD; + break; + case ESP_FLASH_SLOWRD: + addr_bitlen = 24; + dummy_cyclelen = 0; + read_command = CMD_READ; + break; + default: + return FLASH_ERR_NOT_INITIALISED; + } + + // Add dummy cycles to compensate for GPIO matrix + // latency, if necessary... + if (spi_flash_uses_gpio_matrix(chip)) { + if (chip->speed == ESP_FLASH_80MHZ) { + dummy_cyclelen += 2; + } else if (chip->speed == ESP_FLASH_40MHZ) { + dummy_cyclelen += 1; + } + } + + chip->spi->user1.usr_dummy_cyclelen = (dummy_cyclelen - 1); + chip->spi->user1.usr_addr_bitlen = (addr_bitlen - 1); + chip->spi->user2.usr_command_value = read_command; + chip->spi->user2.usr_command_bitlen = (8 - 1); + + typeof (chip->spi->user) user = { + .usr_command = 1, + .usr_mosi = 0, + .usr_miso = 1, + .usr_dummy = (dummy_cyclelen > 0) ? 1 : 0, + .usr_addr = 1, + }; + chip->spi->user = user; + + typeof (chip->spi->ctrl) ctrl = { + .fread_qio = (chip->read_mode == ESP_FLASH_QIO), + .fread_quad = (chip->read_mode == ESP_FLASH_QOUT), + .fread_dio = (chip->read_mode == ESP_FLASH_DIO), + .fread_dual = (chip->read_mode == ESP_FLASH_DOUT), + .fastrd_mode = (chip->read_mode != ESP_FLASH_SLOWRD), + }; + chip->spi->ctrl = ctrl; + + return FLASH_OK; +} + +#include + +esp_flash_err_t spi_flash_common_set_read_mode(const esp_flash_chip_t *chip, uint8_t qe_rdsr_command, uint8_t qe_wrsr_command, uint8_t qe_sr_bitwidth, unsigned qe_sr_bit) +{ + if (spi_flash_is_quad_mode(chip)) { + // Ensure quad modes are enabled, using the Quad Enable parameters supplied. + unsigned sr = spi_flash_common_command(chip, qe_rdsr_command, 0, 0, qe_sr_bitwidth); + ets_printf("before 0x%x\n", sr); + if ((sr & qe_sr_bit) == 0) { + sr |= qe_sr_bit; + spi_flash_common_command(chip, qe_wrsr_command, sr, qe_sr_bitwidth, 0); + + /* Check the new QE bit has stayed set */ + sr = spi_flash_common_command(chip, qe_rdsr_command, 0, 0, qe_sr_bitwidth); + ets_printf("after 0x%x\n", sr); + if ((sr & qe_sr_bit) == 0) { + return FLASH_ERR_NO_RESPONSE; + } + } + } + + // Configure the host, and return + return spi_flash_common_configure_host_read_mode(chip); +} + +esp_flash_err_t spi_flash_generic_set_read_mode(const esp_flash_chip_t *chip) +{ + // On "generic" chips, this involves checking + // bit 1 (QE) of RDSR2 (35h) result + // (it works this way on GigaDevice & Fudan Micro chips, probably others...) + const uint8_t BIT_QE = 1<<1; + return spi_flash_common_set_read_mode(chip, CMD_RDSR2, CMD_WRSR2, 8, BIT_QE); +} + +bool spi_flash_uses_gpio_matrix(const esp_flash_chip_t *chip) +{ + if (chip->pins == NULL) { + return false; + } + if (chip->pins->mosi_io_num != -1 + || chip->pins->miso_io_num != -1 + || chip->pins->sclk_io_num != -1) { + return true; + } + if (spi_flash_is_quad_mode(chip)) { + if (chip->pins->quadwp_io_num != -1 + || chip->pins->quadhd_io_num != -1) { + return true; + } + } + return false; +} + +const esp_flash_driver_t esp_flash_generic_chip_driver = { + .probe = spi_flash_generic_probe, + .read_id = spi_flash_generic_read_id, + .detect_size = spi_flash_generic_detect_size, + .erase_chip = spi_flash_generic_erase_chip, + .erase_sector = spi_flash_generic_erase_sector, + .erase_block = spi_flash_generic_erase_block, + .sector_size = 4 * 1024, + .block_erase_size = 64 * 1024, + + // TODO: figure out if generic chip-wide protection bits exist across some manufacturers + .get_chip_write_protect = NULL, + .set_chip_write_protect = NULL, + + // Chip write protection regions do not appear to be standardised + // at all, this is implemented in chip-specific drivers only. + .num_protectable_regions = 0, + .protectable_regions = NULL, + .get_protected_regions = NULL, + .set_protected_regions = NULL, + + .read = spi_flash_generic_read, + .write = spi_flash_generic_write, + .page_program = spi_flash_generic_page_program, + .page_size = 256, + .write_encrypted = spi_flash_generic_write_encrypted, + + .write_enable = spi_flash_generic_write_enable, + .wait_idle = spi_flash_generic_wait_idle, + .set_read_mode = spi_flash_generic_set_read_mode, +}; diff --git a/components/spi_flash/spi_flash_lowlevel_idf_app.c b/components/spi_flash/spi_flash_lowlevel_idf_app.c new file mode 100644 index 0000000000..9b71a1e863 --- /dev/null +++ b/components/spi_flash/spi_flash_lowlevel_idf_app.c @@ -0,0 +1,60 @@ +// Copyright 2017 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#include +#include "spi_flash_lowlevel_driver.h" + +#include "rom/ets_sys.h" +#include "esp_attr.h" +#include "esp_spi_flash.h" + +static esp_flash_err_t start(const esp_flash_chip_t *chip) +{ + if (chip->spi == &SPI1) { + g_flash_guard_default_ops.start(); + } + + // TODO figure out if we can coexist with the SPI master driver here, for other peripherals + + return FLASH_OK; +} +static esp_flash_err_t end(const esp_flash_chip_t *chip) +{ + if (chip->spi == &SPI1) { + g_flash_guard_default_ops.end(); + } + + // TODO figure out if we can coexist with the SPI master driver here, for other peripherals + + return FLASH_OK; +} + +static esp_flash_err_t delay_ms(unsigned ms) +{ + ets_delay_us(1000 * ms); + return FLASH_OK; +} + + +const esp_flash_os_functions_t default_os_functions = { + .start = start, + .end = end, + .delay_ms = delay_ms, +}; + +void esp_flash_low_level_app_init() +{ + esp_flash_os_functions = &default_os_functions; +} + + diff --git a/components/spi_flash/spi_flash_lowlevel_issi.c b/components/spi_flash/spi_flash_lowlevel_issi.c new file mode 100644 index 0000000000..f97ec5a0c0 --- /dev/null +++ b/components/spi_flash/spi_flash_lowlevel_issi.c @@ -0,0 +1,74 @@ +// Copyright 2017 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#include +#include "spi_flash_lowlevel_driver.h" +#include "spi_flash_lowlevel_generic.h" + +/* Driver for ISSI flash chip, as used in ESP32 D2WD */ + +esp_flash_err_t issi_probe(esp_flash_chip_t *chip, uint32_t flash_id) +{ + /* Check manufacturer and product IDs match our desired masks */ + const uint8_t MFG_ID = 0x9D; + if (flash_id >> 16 != MFG_ID) { + return FLASH_ERR_NOT_FOUND; + } + + const uint16_t FLASH_ID_MASK = 0xCF00; + const uint16_t FLASH_ID_VALUE = 0x4000; + if ((flash_id & FLASH_ID_MASK) != FLASH_ID_VALUE) { + return FLASH_ERR_NOT_FOUND; + } + + return FLASH_OK; +} + +esp_flash_err_t issi_set_read_mode(const esp_flash_chip_t *chip) +{ + /* ISSI uses bit 6 of "basic" SR as Quad Enable */ + const uint8_t BIT_QE = 1<<6; + return spi_flash_common_set_read_mode(chip, CMD_RDSR, CMD_WRSR, 8, BIT_QE); +} + + +const esp_flash_driver_t esp_flash_issi_chip_driver = { + .probe = issi_probe, + .read_id = spi_flash_generic_read_id, + .detect_size = spi_flash_generic_detect_size, + .erase_chip = spi_flash_generic_erase_chip, + .erase_sector = spi_flash_generic_erase_sector, + .erase_block = spi_flash_generic_erase_block, + .sector_size = 4 * 1024, + .block_erase_size = 64 * 1024, + + // TODO: support get/set chip write protect for ISSI flash + .get_chip_write_protect = NULL, + .set_chip_write_protect = NULL, + + // TODO support protected regions on ISSI flash + .num_protectable_regions = 0, + .protectable_regions = NULL, + .get_protected_regions = NULL, + .set_protected_regions = NULL, + + .read = spi_flash_generic_read, + .write = spi_flash_generic_write, + .page_program = spi_flash_generic_page_program, + .page_size = 256, + .write_encrypted = spi_flash_generic_write_encrypted, + + .write_enable = spi_flash_generic_write_enable, + .wait_idle = spi_flash_generic_wait_idle, + .set_read_mode = issi_set_read_mode, +}; diff --git a/components/spi_flash/spi_flash_lowlevel_noos.c b/components/spi_flash/spi_flash_lowlevel_noos.c new file mode 100644 index 0000000000..3fb4b8c4bd --- /dev/null +++ b/components/spi_flash/spi_flash_lowlevel_noos.c @@ -0,0 +1,51 @@ +// Copyright 2017 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#include +#include "spi_flash_lowlevel_driver.h" + +#include "rom/ets_sys.h" +#include "rom/cache.h" +#include "esp_attr.h" +#include "esp_spi_flash.h" + +static esp_flash_err_t start(const esp_flash_chip_t *chip) +{ + if (chip->spi == &SPI1) { + Cache_Read_Disable(0); + Cache_Read_Disable(1); + } + return FLASH_OK; +} +static esp_flash_err_t end(const esp_flash_chip_t *chip) +{ + if (chip->spi == &SPI1) { + Cache_Flush(0); + Cache_Flush(1); + Cache_Read_Enable(0); + Cache_Read_Enable(1); + } + return FLASH_OK; +} + +static esp_flash_err_t delay_ms(unsigned ms) +{ + ets_delay_us(1000 * ms); + return FLASH_OK; +} + +const esp_flash_os_functions_t esp_flash_noos_functions = { + .start = start, + .end = end, + .delay_ms = delay_ms, +}; diff --git a/components/spi_flash/test/test_low_level.c b/components/spi_flash/test/test_low_level.c new file mode 100644 index 0000000000..da77f892fb --- /dev/null +++ b/components/spi_flash/test/test_low_level.c @@ -0,0 +1,181 @@ +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +static uint8_t sector_buf[4096]; + +TEST_CASE("SPI flash metadata functions", "[spi_flash_ll]") +{ + uint32_t id, size; + + TEST_ASSERT_EQUAL(FLASH_OK, esp_flash_read_id(NULL, &id) ); + + TEST_ASSERT_EQUAL(FLASH_OK, esp_flash_detect_size(NULL, &size) ); + + printf("Flash ID %08x detected size %d bytes\n", id, size); +} + +static uint32_t erase_test_region(int num_sectors) +{ + const esp_partition_t *part = get_test_data_partition(); + uint32_t offs = part->address; + + /* chip should be initialised */ + TEST_ASSERT(esp_flash_default_chip != NULL + && esp_flash_default_chip->drv != NULL); + + TEST_ASSERT(num_sectors * 4096 <= part->size); + + bzero(sector_buf, sizeof(sector_buf)); + + printf("Erase @ 0x%x...\n", offs); + TEST_ASSERT_EQUAL(FLASH_OK, esp_flash_erase_region(NULL, offs, num_sectors * 4096) ); + + printf("Verify erased...\n"); + TEST_ASSERT_EQUAL(FLASH_OK, esp_flash_read(NULL, sector_buf, offs, sizeof(sector_buf)) ); + + printf("Buffer starts 0x%02x 0x%02x 0x%02x 0x%02x\n", sector_buf[0], sector_buf[1], sector_buf[2], sector_buf[3]); + for (int i = 0; i < sizeof(sector_buf); i++) { + TEST_ASSERT_EQUAL_HEX8(0xFF, sector_buf[i]); + } + + return offs; +} + +TEST_CASE("SPI flash simple read/write", "[spi_flash_ll]") +{ + uint32_t offs = erase_test_region(1); + + for (int i =0 ; i < sizeof(sector_buf); i++) { + sector_buf[i] = i & 0xFF; + } + + printf("Write...\n"); + TEST_ASSERT_EQUAL(FLASH_OK, esp_flash_write(NULL, offs, sector_buf, sizeof(sector_buf)) ); + + bzero(sector_buf, sizeof(sector_buf)); + + printf("Read back...\n"); + TEST_ASSERT_EQUAL(FLASH_OK, esp_flash_read(NULL, sector_buf, offs, sizeof(sector_buf)) ); + + printf("Buffer starts 0x%02x 0x%02x 0x%02x 0x%02x\n", sector_buf[0], sector_buf[1], sector_buf[2], sector_buf[3]); + + for (int i = 0; i < sizeof(sector_buf); i++) { + TEST_ASSERT_EQUAL_HEX8(i & 0xFF, sector_buf[i]); + } +} + +TEST_CASE("SPI flash unaligned read/write", "[spi_flash_ll]") +{ + uint32_t offs = erase_test_region(2); + + const char *msg = "i am a message"; + TEST_ASSERT(strlen(msg)+1 % 4 != 0); + TEST_ASSERT_EQUAL(FLASH_OK, esp_flash_write(NULL, offs+1, msg, strlen(msg)+1) ); + + char buf[strlen(msg) + 1]; + + memset(buf, 0xEE, sizeof(buf)); + + TEST_ASSERT_EQUAL(FLASH_OK, esp_flash_read(NULL, buf, offs+1, strlen(msg)+1) ); + TEST_ASSERT_EQUAL_STRING_LEN(msg, buf, strlen(msg)); + TEST_ASSERT(memcmp(buf, msg, strlen(msg)+1) == 0); +} + + +TEST_CASE("SPI flash single byte reads/writes", "[spi_flash_ll]") +{ + uint32_t offs = erase_test_region(2); + + for (unsigned v = 0; v < 512; v++) { + TEST_ASSERT_EQUAL(FLASH_OK, esp_flash_write(NULL, offs+v, &v, 1) ); + } + + for (unsigned v = 0; v < 512; v++) { + uint8_t readback; + TEST_ASSERT_EQUAL(FLASH_OK, esp_flash_read(NULL, &readback, offs+v, 1) ); + TEST_ASSERT_EQUAL_HEX8(v, readback); + } +} + +/* this test is notable because it generates a lot of unaligned reads/writes, + and also reads/writes across both a sector boundary & many page boundaries. +*/ +TEST_CASE("SPI flash three byte reads/writes", "[spi_flash_ll]") +{ + uint32_t offs = erase_test_region(2); + + for (uint32_t v = 0; v < 2000; v++) { + TEST_ASSERT_EQUAL(FLASH_OK, esp_flash_write(NULL, offs+3*v, &v, 3) ); + } + + for (uint32_t v = 0; v < 2000; v++) { + uint32_t readback; + TEST_ASSERT_EQUAL(FLASH_OK, esp_flash_read(NULL, &readback, offs+3*v, 3) ); + TEST_ASSERT_EQUAL_HEX32(v & 0xFFFFFF, readback & 0xFFFFFF); + } +} + +TEST_CASE("SPI flash erase large region", "[spi_flash_ll]") +{ + const esp_partition_t *part = get_test_data_partition(); + + /* Write some noise at the start and the end of the region */ + const char *ohai = "OHAI"; + uint32_t readback; + TEST_ASSERT_EQUAL(FLASH_OK, esp_flash_write(NULL, part->address, ohai, 5)); + TEST_ASSERT_EQUAL(FLASH_OK, esp_flash_write(NULL, part->address + part->size - 5, ohai, 5)); + + /* sanity check what we just wrote */ + TEST_ASSERT_EQUAL(FLASH_OK, esp_flash_read(NULL, &readback, part->address + part->size - 5, 4)); + TEST_ASSERT_EQUAL_HEX32(*((const uint32_t*)ohai), readback); + + /* Erase whole region */ + TEST_ASSERT_EQUAL(FLASH_OK, esp_flash_erase_region(NULL, part->address, part->size)); + + /* ensure both areas we wrote are now all-FFs */ + TEST_ASSERT_EQUAL(FLASH_OK, esp_flash_read(NULL, &readback, part->address, 4)); + TEST_ASSERT_EQUAL_HEX32(0xFFFFFFFF, readback); + + TEST_ASSERT_EQUAL(FLASH_OK, esp_flash_read(NULL, &readback, part->address + part->size - 5, 4)); + TEST_ASSERT_EQUAL_HEX32(0xFFFFFFFF, readback); +} + +TEST_CASE("SPI flash test reading with all speed/mode permutations", "[spi_flash_ll]") +{ + /* Note: this only works if the SPI flash chip supports all these modes & speeds */ + + uint32_t offs = erase_test_region(1); + + /* Write some test data */ + const char *message = "This is some test data."; + TEST_ASSERT_EQUAL(FLASH_OK, esp_flash_write(NULL, offs, message, strlen(message)+1) ); + + // Start by copying the default chip to a structure we can tweak + esp_flash_chip_t chip = *esp_flash_default_chip; + + for (chip.read_mode = 0; + chip.read_mode != ESP_FLASH_READ_MODE_MAX; + chip.read_mode++) { + for (chip.speed = 0; + chip.speed != ESP_FLASH_SPEED_MAX; + chip.speed++) { + printf("mode %d speed %d\n", chip.read_mode, chip.speed); + + TEST_ASSERT_EQUAL(FLASH_OK, esp_flash_init(&chip) ); + + char *buf[strlen(message)+1]; + memset(buf, 0xFF, sizeof(buf)); + TEST_ASSERT_EQUAL(FLASH_OK, esp_flash_read(&chip, buf, offs, sizeof(buf)) ); + TEST_ASSERT_EQUAL_STRING_LEN(message, buf, strlen(message)); + } + } +} -- 2.40.0