esp_flash_api.c 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  1. /*
  2. * SPDX-FileCopyrightText: 2015-2023 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <stdlib.h>
  7. #include <stdio.h>
  8. #include <sys/param.h>
  9. #include <string.h>
  10. #include "esp_memory_utils.h"
  11. #include "spi_flash_chip_driver.h"
  12. #include "memspi_host_driver.h"
  13. #include "esp_log.h"
  14. #include "sdkconfig.h"
  15. #include "esp_flash_internal.h"
  16. #include "spi_flash_defs.h"
  17. #include "spi_flash_mmap.h"
  18. #include "esp_rom_caps.h"
  19. #include "esp_rom_spiflash.h"
  20. #include "esp_private/esp_clk.h"
  21. #include "esp_spi_flash_counters.h"
  22. #if CONFIG_IDF_TARGET_ESP32S2
  23. #include "esp_crypto_lock.h" // for locking flash encryption peripheral
  24. #endif //CONFIG_IDF_TARGET_ESP32S2
  25. DRAM_ATTR static const char TAG[] = "spi_flash";
  26. #ifdef CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE
  27. #define MAX_WRITE_CHUNK CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE /* write in chunks */
  28. #else
  29. #define MAX_WRITE_CHUNK 8192 /* write in chunks */
  30. #endif // CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE
  31. #define MAX_READ_CHUNK 16384
  32. #define VERIFY_BUF_LEN 64
  33. #ifdef CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS
  34. #define UNSAFE_WRITE_ADDRESS abort()
  35. #else
  36. #define UNSAFE_WRITE_ADDRESS return ESP_ERR_INVALID_ARG
  37. #endif
  38. /* CHECK_WRITE_ADDRESS macro to fail writes which land in the
  39. bootloader, partition table, or running application region.
  40. */
  41. #define CHECK_WRITE_ADDRESS(CHIP, ADDR, SIZE) do { \
  42. if (CHIP && CHIP->os_func->region_protected) { \
  43. esp_err_t ret = CHIP->os_func->region_protected(CHIP->os_func_data, ADDR, SIZE); \
  44. if (ret == ESP_ERR_NOT_ALLOWED) { \
  45. return ret; /* ESP_ERR_NOT_ALLOWED from read-only partition check */ \
  46. } else if (ret != ESP_OK) { \
  47. UNSAFE_WRITE_ADDRESS; /* FAILS or ABORTS */ \
  48. } \
  49. } \
  50. } while(0)
  51. /* Convenience macro for beginning of all API functions.
  52. * Check the return value of `rom_spiflash_api_funcs->chip_check` is correct,
  53. * and the chip supports the operation in question.
  54. */
  55. #define VERIFY_CHIP_OP(op) do { \
  56. if (err != ESP_OK) return err; \
  57. if (chip->chip_drv->op == NULL) { \
  58. return ESP_ERR_FLASH_UNSUPPORTED_CHIP; \
  59. } \
  60. } while (0)
  61. #if CONFIG_SPI_FLASH_ENABLE_COUNTERS
  62. static esp_flash_counters_t esp_flash_stats;
  63. #define COUNTER_START() uint32_t ts_begin = esp_cpu_get_cycle_count()
  64. #define COUNTER_STOP(counter) \
  65. do{ \
  66. esp_flash_stats.counter.count++; \
  67. esp_flash_stats.counter.time += (esp_cpu_get_cycle_count() - ts_begin) / (esp_clk_cpu_freq() / 1000000); \
  68. } while(0)
  69. #define COUNTER_ADD_BYTES(counter, size) \
  70. do { \
  71. esp_flash_stats.counter.bytes += size; \
  72. } while (0)
  73. const esp_flash_counters_t *esp_flash_get_counters(void)
  74. {
  75. return &esp_flash_stats;
  76. }
  77. void esp_flash_reset_counters(void)
  78. {
  79. memset(&esp_flash_stats, 0, sizeof(esp_flash_stats));
  80. }
  81. void esp_flash_dump_counters(FILE* stream)
  82. {
  83. if (stream != NULL) {
  84. fprintf(stream, " read: count=%8ld time=%8ldus bytes=%8ld\n", esp_flash_stats.read.count, esp_flash_stats.read.time, esp_flash_stats.read.bytes);
  85. fprintf(stream, "write: count=%8ld time=%8ldus bytes=%8ld\n", esp_flash_stats.write.count, esp_flash_stats.write.time, esp_flash_stats.write.bytes);
  86. fprintf(stream, "erase: count=%8ld time=%8ldus bytes=%8ld\n", esp_flash_stats.erase.count, esp_flash_stats.erase.time, esp_flash_stats.erase.bytes);
  87. }
  88. }
  89. const spi_flash_counters_t *spi_flash_get_counters(void)
  90. {
  91. return (spi_flash_counters_t *)esp_flash_get_counters();
  92. }
  93. void spi_flash_reset_counters(void)
  94. {
  95. esp_flash_reset_counters();
  96. }
  97. void spi_flash_dump_counters(void)
  98. {
  99. esp_flash_dump_counters(stdout);
  100. }
  101. #else
  102. #define COUNTER_START()
  103. #define COUNTER_STOP(counter)
  104. #define COUNTER_ADD_BYTES(counter, size)
  105. #endif //CONFIG_SPI_FLASH_ENABLE_COUNTERS
  106. #define IO_STR_LEN 10
  107. static const char io_mode_str[][IO_STR_LEN] = {
  108. "slowrd",
  109. "fastrd",
  110. "dout",
  111. "dio",
  112. "qout",
  113. "qio",
  114. [6 ... 15] = "not used", // reserved io mode for future, not used currently.
  115. "opi_str",
  116. "opi_dtr",
  117. };
  118. _Static_assert(sizeof(io_mode_str)/IO_STR_LEN == SPI_FLASH_READ_MODE_MAX, "the io_mode_str should be consistent with the esp_flash_io_mode_t defined in spi_flash_types.h");
  119. esp_err_t esp_flash_read_chip_id(esp_flash_t* chip, uint32_t* flash_id);
  120. #ifndef CONFIG_SPI_FLASH_ROM_IMPL
  121. static esp_err_t spiflash_start_default(esp_flash_t *chip);
  122. static esp_err_t spiflash_end_default(esp_flash_t *chip, esp_err_t err);
  123. static esp_err_t check_chip_pointer_default(esp_flash_t **inout_chip);
  124. static esp_err_t flash_end_flush_cache(esp_flash_t* chip, esp_err_t err, bool bus_acquired, uint32_t address, uint32_t length);
  125. #endif //CONFIG_SPI_FLASH_ROM_IMPL
  126. typedef struct {
  127. esp_err_t (*start)(esp_flash_t *chip);
  128. esp_err_t (*end)(esp_flash_t *chip, esp_err_t err);
  129. esp_err_t (*chip_check)(esp_flash_t **inout_chip);
  130. esp_err_t (*flash_end_flush_cache)(esp_flash_t* chip, esp_err_t err, bool bus_acquired, uint32_t address, uint32_t length);
  131. } rom_spiflash_api_func_t;
  132. #ifndef CONFIG_SPI_FLASH_ROM_IMPL
  133. // These functions can be placed in the ROM. For now we use the code in IDF.
  134. DRAM_ATTR static rom_spiflash_api_func_t default_spiflash_rom_api = {
  135. .start = spiflash_start_default,
  136. .end = spiflash_end_default,
  137. .chip_check = check_chip_pointer_default,
  138. .flash_end_flush_cache = flash_end_flush_cache,
  139. };
  140. DRAM_ATTR rom_spiflash_api_func_t *rom_spiflash_api_funcs = &default_spiflash_rom_api;
  141. #else
  142. extern rom_spiflash_api_func_t *esp_flash_api_funcs;
  143. #define rom_spiflash_api_funcs esp_flash_api_funcs
  144. #endif // CONFIG_SPI_FLASH_ROM_IMPL
  145. /* Static function to notify OS of a new SPI flash operation.
  146. If returns an error result, caller must abort. If returns ESP_OK, caller must
  147. call rom_spiflash_api_funcs->end() before returning.
  148. */
  149. #ifndef CONFIG_SPI_FLASH_ROM_IMPL
  150. static esp_err_t IRAM_ATTR spiflash_start_default(esp_flash_t *chip)
  151. {
  152. if (chip->os_func != NULL && chip->os_func->start != NULL) {
  153. esp_err_t err = chip->os_func->start(chip->os_func_data);
  154. if (err != ESP_OK) {
  155. return err;
  156. }
  157. }
  158. chip->host->driver->dev_config(chip->host);
  159. return ESP_OK;
  160. }
  161. /* Static function to notify OS that SPI flash operation is complete.
  162. */
  163. static esp_err_t IRAM_ATTR spiflash_end_default(esp_flash_t *chip, esp_err_t err)
  164. {
  165. if (chip->os_func != NULL
  166. && chip->os_func->end != NULL) {
  167. esp_err_t end_err = chip->os_func->end(chip->os_func_data);
  168. if (err == ESP_OK) {
  169. err = end_err; // Only return the 'end' error if we haven't already failed
  170. }
  171. }
  172. return err;
  173. }
  174. // check that the 'chip' parameter is properly initialised
  175. static IRAM_ATTR esp_err_t check_chip_pointer_default(esp_flash_t **inout_chip)
  176. {
  177. esp_flash_t *chip = *inout_chip;
  178. if (chip == NULL) {
  179. chip = esp_flash_default_chip;
  180. }
  181. *inout_chip = chip;
  182. if (chip == NULL || !esp_flash_chip_driver_initialized(chip)) {
  183. return ESP_ERR_FLASH_NOT_INITIALISED;
  184. }
  185. return ESP_OK;
  186. }
  187. static IRAM_ATTR esp_err_t flash_end_flush_cache(esp_flash_t* chip, esp_err_t err, bool bus_acquired, uint32_t address, uint32_t length)
  188. {
  189. if (!bus_acquired) {
  190. // Try to acquire the bus again to flush the cache before exit.
  191. esp_err_t acquire_err = rom_spiflash_api_funcs->start(chip);
  192. if (acquire_err != ESP_OK) {
  193. return (err == ESP_OK)? acquire_err: err;
  194. }
  195. }
  196. if (chip->host->driver->flush_cache) {
  197. esp_err_t flush_err = chip->host->driver->flush_cache(chip->host, address, length);
  198. if (err == ESP_OK) {
  199. err = flush_err;
  200. }
  201. }
  202. return rom_spiflash_api_funcs->end(chip, err);
  203. }
  204. #endif //CONFIG_SPI_FLASH_ROM_IMPL
  205. /* Top-level API functions, calling into chip_drv functions via chip->drv */
  206. static esp_err_t detect_spi_flash_chip(esp_flash_t *chip);
  207. bool IRAM_ATTR esp_flash_chip_driver_initialized(const esp_flash_t *chip)
  208. {
  209. if (!chip->chip_drv) return false;
  210. return true;
  211. }
  212. esp_err_t IRAM_ATTR esp_flash_init(esp_flash_t *chip)
  213. {
  214. // Chip init flow
  215. // 1. Read chip id
  216. // 2. (optional) Detect chip vendor
  217. // 3. Get basic parameters of the chip (size, dummy count, etc.)
  218. // 4. Init chip into desired mode (without breaking the cache!)
  219. esp_err_t err = ESP_OK;
  220. if (chip == NULL || chip->host == NULL || chip->host->driver == NULL ||
  221. ((memspi_host_inst_t*)chip->host)->spi == NULL) {
  222. return ESP_ERR_INVALID_ARG;
  223. }
  224. //read chip id
  225. uint32_t flash_id;
  226. int retries = 10;
  227. do {
  228. err = esp_flash_read_chip_id(chip, &flash_id);
  229. } while (err == ESP_ERR_FLASH_NOT_INITIALISED && retries-- > 0);
  230. if (err != ESP_OK) {
  231. return err;
  232. }
  233. chip->chip_id = flash_id;
  234. if (!esp_flash_chip_driver_initialized(chip)) {
  235. // Detect chip_drv
  236. err = detect_spi_flash_chip(chip);
  237. if (err != ESP_OK) {
  238. return err;
  239. }
  240. }
  241. // Detect flash size
  242. uint32_t size;
  243. err = esp_flash_get_physical_size(chip, &size);
  244. if (err != ESP_OK) {
  245. ESP_LOGE(TAG, "failed to get chip size");
  246. return err;
  247. }
  248. if (chip->chip_drv->get_chip_caps == NULL) {
  249. // chip caps get failed, pass the flash capability check.
  250. ESP_EARLY_LOGW(TAG, "get_chip_caps function pointer hasn't been initialized");
  251. } else {
  252. if (((chip->chip_drv->get_chip_caps(chip) & SPI_FLASH_CHIP_CAP_32MB_SUPPORT) == 0) && (size > (16 *1024 * 1024))) {
  253. ESP_EARLY_LOGW(TAG, "Detected flash size > 16 MB, but access beyond 16 MB is not supported for this flash model yet.");
  254. size = (16 * 1024 * 1024);
  255. }
  256. }
  257. ESP_LOGI(TAG, "flash io: %s", io_mode_str[chip->read_mode]);
  258. err = rom_spiflash_api_funcs->start(chip);
  259. if (err != ESP_OK) {
  260. return err;
  261. }
  262. if (err == ESP_OK) {
  263. // Try to set the flash mode to whatever default mode was chosen
  264. err = chip->chip_drv->set_io_mode(chip);
  265. if (err == ESP_ERR_FLASH_NO_RESPONSE && !esp_flash_is_quad_mode(chip)) {
  266. //some chips (e.g. Winbond) don't support to clear QE, treat as success
  267. err = ESP_OK;
  268. }
  269. }
  270. // Done: all fields on 'chip' are initialised
  271. return rom_spiflash_api_funcs->end(chip, err);
  272. }
  273. // Note: This function is only used for internal. Only call this function to initialize the main flash.
  274. // (flash chip on SPI1 CS0)
  275. esp_err_t IRAM_ATTR esp_flash_init_main(esp_flash_t *chip)
  276. {
  277. // Chip init flow
  278. // 1. Read chip id
  279. // 2. (optional) Detect chip vendor
  280. // 3. Get basic parameters of the chip (size, dummy count, etc.)
  281. // 4. Init chip into desired mode (without breaking the cache!)
  282. esp_err_t err = ESP_OK;
  283. bool octal_mode;
  284. if (chip == NULL || chip->host == NULL || chip->host->driver == NULL ||
  285. ((memspi_host_inst_t*)chip->host)->spi == NULL) {
  286. return ESP_ERR_INVALID_ARG;
  287. }
  288. octal_mode = (chip->read_mode >= SPI_FLASH_OPI_FLAG);
  289. //read chip id
  290. // This can indicate the MSPI support OPI, if the flash works on MSPI in OPI mode, we directly bypass read id.
  291. uint32_t flash_id = 0;
  292. if (octal_mode) {
  293. // bypass the reading but get the flash_id from the ROM variable, to avoid resetting the chip to QSPI mode and read the ID again
  294. flash_id = g_rom_flashchip.device_id;
  295. } else {
  296. int retries = 10;
  297. do {
  298. err = esp_flash_read_chip_id(chip, &flash_id);
  299. } while (err == ESP_ERR_FLASH_NOT_INITIALISED && retries-- > 0);
  300. }
  301. if (err != ESP_OK) {
  302. return err;
  303. }
  304. chip->chip_id = flash_id;
  305. if (!esp_flash_chip_driver_initialized(chip)) {
  306. // Detect chip_drv
  307. err = detect_spi_flash_chip(chip);
  308. if (err != ESP_OK) {
  309. return err;
  310. }
  311. }
  312. // Detect flash size
  313. uint32_t size;
  314. err = esp_flash_get_physical_size(chip, &size);
  315. if (err != ESP_OK) {
  316. ESP_EARLY_LOGE(TAG, "failed to get chip size");
  317. return err;
  318. }
  319. if (chip->chip_drv->get_chip_caps == NULL) {
  320. // chip caps get failed, pass the flash capability check.
  321. ESP_EARLY_LOGW(TAG, "get_chip_caps function pointer hasn't been initialized");
  322. } else {
  323. if (((chip->chip_drv->get_chip_caps(chip) & SPI_FLASH_CHIP_CAP_32MB_SUPPORT) == 0) && (size > (16 *1024 * 1024))) {
  324. ESP_EARLY_LOGW(TAG, "Detected flash size > 16 MB, but access beyond 16 MB is not supported for this flash model yet.");
  325. size = (16 * 1024 * 1024);
  326. }
  327. }
  328. ESP_EARLY_LOGI(TAG, "flash io: %s", io_mode_str[chip->read_mode]);
  329. err = rom_spiflash_api_funcs->start(chip);
  330. if (err != ESP_OK) {
  331. return err;
  332. }
  333. if (err == ESP_OK && !octal_mode) {
  334. // Try to set the flash mode to whatever default mode was chosen
  335. err = chip->chip_drv->set_io_mode(chip);
  336. if (err == ESP_ERR_FLASH_NO_RESPONSE && !esp_flash_is_quad_mode(chip)) {
  337. //some chips (e.g. Winbond) don't support to clear QE, treat as success
  338. err = ESP_OK;
  339. }
  340. }
  341. // Done: all fields on 'chip' are initialised
  342. return rom_spiflash_api_funcs->end(chip, err);
  343. }
  344. static esp_err_t IRAM_ATTR read_id_core(esp_flash_t* chip, uint32_t* out_id, bool sanity_check)
  345. {
  346. bool installed = esp_flash_chip_driver_initialized(chip);
  347. esp_err_t err = rom_spiflash_api_funcs->start(chip);
  348. if (err != ESP_OK) {
  349. return err;
  350. }
  351. esp_err_t (*read_id_func)(void*, uint32_t*);
  352. void* read_id_arg;
  353. if (installed && chip->chip_drv->read_id) {
  354. read_id_func = (void*)chip->chip_drv->read_id;
  355. read_id_arg = (void*)chip;
  356. } else {
  357. //default option if the chip is not detected/chosen yet.
  358. read_id_func = (void*)chip->host->driver->read_id;
  359. read_id_arg = (void*)chip->host;
  360. }
  361. // Inner function fails if it sees all-ones or all-zeroes.
  362. err = read_id_func(read_id_arg, out_id);
  363. if (sanity_check && err == ESP_OK) {
  364. // Send RDID command twice, check for a matching result and retry in case we just powered on
  365. uint32_t new_id;
  366. err = read_id_func(read_id_arg, &new_id);
  367. if (err == ESP_OK && (new_id != *out_id)) {
  368. err = ESP_ERR_FLASH_NOT_INITIALISED;
  369. }
  370. }
  371. return rom_spiflash_api_funcs->end(chip, err);
  372. }
  373. // Faster version with sanity check.
  374. // Called in esp_flash_init and unit test (though not public)
  375. esp_err_t esp_flash_read_chip_id(esp_flash_t* chip, uint32_t* out_id)
  376. {
  377. return read_id_core(chip, out_id, true);
  378. }
  379. #ifndef CONFIG_SPI_FLASH_ROM_IMPL
  380. esp_err_t esp_flash_read_id(esp_flash_t* chip, uint32_t* out_id)
  381. {
  382. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  383. //Accept uninitialized chip when reading chip id
  384. if (err != ESP_OK && !(err == ESP_ERR_FLASH_NOT_INITIALISED && chip != NULL)) return err;
  385. if (out_id == NULL) return ESP_ERR_INVALID_ARG;
  386. return read_id_core(chip, out_id, false);
  387. }
  388. #endif //CONFIG_SPI_FLASH_ROM_IMPL
  389. static esp_err_t IRAM_ATTR NOINLINE_ATTR read_unique_id(esp_flash_t* chip, uint64_t* out_uid)
  390. {
  391. esp_err_t err = rom_spiflash_api_funcs->start(chip);
  392. if (err != ESP_OK) {
  393. return err;
  394. }
  395. err = chip->chip_drv->read_unique_id(chip, out_uid);
  396. return rom_spiflash_api_funcs->end(chip, err);
  397. }
  398. esp_err_t esp_flash_read_unique_chip_id(esp_flash_t *chip, uint64_t* out_uid)
  399. {
  400. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  401. if (err != ESP_OK) {
  402. return err;
  403. }
  404. if (chip->chip_drv->get_chip_caps == NULL) {
  405. // chip caps get failed, pass the flash capability check.
  406. ESP_EARLY_LOGW(TAG, "get_chip_caps function pointer hasn't been initialized");
  407. } else {
  408. if ((chip->chip_drv->get_chip_caps(chip) & SPI_FLASH_CHIP_CAP_UNIQUE_ID) == 0) {
  409. ESP_EARLY_LOGE(TAG, "chip %s doesn't support reading unique id", chip->chip_drv->name);
  410. return ESP_ERR_NOT_SUPPORTED;
  411. }
  412. }
  413. if (out_uid == NULL) {
  414. return ESP_ERR_INVALID_ARG;
  415. };
  416. return read_unique_id(chip, out_uid);
  417. }
  418. static esp_err_t IRAM_ATTR detect_spi_flash_chip(esp_flash_t *chip)
  419. {
  420. esp_err_t err;
  421. uint32_t flash_id = chip->chip_id;
  422. // Detect the chip and set the chip_drv structure for it
  423. const spi_flash_chip_t **drivers = esp_flash_registered_chips;
  424. while (*drivers != NULL && !esp_flash_chip_driver_initialized(chip)) {
  425. chip->chip_drv = *drivers;
  426. // start/end SPI operation each time, for multitasking
  427. // and also so esp_flash_registered_flash_drivers can live in flash
  428. ESP_EARLY_LOGD(TAG, "trying chip: %s", chip->chip_drv->name);
  429. err = rom_spiflash_api_funcs->start(chip);
  430. if (err != ESP_OK) {
  431. return err;
  432. }
  433. if (chip->chip_drv->probe(chip, flash_id) != ESP_OK) {
  434. chip->chip_drv = NULL;
  435. }
  436. // if probe succeeded, chip->drv stays set
  437. drivers++;
  438. err = rom_spiflash_api_funcs->end(chip, err);
  439. if (err != ESP_OK) {
  440. return err;
  441. }
  442. }
  443. if (!esp_flash_chip_driver_initialized(chip)) {
  444. return ESP_ERR_NOT_FOUND;
  445. }
  446. ESP_EARLY_LOGI(TAG, "detected chip: %s", chip->chip_drv->name);
  447. return ESP_OK;
  448. }
  449. esp_err_t IRAM_ATTR esp_flash_get_physical_size(esp_flash_t *chip, uint32_t *flash_size)
  450. {
  451. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  452. if (err != ESP_OK) {
  453. return err;
  454. }
  455. VERIFY_CHIP_OP(detect_size);
  456. if (flash_size == NULL) {
  457. return ESP_ERR_INVALID_ARG;
  458. }
  459. err = rom_spiflash_api_funcs->start(chip);
  460. if (err != ESP_OK) {
  461. return err;
  462. }
  463. uint32_t detect_size;
  464. err = chip->chip_drv->detect_size(chip, &detect_size);
  465. if (err == ESP_OK) {
  466. if (chip->size == 0) {
  467. // chip->size will not be changed if detected, it will always be equal to configured flash size.
  468. chip->size = detect_size;
  469. }
  470. *flash_size = detect_size;
  471. }
  472. return rom_spiflash_api_funcs->end(chip, err);
  473. }
  474. #ifndef CONFIG_SPI_FLASH_ROM_IMPL
  475. /* Return true if regions 'a' and 'b' overlap at all, based on their start offsets and lengths. */
  476. inline static bool regions_overlap(uint32_t a_start, uint32_t a_len,uint32_t b_start, uint32_t b_len);
  477. esp_err_t IRAM_ATTR esp_flash_get_size(esp_flash_t *chip, uint32_t *out_size)
  478. {
  479. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  480. if (err != ESP_OK) {
  481. return err;
  482. }
  483. if (out_size == NULL) {
  484. return ESP_ERR_INVALID_ARG;
  485. }
  486. if (chip->size != 0) {
  487. *out_size = chip->size;
  488. return ESP_OK;
  489. }
  490. //Return flash chip physical size, when this API is called before flash initialisation,
  491. //After initialization will return available size.
  492. return esp_flash_get_physical_size(chip, out_size);
  493. }
  494. esp_err_t IRAM_ATTR esp_flash_erase_chip(esp_flash_t *chip)
  495. {
  496. esp_err_t err = ESP_OK;
  497. uint32_t size = 0;
  498. err = esp_flash_get_size(chip, &size);
  499. if (err != ESP_OK) {
  500. ESP_LOGE(TAG, "esp_flash_get_size failed, flash error code: %d", err);
  501. return err;
  502. }
  503. err = esp_flash_erase_region(chip, 0, size);
  504. return err;
  505. }
  506. esp_err_t IRAM_ATTR esp_flash_erase_region(esp_flash_t *chip, uint32_t start, uint32_t len)
  507. {
  508. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  509. VERIFY_CHIP_OP(erase_sector);
  510. VERIFY_CHIP_OP(erase_block);
  511. CHECK_WRITE_ADDRESS(chip, start, len);
  512. uint32_t block_erase_size = chip->chip_drv->erase_block == NULL ? 0 : chip->chip_drv->block_erase_size;
  513. uint32_t sector_size = chip->chip_drv->sector_size;
  514. COUNTER_START();
  515. if (sector_size == 0 || (block_erase_size % sector_size) != 0) {
  516. return ESP_ERR_FLASH_NOT_INITIALISED;
  517. }
  518. if (start > chip->size || start + len > chip->size) {
  519. return ESP_ERR_INVALID_ARG;
  520. }
  521. if ((start % chip->chip_drv->sector_size) != 0 || (len % chip->chip_drv->sector_size) != 0) {
  522. // Can only erase multiples of the sector size, starting at sector boundary
  523. return ESP_ERR_INVALID_ARG;
  524. }
  525. if (len == 0) {
  526. return ESP_OK;
  527. }
  528. err = ESP_OK;
  529. // Check for write protected regions overlapping the erase region
  530. if (chip->chip_drv->get_protected_regions != NULL &&
  531. chip->chip_drv->num_protectable_regions > 0) {
  532. err = rom_spiflash_api_funcs->start(chip);
  533. if (err != ESP_OK) {
  534. return err;
  535. }
  536. uint64_t protected = 0;
  537. err = chip->chip_drv->get_protected_regions(chip, &protected);
  538. if (err == ESP_OK && protected != 0) {
  539. for (int i = 0; i < chip->chip_drv->num_protectable_regions && err == ESP_OK; i++) {
  540. const esp_flash_region_t *region = &chip->chip_drv->protectable_regions[i];
  541. if ((protected & BIT64(i))
  542. && regions_overlap(start, len, region->offset, region->size)) {
  543. err = ESP_ERR_FLASH_PROTECTED;
  544. }
  545. }
  546. }
  547. // Don't lock the SPI flash for the entire erase, as this may be very long
  548. err = rom_spiflash_api_funcs->end(chip, err);
  549. }
  550. if (err != ESP_OK) {
  551. return err;
  552. }
  553. uint32_t erase_addr = start;
  554. uint32_t len_remain = len;
  555. // Indicate whether the bus is acquired by the driver, needs to be released before return
  556. bool bus_acquired = false;
  557. while (1) {
  558. //check before the operation, in case this is called too close to the last operation
  559. if (chip->chip_drv->yield) {
  560. err = chip->chip_drv->yield(chip, 0);
  561. if (err != ESP_OK) {
  562. return err;
  563. }
  564. }
  565. err = rom_spiflash_api_funcs->start(chip);
  566. if (err != ESP_OK) {
  567. break;
  568. }
  569. bus_acquired = true;
  570. #ifndef CONFIG_SPI_FLASH_BYPASS_BLOCK_ERASE
  571. // If possible erase an entire multi-sector block
  572. if (block_erase_size > 0 && len_remain >= block_erase_size && (erase_addr % block_erase_size) == 0) {
  573. err = chip->chip_drv->erase_block(chip, erase_addr);
  574. erase_addr += block_erase_size;
  575. len_remain -= block_erase_size;
  576. COUNTER_ADD_BYTES(erase, block_erase_size);
  577. } else
  578. #endif
  579. {
  580. // Otherwise erase individual sector only
  581. err = chip->chip_drv->erase_sector(chip, erase_addr);
  582. erase_addr += sector_size;
  583. len_remain -= sector_size;
  584. COUNTER_ADD_BYTES(erase, sector_size);
  585. }
  586. assert(len_remain < len);
  587. if (err != ESP_OK || len_remain == 0) {
  588. // On ESP32, the cache re-enable is in the end() function, while flush_cache should
  589. // happen when the cache is still disabled on ESP32. Break before the end() function and
  590. // do end() later
  591. assert(bus_acquired);
  592. break;
  593. }
  594. err = rom_spiflash_api_funcs->end(chip, ESP_OK);
  595. if (err != ESP_OK) {
  596. break;
  597. }
  598. bus_acquired = false;
  599. }
  600. COUNTER_STOP(erase);
  601. return rom_spiflash_api_funcs->flash_end_flush_cache(chip, err, bus_acquired, start, len);
  602. }
  603. #endif // !CONFIG_SPI_FLASH_ROM_IMPL
  604. #if defined(CONFIG_SPI_FLASH_ROM_IMPL) && ESP_ROM_HAS_ERASE_0_REGION_BUG
  605. /* ROM esp_flash_erase_region implementation doesn't handle 0 erase size correctly.
  606. * Check the size and call ROM function instead of overriding it completely.
  607. * The behavior is slightly different from esp_flash_erase_region above, thought:
  608. * here the check for 0 size is done first, but in esp_flash_erase_region the check is
  609. * done after the other arguments are checked.
  610. */
  611. extern esp_err_t rom_esp_flash_erase_region(esp_flash_t *chip, uint32_t start, uint32_t len);
  612. esp_err_t IRAM_ATTR esp_flash_erase_region(esp_flash_t *chip, uint32_t start, uint32_t len)
  613. {
  614. if (len == 0) {
  615. return ESP_OK;
  616. }
  617. return rom_esp_flash_erase_region(chip, start, len);
  618. }
  619. #endif // defined(CONFIG_SPI_FLASH_ROM_IMPL) && ESP_ROM_HAS_ERASE_0_REGION_BUG
  620. #ifndef CONFIG_SPI_FLASH_ROM_IMPL
  621. esp_err_t IRAM_ATTR esp_flash_get_chip_write_protect(esp_flash_t *chip, bool *out_write_protected)
  622. {
  623. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  624. VERIFY_CHIP_OP(get_chip_write_protect);
  625. if (out_write_protected == NULL) {
  626. return ESP_ERR_INVALID_ARG;
  627. }
  628. err = rom_spiflash_api_funcs->start(chip);
  629. if (err != ESP_OK) {
  630. return err;
  631. }
  632. err = chip->chip_drv->get_chip_write_protect(chip, out_write_protected);
  633. return rom_spiflash_api_funcs->end(chip, err);
  634. }
  635. esp_err_t IRAM_ATTR esp_flash_set_chip_write_protect(esp_flash_t *chip, bool write_protect)
  636. {
  637. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  638. VERIFY_CHIP_OP(set_chip_write_protect);
  639. //TODO: skip writing if already locked or unlocked
  640. err = rom_spiflash_api_funcs->start(chip);
  641. if (err != ESP_OK) {
  642. return err;
  643. }
  644. err = chip->chip_drv->set_chip_write_protect(chip, write_protect);
  645. return rom_spiflash_api_funcs->end(chip, err);
  646. }
  647. esp_err_t esp_flash_get_protectable_regions(const esp_flash_t *chip, const esp_flash_region_t **out_regions, uint32_t *out_num_regions)
  648. {
  649. if(out_num_regions != NULL) {
  650. *out_num_regions = 0; // In case caller doesn't check result
  651. }
  652. esp_err_t err = rom_spiflash_api_funcs->chip_check((esp_flash_t **)&chip);
  653. VERIFY_CHIP_OP(get_protected_regions);
  654. if(out_regions == NULL || out_num_regions == NULL) {
  655. return ESP_ERR_INVALID_ARG;
  656. }
  657. *out_num_regions = chip->chip_drv->num_protectable_regions;
  658. *out_regions = chip->chip_drv->protectable_regions;
  659. return ESP_OK;
  660. }
  661. static esp_err_t find_region(const esp_flash_t *chip, const esp_flash_region_t *region, uint8_t *index)
  662. {
  663. if (region == NULL) {
  664. return ESP_ERR_INVALID_ARG;
  665. }
  666. for(*index = 0; *index < chip->chip_drv->num_protectable_regions; (*index)++) {
  667. if (memcmp(&chip->chip_drv->protectable_regions[*index],
  668. region, sizeof(esp_flash_region_t)) == 0) {
  669. return ESP_OK;
  670. }
  671. }
  672. return ESP_ERR_NOT_FOUND;
  673. }
  674. esp_err_t IRAM_ATTR esp_flash_get_protected_region(esp_flash_t *chip, const esp_flash_region_t *region, bool *out_protected)
  675. {
  676. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  677. VERIFY_CHIP_OP(get_protected_regions);
  678. if (out_protected == NULL) {
  679. return ESP_ERR_INVALID_ARG;
  680. }
  681. uint8_t index;
  682. err = find_region(chip, region, &index);
  683. if (err != ESP_OK) {
  684. return err;
  685. }
  686. uint64_t protection_mask = 0;
  687. err = rom_spiflash_api_funcs->start(chip);
  688. if (err != ESP_OK) {
  689. return err;
  690. }
  691. err = chip->chip_drv->get_protected_regions(chip, &protection_mask);
  692. if (err == ESP_OK) {
  693. *out_protected = protection_mask & (1LL << index);
  694. }
  695. return rom_spiflash_api_funcs->end(chip, err);
  696. }
  697. esp_err_t IRAM_ATTR esp_flash_set_protected_region(esp_flash_t *chip, const esp_flash_region_t *region, bool protect)
  698. {
  699. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  700. VERIFY_CHIP_OP(set_protected_regions);
  701. uint8_t index;
  702. err = find_region(chip, region, &index);
  703. if (err != ESP_OK) {
  704. return err;
  705. }
  706. uint64_t protection_mask = 0;
  707. err = rom_spiflash_api_funcs->start(chip);
  708. if (err != ESP_OK) {
  709. return err;
  710. }
  711. err = chip->chip_drv->get_protected_regions(chip, &protection_mask);
  712. if (err == ESP_OK) {
  713. if (protect) {
  714. protection_mask |= (1LL << index);
  715. } else {
  716. protection_mask &= ~(1LL << index);
  717. }
  718. err = chip->chip_drv->set_protected_regions(chip, protection_mask);
  719. }
  720. return rom_spiflash_api_funcs->end(chip, err);
  721. }
  722. esp_err_t IRAM_ATTR esp_flash_read(esp_flash_t *chip, void *buffer, uint32_t address, uint32_t length)
  723. {
  724. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  725. VERIFY_CHIP_OP(read);
  726. if (buffer == NULL || address > chip->size || address+length > chip->size) {
  727. return ESP_ERR_INVALID_ARG;
  728. }
  729. if (length == 0) {
  730. return ESP_OK;
  731. }
  732. //when the cache is disabled, only the DRAM can be read, check whether we need to receive in another buffer in DRAM.
  733. bool direct_read = false;
  734. //If the buffer is internal already, it's ok to use it directly
  735. direct_read |= esp_ptr_in_dram(buffer);
  736. //If not, we need to check if the HW support direct write
  737. direct_read |= chip->host->driver->supports_direct_read(chip->host, buffer);
  738. uint8_t* temp_buffer = NULL;
  739. //each time, we at most read this length
  740. //after that, we release the lock to allow some other operations
  741. size_t read_chunk_size = MIN(MAX_READ_CHUNK, length);
  742. if (!direct_read) {
  743. size_t actual_len = 0;
  744. if (chip->os_func->get_temp_buffer != NULL) {
  745. temp_buffer = chip->os_func->get_temp_buffer(chip->os_func_data, read_chunk_size, &actual_len);
  746. read_chunk_size = actual_len;
  747. }
  748. if (temp_buffer == NULL) {
  749. return ESP_ERR_NO_MEM;
  750. }
  751. }
  752. COUNTER_START();
  753. err = ESP_OK;
  754. do {
  755. err = rom_spiflash_api_funcs->start(chip);
  756. if (err != ESP_OK) {
  757. break;
  758. }
  759. //if required (dma buffer allocated), read to the buffer instead of the original buffer
  760. uint8_t* buffer_to_read = (temp_buffer)? temp_buffer : buffer;
  761. // Length we will read this iteration is either the chunk size or the remaining length, whichever is smaller
  762. size_t length_to_read = MIN(read_chunk_size, length);
  763. if (err == ESP_OK) {
  764. err = chip->chip_drv->read(chip, buffer_to_read, address, length_to_read);
  765. }
  766. if (err != ESP_OK) {
  767. rom_spiflash_api_funcs->end(chip, err);
  768. break;
  769. }
  770. //even if this is failed, the data is still valid, copy before quit
  771. err = rom_spiflash_api_funcs->end(chip, err);
  772. //copy back to the original buffer
  773. if (temp_buffer) {
  774. memcpy(buffer, temp_buffer, length_to_read);
  775. }
  776. address += length_to_read;
  777. length -= length_to_read;
  778. buffer = (void*)((intptr_t)buffer + length_to_read);
  779. COUNTER_ADD_BYTES(read, length_to_read);
  780. } while (err == ESP_OK && length > 0);
  781. if (chip->os_func->release_temp_buffer != NULL) {
  782. chip->os_func->release_temp_buffer(chip->os_func_data, temp_buffer);
  783. }
  784. COUNTER_STOP(read);
  785. return err;
  786. }
  787. #if CONFIG_SPI_FLASH_WARN_SETTING_ZERO_TO_ONE
  788. static esp_err_t IRAM_ATTR s_check_setting_zero_to_one(esp_flash_t *chip, uint32_t verify_address, uint32_t remain_verify_len, const uint32_t *to_write_buf, bool is_encrypted)
  789. {
  790. esp_err_t err = ESP_FAIL;
  791. uint8_t verify_buffer[VERIFY_BUF_LEN];
  792. uint32_t *val_in_flash = (uint32_t *)verify_buffer;
  793. while (remain_verify_len) {
  794. uint32_t this_len = MIN(remain_verify_len, VERIFY_BUF_LEN);
  795. err = chip->chip_drv->read(chip, verify_buffer, verify_address, this_len);
  796. if (err != ESP_OK) {
  797. ESP_DRAM_LOGE(TAG, "failed to read flash to verify if setting zero to one, err: 0x%x", err);
  798. return err;
  799. }
  800. for (int r = 0; r < this_len / sizeof(uint32_t); r++) {
  801. if (is_encrypted) {
  802. (void)to_write_buf;
  803. if (val_in_flash[r] != 0xFFFFFFFF) {
  804. ESP_DRAM_LOGW(TAG, "Write at offset 0x%x but not erased (0x%08x)",
  805. verify_address + r, val_in_flash[r]);
  806. }
  807. } else {
  808. if ((val_in_flash[r] & to_write_buf[r]) != to_write_buf[r]) {
  809. ESP_DRAM_LOGW(TAG, "Write at offset 0x%x requests 0x%08x but will write 0x%08x -> 0x%08x",
  810. verify_address + r, to_write_buf[r], val_in_flash[r], (val_in_flash[r] & to_write_buf[r]));
  811. }
  812. }
  813. }
  814. remain_verify_len -= this_len;
  815. verify_address += this_len;
  816. }
  817. return ESP_OK;
  818. }
  819. #endif //#if CONFIG_SPI_FLASH_WARN_SETTING_ZERO_TO_ONE
  820. #if CONFIG_SPI_FLASH_VERIFY_WRITE
  821. static esp_err_t IRAM_ATTR s_verify_write(esp_flash_t *chip, uint32_t verify_address, uint32_t remain_verify_len, const uint32_t *expected_buf, bool is_encrypted)
  822. {
  823. esp_err_t err = ESP_FAIL;
  824. uint8_t verify_buffer[VERIFY_BUF_LEN];
  825. uint32_t *val_in_flash = (uint32_t *)verify_buffer;
  826. while (remain_verify_len) {
  827. uint32_t this_len = MIN(remain_verify_len, VERIFY_BUF_LEN);
  828. if (is_encrypted) {
  829. err = esp_flash_read_encrypted(chip, verify_address, verify_buffer, this_len);
  830. } else {
  831. err = chip->chip_drv->read(chip, verify_buffer, verify_address, this_len);
  832. }
  833. if (err != ESP_OK) {
  834. ESP_DRAM_LOGE(TAG, "failed to read flash to verify previous write, err: 0x%x", err);
  835. return err;
  836. }
  837. for (int r = 0; r < this_len / sizeof(uint32_t); r++) {
  838. if (val_in_flash[r] != expected_buf[r]) {
  839. #if CONFIG_SPI_FLASH_LOG_FAILED_WRITE
  840. ESP_DRAM_LOGE(TAG, "Bad write at %d offset: 0x%x, expected: 0x%08x, readback: 0x%08x", r, verify_address + r, expected_buf[r], val_in_flash[r]);
  841. #endif //#if CONFIG_SPI_FLASH_LOG_FAILED_WRITE
  842. return ESP_FAIL;
  843. }
  844. }
  845. expected_buf = (uint32_t *)((void *)expected_buf + this_len);
  846. remain_verify_len -= this_len;
  847. verify_address += this_len;
  848. }
  849. return ESP_OK;
  850. }
  851. #endif //#if CONFIG_SPI_FLASH_VERIFY_WRITE
  852. esp_err_t IRAM_ATTR esp_flash_write(esp_flash_t *chip, const void *buffer, uint32_t address, uint32_t length)
  853. {
  854. esp_err_t ret = ESP_FAIL;
  855. #if CONFIG_SPI_FLASH_VERIFY_WRITE
  856. //used for verify write
  857. bool is_encrypted = false;
  858. #endif //CONFIG_SPI_FLASH_VERIFY_WRITE
  859. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  860. VERIFY_CHIP_OP(write);
  861. CHECK_WRITE_ADDRESS(chip, address, length);
  862. if (buffer == NULL || address > chip->size || address+length > chip->size) {
  863. return ESP_ERR_INVALID_ARG;
  864. }
  865. if (length == 0) {
  866. return ESP_OK;
  867. }
  868. //when the cache is disabled, only the DRAM can be read, check whether we need to copy the data first
  869. bool direct_write = false;
  870. //If the buffer is internal already, it's ok to write it directly
  871. direct_write |= esp_ptr_in_dram(buffer);
  872. //If not, we need to check if the HW support direct write
  873. direct_write |= chip->host->driver->supports_direct_write(chip->host, buffer);
  874. // Indicate whether the bus is acquired by the driver, needs to be released before return
  875. bool bus_acquired = false;
  876. err = ESP_OK;
  877. COUNTER_START();
  878. /* Write output in chunks, either by buffering on stack or
  879. by artificially cutting into MAX_WRITE_CHUNK parts (in an OS
  880. environment, this prevents writing from causing interrupt or higher priority task
  881. starvation.) */
  882. uint32_t write_addr = address;
  883. uint32_t len_remain = length;
  884. while (1) {
  885. uint32_t write_len;
  886. const void *write_buf;
  887. uint32_t temp_buf[8];
  888. if (direct_write) {
  889. write_len = MIN(len_remain, MAX_WRITE_CHUNK);
  890. write_buf = buffer;
  891. } else {
  892. write_len = MIN(len_remain, sizeof(temp_buf));
  893. memcpy(temp_buf, buffer, write_len);
  894. write_buf = temp_buf;
  895. }
  896. //check before the operation, in case this is called too close to the last operation
  897. if (chip->chip_drv->yield) {
  898. err = chip->chip_drv->yield(chip, 0);
  899. if (err != ESP_OK) {
  900. return err;
  901. }
  902. }
  903. err = rom_spiflash_api_funcs->start(chip);
  904. if (err != ESP_OK) {
  905. goto restore_cache;
  906. }
  907. bus_acquired = true;
  908. #if CONFIG_SPI_FLASH_WARN_SETTING_ZERO_TO_ONE
  909. err = s_check_setting_zero_to_one(chip, write_addr, write_len, write_buf, is_encrypted);
  910. if (err != ESP_OK) {
  911. //Error happens, we end flash operation. Re-enable cache and flush it
  912. goto restore_cache;
  913. }
  914. #endif //#if CONFIG_SPI_FLASH_WARN_SETTING_ZERO_TO_ONE
  915. err = chip->chip_drv->write(chip, write_buf, write_addr, write_len);
  916. len_remain -= write_len;
  917. assert(len_remain < length);
  918. COUNTER_ADD_BYTES(write, write_len);
  919. if (err != ESP_OK) {
  920. //Error happens, we end flash operation. Re-enable cache and flush it
  921. assert(bus_acquired);
  922. goto restore_cache;
  923. }
  924. #if CONFIG_SPI_FLASH_VERIFY_WRITE
  925. err = s_verify_write(chip, write_addr, write_len, write_buf, is_encrypted);
  926. if (err != ESP_OK) {
  927. //Error happens, we end flash operation. Re-enable cache and flush it
  928. goto restore_cache;
  929. }
  930. #endif //#if CONFIG_SPI_FLASH_VERIFY_WRITE
  931. if (len_remain == 0) {
  932. //Flash operation done
  933. break;
  934. }
  935. err = rom_spiflash_api_funcs->end(chip, err);
  936. if (err != ESP_OK) {
  937. goto restore_cache;
  938. }
  939. bus_acquired = false;
  940. write_addr += write_len;
  941. buffer = (void *)((intptr_t)buffer + write_len);
  942. }
  943. COUNTER_STOP(write);
  944. err = rom_spiflash_api_funcs->flash_end_flush_cache(chip, err, bus_acquired, address, length);
  945. return err;
  946. restore_cache:
  947. COUNTER_STOP(write);
  948. ret = rom_spiflash_api_funcs->flash_end_flush_cache(chip, err, bus_acquired, address, length);
  949. if (ret != ESP_OK) {
  950. ESP_DRAM_LOGE(TAG, "restore cache fail\n");
  951. }
  952. return err;
  953. }
  954. esp_err_t IRAM_ATTR esp_flash_write_encrypted(esp_flash_t *chip, uint32_t address, const void *buffer, uint32_t length)
  955. {
  956. esp_err_t ret = ESP_FAIL;
  957. #if CONFIG_SPI_FLASH_VERIFY_WRITE
  958. //used for verify write
  959. bool is_encrypted = true;
  960. #endif //CONFIG_SPI_FLASH_VERIFY_WRITE
  961. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  962. // Flash encryption only support on main flash.
  963. if (chip != esp_flash_default_chip) {
  964. return ESP_ERR_NOT_SUPPORTED;
  965. }
  966. if (err != ESP_OK) return err;
  967. if (buffer == NULL || address + length > chip->size) {
  968. return ESP_ERR_INVALID_ARG;
  969. }
  970. if ((address % 16) != 0) {
  971. ESP_EARLY_LOGE(TAG, "flash encrypted write address must be 16 bytes aligned");
  972. return ESP_ERR_INVALID_ARG;
  973. }
  974. if (length == 0) {
  975. return ESP_OK;
  976. }
  977. if ((length % 16) != 0) {
  978. ESP_EARLY_LOGE(TAG, "flash encrypted write length must be multiple of 16");
  979. return ESP_ERR_INVALID_SIZE;
  980. }
  981. bool bus_acquired = false;
  982. const uint8_t *ssrc = (const uint8_t *)buffer;
  983. COUNTER_START();
  984. /* On ESP32, write_encrypted encrypts data in RAM as it writes,
  985. so copy to a temporary buffer - 32 bytes at a time.
  986. Each call to write_encrypted takes a 32 byte "row" of
  987. data to encrypt, and each row is two 16 byte AES blocks
  988. that share a key (as derived from flash address).
  989. On ESP32-S2 and later, the temporary buffer need to be
  990. seperated into 16-bytes, 32-bytes, 64-bytes(if supported).
  991. So, on ESP32-S2 and later, here has a totally different
  992. data prepare implementation.
  993. */
  994. uint8_t encrypt_buf[64] __attribute__((aligned(4)));
  995. uint32_t row_size_length;
  996. for (size_t i = 0; i < length; i += row_size_length) {
  997. uint32_t row_addr = address + i;
  998. uint8_t row_size;
  999. uint8_t encrypt_byte;
  1000. #if CONFIG_IDF_TARGET_ESP32
  1001. if (i == 0 && (row_addr % 32) != 0) {
  1002. /* writing to second block of a 32 byte row */
  1003. row_size = 16;
  1004. row_addr -= 16;
  1005. /* copy to second block in buffer */
  1006. memcpy(encrypt_buf + 16, ssrc + i, row_size);
  1007. /* decrypt the first block from flash, will reencrypt to same bytes */
  1008. esp_flash_read_encrypted(chip, row_addr, encrypt_buf, 16);
  1009. } else if (length - i == 16) {
  1010. /* 16 bytes left, is first block of a 32 byte row */
  1011. row_size = 16;
  1012. /* copy to first block in buffer */
  1013. memcpy(encrypt_buf, ssrc + i, row_size);
  1014. /* decrypt the second block from flash, will reencrypt to same bytes */
  1015. esp_flash_read_encrypted(chip, row_addr + 16, encrypt_buf + 16, 16);
  1016. } else {
  1017. /* Writing a full 32 byte row (2 blocks) */
  1018. row_size = 32;
  1019. memcpy(encrypt_buf, ssrc + i, row_size);
  1020. }
  1021. encrypt_byte = 32;
  1022. row_size_length = row_size;
  1023. #else // FOR ESP32-S2, ESP32-S3, ESP32-C3
  1024. if ((row_addr % 64) == 0 && (length - i) >= 64 && SOC_FLASH_ENCRYPTED_XTS_AES_BLOCK_MAX == 64) {
  1025. row_size = 64;
  1026. memcpy(encrypt_buf, ssrc + i, row_size);
  1027. } else if ((row_addr % 32) == 0 && (length - i) >= 32) {
  1028. row_size = 32;
  1029. memcpy(encrypt_buf, ssrc + i, row_size);
  1030. } else {
  1031. row_size = 16;
  1032. memcpy(encrypt_buf, ssrc + i, row_size);
  1033. }
  1034. encrypt_byte = row_size;
  1035. row_size_length = row_size;
  1036. #endif //CONFIG_IDF_TARGET_ESP32
  1037. #if CONFIG_SPI_FLASH_WARN_SETTING_ZERO_TO_ONE
  1038. err = s_check_setting_zero_to_one(chip, row_addr, encrypt_byte, NULL, is_encrypted);
  1039. if (err != ESP_OK) {
  1040. //Error happens, we end flash operation. Re-enable cache and flush it
  1041. goto restore_cache;
  1042. }
  1043. #endif //#if CONFIG_SPI_FLASH_WARN_SETTING_ZERO_TO_ONE
  1044. #if CONFIG_IDF_TARGET_ESP32S2
  1045. esp_crypto_dma_lock_acquire();
  1046. #endif //CONFIG_IDF_TARGET_ESP32S2
  1047. err = rom_spiflash_api_funcs->start(chip);
  1048. if (err != ESP_OK) {
  1049. #if CONFIG_IDF_TARGET_ESP32S2
  1050. esp_crypto_dma_lock_release();
  1051. #endif //CONFIG_IDF_TARGET_ESP32S2
  1052. //Error happens, we end flash operation. Re-enable cache and flush it
  1053. goto restore_cache;
  1054. }
  1055. bus_acquired = true;
  1056. err = chip->chip_drv->write_encrypted(chip, (uint32_t *)encrypt_buf, row_addr, encrypt_byte);
  1057. if (err!= ESP_OK) {
  1058. #if CONFIG_IDF_TARGET_ESP32S2
  1059. esp_crypto_dma_lock_release();
  1060. #endif //CONFIG_IDF_TARGET_ESP32S2
  1061. bus_acquired = false;
  1062. assert(bus_acquired);
  1063. //Error happens, we end flash operation. Re-enable cache and flush it
  1064. goto restore_cache;
  1065. }
  1066. err = rom_spiflash_api_funcs->end(chip, ESP_OK);
  1067. COUNTER_ADD_BYTES(write, encrypt_byte);
  1068. #if CONFIG_IDF_TARGET_ESP32S2
  1069. esp_crypto_dma_lock_release();
  1070. #endif //CONFIG_IDF_TARGET_ESP32S2
  1071. if (err != ESP_OK) {
  1072. bus_acquired = false;
  1073. //Error happens, we end flash operation. Re-enable cache and flush it
  1074. goto restore_cache;
  1075. }
  1076. bus_acquired = false;
  1077. #if CONFIG_SPI_FLASH_VERIFY_WRITE
  1078. err = s_verify_write(chip, row_addr, encrypt_byte, (uint32_t *)encrypt_buf, is_encrypted);
  1079. if (err != ESP_OK) {
  1080. //Error happens, we end flash operation. Re-enable cache and flush it
  1081. goto restore_cache;
  1082. }
  1083. #endif //CONFIG_SPI_FLASH_VERIFY_WRITE
  1084. }
  1085. COUNTER_STOP(write);
  1086. err = rom_spiflash_api_funcs->flash_end_flush_cache(chip, err, bus_acquired, address, length);
  1087. return err;
  1088. restore_cache:
  1089. COUNTER_STOP(write);
  1090. ret = rom_spiflash_api_funcs->flash_end_flush_cache(chip, err, bus_acquired, address, length);
  1091. if (ret != ESP_OK) {
  1092. ESP_DRAM_LOGE(TAG, "restore cache fail\n");
  1093. }
  1094. return err;
  1095. }
  1096. inline static IRAM_ATTR bool regions_overlap(uint32_t a_start, uint32_t a_len,uint32_t b_start, uint32_t b_len)
  1097. {
  1098. uint32_t a_end = a_start + a_len;
  1099. uint32_t b_end = b_start + b_len;
  1100. return (a_end > b_start && b_end > a_start);
  1101. }
  1102. esp_err_t IRAM_ATTR esp_flash_read_encrypted(esp_flash_t *chip, uint32_t address, void *out_buffer, uint32_t length)
  1103. {
  1104. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  1105. if (err != ESP_OK) return err;
  1106. if (address + length > g_rom_flashchip.chip_size) {
  1107. return ESP_ERR_INVALID_SIZE;
  1108. }
  1109. if (length == 0) {
  1110. return ESP_OK;
  1111. }
  1112. if (out_buffer == NULL) {
  1113. return ESP_ERR_INVALID_ARG;
  1114. }
  1115. COUNTER_START();
  1116. const uint8_t *map;
  1117. spi_flash_mmap_handle_t map_handle;
  1118. size_t map_src = address & ~(SPI_FLASH_MMU_PAGE_SIZE - 1);
  1119. size_t map_size = length + (address - map_src);
  1120. err = spi_flash_mmap(map_src, map_size, SPI_FLASH_MMAP_DATA, (const void **)&map, &map_handle);
  1121. if (err != ESP_OK) {
  1122. return err;
  1123. }
  1124. memcpy(out_buffer, map + (address - map_src), length);
  1125. spi_flash_munmap(map_handle);
  1126. COUNTER_ADD_BYTES(read, length);
  1127. COUNTER_STOP(read);
  1128. return err;
  1129. }
  1130. // test only, non-public
  1131. IRAM_ATTR esp_err_t esp_flash_get_io_mode(esp_flash_t* chip, bool* qe)
  1132. {
  1133. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  1134. VERIFY_CHIP_OP(get_io_mode);
  1135. esp_flash_io_mode_t io_mode;
  1136. err = rom_spiflash_api_funcs->start(chip);
  1137. if (err != ESP_OK) {
  1138. return err;
  1139. }
  1140. err = chip->chip_drv->get_io_mode(chip, &io_mode);
  1141. err = rom_spiflash_api_funcs->end(chip, err);
  1142. if (err == ESP_OK) {
  1143. *qe = (io_mode == SPI_FLASH_QOUT);
  1144. }
  1145. return err;
  1146. }
  1147. IRAM_ATTR esp_err_t esp_flash_set_io_mode(esp_flash_t* chip, bool qe)
  1148. {
  1149. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  1150. VERIFY_CHIP_OP(set_io_mode);
  1151. chip->read_mode = (qe? SPI_FLASH_QOUT: SPI_FLASH_SLOWRD);
  1152. err = rom_spiflash_api_funcs->start(chip);
  1153. if (err != ESP_OK) {
  1154. return err;
  1155. }
  1156. err = chip->chip_drv->set_io_mode(chip);
  1157. return rom_spiflash_api_funcs->end(chip, err);
  1158. }
  1159. #endif //CONFIG_SPI_FLASH_ROM_IMPL
  1160. //init suspend mode cmd, uses internal.
  1161. esp_err_t esp_flash_suspend_cmd_init(esp_flash_t* chip)
  1162. {
  1163. ESP_EARLY_LOGW(TAG, "Flash suspend feature is enabled");
  1164. if (chip->chip_drv->get_chip_caps == NULL) {
  1165. // chip caps get failed, pass the flash capability check.
  1166. ESP_EARLY_LOGW(TAG, "get_chip_caps function pointer hasn't been initialized");
  1167. } else {
  1168. if ((chip->chip_drv->get_chip_caps(chip) & SPI_FLASH_CHIP_CAP_SUSPEND) == 0) {
  1169. ESP_EARLY_LOGW(TAG, "Suspend and resume may not supported for this flash model yet.");
  1170. }
  1171. }
  1172. return chip->chip_drv->sus_setup(chip);
  1173. }
  1174. esp_err_t esp_flash_app_disable_protect(bool disable)
  1175. {
  1176. if (disable) {
  1177. return esp_flash_app_disable_os_functions(esp_flash_default_chip);
  1178. } else {
  1179. return esp_flash_app_enable_os_functions(esp_flash_default_chip);
  1180. }
  1181. }