esp_flash_api.c 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  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. ESP_LOGI(TAG, "flash io: %s", io_mode_str[chip->read_mode]);
  191. err = rom_spiflash_api_funcs->start(chip);
  192. if (err != ESP_OK) {
  193. return err;
  194. }
  195. if (err == ESP_OK) {
  196. // Try to set the flash mode to whatever default mode was chosen
  197. err = chip->chip_drv->set_io_mode(chip);
  198. if (err == ESP_ERR_FLASH_NO_RESPONSE && !esp_flash_is_quad_mode(chip)) {
  199. //some chips (e.g. Winbond) don't support to clear QE, treat as success
  200. err = ESP_OK;
  201. }
  202. }
  203. // Done: all fields on 'chip' are initialised
  204. return rom_spiflash_api_funcs->end(chip, err);
  205. }
  206. static esp_err_t IRAM_ATTR read_id_core(esp_flash_t* chip, uint32_t* out_id, bool sanity_check)
  207. {
  208. bool installed = esp_flash_chip_driver_initialized(chip);
  209. esp_err_t err = rom_spiflash_api_funcs->start(chip);
  210. if (err != ESP_OK) {
  211. return err;
  212. }
  213. esp_err_t (*read_id_func)(void*, uint32_t*);
  214. void* read_id_arg;
  215. if (installed && chip->chip_drv->read_id) {
  216. read_id_func = (void*)chip->chip_drv->read_id;
  217. read_id_arg = (void*)chip;
  218. } else {
  219. //default option if the chip is not detected/chosen yet.
  220. read_id_func = (void*)chip->host->driver->read_id;
  221. read_id_arg = (void*)chip->host;
  222. }
  223. // Inner function fails if it sees all-ones or all-zeroes.
  224. err = read_id_func(read_id_arg, out_id);
  225. if (sanity_check && err == ESP_OK) {
  226. // Send RDID command twice, check for a matching result and retry in case we just powered on
  227. uint32_t new_id;
  228. err = read_id_func(read_id_arg, &new_id);
  229. if (err == ESP_OK && (new_id != *out_id)) {
  230. err = ESP_ERR_FLASH_NOT_INITIALISED;
  231. }
  232. }
  233. return rom_spiflash_api_funcs->end(chip, err);
  234. }
  235. // Faster version with sanity check.
  236. // Called in esp_flash_init and unit test (though not public)
  237. esp_err_t esp_flash_read_chip_id(esp_flash_t* chip, uint32_t* out_id)
  238. {
  239. return read_id_core(chip, out_id, true);
  240. }
  241. #ifndef CONFIG_SPI_FLASH_ROM_IMPL
  242. esp_err_t esp_flash_read_id(esp_flash_t* chip, uint32_t* out_id)
  243. {
  244. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  245. //Accept uninitialized chip when reading chip id
  246. if (err != ESP_OK && !(err == ESP_ERR_FLASH_NOT_INITIALISED && chip != NULL)) return err;
  247. if (out_id == NULL) return ESP_ERR_INVALID_ARG;
  248. return read_id_core(chip, out_id, false);
  249. }
  250. #endif //CONFIG_SPI_FLASH_ROM_IMPL
  251. static esp_err_t IRAM_ATTR NOINLINE_ATTR read_unique_id(esp_flash_t* chip, uint64_t* out_uid)
  252. {
  253. esp_err_t err = rom_spiflash_api_funcs->start(chip);
  254. if (err != ESP_OK) {
  255. return err;
  256. }
  257. err = chip->chip_drv->read_unique_id(chip, out_uid);
  258. return rom_spiflash_api_funcs->end(chip, err);
  259. }
  260. esp_err_t esp_flash_read_unique_chip_id(esp_flash_t *chip, uint64_t* out_uid)
  261. {
  262. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  263. if (err != ESP_OK) {
  264. return err;
  265. }
  266. if (out_uid == NULL) {
  267. return ESP_ERR_INVALID_ARG;
  268. };
  269. return read_unique_id(chip, out_uid);
  270. }
  271. static esp_err_t IRAM_ATTR detect_spi_flash_chip(esp_flash_t *chip)
  272. {
  273. esp_err_t err;
  274. uint32_t flash_id = chip->chip_id;
  275. // Detect the chip and set the chip_drv structure for it
  276. const spi_flash_chip_t **drivers = esp_flash_registered_chips;
  277. while (*drivers != NULL && !esp_flash_chip_driver_initialized(chip)) {
  278. chip->chip_drv = *drivers;
  279. // start/end SPI operation each time, for multitasking
  280. // and also so esp_flash_registered_flash_drivers can live in flash
  281. ESP_LOGD(TAG, "trying chip: %s", chip->chip_drv->name);
  282. err = rom_spiflash_api_funcs->start(chip);
  283. if (err != ESP_OK) {
  284. return err;
  285. }
  286. if (chip->chip_drv->probe(chip, flash_id) != ESP_OK) {
  287. chip->chip_drv = NULL;
  288. }
  289. // if probe succeeded, chip->drv stays set
  290. drivers++;
  291. err = rom_spiflash_api_funcs->end(chip, err);
  292. if (err != ESP_OK) {
  293. return err;
  294. }
  295. }
  296. if (!esp_flash_chip_driver_initialized(chip)) {
  297. return ESP_ERR_NOT_FOUND;
  298. }
  299. ESP_LOGI(TAG, "detected chip: %s", chip->chip_drv->name);
  300. return ESP_OK;
  301. }
  302. #ifndef CONFIG_SPI_FLASH_ROM_IMPL
  303. /* Convenience macro for beginning of all API functions.
  304. * Check the return value of `rom_spiflash_api_funcs->chip_check` is correct,
  305. * and the chip supports the operation in question.
  306. */
  307. #define VERIFY_CHIP_OP(OP) do { \
  308. if (err != ESP_OK) return err; \
  309. if (chip->chip_drv->OP == NULL) { \
  310. return ESP_ERR_FLASH_UNSUPPORTED_CHIP; \
  311. } \
  312. } while (0)
  313. /* Return true if regions 'a' and 'b' overlap at all, based on their start offsets and lengths. */
  314. inline static bool regions_overlap(uint32_t a_start, uint32_t a_len,uint32_t b_start, uint32_t b_len);
  315. esp_err_t IRAM_ATTR esp_flash_get_size(esp_flash_t *chip, uint32_t *out_size)
  316. {
  317. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  318. VERIFY_CHIP_OP(detect_size);
  319. if (out_size == NULL) {
  320. return ESP_ERR_INVALID_ARG;
  321. }
  322. if (chip->size != 0) {
  323. *out_size = chip->size;
  324. return ESP_OK;
  325. }
  326. err = rom_spiflash_api_funcs->start(chip);
  327. if (err != ESP_OK) {
  328. return err;
  329. }
  330. uint32_t detect_size;
  331. err = chip->chip_drv->detect_size(chip, &detect_size);
  332. if (err == ESP_OK) {
  333. chip->size = detect_size;
  334. }
  335. return rom_spiflash_api_funcs->end(chip, err);
  336. }
  337. esp_err_t IRAM_ATTR esp_flash_erase_chip(esp_flash_t *chip)
  338. {
  339. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  340. VERIFY_CHIP_OP(erase_chip);
  341. CHECK_WRITE_ADDRESS(chip, 0, chip->size);
  342. //check before the operation, in case this is called too close to the last operation
  343. if (chip->chip_drv->yield) {
  344. err = chip->chip_drv->yield(chip, 0);
  345. if (err != ESP_OK) {
  346. return err;
  347. }
  348. }
  349. err = rom_spiflash_api_funcs->start(chip);
  350. if (err != ESP_OK) {
  351. return err;
  352. }
  353. err = chip->chip_drv->erase_chip(chip);
  354. if (chip->host->driver->flush_cache) {
  355. esp_err_t flush_cache_err = chip->host->driver->flush_cache(chip->host, 0, chip->size);
  356. if (err == ESP_OK) {
  357. err = flush_cache_err;
  358. }
  359. }
  360. return rom_spiflash_api_funcs->end(chip, err);
  361. }
  362. esp_err_t IRAM_ATTR esp_flash_erase_region(esp_flash_t *chip, uint32_t start, uint32_t len)
  363. {
  364. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  365. VERIFY_CHIP_OP(erase_sector);
  366. VERIFY_CHIP_OP(erase_block);
  367. CHECK_WRITE_ADDRESS(chip, start, len);
  368. uint32_t block_erase_size = chip->chip_drv->erase_block == NULL ? 0 : chip->chip_drv->block_erase_size;
  369. uint32_t sector_size = chip->chip_drv->sector_size;
  370. if (sector_size == 0 || (block_erase_size % sector_size) != 0) {
  371. return ESP_ERR_FLASH_NOT_INITIALISED;
  372. }
  373. if (start > chip->size || start + len > chip->size) {
  374. return ESP_ERR_INVALID_ARG;
  375. }
  376. if ((start % chip->chip_drv->sector_size) != 0 || (len % chip->chip_drv->sector_size) != 0) {
  377. // Can only erase multiples of the sector size, starting at sector boundary
  378. return ESP_ERR_INVALID_ARG;
  379. }
  380. err = ESP_OK;
  381. // Check for write protected regions overlapping the erase region
  382. if (chip->chip_drv->get_protected_regions != NULL &&
  383. chip->chip_drv->num_protectable_regions > 0) {
  384. err = rom_spiflash_api_funcs->start(chip);
  385. if (err != ESP_OK) {
  386. return err;
  387. }
  388. uint64_t protected = 0;
  389. err = chip->chip_drv->get_protected_regions(chip, &protected);
  390. if (err == ESP_OK && protected != 0) {
  391. for (int i = 0; i < chip->chip_drv->num_protectable_regions && err == ESP_OK; i++) {
  392. const esp_flash_region_t *region = &chip->chip_drv->protectable_regions[i];
  393. if ((protected & BIT64(i))
  394. && regions_overlap(start, len, region->offset, region->size)) {
  395. err = ESP_ERR_FLASH_PROTECTED;
  396. }
  397. }
  398. }
  399. // Don't lock the SPI flash for the entire erase, as this may be very long
  400. err = rom_spiflash_api_funcs->end(chip, err);
  401. }
  402. if (err != ESP_OK) {
  403. return err;
  404. }
  405. uint32_t erase_addr = start;
  406. uint32_t len_remain = len;
  407. // Indicate whether the bus is acquired by the driver, needs to be released before return
  408. bool bus_acquired = false;
  409. while (1) {
  410. //check before the operation, in case this is called too close to the last operation
  411. if (chip->chip_drv->yield) {
  412. err = chip->chip_drv->yield(chip, 0);
  413. if (err != ESP_OK) {
  414. return err;
  415. }
  416. }
  417. err = rom_spiflash_api_funcs->start(chip);
  418. if (err != ESP_OK) {
  419. break;
  420. }
  421. bus_acquired = true;
  422. #ifndef CONFIG_SPI_FLASH_BYPASS_BLOCK_ERASE
  423. // If possible erase an entire multi-sector block
  424. if (block_erase_size > 0 && len_remain >= block_erase_size && (erase_addr % block_erase_size) == 0) {
  425. err = chip->chip_drv->erase_block(chip, erase_addr);
  426. erase_addr += block_erase_size;
  427. len_remain -= block_erase_size;
  428. } else
  429. #endif
  430. {
  431. // Otherwise erase individual sector only
  432. err = chip->chip_drv->erase_sector(chip, erase_addr);
  433. erase_addr += sector_size;
  434. len_remain -= sector_size;
  435. }
  436. if (err != ESP_OK || len_remain == 0) {
  437. // On ESP32, the cache re-enable is in the end() function, while flush_cache should
  438. // happen when the cache is still disabled on ESP32. Break before the end() function and
  439. // do end() later
  440. assert(bus_acquired);
  441. break;
  442. }
  443. err = rom_spiflash_api_funcs->end(chip, ESP_OK);
  444. if (err != ESP_OK) {
  445. break;
  446. }
  447. bus_acquired = false;
  448. }
  449. return rom_spiflash_api_funcs->flash_end_flush_cache(chip, err, bus_acquired, start, len);
  450. }
  451. esp_err_t IRAM_ATTR esp_flash_get_chip_write_protect(esp_flash_t *chip, bool *out_write_protected)
  452. {
  453. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  454. VERIFY_CHIP_OP(get_chip_write_protect);
  455. if (out_write_protected == 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. err = chip->chip_drv->get_chip_write_protect(chip, out_write_protected);
  463. return rom_spiflash_api_funcs->end(chip, err);
  464. }
  465. esp_err_t IRAM_ATTR esp_flash_set_chip_write_protect(esp_flash_t *chip, bool write_protect)
  466. {
  467. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  468. VERIFY_CHIP_OP(set_chip_write_protect);
  469. //TODO: skip writing if already locked or unlocked
  470. err = rom_spiflash_api_funcs->start(chip);
  471. if (err != ESP_OK) {
  472. return err;
  473. }
  474. err = chip->chip_drv->set_chip_write_protect(chip, write_protect);
  475. return rom_spiflash_api_funcs->end(chip, err);
  476. }
  477. 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)
  478. {
  479. if(out_num_regions != NULL) {
  480. *out_num_regions = 0; // In case caller doesn't check result
  481. }
  482. esp_err_t err = rom_spiflash_api_funcs->chip_check((esp_flash_t **)&chip);
  483. VERIFY_CHIP_OP(get_protected_regions);
  484. if(out_regions == NULL || out_num_regions == NULL) {
  485. return ESP_ERR_INVALID_ARG;
  486. }
  487. *out_num_regions = chip->chip_drv->num_protectable_regions;
  488. *out_regions = chip->chip_drv->protectable_regions;
  489. return ESP_OK;
  490. }
  491. static esp_err_t find_region(const esp_flash_t *chip, const esp_flash_region_t *region, uint8_t *index)
  492. {
  493. if (region == NULL) {
  494. return ESP_ERR_INVALID_ARG;
  495. }
  496. for(*index = 0; *index < chip->chip_drv->num_protectable_regions; (*index)++) {
  497. if (memcmp(&chip->chip_drv->protectable_regions[*index],
  498. region, sizeof(esp_flash_region_t)) == 0) {
  499. return ESP_OK;
  500. }
  501. }
  502. return ESP_ERR_NOT_FOUND;
  503. }
  504. esp_err_t IRAM_ATTR esp_flash_get_protected_region(esp_flash_t *chip, const esp_flash_region_t *region, bool *out_protected)
  505. {
  506. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  507. VERIFY_CHIP_OP(get_protected_regions);
  508. if (out_protected == NULL) {
  509. return ESP_ERR_INVALID_ARG;
  510. }
  511. uint8_t index;
  512. err = find_region(chip, region, &index);
  513. if (err != ESP_OK) {
  514. return err;
  515. }
  516. uint64_t protection_mask = 0;
  517. err = rom_spiflash_api_funcs->start(chip);
  518. if (err != ESP_OK) {
  519. return err;
  520. }
  521. err = chip->chip_drv->get_protected_regions(chip, &protection_mask);
  522. if (err == ESP_OK) {
  523. *out_protected = protection_mask & (1LL << index);
  524. }
  525. return rom_spiflash_api_funcs->end(chip, err);
  526. }
  527. esp_err_t IRAM_ATTR esp_flash_set_protected_region(esp_flash_t *chip, const esp_flash_region_t *region, bool protect)
  528. {
  529. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  530. VERIFY_CHIP_OP(set_protected_regions);
  531. uint8_t index;
  532. err = find_region(chip, region, &index);
  533. if (err != ESP_OK) {
  534. return err;
  535. }
  536. uint64_t protection_mask = 0;
  537. err = rom_spiflash_api_funcs->start(chip);
  538. if (err != ESP_OK) {
  539. return err;
  540. }
  541. err = chip->chip_drv->get_protected_regions(chip, &protection_mask);
  542. if (err == ESP_OK) {
  543. if (protect) {
  544. protection_mask |= (1LL << index);
  545. } else {
  546. protection_mask &= ~(1LL << index);
  547. }
  548. err = chip->chip_drv->set_protected_regions(chip, protection_mask);
  549. }
  550. return rom_spiflash_api_funcs->end(chip, err);
  551. }
  552. esp_err_t IRAM_ATTR esp_flash_read(esp_flash_t *chip, void *buffer, uint32_t address, uint32_t length)
  553. {
  554. if (length == 0) {
  555. return ESP_OK;
  556. }
  557. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  558. VERIFY_CHIP_OP(read);
  559. if (buffer == NULL || address > chip->size || address+length > chip->size) {
  560. return ESP_ERR_INVALID_ARG;
  561. }
  562. //when the cache is disabled, only the DRAM can be read, check whether we need to receive in another buffer in DRAM.
  563. bool direct_read = chip->host->driver->supports_direct_read(chip->host, buffer);
  564. uint8_t* temp_buffer = NULL;
  565. //each time, we at most read this length
  566. //after that, we release the lock to allow some other operations
  567. size_t read_chunk_size = MIN(MAX_READ_CHUNK, length);
  568. if (!direct_read) {
  569. size_t actual_len = 0;
  570. if (chip->os_func->get_temp_buffer != NULL) {
  571. temp_buffer = chip->os_func->get_temp_buffer(chip->os_func_data, read_chunk_size, &actual_len);
  572. read_chunk_size = actual_len;
  573. }
  574. if (temp_buffer == NULL) {
  575. return ESP_ERR_NO_MEM;
  576. }
  577. }
  578. err = ESP_OK;
  579. do {
  580. err = rom_spiflash_api_funcs->start(chip);
  581. if (err != ESP_OK) {
  582. break;
  583. }
  584. //if required (dma buffer allocated), read to the buffer instead of the original buffer
  585. uint8_t* buffer_to_read = (temp_buffer)? temp_buffer : buffer;
  586. // Length we will read this iteration is either the chunk size or the remaining length, whichever is smaller
  587. size_t length_to_read = MIN(read_chunk_size, length);
  588. if (err == ESP_OK) {
  589. err = chip->chip_drv->read(chip, buffer_to_read, address, length_to_read);
  590. }
  591. if (err != ESP_OK) {
  592. rom_spiflash_api_funcs->end(chip, err);
  593. break;
  594. }
  595. //even if this is failed, the data is still valid, copy before quit
  596. err = rom_spiflash_api_funcs->end(chip, err);
  597. //copy back to the original buffer
  598. if (temp_buffer) {
  599. memcpy(buffer, temp_buffer, length_to_read);
  600. }
  601. address += length_to_read;
  602. length -= length_to_read;
  603. buffer = (void*)((intptr_t)buffer + length_to_read);
  604. } while (err == ESP_OK && length > 0);
  605. if (chip->os_func->release_temp_buffer != NULL) {
  606. chip->os_func->release_temp_buffer(chip->os_func_data, temp_buffer);
  607. }
  608. return err;
  609. }
  610. esp_err_t IRAM_ATTR esp_flash_write(esp_flash_t *chip, const void *buffer, uint32_t address, uint32_t length)
  611. {
  612. if (length == 0) {
  613. return ESP_OK;
  614. }
  615. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  616. VERIFY_CHIP_OP(write);
  617. CHECK_WRITE_ADDRESS(chip, address, length);
  618. if (buffer == NULL || address > chip->size || address+length > chip->size) {
  619. return ESP_ERR_INVALID_ARG;
  620. }
  621. //when the cache is disabled, only the DRAM can be read, check whether we need to copy the data first
  622. bool direct_write = chip->host->driver->supports_direct_write(chip->host, buffer);
  623. // Indicate whether the bus is acquired by the driver, needs to be released before return
  624. bool bus_acquired = false;
  625. err = ESP_OK;
  626. /* Write output in chunks, either by buffering on stack or
  627. by artificially cutting into MAX_WRITE_CHUNK parts (in an OS
  628. environment, this prevents writing from causing interrupt or higher priority task
  629. starvation.) */
  630. uint32_t write_addr = address;
  631. uint32_t len_remain = length;
  632. while (1) {
  633. uint32_t write_len;
  634. const void *write_buf;
  635. uint32_t temp_buf[8];
  636. if (direct_write) {
  637. write_len = MIN(len_remain, MAX_WRITE_CHUNK);
  638. write_buf = buffer;
  639. } else {
  640. write_len = MIN(len_remain, sizeof(temp_buf));
  641. memcpy(temp_buf, buffer, write_len);
  642. write_buf = temp_buf;
  643. }
  644. //check before the operation, in case this is called too close to the last operation
  645. if (chip->chip_drv->yield) {
  646. err = chip->chip_drv->yield(chip, 0);
  647. if (err != ESP_OK) {
  648. return err;
  649. }
  650. }
  651. err = rom_spiflash_api_funcs->start(chip);
  652. if (err != ESP_OK) {
  653. break;
  654. }
  655. bus_acquired = true;
  656. err = chip->chip_drv->write(chip, write_buf, write_addr, write_len);
  657. len_remain -= write_len;
  658. if (err != ESP_OK || len_remain == 0) {
  659. // On ESP32, the cache re-enable is in the end() function, while flush_cache should
  660. // happen when the cache is still disabled on ESP32. Break before the end() function and
  661. // do end() later
  662. assert(bus_acquired);
  663. break;
  664. }
  665. err = rom_spiflash_api_funcs->end(chip, err);
  666. if (err != ESP_OK) {
  667. break;
  668. }
  669. bus_acquired = false;
  670. write_addr += write_len;
  671. buffer = (void *)((intptr_t)buffer + write_len);
  672. }
  673. return rom_spiflash_api_funcs->flash_end_flush_cache(chip, err, bus_acquired, address, length);
  674. }
  675. esp_err_t IRAM_ATTR esp_flash_write_encrypted(esp_flash_t *chip, uint32_t address, const void *buffer, uint32_t length)
  676. {
  677. if (length == 0) {
  678. return ESP_OK;
  679. }
  680. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  681. // Flash encryption only support on main flash.
  682. if (chip != esp_flash_default_chip) {
  683. return ESP_ERR_NOT_SUPPORTED;
  684. }
  685. if (err != ESP_OK) return err;
  686. if (buffer == NULL || address + length > chip->size) {
  687. return ESP_ERR_INVALID_ARG;
  688. }
  689. if ((address % 16) != 0) {
  690. ESP_EARLY_LOGE(TAG, "flash encrypted write address must be 16 bytes aligned");
  691. return ESP_ERR_INVALID_ARG;
  692. }
  693. if ((length % 16) != 0) {
  694. ESP_EARLY_LOGE(TAG, "flash encrypted write length must be multiple of 16");
  695. return ESP_ERR_INVALID_SIZE;
  696. }
  697. bool bus_acquired = false;
  698. const uint8_t *ssrc = (const uint8_t *)buffer;
  699. /* On ESP32, write_encrypted encrypts data in RAM as it writes,
  700. so copy to a temporary buffer - 32 bytes at a time.
  701. Each call to write_encrypted takes a 32 byte "row" of
  702. data to encrypt, and each row is two 16 byte AES blocks
  703. that share a key (as derived from flash address).
  704. On ESP32-S2 and later, the temporary buffer need to be
  705. seperated into 16-bytes, 32-bytes, 64-bytes(if supported).
  706. So, on ESP32-S2 and later, here has a totally different
  707. data prepare implementation.
  708. */
  709. uint8_t encrypt_buf[64] __attribute__((aligned(4)));
  710. uint32_t row_size_length;
  711. for (size_t i = 0; i < length; i += row_size_length) {
  712. uint32_t row_addr = address + i;
  713. uint8_t row_size;
  714. uint8_t encrypt_byte;
  715. #if CONFIG_IDF_TARGET_ESP32
  716. if (i == 0 && (row_addr % 32) != 0) {
  717. /* writing to second block of a 32 byte row */
  718. row_size = 16;
  719. row_addr -= 16;
  720. /* copy to second block in buffer */
  721. memcpy(encrypt_buf + 16, ssrc + i, row_size);
  722. /* decrypt the first block from flash, will reencrypt to same bytes */
  723. esp_flash_read_encrypted(chip, row_addr, encrypt_buf, 16);
  724. } else if (length - i == 16) {
  725. /* 16 bytes left, is first block of a 32 byte row */
  726. row_size = 16;
  727. /* copy to first block in buffer */
  728. memcpy(encrypt_buf, ssrc + i, row_size);
  729. /* decrypt the second block from flash, will reencrypt to same bytes */
  730. esp_flash_read_encrypted(chip, row_addr + 16, encrypt_buf + 16, 16);
  731. } else {
  732. /* Writing a full 32 byte row (2 blocks) */
  733. row_size = 32;
  734. memcpy(encrypt_buf, ssrc + i, row_size);
  735. }
  736. encrypt_byte = 32;
  737. row_size_length = row_size;
  738. #else // FOR ESP32-S2, ESP32-S3, ESP32-C3
  739. if ((row_addr % 64) == 0 && (length - i) >= 64 && SOC_FLASH_ENCRYPTED_XTS_AES_BLOCK_MAX == 64) {
  740. row_size = 64;
  741. memcpy(encrypt_buf, ssrc + i, row_size);
  742. } else if ((row_addr % 32) == 0 && (length - i) >= 32) {
  743. row_size = 32;
  744. memcpy(encrypt_buf, ssrc + i, row_size);
  745. } else {
  746. row_size = 16;
  747. memcpy(encrypt_buf, ssrc + i, row_size);
  748. }
  749. encrypt_byte = row_size;
  750. row_size_length = row_size;
  751. #endif //CONFIG_IDF_TARGET_ESP32
  752. #if CONFIG_IDF_TARGET_ESP32S2
  753. esp_crypto_dma_lock_acquire();
  754. #endif //CONFIG_IDF_TARGET_ESP32S2
  755. err = rom_spiflash_api_funcs->start(chip);
  756. if (err != ESP_OK) {
  757. #if CONFIG_IDF_TARGET_ESP32S2
  758. esp_crypto_dma_lock_release();
  759. #endif //CONFIG_IDF_TARGET_ESP32S2
  760. break;
  761. }
  762. bus_acquired = true;
  763. err = chip->chip_drv->write_encrypted(chip, (uint32_t *)encrypt_buf, row_addr, encrypt_byte);
  764. if (err!= ESP_OK) {
  765. #if CONFIG_IDF_TARGET_ESP32S2
  766. esp_crypto_dma_lock_release();
  767. #endif //CONFIG_IDF_TARGET_ESP32S2
  768. bus_acquired = false;
  769. assert(bus_acquired);
  770. break;
  771. }
  772. err = rom_spiflash_api_funcs->end(chip, ESP_OK);
  773. #if CONFIG_IDF_TARGET_ESP32S2
  774. esp_crypto_dma_lock_release();
  775. #endif //CONFIG_IDF_TARGET_ESP32S2
  776. if (err != ESP_OK) {
  777. bus_acquired = false;
  778. break;
  779. }
  780. bus_acquired = false;
  781. }
  782. return rom_spiflash_api_funcs->flash_end_flush_cache(chip, err, bus_acquired, address, length);
  783. }
  784. inline static IRAM_ATTR bool regions_overlap(uint32_t a_start, uint32_t a_len,uint32_t b_start, uint32_t b_len)
  785. {
  786. uint32_t a_end = a_start + a_len;
  787. uint32_t b_end = b_start + b_len;
  788. return (a_end > b_start && b_end > a_start);
  789. }
  790. //currently the legacy implementation is used, from flash_ops.c
  791. esp_err_t spi_flash_read_encrypted(size_t src, void *dstv, size_t size);
  792. esp_err_t IRAM_ATTR esp_flash_read_encrypted(esp_flash_t *chip, uint32_t address, void *out_buffer, uint32_t length)
  793. {
  794. /*
  795. * Since currently this feature is supported only by the hardware, there
  796. * is no way to support non-standard chips. We use the legacy
  797. * implementation and skip the chip and driver layers.
  798. */
  799. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  800. if (err != ESP_OK) return err;
  801. return spi_flash_read_encrypted(address, out_buffer, length);
  802. }
  803. // test only, non-public
  804. IRAM_ATTR esp_err_t esp_flash_get_io_mode(esp_flash_t* chip, bool* qe)
  805. {
  806. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  807. VERIFY_CHIP_OP(get_io_mode);
  808. esp_flash_io_mode_t io_mode;
  809. err = rom_spiflash_api_funcs->start(chip);
  810. if (err != ESP_OK) {
  811. return err;
  812. }
  813. err = chip->chip_drv->get_io_mode(chip, &io_mode);
  814. err = rom_spiflash_api_funcs->end(chip, err);
  815. if (err == ESP_OK) {
  816. *qe = (io_mode == SPI_FLASH_QOUT);
  817. }
  818. return err;
  819. }
  820. IRAM_ATTR esp_err_t esp_flash_set_io_mode(esp_flash_t* chip, bool qe)
  821. {
  822. esp_err_t err = rom_spiflash_api_funcs->chip_check(&chip);
  823. VERIFY_CHIP_OP(set_io_mode);
  824. chip->read_mode = (qe? SPI_FLASH_QOUT: SPI_FLASH_SLOWRD);
  825. err = rom_spiflash_api_funcs->start(chip);
  826. if (err != ESP_OK) {
  827. return err;
  828. }
  829. err = chip->chip_drv->set_io_mode(chip);
  830. return rom_spiflash_api_funcs->end(chip, err);
  831. }
  832. #endif //CONFIG_SPI_FLASH_ROM_IMPL
  833. //init suspend mode cmd, uses internal.
  834. esp_err_t esp_flash_suspend_cmd_init(esp_flash_t* chip)
  835. {
  836. ESP_EARLY_LOGW(TAG, "Flash suspend feature is enabled");
  837. return chip->chip_drv->sus_setup(chip);
  838. }
  839. #ifndef CONFIG_SPI_FLASH_USE_LEGACY_IMPL
  840. esp_err_t esp_flash_app_disable_protect(bool disable)
  841. {
  842. if (disable) {
  843. return esp_flash_app_disable_os_functions(esp_flash_default_chip);
  844. } else {
  845. return esp_flash_app_enable_os_functions(esp_flash_default_chip);
  846. }
  847. }
  848. #endif
  849. /*------------------------------------------------------------------------------
  850. Adapter layer to original api before IDF v4.0
  851. ------------------------------------------------------------------------------*/
  852. #ifndef CONFIG_SPI_FLASH_USE_LEGACY_IMPL
  853. /* Translate any ESP_ERR_FLASH_xxx error code (new API) to a generic ESP_ERR_xyz error code
  854. */
  855. static IRAM_ATTR esp_err_t spi_flash_translate_rc(esp_err_t err)
  856. {
  857. switch (err) {
  858. case ESP_OK:
  859. case ESP_ERR_INVALID_ARG:
  860. case ESP_ERR_INVALID_SIZE:
  861. case ESP_ERR_NO_MEM:
  862. return err;
  863. case ESP_ERR_FLASH_NOT_INITIALISED:
  864. case ESP_ERR_FLASH_PROTECTED:
  865. return ESP_ERR_INVALID_STATE;
  866. case ESP_ERR_NOT_FOUND:
  867. case ESP_ERR_FLASH_UNSUPPORTED_HOST:
  868. case ESP_ERR_FLASH_UNSUPPORTED_CHIP:
  869. return ESP_ERR_NOT_SUPPORTED;
  870. case ESP_ERR_FLASH_NO_RESPONSE:
  871. return ESP_ERR_INVALID_RESPONSE;
  872. default:
  873. ESP_EARLY_LOGE(TAG, "unexpected spi flash error code: 0x%x", err);
  874. abort();
  875. }
  876. }
  877. esp_err_t IRAM_ATTR spi_flash_erase_range(uint32_t start_addr, uint32_t size)
  878. {
  879. esp_err_t err = esp_flash_erase_region(NULL, start_addr, size);
  880. return spi_flash_translate_rc(err);
  881. }
  882. esp_err_t IRAM_ATTR spi_flash_write(size_t dst, const void *srcv, size_t size)
  883. {
  884. esp_err_t err = esp_flash_write(NULL, srcv, dst, size);
  885. return spi_flash_translate_rc(err);
  886. }
  887. esp_err_t IRAM_ATTR spi_flash_read(size_t src, void *dstv, size_t size)
  888. {
  889. esp_err_t err = esp_flash_read(NULL, dstv, src, size);
  890. return spi_flash_translate_rc(err);
  891. }
  892. esp_err_t IRAM_ATTR spi_flash_write_encrypted(size_t dest_addr, const void *src, size_t size)
  893. {
  894. esp_err_t err = esp_flash_write_encrypted(NULL, dest_addr, src, size);
  895. return spi_flash_translate_rc(err);
  896. }
  897. #endif // CONFIG_SPI_FLASH_USE_LEGACY_IMPL