]> granicus.if.org Git - esp-idf/blob - components/spi_flash/flash_mmap.c
bug fix of assert happen in PSRAM
[esp-idf] / components / spi_flash / flash_mmap.c
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
20 #include <freertos/FreeRTOS.h>
21 #include <freertos/task.h>
22 #include <freertos/semphr.h>
23 #include <rom/spi_flash.h>
24 #include <rom/cache.h>
25 #include <soc/soc.h>
26 #include <soc/dport_reg.h>
27 #include "sdkconfig.h"
28 #include "esp_ipc.h"
29 #include "esp_attr.h"
30 #include "esp_spi_flash.h"
31 #include "esp_flash_encrypt.h"
32 #include "esp_log.h"
33 #include "cache_utils.h"
34 #include "esp_spiram.h"
35
36 #ifndef NDEBUG
37 // Enable built-in checks in queue.h in debug builds
38 #define INVARIANTS
39 #endif
40 #include "rom/queue.h"
41
42 #define REGIONS_COUNT 4
43 #define PAGES_PER_REGION 64
44 #define INVALID_ENTRY_VAL 0x100
45 #define VADDR0_START_ADDR 0x3F400000
46 #define VADDR1_START_ADDR 0x40000000
47 #define VADDR1_FIRST_USABLE_ADDR 0x400D0000
48 #define PRO_IRAM0_FIRST_USABLE_PAGE ((VADDR1_FIRST_USABLE_ADDR - VADDR1_START_ADDR) / SPI_FLASH_MMU_PAGE_SIZE + 64)
49
50 /* Ensure pages in a region haven't been marked as written via
51    spi_flash_mark_modified_region(). If the page has
52    been written, flush the entire flash cache before returning.
53
54    This ensures stale cache entries are never read after fresh calls
55    to spi_flash_mmap(), while keeping the number of cache flushes to a
56    minimum.
57
58    Returns true if cache was flushed.
59 */
60
61 static bool spi_flash_ensure_unmodified_region(size_t start_addr, size_t length);
62
63 typedef struct mmap_entry_{
64     uint32_t handle;
65     int page;
66     int count;
67     LIST_ENTRY(mmap_entry_) entries;
68 } mmap_entry_t;
69
70
71 static LIST_HEAD(mmap_entries_head, mmap_entry_) s_mmap_entries_head =
72         LIST_HEAD_INITIALIZER(s_mmap_entries_head);
73 static uint8_t s_mmap_page_refcnt[REGIONS_COUNT * PAGES_PER_REGION] = {0};
74 static uint32_t s_mmap_last_handle = 0;
75
76
77 static void IRAM_ATTR spi_flash_mmap_init()
78 {
79     if (s_mmap_page_refcnt[0] != 0) {
80         return; /* mmap data already initialised */
81     }
82     
83     DPORT_STALL_OTHER_CPU_START();
84     for (int i = 0; i < REGIONS_COUNT * PAGES_PER_REGION; ++i) {
85         uint32_t entry_pro = DPORT_PRO_FLASH_MMU_TABLE[i];
86         uint32_t entry_app = DPORT_APP_FLASH_MMU_TABLE[i];
87
88         if (entry_pro != entry_app) {
89             // clean up entries used by boot loader
90             entry_pro = DPORT_FLASH_MMU_TABLE_INVALID_VAL;
91             DPORT_PRO_FLASH_MMU_TABLE[i] = DPORT_FLASH_MMU_TABLE_INVALID_VAL;
92         }
93         if ((entry_pro & INVALID_ENTRY_VAL) == 0 && (i == 0 || i == PRO_IRAM0_FIRST_USABLE_PAGE || entry_pro != 0)) {
94             s_mmap_page_refcnt[i] = 1;
95         } else {
96             DPORT_PRO_FLASH_MMU_TABLE[i] = DPORT_FLASH_MMU_TABLE_INVALID_VAL;
97             DPORT_APP_FLASH_MMU_TABLE[i] = DPORT_FLASH_MMU_TABLE_INVALID_VAL;
98         }
99     }
100     DPORT_STALL_OTHER_CPU_END();
101 }
102
103 esp_err_t IRAM_ATTR spi_flash_mmap(size_t src_addr, size_t size, spi_flash_mmap_memory_t memory,
104                          const void** out_ptr, spi_flash_mmap_handle_t* out_handle)
105 {
106     esp_err_t ret;
107     if (src_addr & 0xffff) {
108         return ESP_ERR_INVALID_ARG;
109     }
110     if (src_addr + size > g_rom_flashchip.chip_size) {
111         return ESP_ERR_INVALID_ARG;
112     }
113     // region which should be mapped
114     int phys_page = src_addr / SPI_FLASH_MMU_PAGE_SIZE;
115     int page_count = (size + SPI_FLASH_MMU_PAGE_SIZE - 1) / SPI_FLASH_MMU_PAGE_SIZE;
116     //prepare a linear pages array to feed into spi_flash_mmap_pages
117     int *pages=malloc(sizeof(int)*page_count);
118     if (pages==NULL) {
119         return ESP_ERR_NO_MEM;
120     }
121     for (int i = 0; i < page_count; i++) {
122         pages[i] = phys_page+i;
123     }
124     ret=spi_flash_mmap_pages(pages, page_count, memory, out_ptr, out_handle);
125     free(pages);
126     return ret;
127 }
128
129 esp_err_t IRAM_ATTR spi_flash_mmap_pages(int *pages, size_t page_count, spi_flash_mmap_memory_t memory,
130                          const void** out_ptr, spi_flash_mmap_handle_t* out_handle)
131 {
132     esp_err_t ret;
133     bool did_flush, need_flush = false;
134     if (!page_count) {
135         return ESP_ERR_INVALID_ARG;
136     }
137     for (int i = 0; i < page_count; i++) {
138         if (pages[i] < 0 || pages[i]*SPI_FLASH_MMU_PAGE_SIZE >= g_rom_flashchip.chip_size) {
139             return ESP_ERR_INVALID_ARG;
140         }
141     }
142     mmap_entry_t* new_entry = (mmap_entry_t*) heap_caps_malloc(sizeof(mmap_entry_t), MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT);
143     if (new_entry == 0) {
144         return ESP_ERR_NO_MEM;
145     }
146
147     spi_flash_disable_interrupts_caches_and_other_cpu();
148
149     did_flush = 0;
150     for (int i = 0; i < page_count; i++) {
151         if (spi_flash_ensure_unmodified_region(pages[i]*SPI_FLASH_MMU_PAGE_SIZE, SPI_FLASH_MMU_PAGE_SIZE)) {
152             did_flush = 1;
153         }
154     }
155     spi_flash_mmap_init();
156     // figure out the memory region where we should look for pages
157     int region_begin;   // first page to check
158     int region_size;    // number of pages to check
159     uint32_t region_addr;  // base address of memory region
160     if (memory == SPI_FLASH_MMAP_DATA) {
161         // Vaddr0
162         region_begin = 0;
163         region_size = 64;
164         region_addr = VADDR0_START_ADDR;
165     } else {
166         // only part of VAddr1 is usable, so adjust for that
167         region_begin = PRO_IRAM0_FIRST_USABLE_PAGE;
168         region_size = 3 * 64 - region_begin;
169         region_addr = VADDR1_FIRST_USABLE_ADDR;
170     }
171     if (region_size < page_count) {
172         return ESP_ERR_NO_MEM;
173     }
174     // The following part searches for a range of MMU entries which can be used.
175     // Algorithm is essentially naïve strstr algorithm, except that unused MMU
176     // entries are treated as wildcards.
177     int start;
178     int end = region_begin + region_size - page_count;
179     for (start = region_begin; start < end; ++start) {
180         int pageno = 0;
181         int pos;
182         DPORT_STALL_OTHER_CPU_START();
183         for (pos = start; pos < start + page_count; ++pos, ++pageno) {
184             int table_val = (int) DPORT_PRO_FLASH_MMU_TABLE[pos];
185             uint8_t refcnt = s_mmap_page_refcnt[pos]; 
186             if (refcnt != 0 && table_val != pages[pageno]) {
187                 break;
188             }
189         }
190         DPORT_STALL_OTHER_CPU_END();
191         // whole mapping range matched, bail out
192         if (pos - start == page_count) {
193             break;
194         }
195     }
196     // checked all the region(s) and haven't found anything?
197     if (start == end) {
198         *out_handle = 0;
199         *out_ptr = NULL;
200         ret = ESP_ERR_NO_MEM;
201     } else {
202         // set up mapping using pages
203         uint32_t pageno = 0;
204         DPORT_STALL_OTHER_CPU_START();
205         for (int i = start; i != start + page_count; ++i, ++pageno) {
206             // sanity check: we won't reconfigure entries with non-zero reference count
207             assert(s_mmap_page_refcnt[i] == 0 ||
208                     (DPORT_PRO_FLASH_MMU_TABLE[i] == pages[pageno] &&
209                      DPORT_APP_FLASH_MMU_TABLE[i] == pages[pageno]));
210             if (s_mmap_page_refcnt[i] == 0) {
211                 if (DPORT_PRO_FLASH_MMU_TABLE[i] != pages[pageno] || DPORT_APP_FLASH_MMU_TABLE[i] != pages[pageno]) {
212                     DPORT_PRO_FLASH_MMU_TABLE[i] = pages[pageno];
213                     DPORT_APP_FLASH_MMU_TABLE[i] = pages[pageno];
214                     need_flush = true;
215                 }
216             }
217             ++s_mmap_page_refcnt[i];
218         }
219         DPORT_STALL_OTHER_CPU_END();
220         LIST_INSERT_HEAD(&s_mmap_entries_head, new_entry, entries);
221         new_entry->page = start;
222         new_entry->count = page_count;
223         new_entry->handle = ++s_mmap_last_handle;
224         *out_handle = new_entry->handle;
225         *out_ptr = (void*) (region_addr + (start - region_begin) * SPI_FLASH_MMU_PAGE_SIZE);
226         ret = ESP_OK;
227     }
228
229     /* This is a temporary fix for an issue where some
230        cache reads may see stale data.
231
232        Working on a long term fix that doesn't require invalidating
233        entire cache.
234     */
235     if (!did_flush && need_flush) {
236 #if CONFIG_SPIRAM_SUPPORT
237         esp_spiram_writeback_cache();
238 #endif
239         Cache_Flush(0);
240         Cache_Flush(1);
241     }
242
243     spi_flash_enable_interrupts_caches_and_other_cpu();
244     if (*out_ptr == NULL) {
245         free(new_entry);
246     }
247     return ret;
248 }
249
250 void IRAM_ATTR spi_flash_munmap(spi_flash_mmap_handle_t handle)
251 {
252     spi_flash_disable_interrupts_caches_and_other_cpu();
253     mmap_entry_t* it;
254     // look for handle in linked list
255     for (it = LIST_FIRST(&s_mmap_entries_head); it != NULL; it = LIST_NEXT(it, entries)) {
256         if (it->handle == handle) {
257             // for each page, decrement reference counter
258             // if reference count is zero, disable MMU table entry to
259             // facilitate debugging of use-after-free conditions
260             DPORT_STALL_OTHER_CPU_START();
261             for (int i = it->page; i < it->page + it->count; ++i) {
262                 assert(s_mmap_page_refcnt[i] > 0);
263                 if (--s_mmap_page_refcnt[i] == 0) {
264                     DPORT_PRO_FLASH_MMU_TABLE[i] = INVALID_ENTRY_VAL;
265                     DPORT_APP_FLASH_MMU_TABLE[i] = INVALID_ENTRY_VAL;
266                 }
267             }
268             DPORT_STALL_OTHER_CPU_END();
269             LIST_REMOVE(it, entries);
270             break;
271         }
272     }
273     spi_flash_enable_interrupts_caches_and_other_cpu();
274     if (it == NULL) {
275         assert(0 && "invalid handle, or handle already unmapped");
276     }
277     free(it);
278 }
279
280 void spi_flash_mmap_dump()
281 {
282     spi_flash_mmap_init();
283     mmap_entry_t* it;
284     for (it = LIST_FIRST(&s_mmap_entries_head); it != NULL; it = LIST_NEXT(it, entries)) {
285         printf("handle=%d page=%d count=%d\n", it->handle, it->page, it->count);
286     }
287     for (int i = 0; i < REGIONS_COUNT * PAGES_PER_REGION; ++i) {
288         if (s_mmap_page_refcnt[i] != 0) {
289             printf("page %d: refcnt=%d paddr=%d\n",
290                     i, (int) s_mmap_page_refcnt[i], DPORT_PRO_FLASH_MMU_TABLE[i]);
291         }
292     }
293 }
294
295 /* 256-bit (up to 16MB of 64KB pages) bitset of all flash pages
296    that have been written to since last cache flush.
297
298    Before mmaping a page, need to flush caches if that page has been
299    written to.
300
301    Note: It's possible to do some additional performance tweaks to
302    this algorithm, as we actually only need to flush caches if a page
303    was first mmapped, then written to, then is about to be mmaped a
304    second time. This is a fair bit more complex though, so unless
305    there's an access pattern that this would significantly boost then
306    it's probably not worth it.
307 */
308 static uint32_t written_pages[256/32];
309
310 static bool update_written_pages(size_t start_addr, size_t length, bool mark);
311
312 void IRAM_ATTR spi_flash_mark_modified_region(size_t start_addr, size_t length)
313 {
314     update_written_pages(start_addr, length, true);
315 }
316
317 static IRAM_ATTR bool spi_flash_ensure_unmodified_region(size_t start_addr, size_t length)
318 {
319     return update_written_pages(start_addr, length, false);
320 }
321
322 /* generic implementation for the previous two functions */
323 static inline IRAM_ATTR bool update_written_pages(size_t start_addr, size_t length, bool mark)
324 {
325     /* align start_addr & length to full MMU pages */
326     uint32_t page_start_addr = start_addr & ~(SPI_FLASH_MMU_PAGE_SIZE-1);
327     length += (start_addr - page_start_addr);
328     length = (length + SPI_FLASH_MMU_PAGE_SIZE - 1) & ~(SPI_FLASH_MMU_PAGE_SIZE-1);
329     for (uint32_t addr = page_start_addr; addr < page_start_addr + length; addr += SPI_FLASH_MMU_PAGE_SIZE) {
330         int page = addr / SPI_FLASH_MMU_PAGE_SIZE;
331         if (page >= 256) {
332             return false; /* invalid address */
333         }
334
335         int idx = page / 32;
336         uint32_t bit = 1 << (page % 32);
337
338         if (mark) {
339             written_pages[idx] |= bit;
340         } else if (written_pages[idx] & bit) {
341             /* it is tempting to write a version of this that only
342                flushes each CPU's cache as needed. However this is
343                tricky because mmaped memory can be used on un-pinned
344                cores, or the pointer passed between CPUs.
345             */
346 #if CONFIG_SPIRAM_SUPPORT
347             esp_spiram_writeback_cache();
348 #endif
349             Cache_Flush(0);
350 #ifndef CONFIG_FREERTOS_UNICORE
351             Cache_Flush(1);
352 #endif
353             bzero(written_pages, sizeof(written_pages));
354             return true;
355         }
356     }
357     return false;
358 }
359
360
361 uint32_t spi_flash_cache2phys(const void *cached)
362 {
363     intptr_t c = (intptr_t)cached;
364     size_t cache_page;
365     if (c >= VADDR1_START_ADDR && c < VADDR1_FIRST_USABLE_ADDR) {
366         /* IRAM address, doesn't map to flash */
367         return SPI_FLASH_CACHE2PHYS_FAIL;
368     }
369     else if (c < VADDR1_FIRST_USABLE_ADDR) {
370         /* expect cache is in DROM */
371         cache_page = (c - VADDR0_START_ADDR) / SPI_FLASH_MMU_PAGE_SIZE;
372     } else {
373         /* expect cache is in IROM */
374         cache_page = (c - VADDR1_START_ADDR) / SPI_FLASH_MMU_PAGE_SIZE + 64;
375     }
376
377     if (cache_page >= 256) {
378         /* cached address was not in IROM or DROM */
379         return SPI_FLASH_CACHE2PHYS_FAIL;
380     }
381     DPORT_STALL_OTHER_CPU_START();
382     uint32_t phys_page = DPORT_PRO_FLASH_MMU_TABLE[cache_page];
383     DPORT_STALL_OTHER_CPU_END();
384     if (phys_page == INVALID_ENTRY_VAL) {
385         /* page is not mapped */
386         return SPI_FLASH_CACHE2PHYS_FAIL;
387     }
388     uint32_t phys_offs = phys_page * SPI_FLASH_MMU_PAGE_SIZE;
389     return phys_offs | (c & (SPI_FLASH_MMU_PAGE_SIZE-1));
390 }
391
392
393 const void *spi_flash_phys2cache(uint32_t phys_offs, spi_flash_mmap_memory_t memory)
394 {
395     uint32_t phys_page = phys_offs / SPI_FLASH_MMU_PAGE_SIZE;
396     int start, end, page_delta;
397     intptr_t base;
398
399     if (memory == SPI_FLASH_MMAP_DATA) {
400         start = 0;
401         end = 64;
402         base = VADDR0_START_ADDR;
403         page_delta = 0;
404     } else {
405         start = PRO_IRAM0_FIRST_USABLE_PAGE;
406         end = 256;
407         base = VADDR1_START_ADDR;
408         page_delta = 64;
409     }
410     
411     DPORT_STALL_OTHER_CPU_START();
412     for (int i = start; i < end; i++) {
413         if (DPORT_PRO_FLASH_MMU_TABLE[i] == phys_page) {
414             i -= page_delta;
415             intptr_t cache_page =  base + (SPI_FLASH_MMU_PAGE_SIZE * i);
416             DPORT_STALL_OTHER_CPU_END();
417             return (const void *) (cache_page | (phys_offs & (SPI_FLASH_MMU_PAGE_SIZE-1)));
418         }
419     }
420     DPORT_STALL_OTHER_CPU_END();
421     return NULL;
422 }