flash_ops.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  1. /*
  2. * SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <stdlib.h>
  7. #include <assert.h>
  8. #include <string.h>
  9. #include <stdio.h>
  10. #include <sys/param.h> // For MIN/MAX(a, b)
  11. #include <freertos/FreeRTOS.h>
  12. #include <freertos/task.h>
  13. #include <freertos/semphr.h>
  14. #include <soc/soc.h>
  15. #include <soc/soc_memory_layout.h>
  16. #include "sdkconfig.h"
  17. #include "esp_attr.h"
  18. #include "esp_spi_flash.h"
  19. #include "esp_log.h"
  20. #include "esp_private/system_internal.h"
  21. #include "esp_private/spi_flash_os.h"
  22. #include "esp_private/esp_clk.h"
  23. #if CONFIG_IDF_TARGET_ESP32
  24. #include "esp32/rom/cache.h"
  25. #include "esp32/rom/spi_flash.h"
  26. #elif CONFIG_IDF_TARGET_ESP32S2
  27. #include "esp32s2/rom/cache.h"
  28. #elif CONFIG_IDF_TARGET_ESP32S3
  29. #include "soc/spi_mem_reg.h"
  30. #include "esp32s3/rom/opi_flash.h"
  31. #include "esp32s3/rom/cache.h"
  32. #include "esp32s3/opi_flash_private.h"
  33. #elif CONFIG_IDF_TARGET_ESP32C3
  34. #include "esp32c3/rom/cache.h"
  35. #elif CONFIG_IDF_TARGET_ESP32H2
  36. #include "esp32h2/rom/cache.h"
  37. #elif CONFIG_IDF_TARGET_ESP32C2
  38. #include "esp32c2/rom/cache.h"
  39. #endif
  40. #include "esp_rom_spiflash.h"
  41. #include "esp_flash_partitions.h"
  42. #include "cache_utils.h"
  43. #include "esp_flash.h"
  44. #include "esp_attr.h"
  45. #include "bootloader_flash.h"
  46. #include "esp_compiler.h"
  47. esp_rom_spiflash_result_t IRAM_ATTR spi_flash_write_encrypted_chip(size_t dest_addr, const void *src, size_t size);
  48. /* bytes erased by SPIEraseBlock() ROM function */
  49. #define BLOCK_ERASE_SIZE 65536
  50. /* Limit number of bytes written/read in a single SPI operation,
  51. as these operations disable all higher priority tasks from running.
  52. */
  53. #ifdef CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE
  54. #define MAX_WRITE_CHUNK CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE
  55. #else
  56. #define MAX_WRITE_CHUNK 8192
  57. #endif // CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE
  58. #define MAX_READ_CHUNK 16384
  59. static const char *TAG __attribute__((unused)) = "spi_flash";
  60. #if CONFIG_SPI_FLASH_ENABLE_COUNTERS
  61. static spi_flash_counters_t s_flash_stats;
  62. #define COUNTER_START() uint32_t ts_begin = cpu_hal_get_cycle_count()
  63. #define COUNTER_STOP(counter) \
  64. do{ \
  65. s_flash_stats.counter.count++; \
  66. s_flash_stats.counter.time += (cpu_hal_get_cycle_count() - ts_begin) / (esp_clk_cpu_freq() / 1000000); \
  67. } while(0)
  68. #define COUNTER_ADD_BYTES(counter, size) \
  69. do { \
  70. s_flash_stats.counter.bytes += size; \
  71. } while (0)
  72. #else
  73. #define COUNTER_START()
  74. #define COUNTER_STOP(counter)
  75. #define COUNTER_ADD_BYTES(counter, size)
  76. #endif //CONFIG_SPI_FLASH_ENABLE_COUNTERS
  77. #if CONFIG_SPI_FLASH_USE_LEGACY_IMPL
  78. static esp_err_t spi_flash_translate_rc(esp_rom_spiflash_result_t rc);
  79. #endif //CONFIG_SPI_FLASH_USE_LEGACY_IMPL
  80. static bool is_safe_write_address(size_t addr, size_t size);
  81. static void spi_flash_os_yield(void);
  82. const DRAM_ATTR spi_flash_guard_funcs_t g_flash_guard_default_ops = {
  83. .start = spi_flash_disable_interrupts_caches_and_other_cpu,
  84. .end = spi_flash_enable_interrupts_caches_and_other_cpu,
  85. .op_lock = spi_flash_op_lock,
  86. .op_unlock = spi_flash_op_unlock,
  87. #if !CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED
  88. .is_safe_write_address = is_safe_write_address,
  89. #endif
  90. .yield = spi_flash_os_yield,
  91. };
  92. const DRAM_ATTR spi_flash_guard_funcs_t g_flash_guard_no_os_ops = {
  93. .start = spi_flash_disable_interrupts_caches_and_other_cpu_no_os,
  94. .end = spi_flash_enable_interrupts_caches_no_os,
  95. .op_lock = NULL,
  96. .op_unlock = NULL,
  97. #if !CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED
  98. .is_safe_write_address = NULL,
  99. #endif
  100. .yield = NULL,
  101. };
  102. #ifdef CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS
  103. #define UNSAFE_WRITE_ADDRESS abort()
  104. #else
  105. #define UNSAFE_WRITE_ADDRESS return false
  106. #endif
  107. /* CHECK_WRITE_ADDRESS macro to fail writes which land in the
  108. bootloader, partition table, or running application region.
  109. */
  110. #if CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED
  111. // Following helps in masking "unused variable" warning
  112. #define CHECK_WRITE_ADDRESS(ADDR, SIZE) ({(void) guard;})
  113. #else /* FAILS or ABORTS */
  114. #define CHECK_WRITE_ADDRESS(ADDR, SIZE) do { \
  115. if (guard && guard->is_safe_write_address && !guard->is_safe_write_address(ADDR, SIZE)) { \
  116. return ESP_ERR_INVALID_ARG; \
  117. } \
  118. } while(0)
  119. #endif // CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED
  120. static __attribute__((unused)) bool is_safe_write_address(size_t addr, size_t size)
  121. {
  122. if (!esp_partition_main_flash_region_safe(addr, size)) {
  123. UNSAFE_WRITE_ADDRESS;
  124. }
  125. return true;
  126. }
  127. #if CONFIG_SPI_FLASH_ROM_IMPL
  128. #include "esp_heap_caps.h"
  129. typedef void *(*malloc_internal_cb_t)(size_t size);
  130. void IRAM_ATTR *spi_flash_malloc_internal(size_t size)
  131. {
  132. return heap_caps_malloc(size, MALLOC_CAP_8BIT|MALLOC_CAP_INTERNAL);
  133. }
  134. #endif
  135. void IRAM_ATTR esp_mspi_pin_init(void)
  136. {
  137. #if CONFIG_ESPTOOLPY_OCT_FLASH || CONFIG_SPIRAM_MODE_OCT
  138. esp_rom_opiflash_pin_config();
  139. extern void spi_timing_set_pin_drive_strength(void);
  140. spi_timing_set_pin_drive_strength();
  141. #else
  142. //Set F4R4 board pin drive strength. TODO: IDF-3663
  143. #endif
  144. }
  145. esp_err_t IRAM_ATTR spi_flash_init_chip_state(void)
  146. {
  147. #if CONFIG_ESPTOOLPY_OCT_FLASH
  148. return esp_opiflash_init(rom_spiflash_legacy_data->chip.device_id);
  149. #else
  150. #if CONFIG_IDF_TARGET_ESP32S3
  151. // Currently, only esp32s3 allows high performance mode.
  152. return spi_flash_enable_high_performance_mode();
  153. #else
  154. return ESP_OK;
  155. #endif // CONFIG_IDF_TARGET_ESP32S3
  156. #endif // CONFIG_ESPTOOLPY_OCT_FLASH
  157. }
  158. void spi_flash_init(void)
  159. {
  160. spi_flash_init_lock();
  161. #if CONFIG_SPI_FLASH_ENABLE_COUNTERS
  162. spi_flash_reset_counters();
  163. #endif
  164. #if CONFIG_SPI_FLASH_ROM_IMPL
  165. spi_flash_guard_set(&g_flash_guard_default_ops);
  166. /* These two functions are in ROM only */
  167. extern void spi_flash_mmap_os_func_set(void *(*func1)(size_t size), void (*func2)(void *p));
  168. spi_flash_mmap_os_func_set(spi_flash_malloc_internal, heap_caps_free);
  169. extern esp_err_t spi_flash_mmap_page_num_init(uint32_t page_num);
  170. spi_flash_mmap_page_num_init(128);
  171. #endif
  172. }
  173. #if !CONFIG_SPI_FLASH_ROM_IMPL
  174. static const spi_flash_guard_funcs_t *s_flash_guard_ops;
  175. void IRAM_ATTR spi_flash_guard_set(const spi_flash_guard_funcs_t *funcs)
  176. {
  177. s_flash_guard_ops = funcs;
  178. }
  179. const spi_flash_guard_funcs_t *IRAM_ATTR spi_flash_guard_get(void)
  180. {
  181. return s_flash_guard_ops;
  182. }
  183. #endif
  184. size_t IRAM_ATTR spi_flash_get_chip_size(void)
  185. {
  186. return g_rom_flashchip.chip_size;
  187. }
  188. static inline void IRAM_ATTR spi_flash_guard_start(void)
  189. {
  190. const spi_flash_guard_funcs_t *guard = spi_flash_guard_get();
  191. if (guard && guard->start) {
  192. guard->start();
  193. }
  194. }
  195. static inline void IRAM_ATTR spi_flash_guard_end(void)
  196. {
  197. const spi_flash_guard_funcs_t *guard = spi_flash_guard_get();
  198. if (guard && guard->end) {
  199. guard->end();
  200. }
  201. }
  202. static inline void IRAM_ATTR spi_flash_guard_op_lock(void)
  203. {
  204. const spi_flash_guard_funcs_t *guard = spi_flash_guard_get();
  205. if (guard && guard->op_lock) {
  206. guard->op_lock();
  207. }
  208. }
  209. static inline void IRAM_ATTR spi_flash_guard_op_unlock(void)
  210. {
  211. const spi_flash_guard_funcs_t *guard = spi_flash_guard_get();
  212. if (guard && guard->op_unlock) {
  213. guard->op_unlock();
  214. }
  215. }
  216. static void IRAM_ATTR spi_flash_os_yield(void)
  217. {
  218. #ifdef CONFIG_SPI_FLASH_YIELD_DURING_ERASE
  219. if (likely(xTaskGetSchedulerState() == taskSCHEDULER_RUNNING)) {
  220. vTaskDelay(CONFIG_SPI_FLASH_ERASE_YIELD_TICKS);
  221. }
  222. #endif
  223. }
  224. #ifdef CONFIG_SPI_FLASH_USE_LEGACY_IMPL
  225. static esp_rom_spiflash_result_t IRAM_ATTR spi_flash_unlock(void)
  226. {
  227. static bool unlocked = false;
  228. if (!unlocked) {
  229. spi_flash_guard_start();
  230. bootloader_flash_unlock();
  231. spi_flash_guard_end();
  232. unlocked = true;
  233. }
  234. return ESP_ROM_SPIFLASH_RESULT_OK;
  235. }
  236. #endif // CONFIG_SPI_FLASH_USE_LEGACY_IMPL
  237. esp_err_t IRAM_ATTR spi_flash_erase_sector(size_t sec)
  238. {
  239. const spi_flash_guard_funcs_t *guard = spi_flash_guard_get();
  240. CHECK_WRITE_ADDRESS(sec * SPI_FLASH_SEC_SIZE, SPI_FLASH_SEC_SIZE);
  241. return spi_flash_erase_range(sec * SPI_FLASH_SEC_SIZE, SPI_FLASH_SEC_SIZE);
  242. }
  243. #ifdef CONFIG_SPI_FLASH_USE_LEGACY_IMPL
  244. //deprecated, only used in compatible mode
  245. esp_err_t IRAM_ATTR spi_flash_erase_range(size_t start_addr, size_t size)
  246. {
  247. const spi_flash_guard_funcs_t *guard = spi_flash_guard_get();
  248. CHECK_WRITE_ADDRESS(start_addr, size);
  249. if (start_addr % SPI_FLASH_SEC_SIZE != 0) {
  250. return ESP_ERR_INVALID_ARG;
  251. }
  252. if (size % SPI_FLASH_SEC_SIZE != 0) {
  253. return ESP_ERR_INVALID_SIZE;
  254. }
  255. if (size + start_addr > spi_flash_get_chip_size()) {
  256. return ESP_ERR_INVALID_SIZE;
  257. }
  258. size_t start = start_addr / SPI_FLASH_SEC_SIZE;
  259. size_t end = start + size / SPI_FLASH_SEC_SIZE;
  260. const size_t sectors_per_block = BLOCK_ERASE_SIZE / SPI_FLASH_SEC_SIZE;
  261. COUNTER_START();
  262. esp_rom_spiflash_result_t rc;
  263. rc = spi_flash_unlock();
  264. if (rc == ESP_ROM_SPIFLASH_RESULT_OK) {
  265. #ifdef CONFIG_SPI_FLASH_YIELD_DURING_ERASE
  266. int64_t no_yield_time_us = 0;
  267. #endif
  268. for (size_t sector = start; sector != end && rc == ESP_ROM_SPIFLASH_RESULT_OK; ) {
  269. #ifdef CONFIG_SPI_FLASH_YIELD_DURING_ERASE
  270. int64_t start_time_us = esp_system_get_time();
  271. #endif
  272. spi_flash_guard_start();
  273. #ifndef CONFIG_SPI_FLASH_BYPASS_BLOCK_ERASE
  274. if (sector % sectors_per_block == 0 && end - sector >= sectors_per_block) {
  275. rc = esp_rom_spiflash_erase_block(sector / sectors_per_block);
  276. sector += sectors_per_block;
  277. COUNTER_ADD_BYTES(erase, sectors_per_block * SPI_FLASH_SEC_SIZE);
  278. } else
  279. #endif
  280. {
  281. rc = esp_rom_spiflash_erase_sector(sector);
  282. ++sector;
  283. COUNTER_ADD_BYTES(erase, SPI_FLASH_SEC_SIZE);
  284. }
  285. spi_flash_guard_end();
  286. #ifdef CONFIG_SPI_FLASH_YIELD_DURING_ERASE
  287. no_yield_time_us += (esp_system_get_time() - start_time_us);
  288. if (no_yield_time_us / 1000 >= CONFIG_SPI_FLASH_ERASE_YIELD_DURATION_MS) {
  289. no_yield_time_us = 0;
  290. if (s_flash_guard_ops && s_flash_guard_ops->yield) {
  291. s_flash_guard_ops->yield();
  292. }
  293. }
  294. #endif
  295. }
  296. }
  297. COUNTER_STOP(erase);
  298. spi_flash_guard_start();
  299. // Ensure WEL is 0 after the operation, even if the erase failed.
  300. esp_rom_spiflash_write_disable();
  301. spi_flash_check_and_flush_cache(start_addr, size);
  302. spi_flash_guard_end();
  303. return spi_flash_translate_rc(rc);
  304. }
  305. /* Wrapper around esp_rom_spiflash_write() that verifies data as written if CONFIG_SPI_FLASH_VERIFY_WRITE is set.
  306. If CONFIG_SPI_FLASH_VERIFY_WRITE is not set, this is esp_rom_spiflash_write().
  307. */
  308. static IRAM_ATTR esp_rom_spiflash_result_t spi_flash_write_inner(uint32_t target, const uint32_t *src_addr, int32_t len)
  309. {
  310. #ifndef CONFIG_SPI_FLASH_VERIFY_WRITE
  311. return esp_rom_spiflash_write(target, src_addr, len);
  312. #else // CONFIG_SPI_FLASH_VERIFY_WRITE
  313. esp_rom_spiflash_result_t res = ESP_ROM_SPIFLASH_RESULT_OK;
  314. assert(len % sizeof(uint32_t) == 0);
  315. uint32_t before_buf[ESP_ROM_SPIFLASH_BUFF_BYTE_READ_NUM / sizeof(uint32_t)];
  316. uint32_t after_buf[ESP_ROM_SPIFLASH_BUFF_BYTE_READ_NUM / sizeof(uint32_t)];
  317. uint32_t *expected_buf = before_buf;
  318. int32_t remaining = len;
  319. for(int i = 0; i < len; i += sizeof(before_buf)) {
  320. int i_w = i / sizeof(uint32_t); // index in words (i is an index in bytes)
  321. int32_t read_len = MIN(sizeof(before_buf), remaining);
  322. // Read "before" contents from flash
  323. res = esp_rom_spiflash_read(target + i, before_buf, read_len);
  324. if (res != ESP_ROM_SPIFLASH_RESULT_OK) {
  325. break;
  326. }
  327. for (int r = 0; r < read_len; r += sizeof(uint32_t)) {
  328. int r_w = r / sizeof(uint32_t); // index in words (r is index in bytes)
  329. uint32_t write = src_addr[i_w + r_w];
  330. uint32_t before = before_buf[r_w];
  331. uint32_t expected = write & before;
  332. #ifdef CONFIG_SPI_FLASH_WARN_SETTING_ZERO_TO_ONE
  333. if ((before & write) != write) {
  334. spi_flash_guard_end();
  335. ESP_LOGW(TAG, "Write at offset 0x%x requests 0x%08x but will write 0x%08x -> 0x%08x",
  336. target + i + r, write, before, before & write);
  337. spi_flash_guard_start();
  338. }
  339. #endif
  340. expected_buf[r_w] = expected;
  341. }
  342. res = esp_rom_spiflash_write(target + i, &src_addr[i_w], read_len);
  343. if (res != ESP_ROM_SPIFLASH_RESULT_OK) {
  344. break;
  345. }
  346. res = esp_rom_spiflash_read(target + i, after_buf, read_len);
  347. if (res != ESP_ROM_SPIFLASH_RESULT_OK) {
  348. break;
  349. }
  350. for (int r = 0; r < read_len; r += sizeof(uint32_t)) {
  351. int r_w = r / sizeof(uint32_t); // index in words (r is index in bytes)
  352. uint32_t expected = expected_buf[r_w];
  353. uint32_t actual = after_buf[r_w];
  354. if (expected != actual) {
  355. #ifdef CONFIG_SPI_FLASH_LOG_FAILED_WRITE
  356. spi_flash_guard_end();
  357. ESP_LOGE(TAG, "Bad write at offset 0x%x expected 0x%08x readback 0x%08x", target + i + r, expected, actual);
  358. spi_flash_guard_start();
  359. #endif
  360. res = ESP_ROM_SPIFLASH_RESULT_ERR;
  361. }
  362. }
  363. if (res != ESP_ROM_SPIFLASH_RESULT_OK) {
  364. break;
  365. }
  366. remaining -= read_len;
  367. }
  368. return res;
  369. #endif // CONFIG_SPI_FLASH_VERIFY_WRITE
  370. }
  371. esp_err_t IRAM_ATTR spi_flash_write(size_t dst, const void *srcv, size_t size)
  372. {
  373. const spi_flash_guard_funcs_t *guard = spi_flash_guard_get();
  374. CHECK_WRITE_ADDRESS(dst, size);
  375. // Out of bound writes are checked in ROM code, but we can give better
  376. // error code here
  377. if (dst + size > g_rom_flashchip.chip_size) {
  378. return ESP_ERR_INVALID_SIZE;
  379. }
  380. if (size == 0) {
  381. return ESP_OK;
  382. }
  383. esp_rom_spiflash_result_t rc = ESP_ROM_SPIFLASH_RESULT_OK;
  384. COUNTER_START();
  385. const uint8_t *srcc = (const uint8_t *) srcv;
  386. /*
  387. * Large operations are split into (up to) 3 parts:
  388. * - Left padding: 4 bytes up to the first 4-byte aligned destination offset.
  389. * - Middle part
  390. * - Right padding: 4 bytes from the last 4-byte aligned offset covered.
  391. */
  392. size_t left_off = dst & ~3U;
  393. size_t left_size = MIN(((dst + 3) & ~3U) - dst, size);
  394. size_t mid_off = left_size;
  395. size_t mid_size = (size - left_size) & ~3U;
  396. size_t right_off = left_size + mid_size;
  397. size_t right_size = size - mid_size - left_size;
  398. rc = spi_flash_unlock();
  399. if (rc != ESP_ROM_SPIFLASH_RESULT_OK) {
  400. goto out;
  401. }
  402. if (left_size > 0) {
  403. uint32_t t = 0xffffffff;
  404. memcpy(((uint8_t *) &t) + (dst - left_off), srcc, left_size);
  405. spi_flash_guard_start();
  406. rc = spi_flash_write_inner(left_off, &t, 4);
  407. spi_flash_guard_end();
  408. if (rc != ESP_ROM_SPIFLASH_RESULT_OK) {
  409. goto out;
  410. }
  411. COUNTER_ADD_BYTES(write, 4);
  412. }
  413. if (mid_size > 0) {
  414. /* If src buffer is 4-byte aligned as well and is not in a region that requires cache access to be enabled, we
  415. * can write directly without buffering in RAM. */
  416. #ifdef ESP_PLATFORM
  417. bool direct_write = esp_ptr_internal(srcc)
  418. && esp_ptr_byte_accessible(srcc)
  419. && ((uintptr_t) srcc + mid_off) % 4 == 0;
  420. #else
  421. bool direct_write = true;
  422. #endif
  423. while(mid_size > 0 && rc == ESP_ROM_SPIFLASH_RESULT_OK) {
  424. uint32_t write_buf[8];
  425. uint32_t write_size = MIN(mid_size, MAX_WRITE_CHUNK);
  426. const uint8_t *write_src = srcc + mid_off;
  427. if (!direct_write) {
  428. write_size = MIN(write_size, sizeof(write_buf));
  429. memcpy(write_buf, write_src, write_size);
  430. write_src = (const uint8_t *)write_buf;
  431. }
  432. spi_flash_guard_start();
  433. rc = spi_flash_write_inner(dst + mid_off, (const uint32_t *) write_src, write_size);
  434. spi_flash_guard_end();
  435. COUNTER_ADD_BYTES(write, write_size);
  436. mid_size -= write_size;
  437. mid_off += write_size;
  438. }
  439. if (rc != ESP_ROM_SPIFLASH_RESULT_OK) {
  440. goto out;
  441. }
  442. }
  443. if (right_size > 0) {
  444. uint32_t t = 0xffffffff;
  445. memcpy(&t, srcc + right_off, right_size);
  446. spi_flash_guard_start();
  447. rc = spi_flash_write_inner(dst + right_off, &t, 4);
  448. spi_flash_guard_end();
  449. if (rc != ESP_ROM_SPIFLASH_RESULT_OK) {
  450. goto out;
  451. }
  452. COUNTER_ADD_BYTES(write, 4);
  453. }
  454. out:
  455. COUNTER_STOP(write);
  456. spi_flash_guard_start();
  457. // Ensure WEL is 0 after the operation, even if the write failed.
  458. esp_rom_spiflash_write_disable();
  459. spi_flash_check_and_flush_cache(dst, size);
  460. spi_flash_guard_end();
  461. return spi_flash_translate_rc(rc);
  462. }
  463. #endif // CONFIG_SPI_FLASH_USE_LEGACY_IMPL
  464. #if !CONFIG_SPI_FLASH_USE_LEGACY_IMPL
  465. #if !CONFIG_ESPTOOLPY_OCT_FLASH // Test for encryption on opi flash, IDF-3852.
  466. extern void spi_common_set_dummy_output(esp_rom_spiflash_read_mode_t mode);
  467. extern void spi_dummy_len_fix(uint8_t spi, uint8_t freqdiv);
  468. void IRAM_ATTR flash_rom_init(void)
  469. {
  470. uint32_t freqdiv = 0;
  471. #if CONFIG_IDF_TARGET_ESP32
  472. uint32_t dummy_bit = 0;
  473. #if CONFIG_ESPTOOLPY_FLASHFREQ_80M
  474. dummy_bit = ESP_ROM_SPIFLASH_DUMMY_LEN_PLUS_80M;
  475. #elif CONFIG_ESPTOOLPY_FLASHFREQ_40M
  476. dummy_bit = ESP_ROM_SPIFLASH_DUMMY_LEN_PLUS_40M;
  477. #elif CONFIG_ESPTOOLPY_FLASHFREQ_26M
  478. dummy_bit = ESP_ROM_SPIFLASH_DUMMY_LEN_PLUS_26M;
  479. #elif CONFIG_ESPTOOLPY_FLASHFREQ_20M
  480. dummy_bit = ESP_ROM_SPIFLASH_DUMMY_LEN_PLUS_20M;
  481. #endif
  482. #endif//CONFIG_IDF_TARGET_ESP32
  483. #if CONFIG_ESPTOOLPY_FLASHFREQ_80M
  484. freqdiv = 1;
  485. #elif CONFIG_ESPTOOLPY_FLASHFREQ_40M
  486. freqdiv = 2;
  487. #elif CONFIG_ESPTOOLPY_FLASHFREQ_26M
  488. freqdiv = 3;
  489. #elif CONFIG_ESPTOOLPY_FLASHFREQ_20M
  490. freqdiv = 4;
  491. #endif
  492. #if !CONFIG_IDF_TARGET_ESP32S2 && !CONFIG_IDF_TARGET_ESP32
  493. esp_rom_spiflash_read_mode_t read_mode;
  494. #if CONFIG_ESPTOOLPY_FLASHMODE_QIO
  495. read_mode = ESP_ROM_SPIFLASH_QIO_MODE;
  496. #elif CONFIG_ESPTOOLPY_FLASHMODE_QOUT
  497. read_mode = ESP_ROM_SPIFLASH_QOUT_MODE;
  498. #elif CONFIG_ESPTOOLPY_FLASHMODE_DIO
  499. read_mode = ESP_ROM_SPIFLASH_DIO_MODE;
  500. #elif CONFIG_ESPTOOLPY_FLASHMODE_DOUT
  501. read_mode = ESP_ROM_SPIFLASH_DOUT_MODE;
  502. #endif
  503. #endif //!CONFIG_IDF_TARGET_ESP32S2 && !CONFIG_IDF_TARGET_ESP32
  504. #if CONFIG_IDF_TARGET_ESP32
  505. g_rom_spiflash_dummy_len_plus[1] = dummy_bit;
  506. #else
  507. spi_dummy_len_fix(1, freqdiv);
  508. #endif //CONFIG_IDF_TARGET_ESP32
  509. #if !CONFIG_IDF_TARGET_ESP32S2 && !CONFIG_IDF_TARGET_ESP32
  510. spi_common_set_dummy_output(read_mode);
  511. #endif //!CONFIG_IDF_TARGET_ESP32S2
  512. esp_rom_spiflash_config_clk(freqdiv, 1);
  513. }
  514. #endif //CONFIG_ESPTOOLPY_OCT_FLASH
  515. #else
  516. void IRAM_ATTR flash_rom_init(void)
  517. {
  518. return;
  519. }
  520. esp_err_t IRAM_ATTR spi_flash_write_encrypted(size_t dest_addr, const void *src, size_t size)
  521. {
  522. esp_err_t err = ESP_OK;
  523. const spi_flash_guard_funcs_t *guard = spi_flash_guard_get();
  524. CHECK_WRITE_ADDRESS(dest_addr, size);
  525. if ((dest_addr % 16) != 0) {
  526. return ESP_ERR_INVALID_ARG;
  527. }
  528. if ((size % 16) != 0) {
  529. return ESP_ERR_INVALID_SIZE;
  530. }
  531. COUNTER_START();
  532. esp_rom_spiflash_result_t rc = spi_flash_unlock();
  533. err = spi_flash_translate_rc(rc);
  534. if (err != ESP_OK) {
  535. goto fail;
  536. }
  537. #ifndef CONFIG_SPI_FLASH_VERIFY_WRITE
  538. err = spi_flash_write_encrypted_chip(dest_addr, src, size);
  539. COUNTER_ADD_BYTES(write, size);
  540. spi_flash_guard_start();
  541. esp_rom_spiflash_write_disable();
  542. spi_flash_check_and_flush_cache(dest_addr, size);
  543. spi_flash_guard_end();
  544. #else
  545. const uint32_t* src_w = (const uint32_t*)src;
  546. uint32_t read_buf[ESP_ROM_SPIFLASH_BUFF_BYTE_READ_NUM / sizeof(uint32_t)];
  547. int32_t remaining = size;
  548. for(int i = 0; i < size; i += sizeof(read_buf)) {
  549. int i_w = i / sizeof(uint32_t); // index in words (i is an index in bytes)
  550. int32_t read_len = MIN(sizeof(read_buf), remaining);
  551. // Read "before" contents from flash
  552. esp_err_t err = spi_flash_read(dest_addr + i, read_buf, read_len);
  553. if (err != ESP_OK) {
  554. break;
  555. }
  556. #ifdef CONFIG_SPI_FLASH_WARN_SETTING_ZERO_TO_ONE
  557. //The written data cannot be predicted, so warning is shown if any of the bits is not 1.
  558. for (int r = 0; r < read_len; r += sizeof(uint32_t)) {
  559. uint32_t before = read_buf[r / sizeof(uint32_t)];
  560. if (before != 0xFFFFFFFF) {
  561. ESP_LOGW(TAG, "Encrypted write at offset 0x%x but not erased (0x%08x)",
  562. dest_addr + i + r, before);
  563. }
  564. }
  565. #endif
  566. err = spi_flash_write_encrypted_chip(dest_addr + i, src + i, read_len);
  567. if (err != ESP_OK) {
  568. break;
  569. }
  570. COUNTER_ADD_BYTES(write, size);
  571. spi_flash_guard_start();
  572. esp_rom_spiflash_write_disable();
  573. spi_flash_check_and_flush_cache(dest_addr, size);
  574. spi_flash_guard_end();
  575. err = spi_flash_read_encrypted(dest_addr + i, read_buf, read_len);
  576. if (err != ESP_OK) {
  577. break;
  578. }
  579. for (int r = 0; r < read_len; r += sizeof(uint32_t)) {
  580. int r_w = r / sizeof(uint32_t); // index in words (r is index in bytes)
  581. uint32_t expected = src_w[i_w + r_w];
  582. uint32_t actual = read_buf[r_w];
  583. if (expected != actual) {
  584. #ifdef CONFIG_SPI_FLASH_LOG_FAILED_WRITE
  585. ESP_LOGE(TAG, "Bad write at offset 0x%x expected 0x%08x readback 0x%08x", dest_addr + i + r, expected, actual);
  586. #endif
  587. err = ESP_FAIL;
  588. }
  589. }
  590. if (err != ESP_OK) {
  591. break;
  592. }
  593. remaining -= read_len;
  594. }
  595. #endif // CONFIG_SPI_FLASH_VERIFY_WRITE
  596. fail:
  597. COUNTER_STOP(write);
  598. return err;
  599. }
  600. esp_err_t IRAM_ATTR spi_flash_read(size_t src, void *dstv, size_t size)
  601. {
  602. // Out of bound reads are checked in ROM code, but we can give better
  603. // error code here
  604. if (src + size > g_rom_flashchip.chip_size) {
  605. return ESP_ERR_INVALID_SIZE;
  606. }
  607. if (size == 0) {
  608. return ESP_OK;
  609. }
  610. esp_rom_spiflash_result_t rc = ESP_ROM_SPIFLASH_RESULT_OK;
  611. COUNTER_START();
  612. spi_flash_guard_start();
  613. /* To simplify boundary checks below, we handle small reads separately. */
  614. if (size < 16) {
  615. uint32_t t[6]; /* Enough for 16 bytes + 4 on either side for padding. */
  616. uint32_t read_src = src & ~3U;
  617. uint32_t left_off = src & 3U;
  618. uint32_t read_size = (left_off + size + 3) & ~3U;
  619. rc = esp_rom_spiflash_read(read_src, t, read_size);
  620. if (rc != ESP_ROM_SPIFLASH_RESULT_OK) {
  621. goto out;
  622. }
  623. COUNTER_ADD_BYTES(read, read_size);
  624. #ifdef ESP_PLATFORM
  625. if (esp_ptr_external_ram(dstv)) {
  626. spi_flash_guard_end();
  627. memcpy(dstv, ((uint8_t *) t) + left_off, size);
  628. spi_flash_guard_start();
  629. } else {
  630. memcpy(dstv, ((uint8_t *) t) + left_off, size);
  631. }
  632. #else
  633. memcpy(dstv, ((uint8_t *) t) + left_off, size);
  634. #endif
  635. goto out;
  636. }
  637. uint8_t *dstc = (uint8_t *) dstv;
  638. intptr_t dsti = (intptr_t) dstc;
  639. /*
  640. * Large operations are split into (up to) 3 parts:
  641. * - The middle part: from the first 4-aligned position in src to the first
  642. * 4-aligned position in dst.
  643. */
  644. size_t src_mid_off = (src % 4 == 0 ? 0 : 4 - (src % 4));
  645. size_t dst_mid_off = (dsti % 4 == 0 ? 0 : 4 - (dsti % 4));
  646. size_t mid_size = (size - MAX(src_mid_off, dst_mid_off)) & ~3U;
  647. /*
  648. * - Once the middle part is in place, src_mid_off bytes from the preceding
  649. * 4-aligned source location are added on the left.
  650. */
  651. size_t pad_left_src = src & ~3U;
  652. size_t pad_left_size = src_mid_off;
  653. /*
  654. * - Finally, the right part is added: from the end of the middle part to
  655. * the end. Depending on the alignment of source and destination, this may
  656. * be a 4 or 8 byte read from pad_right_src.
  657. */
  658. size_t pad_right_src = (src + pad_left_size + mid_size) & ~3U;
  659. size_t pad_right_off = (pad_right_src - src);
  660. size_t pad_right_size = (size - pad_right_off);
  661. #ifdef ESP_PLATFORM
  662. bool direct_read = esp_ptr_internal(dstc)
  663. && esp_ptr_byte_accessible(dstc)
  664. && ((uintptr_t) dstc + dst_mid_off) % 4 == 0;
  665. #else
  666. bool direct_read = true;
  667. #endif
  668. if (mid_size > 0) {
  669. uint32_t mid_remaining = mid_size;
  670. uint32_t mid_read = 0;
  671. while (mid_remaining > 0) {
  672. uint32_t read_size = MIN(mid_remaining, MAX_READ_CHUNK);
  673. uint32_t read_buf[8];
  674. uint8_t *read_dst_final = dstc + dst_mid_off + mid_read;
  675. uint8_t *read_dst = read_dst_final;
  676. if (!direct_read) {
  677. read_size = MIN(read_size, sizeof(read_buf));
  678. read_dst = (uint8_t *) read_buf;
  679. }
  680. rc = esp_rom_spiflash_read(src + src_mid_off + mid_read,
  681. (uint32_t *) read_dst, read_size);
  682. if (rc != ESP_ROM_SPIFLASH_RESULT_OK) {
  683. goto out;
  684. }
  685. mid_remaining -= read_size;
  686. mid_read += read_size;
  687. if (!direct_read) {
  688. spi_flash_guard_end();
  689. memcpy(read_dst_final, read_buf, read_size);
  690. spi_flash_guard_start();
  691. } else if (mid_remaining > 0) {
  692. /* Drop guard momentarily, allows other tasks to preempt */
  693. spi_flash_guard_end();
  694. spi_flash_guard_start();
  695. }
  696. }
  697. COUNTER_ADD_BYTES(read, mid_size);
  698. /*
  699. * If offsets in src and dst are different, perform an in-place shift
  700. * to put destination data into its final position.
  701. * Note that the shift can be left (src_mid_off < dst_mid_off) or right.
  702. */
  703. if (src_mid_off != dst_mid_off) {
  704. if (!direct_read) {
  705. spi_flash_guard_end();
  706. }
  707. memmove(dstc + src_mid_off, dstc + dst_mid_off, mid_size);
  708. if (!direct_read) {
  709. spi_flash_guard_start();
  710. }
  711. }
  712. }
  713. if (pad_left_size > 0) {
  714. uint32_t t;
  715. rc = esp_rom_spiflash_read(pad_left_src, &t, 4);
  716. if (rc != ESP_ROM_SPIFLASH_RESULT_OK) {
  717. goto out;
  718. }
  719. COUNTER_ADD_BYTES(read, 4);
  720. if (!direct_read) {
  721. spi_flash_guard_end();
  722. }
  723. memcpy(dstc, ((uint8_t *) &t) + (4 - pad_left_size), pad_left_size);
  724. if (!direct_read) {
  725. spi_flash_guard_start();
  726. }
  727. }
  728. if (pad_right_size > 0) {
  729. uint32_t t[2];
  730. int32_t read_size = (pad_right_size <= 4 ? 4 : 8);
  731. rc = esp_rom_spiflash_read(pad_right_src, t, read_size);
  732. if (rc != ESP_ROM_SPIFLASH_RESULT_OK) {
  733. goto out;
  734. }
  735. COUNTER_ADD_BYTES(read, read_size);
  736. if (!direct_read) {
  737. spi_flash_guard_end();
  738. }
  739. memcpy(dstc + pad_right_off, t, pad_right_size);
  740. if (!direct_read) {
  741. spi_flash_guard_start();
  742. }
  743. }
  744. out:
  745. spi_flash_guard_end();
  746. COUNTER_STOP(read);
  747. return spi_flash_translate_rc(rc);
  748. }
  749. #endif // !CONFIG_SPI_FLASH_USE_LEGACY_IMPL
  750. esp_err_t IRAM_ATTR spi_flash_read_encrypted(size_t src, void *dstv, size_t size)
  751. {
  752. if (src + size > g_rom_flashchip.chip_size) {
  753. return ESP_ERR_INVALID_SIZE;
  754. }
  755. if (size == 0) {
  756. return ESP_OK;
  757. }
  758. esp_err_t err;
  759. const uint8_t *map;
  760. spi_flash_mmap_handle_t map_handle;
  761. size_t map_src = src & ~(SPI_FLASH_MMU_PAGE_SIZE - 1);
  762. size_t map_size = size + (src - map_src);
  763. err = spi_flash_mmap(map_src, map_size, SPI_FLASH_MMAP_DATA, (const void **)&map, &map_handle);
  764. if (err != ESP_OK) {
  765. return err;
  766. }
  767. memcpy(dstv, map + (src - map_src), size);
  768. spi_flash_munmap(map_handle);
  769. return err;
  770. }
  771. #if CONFIG_SPI_FLASH_USE_LEGACY_IMPL
  772. static esp_err_t IRAM_ATTR spi_flash_translate_rc(esp_rom_spiflash_result_t rc)
  773. {
  774. switch (rc) {
  775. case ESP_ROM_SPIFLASH_RESULT_OK:
  776. return ESP_OK;
  777. case ESP_ROM_SPIFLASH_RESULT_TIMEOUT:
  778. return ESP_ERR_FLASH_OP_TIMEOUT;
  779. case ESP_ROM_SPIFLASH_RESULT_ERR:
  780. default:
  781. return ESP_ERR_FLASH_OP_FAIL;
  782. }
  783. }
  784. #endif //CONFIG_SPI_FLASH_USE_LEGACY_IMPL
  785. #if CONFIG_SPI_FLASH_ENABLE_COUNTERS
  786. static inline void dump_counter(spi_flash_counter_t *counter, const char *name)
  787. {
  788. ESP_LOGI(TAG, "%s count=%8d time=%8dus bytes=%8d\n", name,
  789. counter->count, counter->time, counter->bytes);
  790. }
  791. const spi_flash_counters_t *spi_flash_get_counters(void)
  792. {
  793. return &s_flash_stats;
  794. }
  795. void spi_flash_reset_counters(void)
  796. {
  797. memset(&s_flash_stats, 0, sizeof(s_flash_stats));
  798. }
  799. void spi_flash_dump_counters(void)
  800. {
  801. dump_counter(&s_flash_stats.read, "read ");
  802. dump_counter(&s_flash_stats.write, "write");
  803. dump_counter(&s_flash_stats.erase, "erase");
  804. }
  805. #endif //CONFIG_SPI_FLASH_ENABLE_COUNTERS
  806. #if CONFIG_SPI_FLASH_USE_LEGACY_IMPL && !CONFIG_IDF_TARGET_ESP32
  807. // TODO esp32s2: Remove once ESP32-S2 & later chips has new SPI Flash API support
  808. esp_flash_t *esp_flash_default_chip = NULL;
  809. #endif
  810. void IRAM_ATTR spi_flash_set_rom_required_regs(void)
  811. {
  812. #if CONFIG_ESPTOOLPY_OCT_FLASH
  813. //Disable the variable dummy mode when doing timing tuning
  814. CLEAR_PERI_REG_MASK(SPI_MEM_DDR_REG(1), SPI_MEM_SPI_FMEM_VAR_DUMMY);
  815. /**
  816. * STR /DTR mode setting is done every time when `esp_rom_opiflash_exec_cmd` is called
  817. *
  818. * Add any registers that are not set in ROM SPI flash functions here in the future
  819. */
  820. #endif
  821. }
  822. void IRAM_ATTR spi_flash_set_vendor_required_regs(void)
  823. {
  824. #if CONFIG_ESPTOOLPY_OCT_FLASH
  825. //Flash chip requires MSPI specifically, call this function to set them
  826. esp_opiflash_set_required_regs();
  827. #else
  828. //currently we don't need to set other MSPI registers for Quad Flash
  829. #endif
  830. }