flash_ops.c 28 KB

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