flash_ops.c 25 KB

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