flash_ops.c 28 KB

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