flash_ops.c 30 KB

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