esp_flash_api.c 46 KB

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