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