esp_flash_api.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  1. // Copyright 2015-2019 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <stdlib.h>
  15. #include <stdio.h>
  16. #include <sys/param.h>
  17. #include <string.h>
  18. #include "spi_flash_chip_driver.h"
  19. #include "memspi_host_driver.h"
  20. #include "esp_log.h"
  21. #include "sdkconfig.h"
  22. #include "esp_flash_internal.h"
  23. #include "spi_flash_defs.h"
  24. #if CONFIG_IDF_TARGET_ESP32S2
  25. #include "esp_crypto_lock.h" // for locking flash encryption peripheral
  26. #endif //CONFIG_IDF_TARGET_ESP32S2
  27. static const char TAG[] = "spi_flash";
  28. #ifdef CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE
  29. #define MAX_WRITE_CHUNK CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE /* write in chunks */
  30. #else
  31. #define MAX_WRITE_CHUNK 8192 /* write in chunks */
  32. #endif // CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE
  33. #define MAX_READ_CHUNK 16384
  34. #ifdef CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS
  35. #define UNSAFE_WRITE_ADDRESS abort()
  36. #else
  37. #define UNSAFE_WRITE_ADDRESS return ESP_ERR_INVALID_ARG
  38. #endif
  39. /* CHECK_WRITE_ADDRESS macro to fail writes which land in the
  40. bootloader, partition table, or running application region.
  41. */
  42. #if CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED
  43. #define CHECK_WRITE_ADDRESS(CHIP, ADDR, SIZE)
  44. #else /* FAILS or ABORTS */
  45. #define CHECK_WRITE_ADDRESS(CHIP, ADDR, SIZE) do { \
  46. if (CHIP && CHIP->os_func->region_protected && CHIP->os_func->region_protected(CHIP->os_func_data, ADDR, SIZE)) { \
  47. UNSAFE_WRITE_ADDRESS; \
  48. } \
  49. } while(0)
  50. #endif // CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED
  51. #define IO_STR_LEN 7
  52. static const char io_mode_str[][IO_STR_LEN] = {
  53. "slowrd",
  54. "fastrd",
  55. "dout",
  56. "dio",
  57. "qout",
  58. "qio",
  59. };
  60. _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_ll.h");
  61. esp_err_t esp_flash_read_chip_id(esp_flash_t* chip, uint32_t* flash_id);
  62. #ifndef CONFIG_SPI_FLASH_ROM_IMPL
  63. static esp_err_t spiflash_start_default(esp_flash_t *chip);
  64. static esp_err_t spiflash_end_default(esp_flash_t *chip, esp_err_t err);
  65. static esp_err_t check_chip_pointer_default(esp_flash_t **inout_chip);
  66. 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);
  67. #endif //CONFIG_SPI_FLASH_ROM_IMPL
  68. typedef struct {
  69. esp_err_t (*start)(esp_flash_t *chip);
  70. esp_err_t (*end)(esp_flash_t *chip, esp_err_t err);
  71. esp_err_t (*chip_check)(esp_flash_t **inout_chip);
  72. esp_err_t (*flash_end_flush_cache)(esp_flash_t* chip, esp_err_t err, bool bus_acquired, uint32_t address, uint32_t length);
  73. } rom_spiflash_api_func_t;
  74. #ifndef CONFIG_SPI_FLASH_ROM_IMPL
  75. // These functions can be placed in the ROM. For now we use the code in IDF.
  76. DRAM_ATTR static rom_spiflash_api_func_t default_spiflash_rom_api = {
  77. .start = spiflash_start_default,
  78. .end = spiflash_end_default,
  79. .chip_check = check_chip_pointer_default,
  80. .flash_end_flush_cache = flash_end_flush_cache,
  81. };
  82. DRAM_ATTR rom_spiflash_api_func_t *rom_spiflash_api_funcs = &default_spiflash_rom_api;
  83. #else
  84. extern rom_spiflash_api_func_t *esp_flash_api_funcs;
  85. #define rom_spiflash_api_funcs esp_flash_api_funcs
  86. #endif // CONFIG_SPI_FLASH_ROM_IMPL
  87. /* Static function to notify OS of a new SPI flash operation.
  88. If returns an error result, caller must abort. If returns ESP_OK, caller must
  89. call rom_spiflash_api_funcs->end() before returning.
  90. */
  91. #ifndef CONFIG_SPI_FLASH_ROM_IMPL
  92. static esp_err_t IRAM_ATTR spiflash_start_default(esp_flash_t *chip)
  93. {
  94. if (chip->os_func != NULL && chip->os_func->start != NULL) {
  95. esp_err_t err = chip->os_func->start(chip->os_func_data);
  96. if (err != ESP_OK) {
  97. return err;
  98. }
  99. }
  100. chip->host->driver->dev_config(chip->host);
  101. return ESP_OK;
  102. }
  103. /* Static function to notify OS that SPI flash operation is complete.
  104. */
  105. static esp_err_t IRAM_ATTR spiflash_end_default(esp_flash_t *chip, esp_err_t err)
  106. {
  107. if (chip->os_func != NULL
  108. && chip->os_func->end != NULL) {
  109. esp_err_t end_err = chip->os_func->end(chip->os_func_data);
  110. if (err == ESP_OK) {
  111. err = end_err; // Only return the 'end' error if we haven't already failed
  112. }
  113. }
  114. return err;
  115. }
  116. // check that the 'chip' parameter is properly initialised
  117. static esp_err_t check_chip_pointer_default(esp_flash_t **inout_chip)
  118. {
  119. esp_flash_t *chip = *inout_chip;
  120. if (chip == NULL) {
  121. chip = esp_flash_default_chip;
  122. }
  123. *inout_chip = chip;
  124. if (chip == NULL || !esp_flash_chip_driver_initialized(chip)) {
  125. return ESP_ERR_FLASH_NOT_INITIALISED;
  126. }
  127. return ESP_OK;
  128. }
  129. 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)
  130. {
  131. if (!bus_acquired) {
  132. // Try to acquire the bus again to flush the cache before exit.
  133. esp_err_t acquire_err = rom_spiflash_api_funcs->start(chip);
  134. if (acquire_err != ESP_OK) {
  135. return (err == ESP_OK)? acquire_err: err;
  136. }
  137. }
  138. if (chip->host->driver->flush_cache) {
  139. esp_err_t flush_err = chip->host->driver->flush_cache(chip->host, address, length);
  140. if (err == ESP_OK) {
  141. err = flush_err;
  142. }
  143. }
  144. return rom_spiflash_api_funcs->end(chip, err);
  145. }
  146. #endif //CONFIG_SPI_FLASH_ROM_IMPL
  147. /* Top-level API functions, calling into chip_drv functions via chip->drv */
  148. static esp_err_t detect_spi_flash_chip(esp_flash_t *chip);
  149. bool esp_flash_chip_driver_initialized(const esp_flash_t *chip)
  150. {
  151. if (!chip->chip_drv) return false;
  152. return true;
  153. }
  154. esp_err_t IRAM_ATTR esp_flash_init(esp_flash_t *chip)
  155. {
  156. // Chip init flow
  157. // 1. Read chip id
  158. // 2. (optional) Detect chip vendor
  159. // 3. Get basic parameters of the chip (size, dummy count, etc.)
  160. // 4. Init chip into desired mode (without breaking the cache!)
  161. esp_err_t err = ESP_OK;
  162. if (chip == NULL || chip->host == NULL || chip->host->driver == NULL ||
  163. ((memspi_host_inst_t*)chip->host)->spi == NULL) {
  164. return ESP_ERR_INVALID_ARG;
  165. }
  166. //read chip id
  167. uint32_t flash_id;
  168. int retries = 10;
  169. do {
  170. err = esp_flash_read_chip_id(chip, &flash_id);
  171. } while (err == ESP_ERR_FLASH_NOT_INITIALISED && retries-- > 0);
  172. if (err != ESP_OK) {
  173. return err;
  174. }
  175. chip->chip_id = flash_id;
  176. if (!esp_flash_chip_driver_initialized(chip)) {
  177. // Detect chip_drv
  178. err = detect_spi_flash_chip(chip);
  179. if (err != ESP_OK) {
  180. return err;
  181. }
  182. }
  183. // Detect flash size
  184. uint32_t size;
  185. err = esp_flash_get_size(chip, &size);
  186. if (err != ESP_OK) {
  187. ESP_LOGE(TAG, "failed to get chip size");
  188. return err;
  189. }
  190. if (chip->chip_drv->get_chip_caps == NULL) {
  191. // chip caps get failed, pass the flash capability check.
  192. ESP_EARLY_LOGW(TAG, "get_chip_caps function pointer hasn't been initialized");
  193. } else {
  194. if (((chip->chip_drv->get_chip_caps(chip) & SPI_FLASH_CHIP_CAP_32MB_SUPPORT) == 0) && (size > (16 *1024 * 1024))) {
  195. ESP_EARLY_LOGW(TAG, "Detected flash size > 16 MB, but access beyond 16 MB is not supported for this flash model yet.");
  196. size = (16 * 1024 * 1024);
  197. }
  198. }
  199. ESP_LOGI(TAG, "flash io: %s", io_mode_str[chip->read_mode]);
  200. err = rom_spiflash_api_funcs->start(chip);
  201. if (err != ESP_OK) {
  202. return err;
  203. }
  204. if (err == ESP_OK) {
  205. // Try to set the flash mode to whatever default mode was chosen
  206. err = chip->chip_drv->set_io_mode(chip);
  207. if (err == ESP_ERR_FLASH_NO_RESPONSE && !esp_flash_is_quad_mode(chip)) {
  208. //some chips (e.g. Winbond) don't support to clear QE, treat as success
  209. err = ESP_OK;
  210. }
  211. }
  212. // Done: all fields on 'chip' are initialised
  213. return rom_spiflash_api_funcs->end(chip, err);
  214. }
  215. static esp_err_t IRAM_ATTR read_id_core(esp_flash_t* chip, uint32_t* out_id, bool sanity_check)
  216. {
  217. bool installed = esp_flash_chip_driver_initialized(chip);
  218. esp_err_t err = rom_spiflash_api_funcs->start(chip);
  219. if (err != ESP_OK) {
  220. return err;
  221. }
  222. esp_err_t (*read_id_func)(void*, uint32_t*);
  223. void* read_id_arg;
  224. if (installed && chip->chip_drv->read_id) {
  225. read_id_func = (void*)chip->chip_drv->read_id;
  226. read_id_arg = (void*)chip;
  227. } else {
  228. //default option if the chip is not detected/chosen yet.
  229. read_id_func = (void*)chip->host->driver->read_id;
  230. read_id_arg = (void*)chip->host;
  231. }
  232. // Inner function fails if it sees all-ones or all-zeroes.
  233. err = read_id_func(read_id_arg, out_id);
  234. if (sanity_check && err == ESP_OK) {
  235. // Send RDID command twice, check for a matching result and retry in case we just powered on
  236. uint32_t new_id;
  237. err = read_id_func(read_id_arg, &new_id);
  238. if (err == ESP_OK && (new_id != *out_id)) {
  239. err = ESP_ERR_FLASH_NOT_INITIALISED;
  240. }
  241. }
  242. return rom_spiflash_api_funcs->end(chip, err);
  243. }
  244. // Faster version with sanity check.
  245. // Called in esp_flash_init and unit test (though not public)
  246. esp_err_t esp_flash_read_chip_id(esp_flash_t* chip, uint32_t* out_id)
  247. {
  248. return read_id_core(chip, out_id, true);
  249. }
  250. #ifndef CONFIG_SPI_FLASH_ROM_IMPL
  251. esp_err_t esp_flash_read_id(esp_flash_t* chip, uint32_t* out_id)
  252. {
  253. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  254. //Accept uninitialized chip when reading chip id
  255. if (err != ESP_OK && !(err == ESP_ERR_FLASH_NOT_INITIALISED && chip != NULL)) return err;
  256. if (out_id == NULL) return ESP_ERR_INVALID_ARG;
  257. return read_id_core(chip, out_id, false);
  258. }
  259. #endif //CONFIG_SPI_FLASH_ROM_IMPL
  260. static esp_err_t IRAM_ATTR NOINLINE_ATTR read_unique_id(esp_flash_t* chip, uint64_t* out_uid)
  261. {
  262. esp_err_t err = rom_spiflash_api_funcs->start(chip);
  263. if (err != ESP_OK) {
  264. return err;
  265. }
  266. err = chip->chip_drv->read_unique_id(chip, out_uid);
  267. return rom_spiflash_api_funcs->end(chip, err);
  268. }
  269. esp_err_t esp_flash_read_unique_chip_id(esp_flash_t *chip, uint64_t* out_uid)
  270. {
  271. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  272. if (err != ESP_OK) {
  273. return err;
  274. }
  275. if (chip->chip_drv->get_chip_caps == NULL) {
  276. // chip caps get failed, pass the flash capability check.
  277. ESP_EARLY_LOGW(TAG, "get_chip_caps function pointer hasn't been initialized");
  278. } else {
  279. if ((chip->chip_drv->get_chip_caps(chip) & SPI_FLASH_CHIP_CAP_UNIQUE_ID) == 0) {
  280. ESP_EARLY_LOGE(TAG, "chip %s doesn't support reading unique id", chip->chip_drv->name);
  281. return ESP_ERR_NOT_SUPPORTED;
  282. }
  283. }
  284. if (out_uid == NULL) {
  285. return ESP_ERR_INVALID_ARG;
  286. };
  287. return read_unique_id(chip, out_uid);
  288. }
  289. static esp_err_t IRAM_ATTR detect_spi_flash_chip(esp_flash_t *chip)
  290. {
  291. esp_err_t err;
  292. uint32_t flash_id = chip->chip_id;
  293. // Detect the chip and set the chip_drv structure for it
  294. const spi_flash_chip_t **drivers = esp_flash_registered_chips;
  295. while (*drivers != NULL && !esp_flash_chip_driver_initialized(chip)) {
  296. chip->chip_drv = *drivers;
  297. // start/end SPI operation each time, for multitasking
  298. // and also so esp_flash_registered_flash_drivers can live in flash
  299. ESP_LOGD(TAG, "trying chip: %s", chip->chip_drv->name);
  300. err = rom_spiflash_api_funcs->start(chip);
  301. if (err != ESP_OK) {
  302. return err;
  303. }
  304. if (chip->chip_drv->probe(chip, flash_id) != ESP_OK) {
  305. chip->chip_drv = NULL;
  306. }
  307. // if probe succeeded, chip->drv stays set
  308. drivers++;
  309. err = rom_spiflash_api_funcs->end(chip, err);
  310. if (err != ESP_OK) {
  311. return err;
  312. }
  313. }
  314. if (!esp_flash_chip_driver_initialized(chip)) {
  315. return ESP_ERR_NOT_FOUND;
  316. }
  317. ESP_LOGI(TAG, "detected chip: %s", chip->chip_drv->name);
  318. return ESP_OK;
  319. }
  320. #ifndef CONFIG_SPI_FLASH_ROM_IMPL
  321. /* Convenience macro for beginning of all API functions.
  322. * Check the return value of `rom_spiflash_api_funcs->chip_check` is correct,
  323. * and the chip supports the operation in question.
  324. */
  325. #define VERIFY_CHIP_OP(OP) do { \
  326. if (err != ESP_OK) return err; \
  327. if (chip->chip_drv->OP == NULL) { \
  328. return ESP_ERR_FLASH_UNSUPPORTED_CHIP; \
  329. } \
  330. } while (0)
  331. /* Return true if regions 'a' and 'b' overlap at all, based on their start offsets and lengths. */
  332. inline static bool regions_overlap(uint32_t a_start, uint32_t a_len,uint32_t b_start, uint32_t b_len);
  333. esp_err_t IRAM_ATTR esp_flash_get_size(esp_flash_t *chip, uint32_t *out_size)
  334. {
  335. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  336. VERIFY_CHIP_OP(detect_size);
  337. if (out_size == NULL) {
  338. return ESP_ERR_INVALID_ARG;
  339. }
  340. if (chip->size != 0) {
  341. *out_size = chip->size;
  342. return ESP_OK;
  343. }
  344. err = rom_spiflash_api_funcs->start(chip);
  345. if (err != ESP_OK) {
  346. return err;
  347. }
  348. uint32_t detect_size;
  349. err = chip->chip_drv->detect_size(chip, &detect_size);
  350. if (err == ESP_OK) {
  351. chip->size = detect_size;
  352. *out_size = chip->size;
  353. }
  354. return rom_spiflash_api_funcs->end(chip, err);
  355. }
  356. esp_err_t IRAM_ATTR esp_flash_erase_chip(esp_flash_t *chip)
  357. {
  358. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  359. VERIFY_CHIP_OP(erase_chip);
  360. CHECK_WRITE_ADDRESS(chip, 0, chip->size);
  361. //check before the operation, in case this is called too close to the last operation
  362. if (chip->chip_drv->yield) {
  363. err = chip->chip_drv->yield(chip, 0);
  364. if (err != ESP_OK) {
  365. return err;
  366. }
  367. }
  368. err = rom_spiflash_api_funcs->start(chip);
  369. if (err != ESP_OK) {
  370. return err;
  371. }
  372. err = chip->chip_drv->erase_chip(chip);
  373. if (chip->host->driver->flush_cache) {
  374. esp_err_t flush_cache_err = chip->host->driver->flush_cache(chip->host, 0, chip->size);
  375. if (err == ESP_OK) {
  376. err = flush_cache_err;
  377. }
  378. }
  379. return rom_spiflash_api_funcs->end(chip, err);
  380. }
  381. esp_err_t IRAM_ATTR esp_flash_erase_region(esp_flash_t *chip, uint32_t start, uint32_t len)
  382. {
  383. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  384. VERIFY_CHIP_OP(erase_sector);
  385. VERIFY_CHIP_OP(erase_block);
  386. CHECK_WRITE_ADDRESS(chip, start, len);
  387. uint32_t block_erase_size = chip->chip_drv->erase_block == NULL ? 0 : chip->chip_drv->block_erase_size;
  388. uint32_t sector_size = chip->chip_drv->sector_size;
  389. if (sector_size == 0 || (block_erase_size % sector_size) != 0) {
  390. return ESP_ERR_FLASH_NOT_INITIALISED;
  391. }
  392. if (start > chip->size || start + len > chip->size) {
  393. return ESP_ERR_INVALID_ARG;
  394. }
  395. if ((start % chip->chip_drv->sector_size) != 0 || (len % chip->chip_drv->sector_size) != 0) {
  396. // Can only erase multiples of the sector size, starting at sector boundary
  397. return ESP_ERR_INVALID_ARG;
  398. }
  399. err = ESP_OK;
  400. // Check for write protected regions overlapping the erase region
  401. if (chip->chip_drv->get_protected_regions != NULL &&
  402. chip->chip_drv->num_protectable_regions > 0) {
  403. err = rom_spiflash_api_funcs->start(chip);
  404. if (err != ESP_OK) {
  405. return err;
  406. }
  407. uint64_t protected = 0;
  408. err = chip->chip_drv->get_protected_regions(chip, &protected);
  409. if (err == ESP_OK && protected != 0) {
  410. for (int i = 0; i < chip->chip_drv->num_protectable_regions && err == ESP_OK; i++) {
  411. const esp_flash_region_t *region = &chip->chip_drv->protectable_regions[i];
  412. if ((protected & BIT64(i))
  413. && regions_overlap(start, len, region->offset, region->size)) {
  414. err = ESP_ERR_FLASH_PROTECTED;
  415. }
  416. }
  417. }
  418. // Don't lock the SPI flash for the entire erase, as this may be very long
  419. err = rom_spiflash_api_funcs->end(chip, err);
  420. }
  421. if (err != ESP_OK) {
  422. return err;
  423. }
  424. uint32_t erase_addr = start;
  425. uint32_t len_remain = len;
  426. // Indicate whether the bus is acquired by the driver, needs to be released before return
  427. bool bus_acquired = false;
  428. while (1) {
  429. //check before the operation, in case this is called too close to the last operation
  430. if (chip->chip_drv->yield) {
  431. err = chip->chip_drv->yield(chip, 0);
  432. if (err != ESP_OK) {
  433. return err;
  434. }
  435. }
  436. err = rom_spiflash_api_funcs->start(chip);
  437. if (err != ESP_OK) {
  438. break;
  439. }
  440. bus_acquired = true;
  441. #ifndef CONFIG_SPI_FLASH_BYPASS_BLOCK_ERASE
  442. // If possible erase an entire multi-sector block
  443. if (block_erase_size > 0 && len_remain >= block_erase_size && (erase_addr % block_erase_size) == 0) {
  444. err = chip->chip_drv->erase_block(chip, erase_addr);
  445. erase_addr += block_erase_size;
  446. len_remain -= block_erase_size;
  447. } else
  448. #endif
  449. {
  450. // Otherwise erase individual sector only
  451. err = chip->chip_drv->erase_sector(chip, erase_addr);
  452. erase_addr += sector_size;
  453. len_remain -= sector_size;
  454. }
  455. if (err != ESP_OK || len_remain == 0) {
  456. // On ESP32, the cache re-enable is in the end() function, while flush_cache should
  457. // happen when the cache is still disabled on ESP32. Break before the end() function and
  458. // do end() later
  459. assert(bus_acquired);
  460. break;
  461. }
  462. err = rom_spiflash_api_funcs->end(chip, ESP_OK);
  463. if (err != ESP_OK) {
  464. break;
  465. }
  466. bus_acquired = false;
  467. }
  468. return rom_spiflash_api_funcs->flash_end_flush_cache(chip, err, bus_acquired, start, len);
  469. }
  470. esp_err_t IRAM_ATTR esp_flash_get_chip_write_protect(esp_flash_t *chip, bool *out_write_protected)
  471. {
  472. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  473. VERIFY_CHIP_OP(get_chip_write_protect);
  474. if (out_write_protected == NULL) {
  475. return ESP_ERR_INVALID_ARG;
  476. }
  477. err = rom_spiflash_api_funcs->start(chip);
  478. if (err != ESP_OK) {
  479. return err;
  480. }
  481. err = chip->chip_drv->get_chip_write_protect(chip, out_write_protected);
  482. return rom_spiflash_api_funcs->end(chip, err);
  483. }
  484. esp_err_t IRAM_ATTR esp_flash_set_chip_write_protect(esp_flash_t *chip, bool write_protect)
  485. {
  486. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  487. VERIFY_CHIP_OP(set_chip_write_protect);
  488. //TODO: skip writing if already locked or unlocked
  489. err = rom_spiflash_api_funcs->start(chip);
  490. if (err != ESP_OK) {
  491. return err;
  492. }
  493. err = chip->chip_drv->set_chip_write_protect(chip, write_protect);
  494. return rom_spiflash_api_funcs->end(chip, err);
  495. }
  496. 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)
  497. {
  498. if(out_num_regions != NULL) {
  499. *out_num_regions = 0; // In case caller doesn't check result
  500. }
  501. esp_err_t err = rom_spiflash_api_funcs->chip_check((esp_flash_t **)&chip);
  502. VERIFY_CHIP_OP(get_protected_regions);
  503. if(out_regions == NULL || out_num_regions == NULL) {
  504. return ESP_ERR_INVALID_ARG;
  505. }
  506. *out_num_regions = chip->chip_drv->num_protectable_regions;
  507. *out_regions = chip->chip_drv->protectable_regions;
  508. return ESP_OK;
  509. }
  510. static esp_err_t find_region(const esp_flash_t *chip, const esp_flash_region_t *region, uint8_t *index)
  511. {
  512. if (region == NULL) {
  513. return ESP_ERR_INVALID_ARG;
  514. }
  515. for(*index = 0; *index < chip->chip_drv->num_protectable_regions; (*index)++) {
  516. if (memcmp(&chip->chip_drv->protectable_regions[*index],
  517. region, sizeof(esp_flash_region_t)) == 0) {
  518. return ESP_OK;
  519. }
  520. }
  521. return ESP_ERR_NOT_FOUND;
  522. }
  523. esp_err_t IRAM_ATTR esp_flash_get_protected_region(esp_flash_t *chip, const esp_flash_region_t *region, bool *out_protected)
  524. {
  525. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  526. VERIFY_CHIP_OP(get_protected_regions);
  527. if (out_protected == NULL) {
  528. return ESP_ERR_INVALID_ARG;
  529. }
  530. uint8_t index;
  531. err = find_region(chip, region, &index);
  532. if (err != ESP_OK) {
  533. return err;
  534. }
  535. uint64_t protection_mask = 0;
  536. err = rom_spiflash_api_funcs->start(chip);
  537. if (err != ESP_OK) {
  538. return err;
  539. }
  540. err = chip->chip_drv->get_protected_regions(chip, &protection_mask);
  541. if (err == ESP_OK) {
  542. *out_protected = protection_mask & (1LL << index);
  543. }
  544. return rom_spiflash_api_funcs->end(chip, err);
  545. }
  546. esp_err_t IRAM_ATTR esp_flash_set_protected_region(esp_flash_t *chip, const esp_flash_region_t *region, bool protect)
  547. {
  548. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  549. VERIFY_CHIP_OP(set_protected_regions);
  550. uint8_t index;
  551. err = find_region(chip, region, &index);
  552. if (err != ESP_OK) {
  553. return err;
  554. }
  555. uint64_t protection_mask = 0;
  556. err = rom_spiflash_api_funcs->start(chip);
  557. if (err != ESP_OK) {
  558. return err;
  559. }
  560. err = chip->chip_drv->get_protected_regions(chip, &protection_mask);
  561. if (err == ESP_OK) {
  562. if (protect) {
  563. protection_mask |= (1LL << index);
  564. } else {
  565. protection_mask &= ~(1LL << index);
  566. }
  567. err = chip->chip_drv->set_protected_regions(chip, protection_mask);
  568. }
  569. return rom_spiflash_api_funcs->end(chip, err);
  570. }
  571. esp_err_t IRAM_ATTR esp_flash_read(esp_flash_t *chip, void *buffer, uint32_t address, uint32_t length)
  572. {
  573. if (length == 0) {
  574. return ESP_OK;
  575. }
  576. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  577. VERIFY_CHIP_OP(read);
  578. if (buffer == NULL || address > chip->size || address+length > chip->size) {
  579. return ESP_ERR_INVALID_ARG;
  580. }
  581. //when the cache is disabled, only the DRAM can be read, check whether we need to receive in another buffer in DRAM.
  582. bool direct_read = chip->host->driver->supports_direct_read(chip->host, buffer);
  583. uint8_t* temp_buffer = NULL;
  584. //each time, we at most read this length
  585. //after that, we release the lock to allow some other operations
  586. size_t read_chunk_size = MIN(MAX_READ_CHUNK, length);
  587. if (!direct_read) {
  588. size_t actual_len = 0;
  589. if (chip->os_func->get_temp_buffer != NULL) {
  590. temp_buffer = chip->os_func->get_temp_buffer(chip->os_func_data, read_chunk_size, &actual_len);
  591. read_chunk_size = actual_len;
  592. }
  593. if (temp_buffer == NULL) {
  594. return ESP_ERR_NO_MEM;
  595. }
  596. }
  597. err = ESP_OK;
  598. do {
  599. err = rom_spiflash_api_funcs->start(chip);
  600. if (err != ESP_OK) {
  601. break;
  602. }
  603. //if required (dma buffer allocated), read to the buffer instead of the original buffer
  604. uint8_t* buffer_to_read = (temp_buffer)? temp_buffer : buffer;
  605. // Length we will read this iteration is either the chunk size or the remaining length, whichever is smaller
  606. size_t length_to_read = MIN(read_chunk_size, length);
  607. if (err == ESP_OK) {
  608. err = chip->chip_drv->read(chip, buffer_to_read, address, length_to_read);
  609. }
  610. if (err != ESP_OK) {
  611. rom_spiflash_api_funcs->end(chip, err);
  612. break;
  613. }
  614. //even if this is failed, the data is still valid, copy before quit
  615. err = rom_spiflash_api_funcs->end(chip, err);
  616. //copy back to the original buffer
  617. if (temp_buffer) {
  618. memcpy(buffer, temp_buffer, length_to_read);
  619. }
  620. address += length_to_read;
  621. length -= length_to_read;
  622. buffer = (void*)((intptr_t)buffer + length_to_read);
  623. } while (err == ESP_OK && length > 0);
  624. if (chip->os_func->release_temp_buffer != NULL) {
  625. chip->os_func->release_temp_buffer(chip->os_func_data, temp_buffer);
  626. }
  627. return err;
  628. }
  629. esp_err_t IRAM_ATTR esp_flash_write(esp_flash_t *chip, const void *buffer, uint32_t address, uint32_t length)
  630. {
  631. if (length == 0) {
  632. return ESP_OK;
  633. }
  634. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  635. VERIFY_CHIP_OP(write);
  636. CHECK_WRITE_ADDRESS(chip, address, length);
  637. if (buffer == NULL || address > chip->size || address+length > chip->size) {
  638. return ESP_ERR_INVALID_ARG;
  639. }
  640. //when the cache is disabled, only the DRAM can be read, check whether we need to copy the data first
  641. bool direct_write = chip->host->driver->supports_direct_write(chip->host, buffer);
  642. // Indicate whether the bus is acquired by the driver, needs to be released before return
  643. bool bus_acquired = false;
  644. err = ESP_OK;
  645. /* Write output in chunks, either by buffering on stack or
  646. by artificially cutting into MAX_WRITE_CHUNK parts (in an OS
  647. environment, this prevents writing from causing interrupt or higher priority task
  648. starvation.) */
  649. uint32_t write_addr = address;
  650. uint32_t len_remain = length;
  651. while (1) {
  652. uint32_t write_len;
  653. const void *write_buf;
  654. uint32_t temp_buf[8];
  655. if (direct_write) {
  656. write_len = MIN(len_remain, MAX_WRITE_CHUNK);
  657. write_buf = buffer;
  658. } else {
  659. write_len = MIN(len_remain, sizeof(temp_buf));
  660. memcpy(temp_buf, buffer, write_len);
  661. write_buf = temp_buf;
  662. }
  663. //check before the operation, in case this is called too close to the last operation
  664. if (chip->chip_drv->yield) {
  665. err = chip->chip_drv->yield(chip, 0);
  666. if (err != ESP_OK) {
  667. return err;
  668. }
  669. }
  670. err = rom_spiflash_api_funcs->start(chip);
  671. if (err != ESP_OK) {
  672. break;
  673. }
  674. bus_acquired = true;
  675. err = chip->chip_drv->write(chip, write_buf, write_addr, write_len);
  676. len_remain -= write_len;
  677. if (err != ESP_OK || len_remain == 0) {
  678. // On ESP32, the cache re-enable is in the end() function, while flush_cache should
  679. // happen when the cache is still disabled on ESP32. Break before the end() function and
  680. // do end() later
  681. assert(bus_acquired);
  682. break;
  683. }
  684. err = rom_spiflash_api_funcs->end(chip, err);
  685. if (err != ESP_OK) {
  686. break;
  687. }
  688. bus_acquired = false;
  689. write_addr += write_len;
  690. buffer = (void *)((intptr_t)buffer + write_len);
  691. }
  692. return rom_spiflash_api_funcs->flash_end_flush_cache(chip, err, bus_acquired, address, length);
  693. }
  694. esp_err_t IRAM_ATTR esp_flash_write_encrypted(esp_flash_t *chip, uint32_t address, const void *buffer, uint32_t length)
  695. {
  696. if (length == 0) {
  697. return ESP_OK;
  698. }
  699. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  700. // Flash encryption only support on main flash.
  701. if (chip != esp_flash_default_chip) {
  702. return ESP_ERR_NOT_SUPPORTED;
  703. }
  704. if (err != ESP_OK) return err;
  705. if (buffer == NULL || address + length > chip->size) {
  706. return ESP_ERR_INVALID_ARG;
  707. }
  708. if ((address % 16) != 0) {
  709. ESP_EARLY_LOGE(TAG, "flash encrypted write address must be 16 bytes aligned");
  710. return ESP_ERR_INVALID_ARG;
  711. }
  712. if ((length % 16) != 0) {
  713. ESP_EARLY_LOGE(TAG, "flash encrypted write length must be multiple of 16");
  714. return ESP_ERR_INVALID_SIZE;
  715. }
  716. bool bus_acquired = false;
  717. const uint8_t *ssrc = (const uint8_t *)buffer;
  718. /* On ESP32, write_encrypted encrypts data in RAM as it writes,
  719. so copy to a temporary buffer - 32 bytes at a time.
  720. Each call to write_encrypted takes a 32 byte "row" of
  721. data to encrypt, and each row is two 16 byte AES blocks
  722. that share a key (as derived from flash address).
  723. On ESP32-S2 and later, the temporary buffer need to be
  724. seperated into 16-bytes, 32-bytes, 64-bytes(if supported).
  725. So, on ESP32-S2 and later, here has a totally different
  726. data prepare implementation.
  727. */
  728. uint8_t encrypt_buf[64] __attribute__((aligned(4)));
  729. uint32_t row_size_length;
  730. for (size_t i = 0; i < length; i += row_size_length) {
  731. uint32_t row_addr = address + i;
  732. uint8_t row_size;
  733. uint8_t encrypt_byte;
  734. #if CONFIG_IDF_TARGET_ESP32
  735. if (i == 0 && (row_addr % 32) != 0) {
  736. /* writing to second block of a 32 byte row */
  737. row_size = 16;
  738. row_addr -= 16;
  739. /* copy to second block in buffer */
  740. memcpy(encrypt_buf + 16, ssrc + i, row_size);
  741. /* decrypt the first block from flash, will reencrypt to same bytes */
  742. esp_flash_read_encrypted(chip, row_addr, encrypt_buf, 16);
  743. } else if (length - i == 16) {
  744. /* 16 bytes left, is first block of a 32 byte row */
  745. row_size = 16;
  746. /* copy to first block in buffer */
  747. memcpy(encrypt_buf, ssrc + i, row_size);
  748. /* decrypt the second block from flash, will reencrypt to same bytes */
  749. esp_flash_read_encrypted(chip, row_addr + 16, encrypt_buf + 16, 16);
  750. } else {
  751. /* Writing a full 32 byte row (2 blocks) */
  752. row_size = 32;
  753. memcpy(encrypt_buf, ssrc + i, row_size);
  754. }
  755. encrypt_byte = 32;
  756. row_size_length = row_size;
  757. #else // FOR ESP32-S2, ESP32-S3, ESP32-C3
  758. if ((row_addr % 64) == 0 && (length - i) >= 64 && SOC_FLASH_ENCRYPTED_XTS_AES_BLOCK_MAX == 64) {
  759. row_size = 64;
  760. memcpy(encrypt_buf, ssrc + i, row_size);
  761. } else if ((row_addr % 32) == 0 && (length - i) >= 32) {
  762. row_size = 32;
  763. memcpy(encrypt_buf, ssrc + i, row_size);
  764. } else {
  765. row_size = 16;
  766. memcpy(encrypt_buf, ssrc + i, row_size);
  767. }
  768. encrypt_byte = row_size;
  769. row_size_length = row_size;
  770. #endif //CONFIG_IDF_TARGET_ESP32
  771. #if CONFIG_IDF_TARGET_ESP32S2
  772. esp_crypto_dma_lock_acquire();
  773. #endif //CONFIG_IDF_TARGET_ESP32S2
  774. err = rom_spiflash_api_funcs->start(chip);
  775. if (err != ESP_OK) {
  776. #if CONFIG_IDF_TARGET_ESP32S2
  777. esp_crypto_dma_lock_release();
  778. #endif //CONFIG_IDF_TARGET_ESP32S2
  779. break;
  780. }
  781. bus_acquired = true;
  782. err = chip->chip_drv->write_encrypted(chip, (uint32_t *)encrypt_buf, row_addr, encrypt_byte);
  783. if (err!= ESP_OK) {
  784. #if CONFIG_IDF_TARGET_ESP32S2
  785. esp_crypto_dma_lock_release();
  786. #endif //CONFIG_IDF_TARGET_ESP32S2
  787. bus_acquired = false;
  788. assert(bus_acquired);
  789. break;
  790. }
  791. err = rom_spiflash_api_funcs->end(chip, ESP_OK);
  792. #if CONFIG_IDF_TARGET_ESP32S2
  793. esp_crypto_dma_lock_release();
  794. #endif //CONFIG_IDF_TARGET_ESP32S2
  795. if (err != ESP_OK) {
  796. bus_acquired = false;
  797. break;
  798. }
  799. bus_acquired = false;
  800. }
  801. return rom_spiflash_api_funcs->flash_end_flush_cache(chip, err, bus_acquired, address, length);
  802. }
  803. inline static IRAM_ATTR bool regions_overlap(uint32_t a_start, uint32_t a_len,uint32_t b_start, uint32_t b_len)
  804. {
  805. uint32_t a_end = a_start + a_len;
  806. uint32_t b_end = b_start + b_len;
  807. return (a_end > b_start && b_end > a_start);
  808. }
  809. //currently the legacy implementation is used, from flash_ops.c
  810. esp_err_t spi_flash_read_encrypted(size_t src, void *dstv, size_t size);
  811. esp_err_t IRAM_ATTR esp_flash_read_encrypted(esp_flash_t *chip, uint32_t address, void *out_buffer, uint32_t length)
  812. {
  813. /*
  814. * Since currently this feature is supported only by the hardware, there
  815. * is no way to support non-standard chips. We use the legacy
  816. * implementation and skip the chip and driver layers.
  817. */
  818. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  819. if (err != ESP_OK) return err;
  820. return spi_flash_read_encrypted(address, out_buffer, length);
  821. }
  822. // test only, non-public
  823. IRAM_ATTR esp_err_t esp_flash_get_io_mode(esp_flash_t* chip, bool* qe)
  824. {
  825. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  826. VERIFY_CHIP_OP(get_io_mode);
  827. esp_flash_io_mode_t io_mode;
  828. err = rom_spiflash_api_funcs->start(chip);
  829. if (err != ESP_OK) {
  830. return err;
  831. }
  832. err = chip->chip_drv->get_io_mode(chip, &io_mode);
  833. err = rom_spiflash_api_funcs->end(chip, err);
  834. if (err == ESP_OK) {
  835. *qe = (io_mode == SPI_FLASH_QOUT);
  836. }
  837. return err;
  838. }
  839. IRAM_ATTR esp_err_t esp_flash_set_io_mode(esp_flash_t* chip, bool qe)
  840. {
  841. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  842. VERIFY_CHIP_OP(set_io_mode);
  843. chip->read_mode = (qe? SPI_FLASH_QOUT: SPI_FLASH_SLOWRD);
  844. err = rom_spiflash_api_funcs->start(chip);
  845. if (err != ESP_OK) {
  846. return err;
  847. }
  848. err = chip->chip_drv->set_io_mode(chip);
  849. return rom_spiflash_api_funcs->end(chip, err);
  850. }
  851. #endif //CONFIG_SPI_FLASH_ROM_IMPL
  852. //init suspend mode cmd, uses internal.
  853. esp_err_t esp_flash_suspend_cmd_init(esp_flash_t* chip)
  854. {
  855. ESP_EARLY_LOGW(TAG, "Flash suspend feature is enabled");
  856. if (chip->chip_drv->get_chip_caps == NULL) {
  857. // chip caps get failed, pass the flash capability check.
  858. ESP_EARLY_LOGW(TAG, "get_chip_caps function pointer hasn't been initialized");
  859. } else {
  860. if ((chip->chip_drv->get_chip_caps(chip) & SPI_FLASH_CHIP_CAP_SUSPEND) == 0) {
  861. ESP_EARLY_LOGW(TAG, "Suspend and resume may not supported for this flash model yet.");
  862. }
  863. }
  864. return chip->chip_drv->sus_setup(chip);
  865. }
  866. #ifndef CONFIG_SPI_FLASH_USE_LEGACY_IMPL
  867. esp_err_t esp_flash_app_disable_protect(bool disable)
  868. {
  869. if (disable) {
  870. return esp_flash_app_disable_os_functions(esp_flash_default_chip);
  871. } else {
  872. return esp_flash_app_enable_os_functions(esp_flash_default_chip);
  873. }
  874. }
  875. #endif
  876. /*------------------------------------------------------------------------------
  877. Adapter layer to original api before IDF v4.0
  878. ------------------------------------------------------------------------------*/
  879. #ifndef CONFIG_SPI_FLASH_USE_LEGACY_IMPL
  880. /* Translate any ESP_ERR_FLASH_xxx error code (new API) to a generic ESP_ERR_xyz error code
  881. */
  882. static IRAM_ATTR esp_err_t spi_flash_translate_rc(esp_err_t err)
  883. {
  884. switch (err) {
  885. case ESP_OK:
  886. case ESP_ERR_INVALID_ARG:
  887. case ESP_ERR_INVALID_SIZE:
  888. case ESP_ERR_NO_MEM:
  889. return err;
  890. case ESP_ERR_FLASH_NOT_INITIALISED:
  891. case ESP_ERR_FLASH_PROTECTED:
  892. return ESP_ERR_INVALID_STATE;
  893. case ESP_ERR_NOT_FOUND:
  894. case ESP_ERR_FLASH_UNSUPPORTED_HOST:
  895. case ESP_ERR_FLASH_UNSUPPORTED_CHIP:
  896. return ESP_ERR_NOT_SUPPORTED;
  897. case ESP_ERR_FLASH_NO_RESPONSE:
  898. return ESP_ERR_INVALID_RESPONSE;
  899. default:
  900. ESP_EARLY_LOGE(TAG, "unexpected spi flash error code: 0x%x", err);
  901. abort();
  902. }
  903. }
  904. esp_err_t IRAM_ATTR spi_flash_erase_range(uint32_t start_addr, uint32_t size)
  905. {
  906. esp_err_t err = esp_flash_erase_region(NULL, start_addr, size);
  907. return spi_flash_translate_rc(err);
  908. }
  909. esp_err_t IRAM_ATTR spi_flash_write(size_t dst, const void *srcv, size_t size)
  910. {
  911. esp_err_t err = esp_flash_write(NULL, srcv, dst, size);
  912. return spi_flash_translate_rc(err);
  913. }
  914. esp_err_t IRAM_ATTR spi_flash_read(size_t src, void *dstv, size_t size)
  915. {
  916. esp_err_t err = esp_flash_read(NULL, dstv, src, size);
  917. return spi_flash_translate_rc(err);
  918. }
  919. esp_err_t IRAM_ATTR spi_flash_write_encrypted(size_t dest_addr, const void *src, size_t size)
  920. {
  921. esp_err_t err = esp_flash_write_encrypted(NULL, dest_addr, src, size);
  922. return spi_flash_translate_rc(err);
  923. }
  924. #endif // CONFIG_SPI_FLASH_USE_LEGACY_IMPL