• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2015-2016 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 <assert.h>
17 #include <string.h>
18 #include <stdio.h>
19 #include <sys/param.h>  // For MIN/MAX(a, b)
20 
21 #include <esp_osal/esp_osal.h>
22 #include <esp_osal/task.h>
23 #include <esp_osal/semphr.h>
24 #include <soc/soc.h>
25 #include <soc/soc_memory_layout.h>
26 #include "sdkconfig.h"
27 #include "esp_attr.h"
28 #include "esp_spi_flash.h"
29 #include "esp_log.h"
30 #include "esp_private/system_internal.h"
31 #if CONFIG_IDF_TARGET_ESP32
32 #include "esp32/rom/cache.h"
33 #include "esp32/rom/spi_flash.h"
34 #include "esp32/clk.h"
35 #elif CONFIG_IDF_TARGET_ESP32S2
36 #include "esp32s2/rom/cache.h"
37 #include "esp32s2/rom/spi_flash.h"
38 #include "esp32s2/clk.h"
39 #elif CONFIG_IDF_TARGET_ESP32S3
40 #include "esp32s3/rom/spi_flash.h"
41 #include "esp32s3/rom/cache.h"
42 #include "esp32s3/clk.h"
43 #elif CONFIG_IDF_TARGET_ESP32C3
44 #include "esp32c3/rom/cache.h"
45 #include "esp32c3/rom/spi_flash.h"
46 #include "esp32c3/clk.h"
47 #endif
48 #include "esp_flash_partitions.h"
49 #include "cache_utils.h"
50 #include "esp_flash.h"
51 #include "esp_attr.h"
52 
53 esp_rom_spiflash_result_t IRAM_ATTR spi_flash_write_encrypted_chip(size_t dest_addr, const void *src, size_t size);
54 
55 /* bytes erased by SPIEraseBlock() ROM function */
56 #define BLOCK_ERASE_SIZE 65536
57 
58 /* Limit number of bytes written/read in a single SPI operation,
59    as these operations disable all higher priority tasks from running.
60 */
61 #ifdef CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE
62 #define MAX_WRITE_CHUNK CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE
63 #else
64 #define MAX_WRITE_CHUNK 8192
65 #endif // CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE
66 
67 #define MAX_READ_CHUNK 16384
68 
69 static const char *TAG __attribute__((unused)) = "spi_flash";
70 
71 #if CONFIG_SPI_FLASH_ENABLE_COUNTERS
72 static spi_flash_counters_t s_flash_stats;
73 
74 #define COUNTER_START()     uint32_t ts_begin = cpu_hal_get_cycle_count()
75 #define COUNTER_STOP(counter)  \
76     do{ \
77         s_flash_stats.counter.count++; \
78         s_flash_stats.counter.time += (cpu_hal_get_cycle_count() - ts_begin) / (esp_clk_cpu_freq() / 1000000); \
79     } while(0)
80 
81 #define COUNTER_ADD_BYTES(counter, size) \
82     do { \
83         s_flash_stats.counter.bytes += size; \
84     } while (0)
85 
86 #else
87 #define COUNTER_START()
88 #define COUNTER_STOP(counter)
89 #define COUNTER_ADD_BYTES(counter, size)
90 
91 #endif //CONFIG_SPI_FLASH_ENABLE_COUNTERS
92 
93 static esp_err_t spi_flash_translate_rc(esp_rom_spiflash_result_t rc);
94 static bool is_safe_write_address(size_t addr, size_t size);
95 static void spi_flash_os_yield(void);
96 
97 const DRAM_ATTR spi_flash_guard_funcs_t g_flash_guard_default_ops = {
98     .start                  = spi_flash_disable_interrupts_caches_and_other_cpu,
99     .end                    = spi_flash_enable_interrupts_caches_and_other_cpu,
100     .op_lock                = spi_flash_op_lock,
101     .op_unlock              = spi_flash_op_unlock,
102 #if !CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED
103     .is_safe_write_address  = is_safe_write_address,
104 #endif
105     .yield                  = spi_flash_os_yield,
106 };
107 
108 const DRAM_ATTR spi_flash_guard_funcs_t g_flash_guard_no_os_ops = {
109     .start                  = spi_flash_disable_interrupts_caches_and_other_cpu_no_os,
110     .end                    = spi_flash_enable_interrupts_caches_no_os,
111     .op_lock                = NULL,
112     .op_unlock              = NULL,
113 #if !CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED
114     .is_safe_write_address  = NULL,
115 #endif
116     .yield                  = NULL,
117 };
118 
119 #ifdef CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS
120 #define UNSAFE_WRITE_ADDRESS abort()
121 #else
122 #define UNSAFE_WRITE_ADDRESS return false
123 #endif
124 
125 
126 /* CHECK_WRITE_ADDRESS macro to fail writes which land in the
127    bootloader, partition table, or running application region.
128 */
129 #if CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED
130 #define CHECK_WRITE_ADDRESS(ADDR, SIZE)
131 #else /* FAILS or ABORTS */
132 #define CHECK_WRITE_ADDRESS(ADDR, SIZE) do {                            \
133         if (guard && guard->is_safe_write_address && !guard->is_safe_write_address(ADDR, SIZE)) {                       \
134             return ESP_ERR_INVALID_ARG;                                 \
135         }                                                               \
136     } while(0)
137 #endif // CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED
138 
is_safe_write_address(size_t addr,size_t size)139 static __attribute__((unused)) bool is_safe_write_address(size_t addr, size_t size)
140 {
141     if (!esp_partition_main_flash_region_safe(addr, size)) {
142         UNSAFE_WRITE_ADDRESS;
143     }
144     return true;
145 }
146 
147 #if CONFIG_SPI_FLASH_ROM_IMPL
148 #include "esp_heap_caps.h"
149 typedef void *(*malloc_internal_cb_t)(size_t size);
150 
spi_flash_malloc_internal(size_t size)151 void IRAM_ATTR *spi_flash_malloc_internal(size_t size)
152 {
153     return heap_caps_malloc(size, MALLOC_CAP_8BIT|MALLOC_CAP_INTERNAL);
154 }
155 #endif
156 
spi_flash_init(void)157 void spi_flash_init(void)
158 {
159     spi_flash_init_lock();
160 #if CONFIG_SPI_FLASH_ENABLE_COUNTERS
161     spi_flash_reset_counters();
162 #endif
163 
164 #if CONFIG_SPI_FLASH_ROM_IMPL
165     spi_flash_guard_set(&g_flash_guard_default_ops);
166 
167     /* These two functions are in ROM only */
168     extern void spi_flash_mmap_os_func_set(void *(*func1)(size_t size), void (*func2)(void *p));
169     spi_flash_mmap_os_func_set(spi_flash_malloc_internal, heap_caps_free);
170 
171     extern esp_err_t spi_flash_mmap_page_num_init(uint32_t page_num);
172     spi_flash_mmap_page_num_init(128);
173 #endif
174 }
175 
176 #if !CONFIG_SPI_FLASH_ROM_IMPL
177 
178 static const spi_flash_guard_funcs_t *s_flash_guard_ops;
179 
spi_flash_guard_set(const spi_flash_guard_funcs_t * funcs)180 void IRAM_ATTR spi_flash_guard_set(const spi_flash_guard_funcs_t *funcs)
181 {
182     s_flash_guard_ops = funcs;
183 }
184 
spi_flash_guard_get(void)185 const spi_flash_guard_funcs_t *IRAM_ATTR spi_flash_guard_get(void)
186 {
187     return s_flash_guard_ops;
188 }
189 
190 #endif
191 
spi_flash_get_chip_size(void)192 size_t IRAM_ATTR spi_flash_get_chip_size(void)
193 {
194     return g_rom_flashchip.chip_size;
195 }
196 
spi_flash_guard_start(void)197 static inline void IRAM_ATTR spi_flash_guard_start(void)
198 {
199     const spi_flash_guard_funcs_t *guard =  spi_flash_guard_get();
200     if (guard && guard->start) {
201         guard->start();
202     }
203 }
204 
spi_flash_guard_end(void)205 static inline void IRAM_ATTR spi_flash_guard_end(void)
206 {
207     const spi_flash_guard_funcs_t *guard =  spi_flash_guard_get();
208     if (guard && guard->end) {
209         guard->end();
210     }
211 }
212 
spi_flash_guard_op_lock(void)213 static inline void IRAM_ATTR spi_flash_guard_op_lock(void)
214 {
215     const spi_flash_guard_funcs_t *guard =  spi_flash_guard_get();
216     if (guard && guard->op_lock) {
217         guard->op_lock();
218     }
219 }
220 
spi_flash_guard_op_unlock(void)221 static inline void IRAM_ATTR spi_flash_guard_op_unlock(void)
222 {
223     const spi_flash_guard_funcs_t *guard =  spi_flash_guard_get();
224     if (guard && guard->op_unlock) {
225         guard->op_unlock();
226     }
227 }
228 
spi_flash_os_yield(void)229 static void IRAM_ATTR spi_flash_os_yield(void)
230 {
231 #ifdef CONFIG_SPI_FLASH_YIELD_DURING_ERASE
232     vTaskDelay(CONFIG_SPI_FLASH_ERASE_YIELD_TICKS);
233 #endif
234 }
235 
236 #ifdef CONFIG_SPI_FLASH_USE_LEGACY_IMPL
spi_flash_unlock(void)237 static esp_rom_spiflash_result_t IRAM_ATTR spi_flash_unlock(void)
238 {
239     static bool unlocked = false;
240     if (!unlocked) {
241         spi_flash_guard_start();
242         esp_rom_spiflash_result_t rc = esp_rom_spiflash_unlock();
243         spi_flash_guard_end();
244         if (rc != ESP_ROM_SPIFLASH_RESULT_OK) {
245             return rc;
246         }
247         unlocked = true;
248     }
249     return ESP_ROM_SPIFLASH_RESULT_OK;
250 }
251 #else
spi_flash_unlock(void)252 static esp_rom_spiflash_result_t IRAM_ATTR spi_flash_unlock(void)
253 {
254     esp_err_t err = esp_flash_set_chip_write_protect(NULL, false);
255     if (err != ESP_OK) {
256         return ESP_ROM_SPIFLASH_RESULT_ERR;
257     }
258     return ESP_ROM_SPIFLASH_RESULT_OK;
259 }
260 #endif // CONFIG_SPI_FLASH_USE_LEGACY_IMPL
261 
spi_flash_erase_sector(size_t sec)262 esp_err_t IRAM_ATTR spi_flash_erase_sector(size_t sec)
263 {
264     const spi_flash_guard_funcs_t *guard = spi_flash_guard_get();
265     CHECK_WRITE_ADDRESS(sec * SPI_FLASH_SEC_SIZE, SPI_FLASH_SEC_SIZE);
266     return spi_flash_erase_range(sec * SPI_FLASH_SEC_SIZE, SPI_FLASH_SEC_SIZE);
267 }
268 
269 #ifdef CONFIG_SPI_FLASH_USE_LEGACY_IMPL
270 //deprecated, only used in compatible mode
spi_flash_erase_range(size_t start_addr,size_t size)271 esp_err_t IRAM_ATTR spi_flash_erase_range(size_t start_addr, size_t size)
272 {
273     const spi_flash_guard_funcs_t *guard =  spi_flash_guard_get();
274     CHECK_WRITE_ADDRESS(start_addr, size);
275     if (start_addr % SPI_FLASH_SEC_SIZE != 0) {
276         return ESP_ERR_INVALID_ARG;
277     }
278     if (size % SPI_FLASH_SEC_SIZE != 0) {
279         return ESP_ERR_INVALID_SIZE;
280     }
281     if (size + start_addr > spi_flash_get_chip_size()) {
282         return ESP_ERR_INVALID_SIZE;
283     }
284     size_t start = start_addr / SPI_FLASH_SEC_SIZE;
285     size_t end = start + size / SPI_FLASH_SEC_SIZE;
286     const size_t sectors_per_block = BLOCK_ERASE_SIZE / SPI_FLASH_SEC_SIZE;
287     COUNTER_START();
288     esp_rom_spiflash_result_t rc;
289     rc = spi_flash_unlock();
290     if (rc == ESP_ROM_SPIFLASH_RESULT_OK) {
291 #ifdef CONFIG_SPI_FLASH_YIELD_DURING_ERASE
292         int64_t no_yield_time_us = 0;
293 #endif
294         for (size_t sector = start; sector != end && rc == ESP_ROM_SPIFLASH_RESULT_OK; ) {
295 #ifdef CONFIG_SPI_FLASH_YIELD_DURING_ERASE
296             int64_t start_time_us = esp_system_get_time();
297 #endif
298             spi_flash_guard_start();
299 #ifndef CONFIG_SPI_FLASH_BYPASS_BLOCK_ERASE
300             if (sector % sectors_per_block == 0 && end - sector >= sectors_per_block) {
301                 rc = esp_rom_spiflash_erase_block(sector / sectors_per_block);
302                 sector += sectors_per_block;
303                 COUNTER_ADD_BYTES(erase, sectors_per_block * SPI_FLASH_SEC_SIZE);
304             } else
305 #endif
306             {
307                 rc = esp_rom_spiflash_erase_sector(sector);
308                 ++sector;
309                 COUNTER_ADD_BYTES(erase, SPI_FLASH_SEC_SIZE);
310             }
311             spi_flash_guard_end();
312 #ifdef CONFIG_SPI_FLASH_YIELD_DURING_ERASE
313             no_yield_time_us += (esp_system_get_time() - start_time_us);
314             if (no_yield_time_us / 1000 >= CONFIG_SPI_FLASH_ERASE_YIELD_DURATION_MS) {
315                 no_yield_time_us = 0;
316                 if (s_flash_guard_ops && s_flash_guard_ops->yield) {
317                     s_flash_guard_ops->yield();
318                 }
319             }
320 #endif
321         }
322     }
323     COUNTER_STOP(erase);
324 
325     spi_flash_guard_start();
326     // Ensure WEL is 0 after the operation, even if the erase failed.
327     esp_rom_spiflash_write_disable();
328     spi_flash_check_and_flush_cache(start_addr, size);
329     spi_flash_guard_end();
330 
331     return spi_flash_translate_rc(rc);
332 }
333 
334 /* Wrapper around esp_rom_spiflash_write() that verifies data as written if CONFIG_SPI_FLASH_VERIFY_WRITE is set.
335 
336    If CONFIG_SPI_FLASH_VERIFY_WRITE is not set, this is esp_rom_spiflash_write().
337 */
spi_flash_write_inner(uint32_t target,const uint32_t * src_addr,int32_t len)338 static IRAM_ATTR esp_rom_spiflash_result_t spi_flash_write_inner(uint32_t target, const uint32_t *src_addr, int32_t len)
339 {
340 #ifndef CONFIG_SPI_FLASH_VERIFY_WRITE
341     return esp_rom_spiflash_write(target, src_addr, len);
342 #else // CONFIG_SPI_FLASH_VERIFY_WRITE
343     esp_rom_spiflash_result_t res = ESP_ROM_SPIFLASH_RESULT_OK;
344     assert(len % sizeof(uint32_t) == 0);
345 
346     uint32_t before_buf[ESP_ROM_SPIFLASH_BUFF_BYTE_READ_NUM / sizeof(uint32_t)];
347     uint32_t after_buf[ESP_ROM_SPIFLASH_BUFF_BYTE_READ_NUM / sizeof(uint32_t)];
348     uint32_t *expected_buf = before_buf;
349     int32_t remaining = len;
350     for(int i = 0; i < len; i += sizeof(before_buf)) {
351         int i_w = i / sizeof(uint32_t); // index in words (i is an index in bytes)
352         int32_t read_len = MIN(sizeof(before_buf), remaining);
353 
354         // Read "before" contents from flash
355         res = esp_rom_spiflash_read(target + i, before_buf, read_len);
356         if (res != ESP_ROM_SPIFLASH_RESULT_OK) {
357             break;
358         }
359 
360         for (int r = 0; r < read_len; r += sizeof(uint32_t)) {
361             int r_w = r / sizeof(uint32_t); // index in words (r is index in bytes)
362 
363             uint32_t write = src_addr[i_w + r_w];
364             uint32_t before = before_buf[r_w];
365             uint32_t expected = write & before;
366 #ifdef CONFIG_SPI_FLASH_WARN_SETTING_ZERO_TO_ONE
367             if ((before & write) != write) {
368                 spi_flash_guard_end();
369                 ESP_LOGW(TAG, "Write at offset 0x%x requests 0x%08x but will write 0x%08x -> 0x%08x",
370                          target + i + r, write, before, before & write);
371                 spi_flash_guard_start();
372             }
373 #endif
374             expected_buf[r_w] = expected;
375         }
376 
377         res = esp_rom_spiflash_write(target + i, &src_addr[i_w], read_len);
378         if (res != ESP_ROM_SPIFLASH_RESULT_OK) {
379             break;
380         }
381 
382         res = esp_rom_spiflash_read(target + i, after_buf, read_len);
383         if (res != ESP_ROM_SPIFLASH_RESULT_OK) {
384             break;
385         }
386 
387         for (int r = 0; r < read_len; r += sizeof(uint32_t)) {
388             int r_w = r / sizeof(uint32_t); // index in words (r is index in bytes)
389 
390             uint32_t expected = expected_buf[r_w];
391             uint32_t actual = after_buf[r_w];
392             if (expected != actual) {
393 #ifdef CONFIG_SPI_FLASH_LOG_FAILED_WRITE
394                 spi_flash_guard_end();
395                 ESP_LOGE(TAG, "Bad write at offset 0x%x expected 0x%08x readback 0x%08x", target + i + r, expected, actual);
396                 spi_flash_guard_start();
397 #endif
398                 res = ESP_ROM_SPIFLASH_RESULT_ERR;
399             }
400         }
401         if (res != ESP_ROM_SPIFLASH_RESULT_OK) {
402             break;
403         }
404         remaining -= read_len;
405     }
406     return res;
407 #endif // CONFIG_SPI_FLASH_VERIFY_WRITE
408 }
409 
410 
spi_flash_write(size_t dst,const void * srcv,size_t size)411 esp_err_t IRAM_ATTR spi_flash_write(size_t dst, const void *srcv, size_t size)
412 {
413     const spi_flash_guard_funcs_t *guard =  spi_flash_guard_get();
414     CHECK_WRITE_ADDRESS(dst, size);
415     // Out of bound writes are checked in ROM code, but we can give better
416     // error code here
417     if (dst + size > g_rom_flashchip.chip_size) {
418         return ESP_ERR_INVALID_SIZE;
419     }
420     if (size == 0) {
421         return ESP_OK;
422     }
423 
424     esp_rom_spiflash_result_t rc = ESP_ROM_SPIFLASH_RESULT_OK;
425     COUNTER_START();
426     const uint8_t *srcc = (const uint8_t *) srcv;
427     /*
428      * Large operations are split into (up to) 3 parts:
429      * - Left padding: 4 bytes up to the first 4-byte aligned destination offset.
430      * - Middle part
431      * - Right padding: 4 bytes from the last 4-byte aligned offset covered.
432      */
433     size_t left_off = dst & ~3U;
434     size_t left_size = MIN(((dst + 3) & ~3U) - dst, size);
435     size_t mid_off = left_size;
436     size_t mid_size = (size - left_size) & ~3U;
437     size_t right_off = left_size + mid_size;
438     size_t right_size = size - mid_size - left_size;
439 
440     rc = spi_flash_unlock();
441     if (rc != ESP_ROM_SPIFLASH_RESULT_OK) {
442         goto out;
443     }
444     if (left_size > 0) {
445         uint32_t t = 0xffffffff;
446         memcpy(((uint8_t *) &t) + (dst - left_off), srcc, left_size);
447         spi_flash_guard_start();
448         rc = spi_flash_write_inner(left_off, &t, 4);
449         spi_flash_guard_end();
450         if (rc != ESP_ROM_SPIFLASH_RESULT_OK) {
451             goto out;
452         }
453         COUNTER_ADD_BYTES(write, 4);
454     }
455     if (mid_size > 0) {
456         /* If src buffer is 4-byte aligned as well and is not in a region that requires cache access to be enabled, we
457          * can write directly without buffering in RAM. */
458 #ifdef ESP_PLATFORM
459         bool direct_write = esp_ptr_internal(srcc)
460                 && esp_ptr_byte_accessible(srcc)
461                 && ((uintptr_t) srcc + mid_off) % 4 == 0;
462 #else
463         bool direct_write = true;
464 #endif
465         while(mid_size > 0 && rc == ESP_ROM_SPIFLASH_RESULT_OK) {
466             uint32_t write_buf[8];
467             uint32_t write_size = MIN(mid_size, MAX_WRITE_CHUNK);
468             const uint8_t *write_src = srcc + mid_off;
469             if (!direct_write) {
470                 write_size = MIN(write_size, sizeof(write_buf));
471                 memcpy(write_buf, write_src, write_size);
472                 write_src = (const uint8_t *)write_buf;
473             }
474             spi_flash_guard_start();
475             rc = spi_flash_write_inner(dst + mid_off, (const uint32_t *) write_src, write_size);
476             spi_flash_guard_end();
477             COUNTER_ADD_BYTES(write, write_size);
478             mid_size -= write_size;
479             mid_off += write_size;
480         }
481         if (rc != ESP_ROM_SPIFLASH_RESULT_OK) {
482             goto out;
483         }
484     }
485 
486     if (right_size > 0) {
487         uint32_t t = 0xffffffff;
488         memcpy(&t, srcc + right_off, right_size);
489         spi_flash_guard_start();
490         rc = spi_flash_write_inner(dst + right_off, &t, 4);
491         spi_flash_guard_end();
492         if (rc != ESP_ROM_SPIFLASH_RESULT_OK) {
493             goto out;
494         }
495         COUNTER_ADD_BYTES(write, 4);
496     }
497 out:
498     COUNTER_STOP(write);
499 
500     spi_flash_guard_start();
501     // Ensure WEL is 0 after the operation, even if the write failed.
502     esp_rom_spiflash_write_disable();
503     spi_flash_check_and_flush_cache(dst, size);
504     spi_flash_guard_end();
505 
506     return spi_flash_translate_rc(rc);
507 }
508 #endif // CONFIG_SPI_FLASH_USE_LEGACY_IMPL
509 
510 #if !CONFIG_SPI_FLASH_USE_LEGACY_IMPL
511 extern void spi_common_set_dummy_output(esp_rom_spiflash_read_mode_t mode);
512 extern void spi_dummy_len_fix(uint8_t spi, uint8_t freqdiv);
flash_rom_init(void)513 void IRAM_ATTR flash_rom_init(void)
514 {
515     uint32_t freqdiv = 0;
516 
517 #if CONFIG_IDF_TARGET_ESP32
518     uint32_t dummy_bit = 0;
519 #if CONFIG_ESPTOOLPY_FLASHFREQ_80M
520     dummy_bit = ESP_ROM_SPIFLASH_DUMMY_LEN_PLUS_80M;
521 #elif CONFIG_ESPTOOLPY_FLASHFREQ_40M
522     dummy_bit = ESP_ROM_SPIFLASH_DUMMY_LEN_PLUS_40M;
523 #elif CONFIG_ESPTOOLPY_FLASHFREQ_26M
524     dummy_bit = ESP_ROM_SPIFLASH_DUMMY_LEN_PLUS_26M;
525 #elif CONFIG_ESPTOOLPY_FLASHFREQ_20M
526     dummy_bit = ESP_ROM_SPIFLASH_DUMMY_LEN_PLUS_20M;
527 #endif
528 #endif//CONFIG_IDF_TARGET_ESP32
529 
530 #if CONFIG_ESPTOOLPY_FLASHFREQ_80M
531     freqdiv = 1;
532 #elif CONFIG_ESPTOOLPY_FLASHFREQ_40M
533     freqdiv = 2;
534 #elif CONFIG_ESPTOOLPY_FLASHFREQ_26M
535     freqdiv = 3;
536 #elif CONFIG_ESPTOOLPY_FLASHFREQ_20M
537     freqdiv = 4;
538 #endif
539 
540 #if !CONFIG_IDF_TARGET_ESP32S2 && !CONFIG_IDF_TARGET_ESP32
541     esp_rom_spiflash_read_mode_t read_mode;
542 #if CONFIG_ESPTOOLPY_FLASHMODE_QIO
543     read_mode = ESP_ROM_SPIFLASH_QIO_MODE;
544 #elif CONFIG_ESPTOOLPY_FLASHMODE_QOUT
545     read_mode = ESP_ROM_SPIFLASH_QOUT_MODE;
546 #elif CONFIG_ESPTOOLPY_FLASHMODE_DIO
547     read_mode = ESP_ROM_SPIFLASH_DIO_MODE;
548 #elif CONFIG_ESPTOOLPY_FLASHMODE_DOUT
549     read_mode = ESP_ROM_SPIFLASH_DOUT_MODE;
550 #endif
551 #endif //!CONFIG_IDF_TARGET_ESP32S2 && !CONFIG_IDF_TARGET_ESP32
552 
553 #if CONFIG_IDF_TARGET_ESP32
554     g_rom_spiflash_dummy_len_plus[1] = dummy_bit;
555 #else
556     spi_dummy_len_fix(1, freqdiv);
557 #endif //CONFIG_IDF_TARGET_ESP32
558 
559 #if !CONFIG_IDF_TARGET_ESP32S2 && !CONFIG_IDF_TARGET_ESP32
560     spi_common_set_dummy_output(read_mode);
561 #endif //!CONFIG_IDF_TARGET_ESP32S2
562     esp_rom_spiflash_config_clk(freqdiv, 1);
563 }
564 #else
flash_rom_init(void)565 void IRAM_ATTR flash_rom_init(void)
566 {
567     return;
568 }
569 #endif // !CONFIG_SPI_FLASH_USE_LEGACY_IMPL
570 
spi_flash_write_encrypted(size_t dest_addr,const void * src,size_t size)571 esp_err_t IRAM_ATTR spi_flash_write_encrypted(size_t dest_addr, const void *src, size_t size)
572 {
573     esp_err_t err = ESP_OK;
574     const spi_flash_guard_funcs_t *guard =  spi_flash_guard_get();
575     CHECK_WRITE_ADDRESS(dest_addr, size);
576     if ((dest_addr % 16) != 0) {
577         return ESP_ERR_INVALID_ARG;
578     }
579     if ((size % 16) != 0) {
580         return ESP_ERR_INVALID_SIZE;
581     }
582 
583     COUNTER_START();
584     esp_rom_spiflash_result_t rc = spi_flash_unlock();
585     err = spi_flash_translate_rc(rc);
586     if (err != ESP_OK) {
587         goto fail;
588     }
589 
590 #ifndef CONFIG_SPI_FLASH_VERIFY_WRITE
591     err = spi_flash_write_encrypted_chip(dest_addr, src, size);
592     COUNTER_ADD_BYTES(write, size);
593     spi_flash_guard_start();
594     esp_rom_spiflash_write_disable();
595     spi_flash_check_and_flush_cache(dest_addr, size);
596     spi_flash_guard_end();
597 #else
598     const uint32_t* src_w = (const uint32_t*)src;
599     uint32_t read_buf[ESP_ROM_SPIFLASH_BUFF_BYTE_READ_NUM / sizeof(uint32_t)];
600     int32_t remaining = size;
601     for(int i = 0; i < size; i += sizeof(read_buf)) {
602         int i_w = i / sizeof(uint32_t); // index in words (i is an index in bytes)
603         int32_t read_len = MIN(sizeof(read_buf), remaining);
604 
605         // Read "before" contents from flash
606         esp_err_t err = spi_flash_read(dest_addr + i, read_buf, read_len);
607         if (err != ESP_OK) {
608             break;
609         }
610 
611 #ifdef CONFIG_SPI_FLASH_WARN_SETTING_ZERO_TO_ONE
612         //The written data cannot be predicted, so warning is shown if any of the bits is not 1.
613         for (int r = 0; r < read_len; r += sizeof(uint32_t)) {
614             uint32_t before = read_buf[r / sizeof(uint32_t)];
615             if (before != 0xFFFFFFFF) {
616                 ESP_LOGW(TAG, "Encrypted write at offset 0x%x but not erased (0x%08x)",
617                          dest_addr + i + r, before);
618             }
619         }
620 #endif
621 
622         err = spi_flash_write_encrypted_chip(dest_addr + i, src + i, read_len);
623         if (err != ESP_OK) {
624             break;
625         }
626         COUNTER_ADD_BYTES(write, size);
627 
628         spi_flash_guard_start();
629         esp_rom_spiflash_write_disable();
630         spi_flash_check_and_flush_cache(dest_addr, size);
631         spi_flash_guard_end();
632 
633         err = spi_flash_read_encrypted(dest_addr + i, read_buf, read_len);
634         if (err != ESP_OK) {
635             break;
636         }
637 
638         for (int r = 0; r < read_len; r += sizeof(uint32_t)) {
639             int r_w = r / sizeof(uint32_t); // index in words (r is index in bytes)
640 
641             uint32_t expected = src_w[i_w + r_w];
642             uint32_t actual = read_buf[r_w];
643             if (expected != actual) {
644 #ifdef CONFIG_SPI_FLASH_LOG_FAILED_WRITE
645                 ESP_LOGE(TAG, "Bad write at offset 0x%x expected 0x%08x readback 0x%08x", dest_addr + i + r, expected, actual);
646 #endif
647                 err = ESP_FAIL;
648             }
649         }
650         if (err != ESP_OK) {
651             break;
652         }
653         remaining -= read_len;
654     }
655 #endif // CONFIG_SPI_FLASH_VERIFY_WRITE
656 
657 fail:
658 
659     COUNTER_STOP(write);
660     return err;
661 }
662 
663 
664 #ifdef CONFIG_SPI_FLASH_USE_LEGACY_IMPL
spi_flash_read(size_t src,void * dstv,size_t size)665 esp_err_t IRAM_ATTR spi_flash_read(size_t src, void *dstv, size_t size)
666 {
667     // Out of bound reads are checked in ROM code, but we can give better
668     // error code here
669     if (src + size > g_rom_flashchip.chip_size) {
670         return ESP_ERR_INVALID_SIZE;
671     }
672     if (size == 0) {
673         return ESP_OK;
674     }
675 
676     esp_rom_spiflash_result_t rc = ESP_ROM_SPIFLASH_RESULT_OK;
677     COUNTER_START();
678     spi_flash_guard_start();
679     /* To simplify boundary checks below, we handle small reads separately. */
680     if (size < 16) {
681         uint32_t t[6]; /* Enough for 16 bytes + 4 on either side for padding. */
682         uint32_t read_src = src & ~3U;
683         uint32_t left_off = src & 3U;
684         uint32_t read_size = (left_off + size + 3) & ~3U;
685         rc = esp_rom_spiflash_read(read_src, t, read_size);
686         if (rc != ESP_ROM_SPIFLASH_RESULT_OK) {
687             goto out;
688         }
689         COUNTER_ADD_BYTES(read, read_size);
690 #ifdef ESP_PLATFORM
691         if (esp_ptr_external_ram(dstv)) {
692             spi_flash_guard_end();
693             memcpy(dstv, ((uint8_t *) t) + left_off, size);
694             spi_flash_guard_start();
695         } else {
696             memcpy(dstv, ((uint8_t *) t) + left_off, size);
697         }
698 #else
699         memcpy(dstv, ((uint8_t *) t) + left_off, size);
700 #endif
701         goto out;
702     }
703     uint8_t *dstc = (uint8_t *) dstv;
704     intptr_t dsti = (intptr_t) dstc;
705     /*
706      * Large operations are split into (up to) 3 parts:
707      * - The middle part: from the first 4-aligned position in src to the first
708      *   4-aligned position in dst.
709      */
710     size_t src_mid_off = (src % 4 == 0 ? 0 : 4 - (src % 4));
711     size_t dst_mid_off = (dsti % 4 == 0 ? 0 : 4 - (dsti % 4));
712     size_t mid_size = (size - MAX(src_mid_off, dst_mid_off)) & ~3U;
713     /*
714      * - Once the middle part is in place, src_mid_off bytes from the preceding
715      *   4-aligned source location are added on the left.
716      */
717     size_t pad_left_src = src & ~3U;
718     size_t pad_left_size = src_mid_off;
719     /*
720      * - Finally, the right part is added: from the end of the middle part to
721      *   the end. Depending on the alignment of source and destination, this may
722      *   be a 4 or 8 byte read from pad_right_src.
723      */
724     size_t pad_right_src = (src + pad_left_size + mid_size) & ~3U;
725     size_t pad_right_off = (pad_right_src - src);
726     size_t pad_right_size = (size - pad_right_off);
727 
728 #ifdef ESP_PLATFORM
729     bool direct_read = esp_ptr_internal(dstc)
730             && esp_ptr_byte_accessible(dstc)
731             && ((uintptr_t) dstc + dst_mid_off) % 4 == 0;
732 #else
733     bool direct_read = true;
734 #endif
735     if (mid_size > 0) {
736         uint32_t mid_remaining = mid_size;
737         uint32_t mid_read = 0;
738         while (mid_remaining > 0) {
739             uint32_t read_size = MIN(mid_remaining, MAX_READ_CHUNK);
740             uint32_t read_buf[8];
741             uint8_t *read_dst_final = dstc + dst_mid_off + mid_read;
742             uint8_t *read_dst = read_dst_final;
743             if (!direct_read) {
744                 read_size = MIN(read_size, sizeof(read_buf));
745                 read_dst = (uint8_t *) read_buf;
746             }
747             rc = esp_rom_spiflash_read(src + src_mid_off + mid_read,
748                     (uint32_t *) read_dst, read_size);
749             if (rc != ESP_ROM_SPIFLASH_RESULT_OK) {
750                 goto out;
751             }
752             mid_remaining -= read_size;
753             mid_read += read_size;
754             if (!direct_read) {
755                 spi_flash_guard_end();
756                 memcpy(read_dst_final, read_buf, read_size);
757                 spi_flash_guard_start();
758             } else if (mid_remaining > 0) {
759                 /* Drop guard momentarily, allows other tasks to preempt */
760                 spi_flash_guard_end();
761                 spi_flash_guard_start();
762             }
763         }
764         COUNTER_ADD_BYTES(read, mid_size);
765         /*
766          * If offsets in src and dst are different, perform an in-place shift
767          * to put destination data into its final position.
768          * Note that the shift can be left (src_mid_off < dst_mid_off) or right.
769          */
770         if (src_mid_off != dst_mid_off) {
771             if (!direct_read) {
772                 spi_flash_guard_end();
773             }
774             memmove(dstc + src_mid_off, dstc + dst_mid_off, mid_size);
775             if (!direct_read) {
776                 spi_flash_guard_start();
777             }
778         }
779     }
780     if (pad_left_size > 0) {
781         uint32_t t;
782         rc = esp_rom_spiflash_read(pad_left_src, &t, 4);
783         if (rc != ESP_ROM_SPIFLASH_RESULT_OK) {
784             goto out;
785         }
786         COUNTER_ADD_BYTES(read, 4);
787         if (!direct_read) {
788             spi_flash_guard_end();
789         }
790         memcpy(dstc, ((uint8_t *) &t) + (4 - pad_left_size), pad_left_size);
791         if (!direct_read) {
792             spi_flash_guard_start();
793         }
794     }
795     if (pad_right_size > 0) {
796         uint32_t t[2];
797         int32_t read_size = (pad_right_size <= 4 ? 4 : 8);
798         rc = esp_rom_spiflash_read(pad_right_src, t, read_size);
799         if (rc != ESP_ROM_SPIFLASH_RESULT_OK) {
800             goto out;
801         }
802         COUNTER_ADD_BYTES(read, read_size);
803         if (!direct_read) {
804             spi_flash_guard_end();
805         }
806         memcpy(dstc + pad_right_off, t, pad_right_size);
807         if (!direct_read) {
808             spi_flash_guard_start();
809         }
810     }
811 out:
812     spi_flash_guard_end();
813     COUNTER_STOP(read);
814     return spi_flash_translate_rc(rc);
815 }
816 #endif
817 
spi_flash_read_encrypted(size_t src,void * dstv,size_t size)818 esp_err_t IRAM_ATTR spi_flash_read_encrypted(size_t src, void *dstv, size_t size)
819 {
820     if (src + size > g_rom_flashchip.chip_size) {
821         return ESP_ERR_INVALID_SIZE;
822     }
823     if (size == 0) {
824         return ESP_OK;
825     }
826 
827     esp_err_t err;
828     const uint8_t *map;
829     spi_flash_mmap_handle_t map_handle;
830     size_t map_src = src & ~(SPI_FLASH_MMU_PAGE_SIZE - 1);
831     size_t map_size = size + (src - map_src);
832 
833     err = spi_flash_mmap(map_src, map_size, SPI_FLASH_MMAP_DATA, (const void **)&map, &map_handle);
834     if (err != ESP_OK) {
835         return err;
836     }
837     memcpy(dstv, map + (src - map_src), size);
838     spi_flash_munmap(map_handle);
839     return err;
840 }
841 
842 
spi_flash_translate_rc(esp_rom_spiflash_result_t rc)843 static esp_err_t IRAM_ATTR spi_flash_translate_rc(esp_rom_spiflash_result_t rc)
844 {
845     switch (rc) {
846     case ESP_ROM_SPIFLASH_RESULT_OK:
847         return ESP_OK;
848     case ESP_ROM_SPIFLASH_RESULT_TIMEOUT:
849         return ESP_ERR_FLASH_OP_TIMEOUT;
850     case ESP_ROM_SPIFLASH_RESULT_ERR:
851     default:
852         return ESP_ERR_FLASH_OP_FAIL;
853     }
854 }
855 
856 #if CONFIG_SPI_FLASH_ENABLE_COUNTERS
857 
dump_counter(spi_flash_counter_t * counter,const char * name)858 static inline void dump_counter(spi_flash_counter_t *counter, const char *name)
859 {
860     ESP_LOGI(TAG, "%s  count=%8d  time=%8dus  bytes=%8d\n", name,
861              counter->count, counter->time, counter->bytes);
862 }
863 
spi_flash_get_counters(void)864 const spi_flash_counters_t *spi_flash_get_counters(void)
865 {
866     return &s_flash_stats;
867 }
868 
spi_flash_reset_counters(void)869 void spi_flash_reset_counters(void)
870 {
871     memset(&s_flash_stats, 0, sizeof(s_flash_stats));
872 }
873 
spi_flash_dump_counters(void)874 void spi_flash_dump_counters(void)
875 {
876     dump_counter(&s_flash_stats.read,  "read ");
877     dump_counter(&s_flash_stats.write, "write");
878     dump_counter(&s_flash_stats.erase, "erase");
879 }
880 
881 #endif //CONFIG_SPI_FLASH_ENABLE_COUNTERS
882 
883 #if CONFIG_SPI_FLASH_USE_LEGACY_IMPL && !CONFIG_IDF_TARGET_ESP32
884 // TODO esp32s2: Remove once ESP32-S2 & later chips has new SPI Flash API support
885 esp_flash_t *esp_flash_default_chip = NULL;
886 #endif
887