1 // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
15 #ifndef ESP_SPI_FLASH_H
16 #define ESP_SPI_FLASH_H
22 #include "sdkconfig.h"
28 #define ESP_ERR_FLASH_BASE 0x10010
29 #define ESP_ERR_FLASH_OP_FAIL (ESP_ERR_FLASH_BASE + 1)
30 #define ESP_ERR_FLASH_OP_TIMEOUT (ESP_ERR_FLASH_BASE + 2)
32 #define SPI_FLASH_SEC_SIZE 4096 /**< SPI Flash sector size */
34 #define SPI_FLASH_MMU_PAGE_SIZE 0x10000 /**< Flash cache MMU mapping page size */
37 * @brief Initialize SPI flash access driver
39 * This function must be called exactly once, before any other
40 * spi_flash_* functions are called.
41 * Currently this function is called from startup code. There is
42 * no need to call it from application code.
45 void spi_flash_init();
48 * @brief Get flash chip size, as set in binary image header
50 * @note This value does not necessarily match real flash size.
52 * @return size of flash chip, in bytes
54 size_t spi_flash_get_chip_size();
57 * @brief Erase the Flash sector.
59 * @param sector Sector number, the count starts at sector 0, 4KB per sector.
63 esp_err_t spi_flash_erase_sector(size_t sector);
66 * @brief Erase a range of flash sectors
68 * @param start_address Address where erase operation has to start.
70 * @param size Size of erased range, in bytes. Must be divisible by 4kB.
74 esp_err_t spi_flash_erase_range(size_t start_address, size_t size);
78 * @brief Write data to Flash.
80 * @note For fastest write performance, write a 4 byte aligned size at a
81 * 4 byte aligned offset in flash from a source buffer in DRAM. Varying any of
82 * these parameters will still work, but will be slower due to buffering.
84 * @note Writing more than 8KB at a time will be split into multiple
85 * write operations to avoid disrupting other tasks in the system.
87 * @param dest_addr Destination address in Flash.
88 * @param src Pointer to the source buffer.
89 * @param size Length of data, in bytes.
93 esp_err_t spi_flash_write(size_t dest_addr, const void *src, size_t size);
97 * @brief Write data encrypted to Flash.
99 * @note Flash encryption must be enabled for this function to work.
101 * @note Flash encryption must be enabled when calling this function.
102 * If flash encryption is disabled, the function returns
103 * ESP_ERR_INVALID_STATE. Use esp_flash_encryption_enabled()
104 * function to determine if flash encryption is enabled.
106 * @note Both dest_addr and size must be multiples of 16 bytes. For
107 * absolute best performance, both dest_addr and size arguments should
108 * be multiples of 32 bytes.
110 * @param dest_addr Destination address in Flash. Must be a multiple of 16 bytes.
111 * @param src Pointer to the source buffer.
112 * @param size Length of data, in bytes. Must be a multiple of 16 bytes.
116 esp_err_t spi_flash_write_encrypted(size_t dest_addr, const void *src, size_t size);
119 * @brief Read data from Flash.
121 * @note For fastest read performance, all parameters should be
122 * 4 byte aligned. If source address and read size are not 4 byte
123 * aligned, read may be split into multiple flash operations. If
124 * destination buffer is not 4 byte aligned, a temporary buffer will
125 * be allocated on the stack.
127 * @note Reading more than 16KB of data at a time will be split
128 * into multiple reads to avoid disruption to other tasks in the
129 * system. Consider using spi_flash_mmap() to read large amounts
132 * @param src_addr source address of the data in Flash.
133 * @param dest pointer to the destination buffer
134 * @param size length of data
139 esp_err_t spi_flash_read(size_t src_addr, void *dest, size_t size);
143 * @brief Read data from Encrypted Flash.
145 * If flash encryption is enabled, this function will transparently decrypt data as it is read.
146 * If flash encryption is not enabled, this function behaves the same as spi_flash_read().
148 * See esp_flash_encryption_enabled() for a function to check if flash encryption is enabled.
150 * @param src source address of the data in Flash.
151 * @param dest pointer to the destination buffer
152 * @param size length of data
156 esp_err_t spi_flash_read_encrypted(size_t src, void *dest, size_t size);
159 * @brief Enumeration which specifies memory space requested in an mmap call
162 SPI_FLASH_MMAP_DATA, /**< map to data memory (Vaddr0), allows byte-aligned access, 4 MB total */
163 SPI_FLASH_MMAP_INST, /**< map to instruction memory (Vaddr1-3), allows only 4-byte-aligned access, 11 MB total */
164 } spi_flash_mmap_memory_t;
167 * @brief Opaque handle for memory region obtained from spi_flash_mmap.
169 typedef uint32_t spi_flash_mmap_handle_t;
172 * @brief Map region of flash memory into data or instruction address space
174 * This function allocates sufficient number of 64kB MMU pages and configures
175 * them to map the requested region of flash memory into the address space.
176 * It may reuse MMU pages which already provide the required mapping.
178 * As with any allocator, if mmap/munmap are heavily used then the address space
179 * may become fragmented. To troubleshoot issues with page allocation, use
180 * spi_flash_mmap_dump() function.
182 * @param src_addr Physical address in flash where requested region starts.
183 * This address *must* be aligned to 64kB boundary
184 * (SPI_FLASH_MMU_PAGE_SIZE)
185 * @param size Size of region to be mapped. This size will be rounded
186 * up to a 64kB boundary
187 * @param memory Address space where the region should be mapped (data or instruction)
188 * @param[out] out_ptr Output, pointer to the mapped memory region
189 * @param[out] out_handle Output, handle which should be used for spi_flash_munmap call
191 * @return ESP_OK on success, ESP_ERR_NO_MEM if pages can not be allocated
193 esp_err_t spi_flash_mmap(size_t src_addr, size_t size, spi_flash_mmap_memory_t memory,
194 const void** out_ptr, spi_flash_mmap_handle_t* out_handle);
197 * @brief Map sequences of pages of flash memory into data or instruction address space
199 * This function allocates sufficient number of 64kB MMU pages and configures
200 * them to map the indicated pages of flash memory contiguously into address space.
201 * In this respect, it works in a similar way as spi_flash_mmap() but it allows mapping
202 * a (maybe non-contiguous) set of pages into a contiguous region of memory.
204 * @param pages An array of numbers indicating the 64kB pages in flash to be mapped
205 * contiguously into memory. These indicate the indexes of the 64kB pages,
206 * not the byte-size addresses as used in other functions.
207 * Array must be located in internal memory.
208 * @param page_count Number of entries in the pages array
209 * @param memory Address space where the region should be mapped (instruction or data)
210 * @param[out] out_ptr Output, pointer to the mapped memory region
211 * @param[out] out_handle Output, handle which should be used for spi_flash_munmap call
214 * - ESP_OK on success
215 * - ESP_ERR_NO_MEM if pages can not be allocated
216 * - ESP_ERR_INVALID_ARG if pagecount is zero or pages array is not in
219 esp_err_t spi_flash_mmap_pages(const int *pages, size_t page_count, spi_flash_mmap_memory_t memory,
220 const void** out_ptr, spi_flash_mmap_handle_t* out_handle);
224 * @brief Release region previously obtained using spi_flash_mmap
226 * @note Calling this function will not necessarily unmap memory region.
227 * Region will only be unmapped when there are no other handles which
228 * reference this region. In case of partially overlapping regions
229 * it is possible that memory will be unmapped partially.
231 * @param handle Handle obtained from spi_flash_mmap
233 void spi_flash_munmap(spi_flash_mmap_handle_t handle);
236 * @brief Display information about mapped regions
238 * This function lists handles obtained using spi_flash_mmap, along with range
239 * of pages allocated to each handle. It also lists all non-zero entries of
240 * MMU table and corresponding reference counts.
242 void spi_flash_mmap_dump();
245 * @brief get free pages number which can be mmap
247 * This function will return free page number of the mmu table which can mmap,
248 * when you want to call spi_flash_mmap to mmap an ranger of flash data to Dcache or Icache
249 * memmory region, maybe the size of MMU table will exceed,so if you are not sure the
250 * size need mmap is ok, can call the interface and watch how many MMU table page can be
253 * @param memory memmory type of MMU table free page
255 * @return number of free pages which can be mmaped
257 uint32_t spi_flash_mmap_get_free_pages(spi_flash_mmap_memory_t memory);
260 #define SPI_FLASH_CACHE2PHYS_FAIL UINT32_MAX /*<! Result from spi_flash_cache2phys() if flash cache address is invalid */
263 * @brief Given a memory address where flash is mapped, return the corresponding physical flash offset.
265 * Cache address does not have have been assigned via spi_flash_mmap(), any address in memory mapped flash space can be looked up.
267 * @param cached Pointer to flashed cached memory.
270 * - SPI_FLASH_CACHE2PHYS_FAIL If cache address is outside flash cache region, or the address is not mapped.
271 * - Otherwise, returns physical offset in flash
273 size_t spi_flash_cache2phys(const void *cached);
275 /** @brief Given a physical offset in flash, return the address where it is mapped in the memory space.
277 * Physical address does not have to have been assigned via spi_flash_mmap(), any address in flash can be looked up.
279 * @note Only the first matching cache address is returned. If MMU flash cache table is configured so multiple entries
280 * point to the same physical address, there may be more than one cache address corresponding to that physical
281 * address. It is also possible for a single physical address to be mapped to both the IROM and DROM regions.
283 * @note This function doesn't impose any alignment constraints, but if memory argument is SPI_FLASH_MMAP_INST and
284 * phys_offs is not 4-byte aligned, then reading from the returned pointer will result in a crash.
286 * @param phys_offs Physical offset in flash memory to look up.
287 * @param memory Address space type to look up a flash cache address mapping for (instruction or data)
290 * - NULL if the physical address is invalid or not mapped to flash cache of the specified memory type.
291 * - Cached memory address (in IROM or DROM space) corresponding to phys_offs.
293 const void *spi_flash_phys2cache(size_t phys_offs, spi_flash_mmap_memory_t memory);
295 /** @brief Check at runtime if flash cache is enabled on both CPUs
297 * @return true if both CPUs have flash cache enabled, false otherwise.
299 bool spi_flash_cache_enabled();
302 * @brief SPI flash critical section enter function.
305 typedef void (*spi_flash_guard_start_func_t)(void);
307 * @brief SPI flash critical section exit function.
309 typedef void (*spi_flash_guard_end_func_t)(void);
311 * @brief SPI flash operation lock function.
313 typedef void (*spi_flash_op_lock_func_t)(void);
315 * @brief SPI flash operation unlock function.
317 typedef void (*spi_flash_op_unlock_func_t)(void);
320 * Structure holding SPI flash access critical sections management functions.
322 * Flash API uses two types of flash access management functions:
323 * 1) Functions which prepare/restore flash cache and interrupts before calling
324 * appropriate ROM functions (SPIWrite, SPIRead and SPIEraseBlock):
325 * - 'start' function should disables flash cache and non-IRAM interrupts and
326 * is invoked before the call to one of ROM function above.
327 * - 'end' function should restore state of flash cache and non-IRAM interrupts and
328 * is invoked after the call to one of ROM function above.
329 * These two functions are not recursive.
330 * 2) Functions which synchronizes access to internal data used by flash API.
331 * This functions are mostly intended to synchronize access to flash API internal data
332 * in multithreaded environment and use OS primitives:
333 * - 'op_lock' locks access to flash API internal data.
334 * - 'op_unlock' unlocks access to flash API internal data.
335 * These two functions are recursive and can be used around the outside of multiple calls to
336 * 'start' & 'end', in order to create atomic multi-part flash operations.
338 * Different versions of the guarding functions should be used depending on the context of
339 * execution (with or without functional OS). In normal conditions when flash API is called
340 * from task the functions use OS primitives. When there is no OS at all or when
341 * it is not guaranteed that OS is functional (accessing flash from exception handler) these
342 * functions cannot use OS primitives or even does not need them (multithreaded access is not possible).
344 * @note Structure and corresponding guard functions should not reside in flash.
345 * For example structure can be placed in DRAM and functions in IRAM sections.
348 spi_flash_guard_start_func_t start; /**< critical section start function. */
349 spi_flash_guard_end_func_t end; /**< critical section end function. */
350 spi_flash_op_lock_func_t op_lock; /**< flash access API lock function.*/
351 spi_flash_op_unlock_func_t op_unlock; /**< flash access API unlock function.*/
352 } spi_flash_guard_funcs_t;
355 * @brief Sets guard functions to access flash.
357 * @note Pointed structure and corresponding guard functions should not reside in flash.
358 * For example structure can be placed in DRAM and functions in IRAM sections.
360 * @param funcs pointer to structure holding flash access guard functions.
362 void spi_flash_guard_set(const spi_flash_guard_funcs_t* funcs);
366 * @brief Get the guard functions used for flash access
368 * @return The guard functions that were set via spi_flash_guard_set(). These functions
369 * can be called if implementing custom low-level SPI flash operations.
371 const spi_flash_guard_funcs_t *spi_flash_guard_get();
374 * @brief Default OS-aware flash access guard functions
376 extern const spi_flash_guard_funcs_t g_flash_guard_default_ops;
379 * @brief Non-OS flash access guard functions
381 * @note This version of flash guard functions is to be used when no OS is present or from panic handler.
382 * It does not use any OS primitives and IPC and implies that only calling CPU is active.
384 extern const spi_flash_guard_funcs_t g_flash_guard_no_os_ops;
386 #if CONFIG_SPI_FLASH_ENABLE_COUNTERS
389 * Structure holding statistics for one type of operation
392 uint32_t count; // number of times operation was executed
393 uint32_t time; // total time taken, in microseconds
394 uint32_t bytes; // total number of bytes
395 } spi_flash_counter_t;
398 spi_flash_counter_t read;
399 spi_flash_counter_t write;
400 spi_flash_counter_t erase;
401 } spi_flash_counters_t;
404 * @brief Reset SPI flash operation counters
406 void spi_flash_reset_counters();
409 * @brief Print SPI flash operation counters
411 void spi_flash_dump_counters();
414 * @brief Return current SPI flash operation counters
416 * @return pointer to the spi_flash_counters_t structure holding values
417 * of the operation counters
419 const spi_flash_counters_t* spi_flash_get_counters();
421 #endif //CONFIG_SPI_FLASH_ENABLE_COUNTERS
428 #endif /* ESP_SPI_FLASH_H */