flash_ops.c 30 KB

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