flash_ops.c 29 KB

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