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