1 // Copyright 2015-2019 Espressif Systems (Shanghai) PTE LTD
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #pragma once
16 #include "esp_err.h"
17 #include <stdint.h>
18 #include <stdbool.h>
19
20 #include "hal/spi_flash_types.h"
21
22 #ifdef __cplusplus
23 extern "C" {
24 #endif
25
26 struct spi_flash_chip_t;
27 typedef struct spi_flash_chip_t spi_flash_chip_t;
28
29 typedef struct esp_flash_t esp_flash_t;
30
31 /** @brief Structure for describing a region of flash */
32 typedef struct {
33 uint32_t offset; ///< Start address of this region
34 uint32_t size; ///< Size of the region
35 } esp_flash_region_t;
36
37 /** @brief OS-level integration hooks for accessing flash chips inside a running OS
38 *
39 * It's in the public header because some instances should be allocated statically in the startup
40 * code. May be updated according to hardware version and new flash chip feature requirements,
41 * shouldn't be treated as public API.
42 *
43 * For advanced developers, you may replace some of them with your implementations at your own
44 * risk.
45 */
46 typedef struct {
47 /**
48 * Called before commencing any flash operation. Does not need to be
49 * recursive (ie is called at most once for each call to 'end').
50 */
51 esp_err_t (*start)(void *arg);
52
53 /** Called after completing any flash operation. */
54 esp_err_t (*end)(void *arg);
55
56 /** Called before any erase/write operations to check whether the region is limited by the OS */
57 esp_err_t (*region_protected)(void* arg, size_t start_addr, size_t size);
58
59 /** Delay for at least 'us' microseconds. Called in between 'start' and 'end'. */
60 esp_err_t (*delay_us)(void *arg, uint32_t us);
61
62 /** Called for get temp buffer when buffer from application cannot be directly read into/write from. */
63 void *(*get_temp_buffer)(void* arg, size_t reqest_size, size_t* out_size);
64
65 /** Called for release temp buffer. */
66 void (*release_temp_buffer)(void* arg, void *temp_buf);
67
68 #define SPI_FLASH_YIELD_REQ_YIELD BIT(0)
69 #define SPI_FLASH_YIELD_REQ_SUSPEND BIT(1)
70
71 /** Yield to other tasks. Called during erase operations.
72 * @return ESP_OK means yield needs to be called (got an event to handle), while ESP_ERR_TIMEOUT means skip yield.*/
73 esp_err_t (*check_yield)(void *arg, uint32_t chip_status, uint32_t* out_request);
74
75 #define SPI_FLASH_YIELD_STA_RESUME BIT(2)
76
77 /** Yield to other tasks. Called during erase operations. */
78 esp_err_t (*yield)(void *arg, uint32_t* out_status);
79
80 /** Called for get system time. */
81 int64_t (*get_system_time)(void *arg);
82
83 } esp_flash_os_functions_t;
84
85 /** @brief Structure to describe a SPI flash chip connected to the system.
86
87 Structure must be initialized before use (passed to esp_flash_init()). It's in the public
88 header because some instances should be allocated statically in the startup code. May be
89 updated according to hardware version and new flash chip feature requirements, shouldn't be
90 treated as public API.
91
92 For advanced developers, you may replace some of them with your implementations at your own
93 risk.
94 */
95 struct esp_flash_t {
96 spi_flash_host_inst_t* host; ///< Pointer to hardware-specific "host_driver" structure. Must be initialized before used.
97 const spi_flash_chip_t *chip_drv; ///< Pointer to chip-model-specific "adapter" structure. If NULL, will be detected during initialisation.
98
99 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.
100 void *os_func_data; ///< Pointer to argument for os-specific hooks. Left NULL and will be initialized with ``os_func``.
101
102 esp_flash_io_mode_t read_mode; ///< Configured SPI flash read mode. Set before ``esp_flash_init`` is called.
103 uint32_t size; ///< Size of SPI flash in bytes. If 0, size will be detected during initialisation.
104 uint32_t chip_id; ///< Detected chip id.
105 uint32_t busy :1; ///< This flag is used to verify chip's status.
106 uint32_t reserved_flags :31; ///< reserved.
107 };
108
109
110 /** @brief Initialise SPI flash chip interface.
111 *
112 * This function must be called before any other API functions are called for this chip.
113 *
114 * @note Only the ``host`` and ``read_mode`` fields of the chip structure must
115 * be initialised before this function is called. Other fields may be
116 * auto-detected if left set to zero or NULL.
117 *
118 * @note If the chip->drv pointer is NULL, chip chip_drv will be auto-detected
119 * based on its manufacturer & product IDs. See
120 * ``esp_flash_registered_flash_drivers`` pointer for details of this process.
121 *
122 * @param chip Pointer to SPI flash chip to use. If NULL, esp_flash_default_chip is substituted.
123 * @return ESP_OK on success, or a flash error code if initialisation fails.
124 */
125 esp_err_t esp_flash_init(esp_flash_t *chip);
126
127 /**
128 * Check if appropriate chip driver is set.
129 *
130 * @param chip Pointer to SPI flash chip to use. If NULL, esp_flash_default_chip is substituted.
131 *
132 * @return true if set, otherwise false.
133 */
134 bool esp_flash_chip_driver_initialized(const esp_flash_t *chip);
135
136 /** @brief Read flash ID via the common "RDID" SPI flash command.
137 *
138 * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
139 * @param[out] out_id Pointer to receive ID value.
140 *
141 * ID is a 24-bit value. Lower 16 bits of 'id' are the chip ID, upper 8 bits are the manufacturer ID.
142 *
143 * @return ESP_OK on success, or a flash error code if operation failed.
144 */
145 esp_err_t esp_flash_read_id(esp_flash_t *chip, uint32_t *out_id);
146
147 /** @brief Detect flash size based on flash ID.
148 *
149 * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
150 * @param[out] out_size Detected size in bytes.
151 *
152 * @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
153 * the manufacturer doesn't follow this convention, the size may be incorrectly detected.
154 *
155 * @return ESP_OK on success, or a flash error code if operation failed.
156 */
157 esp_err_t esp_flash_get_size(esp_flash_t *chip, uint32_t *out_size);
158
159 /** @brief Read flash unique ID via the common "RDUID" SPI flash command.
160 *
161 * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init().
162 * @param[out] out_id Pointer to receive unique ID value.
163 *
164 * ID is a 64-bit value.
165 *
166 * @return
167 * - ESP_OK on success, or a flash error code if operation failed.
168 * - ESP_ERR_NOT_SUPPORTED if the chip doesn't support read id.
169 */
170 esp_err_t esp_flash_read_unique_chip_id(esp_flash_t *chip, uint64_t *out_id);
171
172 /** @brief Erase flash chip contents
173 *
174 * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
175 *
176 *
177 * @return
178 * - ESP_OK on success,
179 * - ESP_ERR_NOT_SUPPORTED if the chip is not able to perform the operation. This is indicated by WREN = 1 after the command is sent.
180 * - Other flash error code if operation failed.
181 */
182 esp_err_t esp_flash_erase_chip(esp_flash_t *chip);
183
184 /** @brief Erase a region of the flash chip
185 *
186 * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
187 * @param start Address to start erasing flash. Must be sector aligned.
188 * @param len Length of region to erase. Must also be sector aligned.
189 *
190 * Sector size is specifyed in chip->drv->sector_size field (typically 4096 bytes.) ESP_ERR_INVALID_ARG will be
191 * returned if the start & length are not a multiple of this size.
192 *
193 * Erase is performed using block (multi-sector) erases where possible (block size is specified in
194 * chip->drv->block_erase_size field, typically 65536 bytes). Remaining sectors are erased using individual sector erase
195 * commands.
196 *
197 * @return
198 * - ESP_OK on success,
199 * - ESP_ERR_NOT_SUPPORTED if the chip is not able to perform the operation. This is indicated by WREN = 1 after the command is sent.
200 * - Other flash error code if operation failed.
201 */
202 esp_err_t esp_flash_erase_region(esp_flash_t *chip, uint32_t start, uint32_t len);
203
204 /** @brief Read if the entire chip is write protected
205 *
206 * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
207 * @param[out] write_protected Pointer to boolean, set to the value of the write protect flag.
208 *
209 * @note A correct result for this flag depends on the SPI flash chip model and chip_drv in use (via the 'chip->drv'
210 * field).
211 *
212 * @return ESP_OK on success, or a flash error code if operation failed.
213 */
214 esp_err_t esp_flash_get_chip_write_protect(esp_flash_t *chip, bool *write_protected);
215
216 /** @brief Set write protection for the SPI flash chip
217 *
218 * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
219 * @param write_protect Boolean value for the write protect flag
220 *
221 * @note Correct behaviour of this function depends on the SPI flash chip model and chip_drv in use (via the 'chip->drv'
222 * field).
223 *
224 * Some SPI flash chips may require a power cycle before write protect status can be cleared. Otherwise,
225 * write protection can be removed via a follow-up call to this function.
226 *
227 * @return ESP_OK on success, or a flash error code if operation failed.
228 */
229 esp_err_t esp_flash_set_chip_write_protect(esp_flash_t *chip, bool write_protect);
230
231
232 /** @brief Read the list of individually protectable regions of this SPI flash chip.
233 *
234 * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
235 * @param[out] out_regions Pointer to receive a pointer to the array of protectable regions of the chip.
236 * @param[out] out_num_regions Pointer to an integer receiving the count of protectable regions in the array returned in 'regions'.
237 *
238 * @note Correct behaviour of this function depends on the SPI flash chip model and chip_drv in use (via the 'chip->drv'
239 * field).
240 *
241 * @return ESP_OK on success, or a flash error code if operation failed.
242 */
243 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);
244
245
246 /** @brief Detect if a region of the SPI flash chip is protected
247 *
248 * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
249 * @param region Pointer to a struct describing a protected region. This must match one of the regions returned from esp_flash_get_protectable_regions(...).
250 * @param[out] out_protected Pointer to a flag which is set based on the protected status for this region.
251 *
252 * @note It is possible for this result to be false and write operations to still fail, if protection is enabled for the entire chip.
253 *
254 * @note Correct behaviour of this function depends on the SPI flash chip model and chip_drv in use (via the 'chip->drv'
255 * field).
256 *
257 * @return ESP_OK on success, or a flash error code if operation failed.
258 */
259 esp_err_t esp_flash_get_protected_region(esp_flash_t *chip, const esp_flash_region_t *region, bool *out_protected);
260
261 /** @brief Update the protected status for a region of the SPI flash chip
262 *
263 * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
264 * @param region Pointer to a struct describing a protected region. This must match one of the regions returned from esp_flash_get_protectable_regions(...).
265 * @param protect Write protection flag to set.
266 *
267 * @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.
268 *
269 * @note Correct behaviour of this function depends on the SPI flash chip model and chip_drv in use (via the 'chip->drv'
270 * field).
271 *
272 * @return ESP_OK on success, or a flash error code if operation failed.
273 */
274 esp_err_t esp_flash_set_protected_region(esp_flash_t *chip, const esp_flash_region_t *region, bool protect);
275
276 /** @brief Read data from the SPI flash chip
277 *
278 * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
279 * @param buffer Pointer to a buffer where the data will be read. To get better performance, this should be in the DRAM and word aligned.
280 * @param address Address on flash to read from. Must be less than chip->size field.
281 * @param length Length (in bytes) of data to read.
282 *
283 * There are no alignment constraints on buffer, address or length.
284 *
285 * @note If on-chip flash encryption is used, this function returns raw (ie encrypted) data. Use the flash cache
286 * to transparently decrypt data.
287 *
288 * @return
289 * - ESP_OK: success
290 * - ESP_ERR_NO_MEM: Buffer is in external PSRAM which cannot be concurrently accessed, and a temporary internal buffer could not be allocated.
291 * - or a flash error code if operation failed.
292 */
293 esp_err_t esp_flash_read(esp_flash_t *chip, void *buffer, uint32_t address, uint32_t length);
294
295 /** @brief Write data to the SPI flash chip
296 *
297 * @param chip Pointer to identify flash chip. Must have been successfully initialised via esp_flash_init()
298 * @param address Address on flash to write to. Must be previously erased (SPI NOR flash can only write bits 1->0).
299 * @param buffer Pointer to a buffer with the data to write. To get better performance, this should be in the DRAM and word aligned.
300 * @param length Length (in bytes) of data to write.
301 *
302 * There are no alignment constraints on buffer, address or length.
303 *
304 * @return
305 * - ESP_OK on success,
306 * - ESP_ERR_NOT_SUPPORTED if the chip is not able to perform the operation. This is indicated by WREN = 1 after the command is sent.
307 * - Other flash error code if operation failed.
308 */
309 esp_err_t esp_flash_write(esp_flash_t *chip, const void *buffer, uint32_t address, uint32_t length);
310
311 /** @brief Encrypted and write data to the SPI flash chip using on-chip hardware flash encryption
312 *
313 * @param chip Pointer to identify flash chip. Must be NULL (the main flash chip). For other chips, encrypted write is not supported.
314 * @param address Address on flash to write to. 16 byte aligned. Must be previously erased (SPI NOR flash can only write bits 1->0).
315 * @param buffer Pointer to a buffer with the data to write.
316 * @param length Length (in bytes) of data to write. 16 byte aligned.
317 *
318 * @note Both address & length must be 16 byte aligned, as this is the encryption block size
319 *
320 * @return
321 * - ESP_OK: on success
322 * - ESP_ERR_NOT_SUPPORTED: encrypted write not supported for this chip.
323 * - ESP_ERR_INVALID_ARG: Either the address, buffer or length is invalid.
324 * - or other flash error code from spi_flash_write_encrypted().
325 */
326 esp_err_t esp_flash_write_encrypted(esp_flash_t *chip, uint32_t address, const void *buffer, uint32_t length);
327
328 /** @brief Read and decrypt data from the SPI flash chip using on-chip hardware flash encryption
329 *
330 * @param chip Pointer to identify flash chip. Must be NULL (the main flash chip). For other chips, encrypted read is not supported.
331 * @param address Address on flash to read from.
332 * @param out_buffer Pointer to a buffer for the data to read to.
333 * @param length Length (in bytes) of data to read.
334 *
335 * @return
336 * - ESP_OK: on success
337 * - ESP_ERR_NOT_SUPPORTED: encrypted read not supported for this chip.
338 * - or other flash error code from spi_flash_read_encrypted().
339 */
340 esp_err_t esp_flash_read_encrypted(esp_flash_t *chip, uint32_t address, void *out_buffer, uint32_t length);
341
342 /** @brief Pointer to the "default" SPI flash chip, ie the main chip attached to the MCU.
343
344 This chip is used if the 'chip' argument pass to esp_flash_xxx API functions is ever NULL.
345 */
346 extern esp_flash_t *esp_flash_default_chip;
347
348
349 /*******************************************************************************
350 * Utility Functions
351 ******************************************************************************/
352
353 /**
354 * @brief Returns true if chip is configured for Quad I/O or Quad Fast Read.
355 *
356 * @param chip Pointer to SPI flash chip to use. If NULL, esp_flash_default_chip is substituted.
357 *
358 * @return true if flash works in quad mode, otherwise false
359 */
esp_flash_is_quad_mode(const esp_flash_t * chip)360 static inline bool esp_flash_is_quad_mode(const esp_flash_t *chip)
361 {
362 return (chip->read_mode == SPI_FLASH_QIO) || (chip->read_mode == SPI_FLASH_QOUT);
363 }
364
365 #ifdef __cplusplus
366 }
367 #endif
368