flash_ops.c 29 KB

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