esp_flash_api.c 44 KB

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