esp_flash_api.c 37 KB

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