flash_ops.c 30 KB

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