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