]> granicus.if.org Git - esp-idf/blob - components/spi_flash/flash_mmap.c
Merge branch 'feature/deactivate_wakeup_trigger' into 'master'
[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 static void IRAM_ATTR get_mmu_region(spi_flash_mmap_memory_t memory, int* out_begin, int* out_size,uint32_t* region_addr)
104 {
105     if (memory == SPI_FLASH_MMAP_DATA) {
106         // Vaddr0
107         *out_begin = 0;
108         *out_size = 64;
109         *region_addr = VADDR0_START_ADDR;
110     } else {
111         // only part of VAddr1 is usable, so adjust for that
112         *out_begin = PRO_IRAM0_FIRST_USABLE_PAGE;
113         *out_size = 3 * 64 - *out_begin;
114         *region_addr = VADDR1_FIRST_USABLE_ADDR;
115     }
116 }
117
118 esp_err_t IRAM_ATTR spi_flash_mmap(size_t src_addr, size_t size, spi_flash_mmap_memory_t memory,
119                          const void** out_ptr, spi_flash_mmap_handle_t* out_handle)
120 {
121     esp_err_t ret;
122     if (src_addr & 0xffff) {
123         return ESP_ERR_INVALID_ARG;
124     }
125     if (src_addr + size > g_rom_flashchip.chip_size) {
126         return ESP_ERR_INVALID_ARG;
127     }
128     // region which should be mapped
129     int phys_page = src_addr / SPI_FLASH_MMU_PAGE_SIZE;
130     int page_count = (size + SPI_FLASH_MMU_PAGE_SIZE - 1) / SPI_FLASH_MMU_PAGE_SIZE;
131     //prepare a linear pages array to feed into spi_flash_mmap_pages
132     int *pages=malloc(sizeof(int)*page_count);
133     if (pages==NULL) {
134         return ESP_ERR_NO_MEM;
135     }
136     for (int i = 0; i < page_count; i++) {
137         pages[i] = phys_page+i;
138     }
139     ret=spi_flash_mmap_pages(pages, page_count, memory, out_ptr, out_handle);
140     free(pages);
141     return ret;
142 }
143
144 esp_err_t IRAM_ATTR spi_flash_mmap_pages(int *pages, size_t page_count, spi_flash_mmap_memory_t memory,
145                          const void** out_ptr, spi_flash_mmap_handle_t* out_handle)
146 {
147     esp_err_t ret;
148     bool did_flush, need_flush = false;
149     if (!page_count) {
150         return ESP_ERR_INVALID_ARG;
151     }
152     for (int i = 0; i < page_count; i++) {
153         if (pages[i] < 0 || pages[i]*SPI_FLASH_MMU_PAGE_SIZE >= g_rom_flashchip.chip_size) {
154             return ESP_ERR_INVALID_ARG;
155         }
156     }
157     mmap_entry_t* new_entry = (mmap_entry_t*) heap_caps_malloc(sizeof(mmap_entry_t), MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT);
158     if (new_entry == 0) {
159         return ESP_ERR_NO_MEM;
160     }
161
162     spi_flash_disable_interrupts_caches_and_other_cpu();
163
164     did_flush = 0;
165     for (int i = 0; i < page_count; i++) {
166         if (spi_flash_ensure_unmodified_region(pages[i]*SPI_FLASH_MMU_PAGE_SIZE, SPI_FLASH_MMU_PAGE_SIZE)) {
167             did_flush = 1;
168         }
169     }
170     spi_flash_mmap_init();
171     // figure out the memory region where we should look for pages
172     int region_begin;   // first page to check
173     int region_size;    // number of pages to check
174     uint32_t region_addr;  // base address of memory region
175     get_mmu_region(memory,&region_begin,&region_size,&region_addr);
176     if (region_size < page_count) {
177         return ESP_ERR_NO_MEM;
178     }
179     // The following part searches for a range of MMU entries which can be used.
180     // Algorithm is essentially naïve strstr algorithm, except that unused MMU
181     // entries are treated as wildcards.
182     int start;
183     // the " + 1" is a fix when loop the MMU table pages, because the last MMU page 
184     // is valid as well if it have not been used
185     int end = region_begin + region_size - page_count + 1;
186     for (start = region_begin; start < end; ++start) {
187         int pageno = 0;
188         int pos;
189         DPORT_STALL_OTHER_CPU_START();
190         for (pos = start; pos < start + page_count; ++pos, ++pageno) {
191             int table_val = (int) DPORT_PRO_FLASH_MMU_TABLE[pos];
192             uint8_t refcnt = s_mmap_page_refcnt[pos]; 
193             if (refcnt != 0 && table_val != pages[pageno]) {
194                 break;
195             }
196         }
197         DPORT_STALL_OTHER_CPU_END();
198         // whole mapping range matched, bail out
199         if (pos - start == page_count) {
200             break;
201         }
202     }
203     // checked all the region(s) and haven't found anything?
204     if (start == end) {
205         *out_handle = 0;
206         *out_ptr = NULL;
207         ret = ESP_ERR_NO_MEM;
208     } else {
209         // set up mapping using pages
210         uint32_t pageno = 0;
211         DPORT_STALL_OTHER_CPU_START();
212         for (int i = start; i != start + page_count; ++i, ++pageno) {
213             // sanity check: we won't reconfigure entries with non-zero reference count
214             assert(s_mmap_page_refcnt[i] == 0 ||
215                     (DPORT_PRO_FLASH_MMU_TABLE[i] == pages[pageno] &&
216                      DPORT_APP_FLASH_MMU_TABLE[i] == pages[pageno]));
217             if (s_mmap_page_refcnt[i] == 0) {
218                 if (DPORT_PRO_FLASH_MMU_TABLE[i] != pages[pageno] || DPORT_APP_FLASH_MMU_TABLE[i] != pages[pageno]) {
219                     DPORT_PRO_FLASH_MMU_TABLE[i] = pages[pageno];
220                     DPORT_APP_FLASH_MMU_TABLE[i] = pages[pageno];
221                     need_flush = true;
222                 }
223             }
224             ++s_mmap_page_refcnt[i];
225         }
226         DPORT_STALL_OTHER_CPU_END();
227         LIST_INSERT_HEAD(&s_mmap_entries_head, new_entry, entries);
228         new_entry->page = start;
229         new_entry->count = page_count;
230         new_entry->handle = ++s_mmap_last_handle;
231         *out_handle = new_entry->handle;
232         *out_ptr = (void*) (region_addr + (start - region_begin) * SPI_FLASH_MMU_PAGE_SIZE);
233         ret = ESP_OK;
234     }
235
236     /* This is a temporary fix for an issue where some
237        cache reads may see stale data.
238
239        Working on a long term fix that doesn't require invalidating
240        entire cache.
241     */
242     if (!did_flush && need_flush) {
243 #if CONFIG_SPIRAM_SUPPORT
244         esp_spiram_writeback_cache();
245 #endif
246         Cache_Flush(0);
247         Cache_Flush(1);
248     }
249
250     spi_flash_enable_interrupts_caches_and_other_cpu();
251     if (*out_ptr == NULL) {
252         free(new_entry);
253     }
254     return ret;
255 }
256
257 void IRAM_ATTR spi_flash_munmap(spi_flash_mmap_handle_t handle)
258 {
259     spi_flash_disable_interrupts_caches_and_other_cpu();
260     mmap_entry_t* it;
261     // look for handle in linked list
262     for (it = LIST_FIRST(&s_mmap_entries_head); it != NULL; it = LIST_NEXT(it, entries)) {
263         if (it->handle == handle) {
264             // for each page, decrement reference counter
265             // if reference count is zero, disable MMU table entry to
266             // facilitate debugging of use-after-free conditions
267             DPORT_STALL_OTHER_CPU_START();
268             for (int i = it->page; i < it->page + it->count; ++i) {
269                 assert(s_mmap_page_refcnt[i] > 0);
270                 if (--s_mmap_page_refcnt[i] == 0) {
271                     DPORT_PRO_FLASH_MMU_TABLE[i] = INVALID_ENTRY_VAL;
272                     DPORT_APP_FLASH_MMU_TABLE[i] = INVALID_ENTRY_VAL;
273                 }
274             }
275             DPORT_STALL_OTHER_CPU_END();
276             LIST_REMOVE(it, entries);
277             break;
278         }
279     }
280     spi_flash_enable_interrupts_caches_and_other_cpu();
281     if (it == NULL) {
282         assert(0 && "invalid handle, or handle already unmapped");
283     }
284     free(it);
285 }
286
287 void spi_flash_mmap_dump()
288 {
289     spi_flash_mmap_init();
290     mmap_entry_t* it;
291     for (it = LIST_FIRST(&s_mmap_entries_head); it != NULL; it = LIST_NEXT(it, entries)) {
292         printf("handle=%d page=%d count=%d\n", it->handle, it->page, it->count);
293     }
294     for (int i = 0; i < REGIONS_COUNT * PAGES_PER_REGION; ++i) {
295         if (s_mmap_page_refcnt[i] != 0) {
296             printf("page %d: refcnt=%d paddr=%d\n",
297                     i, (int) s_mmap_page_refcnt[i], DPORT_PRO_FLASH_MMU_TABLE[i]);
298         }
299     }
300 }
301
302 uint32_t spi_flash_mmap_get_free_pages(spi_flash_mmap_memory_t memory)
303 {
304     spi_flash_mmap_init();
305     int count = 0;
306     int region_begin;   // first page to check
307     int region_size;    // number of pages to check
308     uint32_t region_addr;  // base address of memory region
309     get_mmu_region(memory,&region_begin,&region_size,&region_addr);
310     DPORT_STALL_OTHER_CPU_START();
311     for (int i = region_begin; i < region_begin + region_size; ++i) {
312         if (s_mmap_page_refcnt[i] == 0 && DPORT_PRO_FLASH_MMU_TABLE[i] == INVALID_ENTRY_VAL) {
313             count++;
314         }
315     }
316     DPORT_STALL_OTHER_CPU_END();
317     return count;
318 }
319
320 /* 256-bit (up to 16MB of 64KB pages) bitset of all flash pages
321    that have been written to since last cache flush.
322
323    Before mmaping a page, need to flush caches if that page has been
324    written to.
325
326    Note: It's possible to do some additional performance tweaks to
327    this algorithm, as we actually only need to flush caches if a page
328    was first mmapped, then written to, then is about to be mmaped a
329    second time. This is a fair bit more complex though, so unless
330    there's an access pattern that this would significantly boost then
331    it's probably not worth it.
332 */
333 static uint32_t written_pages[256/32];
334
335 static bool update_written_pages(size_t start_addr, size_t length, bool mark);
336
337 void IRAM_ATTR spi_flash_mark_modified_region(size_t start_addr, size_t length)
338 {
339     update_written_pages(start_addr, length, true);
340 }
341
342 static IRAM_ATTR bool spi_flash_ensure_unmodified_region(size_t start_addr, size_t length)
343 {
344     return update_written_pages(start_addr, length, false);
345 }
346
347 /* generic implementation for the previous two functions */
348 static inline IRAM_ATTR bool update_written_pages(size_t start_addr, size_t length, bool mark)
349 {
350     /* align start_addr & length to full MMU pages */
351     uint32_t page_start_addr = start_addr & ~(SPI_FLASH_MMU_PAGE_SIZE-1);
352     length += (start_addr - page_start_addr);
353     length = (length + SPI_FLASH_MMU_PAGE_SIZE - 1) & ~(SPI_FLASH_MMU_PAGE_SIZE-1);
354     for (uint32_t addr = page_start_addr; addr < page_start_addr + length; addr += SPI_FLASH_MMU_PAGE_SIZE) {
355         int page = addr / SPI_FLASH_MMU_PAGE_SIZE;
356         if (page >= 256) {
357             return false; /* invalid address */
358         }
359
360         int idx = page / 32;
361         uint32_t bit = 1 << (page % 32);
362
363         if (mark) {
364             written_pages[idx] |= bit;
365         } else if (written_pages[idx] & bit) {
366             /* it is tempting to write a version of this that only
367                flushes each CPU's cache as needed. However this is
368                tricky because mmaped memory can be used on un-pinned
369                cores, or the pointer passed between CPUs.
370             */
371 #if CONFIG_SPIRAM_SUPPORT
372             esp_spiram_writeback_cache();
373 #endif
374             Cache_Flush(0);
375 #ifndef CONFIG_FREERTOS_UNICORE
376             Cache_Flush(1);
377 #endif
378             bzero(written_pages, sizeof(written_pages));
379             return true;
380         }
381     }
382     return false;
383 }
384
385
386 uint32_t spi_flash_cache2phys(const void *cached)
387 {
388     intptr_t c = (intptr_t)cached;
389     size_t cache_page;
390     if (c >= VADDR1_START_ADDR && c < VADDR1_FIRST_USABLE_ADDR) {
391         /* IRAM address, doesn't map to flash */
392         return SPI_FLASH_CACHE2PHYS_FAIL;
393     }
394     else if (c < VADDR1_FIRST_USABLE_ADDR) {
395         /* expect cache is in DROM */
396         cache_page = (c - VADDR0_START_ADDR) / SPI_FLASH_MMU_PAGE_SIZE;
397     } else {
398         /* expect cache is in IROM */
399         cache_page = (c - VADDR1_START_ADDR) / SPI_FLASH_MMU_PAGE_SIZE + 64;
400     }
401
402     if (cache_page >= 256) {
403         /* cached address was not in IROM or DROM */
404         return SPI_FLASH_CACHE2PHYS_FAIL;
405     }
406     DPORT_STALL_OTHER_CPU_START();
407     uint32_t phys_page = DPORT_PRO_FLASH_MMU_TABLE[cache_page];
408     DPORT_STALL_OTHER_CPU_END();
409     if (phys_page == INVALID_ENTRY_VAL) {
410         /* page is not mapped */
411         return SPI_FLASH_CACHE2PHYS_FAIL;
412     }
413     uint32_t phys_offs = phys_page * SPI_FLASH_MMU_PAGE_SIZE;
414     return phys_offs | (c & (SPI_FLASH_MMU_PAGE_SIZE-1));
415 }
416
417
418 const void *spi_flash_phys2cache(uint32_t phys_offs, spi_flash_mmap_memory_t memory)
419 {
420     uint32_t phys_page = phys_offs / SPI_FLASH_MMU_PAGE_SIZE;
421     int start, end, page_delta;
422     intptr_t base;
423
424     if (memory == SPI_FLASH_MMAP_DATA) {
425         start = 0;
426         end = 64;
427         base = VADDR0_START_ADDR;
428         page_delta = 0;
429     } else {
430         start = PRO_IRAM0_FIRST_USABLE_PAGE;
431         end = 256;
432         base = VADDR1_START_ADDR;
433         page_delta = 64;
434     }
435     
436     DPORT_STALL_OTHER_CPU_START();
437     for (int i = start; i < end; i++) {
438         if (DPORT_PRO_FLASH_MMU_TABLE[i] == phys_page) {
439             i -= page_delta;
440             intptr_t cache_page =  base + (SPI_FLASH_MMU_PAGE_SIZE * i);
441             DPORT_STALL_OTHER_CPU_END();
442             return (const void *) (cache_page | (phys_offs & (SPI_FLASH_MMU_PAGE_SIZE-1)));
443         }
444     }
445     DPORT_STALL_OTHER_CPU_END();
446     return NULL;
447 }