]> granicus.if.org Git - esp-idf/blob - components/spi_flash/flash_mmap.c
Merge branch 'bugfix/OTA_and_flash_encryption_incompatible' 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     for (int i = 0; i < REGIONS_COUNT * PAGES_PER_REGION; ++i) {
78         uint32_t entry_pro = DPORT_PRO_FLASH_MMU_TABLE[i];
79         uint32_t entry_app = DPORT_APP_FLASH_MMU_TABLE[i];
80         if (entry_pro != entry_app) {
81             // clean up entries used by boot loader
82             entry_pro = 0;
83             DPORT_PRO_FLASH_MMU_TABLE[i] = 0;
84         }
85         if ((entry_pro & 0x100) == 0 && (i == 0 || i == PRO_IRAM0_FIRST_USABLE_PAGE || entry_pro != 0)) {
86             s_mmap_page_refcnt[i] = 1;
87         }
88     }
89 }
90
91 esp_err_t IRAM_ATTR spi_flash_mmap(size_t src_addr, size_t size, spi_flash_mmap_memory_t memory,
92                          const void** out_ptr, spi_flash_mmap_handle_t* out_handle)
93 {
94     esp_err_t ret;
95     bool did_flush, need_flush = false;
96     mmap_entry_t* new_entry = (mmap_entry_t*) malloc(sizeof(mmap_entry_t));
97     if (new_entry == 0) {
98         return ESP_ERR_NO_MEM;
99     }
100     if (src_addr & 0xffff) {
101         return ESP_ERR_INVALID_ARG;
102     }
103     if (src_addr + size > g_rom_flashchip.chip_size) {
104         return ESP_ERR_INVALID_ARG;
105     }
106
107     spi_flash_disable_interrupts_caches_and_other_cpu();
108
109     did_flush = spi_flash_ensure_unmodified_region(src_addr, size);
110
111     if (s_mmap_page_refcnt[0] == 0) {
112         spi_flash_mmap_init();
113     }
114     // figure out the memory region where we should look for pages
115     int region_begin;   // first page to check
116     int region_size;    // number of pages to check
117     uint32_t region_addr;  // base address of memory region
118     if (memory == SPI_FLASH_MMAP_DATA) {
119         // Vaddr0
120         region_begin = 0;
121         region_size = 64;
122         region_addr = VADDR0_START_ADDR;
123     } else {
124         // only part of VAddr1 is usable, so adjust for that
125         region_begin = VADDR1_FIRST_USABLE_ADDR;
126         region_size = 3 * 64 - region_begin;
127         region_addr = VADDR1_FIRST_USABLE_ADDR;
128     }
129     // region which should be mapped
130     int phys_page = src_addr / SPI_FLASH_MMU_PAGE_SIZE;
131     int page_count = (size + SPI_FLASH_MMU_PAGE_SIZE - 1) / SPI_FLASH_MMU_PAGE_SIZE;
132     // The following part searches for a range of MMU entries which can be used.
133     // Algorithm is essentially naïve strstr algorithm, except that unused MMU
134     // entries are treated as wildcards.
135     int start;
136     int end = region_begin + region_size - page_count;
137     for (start = region_begin; start < end; ++start) {
138         int page = phys_page;
139         int pos;
140         for (pos = start; pos < start + page_count; ++pos, ++page) {
141             int table_val = (int) DPORT_PRO_FLASH_MMU_TABLE[pos];
142             uint8_t refcnt = s_mmap_page_refcnt[pos];
143             if (refcnt != 0 && table_val != page) {
144                 break;
145             }
146         }
147         // whole mapping range matched, bail out
148         if (pos - start == page_count) {
149             break;
150         }
151     }
152     // checked all the region(s) and haven't found anything?
153     if (start == end) {
154         *out_handle = 0;
155         *out_ptr = NULL;
156         ret = ESP_ERR_NO_MEM;
157     } else {
158         // set up mapping using pages [start, start + page_count)
159         uint32_t entry_val = (uint32_t) phys_page;
160         for (int i = start; i != start + page_count; ++i, ++entry_val) {
161             // sanity check: we won't reconfigure entries with non-zero reference count
162             assert(s_mmap_page_refcnt[i] == 0 ||
163                     (DPORT_PRO_FLASH_MMU_TABLE[i] == entry_val &&
164                      DPORT_APP_FLASH_MMU_TABLE[i] == entry_val));
165             if (s_mmap_page_refcnt[i] == 0) {
166                 if (DPORT_PRO_FLASH_MMU_TABLE[i] != entry_val || DPORT_APP_FLASH_MMU_TABLE[i] != entry_val) {
167                     DPORT_PRO_FLASH_MMU_TABLE[i] = entry_val;
168                     DPORT_APP_FLASH_MMU_TABLE[i] = entry_val;
169                     need_flush = true;
170                 }
171             }
172             ++s_mmap_page_refcnt[i];
173         }
174
175         LIST_INSERT_HEAD(&s_mmap_entries_head, new_entry, entries);
176         new_entry->page = start;
177         new_entry->count = page_count;
178         new_entry->handle = ++s_mmap_last_handle;
179         *out_handle = new_entry->handle;
180         *out_ptr = (void*) (region_addr + start * SPI_FLASH_MMU_PAGE_SIZE);
181         ret = ESP_OK;
182     }
183
184     /* This is a temporary fix for an issue where some
185        encrypted cache reads may see stale data.
186
187        Working on a long term fix that doesn't require invalidating
188        entire cache.
189     */
190     if (esp_flash_encryption_enabled() && !did_flush && need_flush) {
191         Cache_Flush(0);
192         Cache_Flush(1);
193     }
194
195     spi_flash_enable_interrupts_caches_and_other_cpu();
196     if (*out_ptr == NULL) {
197         free(new_entry);
198     }
199     return ret;
200 }
201
202 void IRAM_ATTR spi_flash_munmap(spi_flash_mmap_handle_t handle)
203 {
204     spi_flash_disable_interrupts_caches_and_other_cpu();
205     mmap_entry_t* it;
206     // look for handle in linked list
207     for (it = LIST_FIRST(&s_mmap_entries_head); it != NULL; it = LIST_NEXT(it, entries)) {
208         if (it->handle == handle) {
209             // for each page, decrement reference counter
210             // if reference count is zero, disable MMU table entry to
211             // facilitate debugging of use-after-free conditions
212             for (int i = it->page; i < it->page + it->count; ++i) {
213                 assert(s_mmap_page_refcnt[i] > 0);
214                 if (--s_mmap_page_refcnt[i] == 0) {
215                     DPORT_PRO_FLASH_MMU_TABLE[i] = INVALID_ENTRY_VAL;
216                     DPORT_APP_FLASH_MMU_TABLE[i] = INVALID_ENTRY_VAL;
217                 }
218             }
219             LIST_REMOVE(it, entries);
220             break;
221         }
222     }
223     spi_flash_enable_interrupts_caches_and_other_cpu();
224     if (it == NULL) {
225         assert(0 && "invalid handle, or handle already unmapped");
226     }
227     free(it);
228 }
229
230 void spi_flash_mmap_dump()
231 {
232     if (s_mmap_page_refcnt[0] == 0) {
233         spi_flash_mmap_init();
234     }
235     mmap_entry_t* it;
236     for (it = LIST_FIRST(&s_mmap_entries_head); it != NULL; it = LIST_NEXT(it, entries)) {
237         printf("handle=%d page=%d count=%d\n", it->handle, it->page, it->count);
238     }
239     for (int i = 0; i < REGIONS_COUNT * PAGES_PER_REGION; ++i) {
240         if (s_mmap_page_refcnt[i] != 0) {
241             printf("page %d: refcnt=%d paddr=%d\n",
242                     i, (int) s_mmap_page_refcnt[i], DPORT_PRO_FLASH_MMU_TABLE[i]);
243         }
244     }
245 }
246
247 /* 256-bit (up to 16MB of 64KB pages) bitset of all flash pages
248    that have been written to since last cache flush.
249
250    Before mmaping a page, need to flush caches if that page has been
251    written to.
252
253    Note: It's possible to do some additional performance tweaks to
254    this algorithm, as we actually only need to flush caches if a page
255    was first mmapped, then written to, then is about to be mmaped a
256    second time. This is a fair bit more complex though, so unless
257    there's an access pattern that this would significantly boost then
258    it's probably not worth it.
259 */
260 static uint32_t written_pages[256/32];
261
262 static bool update_written_pages(size_t start_addr, size_t length, bool mark);
263
264 void IRAM_ATTR spi_flash_mark_modified_region(size_t start_addr, size_t length)
265 {
266     update_written_pages(start_addr, length, true);
267 }
268
269 static IRAM_ATTR bool spi_flash_ensure_unmodified_region(size_t start_addr, size_t length)
270 {
271     return update_written_pages(start_addr, length, false);
272 }
273
274 /* generic implementation for the previous two functions */
275 static inline IRAM_ATTR bool update_written_pages(size_t start_addr, size_t length, bool mark)
276 {
277     /* align start_addr & length to full MMU pages */
278     uint32_t page_start_addr = start_addr & ~(SPI_FLASH_MMU_PAGE_SIZE-1);
279     length += (start_addr - page_start_addr);
280     length = (length + SPI_FLASH_MMU_PAGE_SIZE - 1) & ~(SPI_FLASH_MMU_PAGE_SIZE-1);
281     for (uint32_t addr = page_start_addr; addr < page_start_addr + length; addr += SPI_FLASH_MMU_PAGE_SIZE) {
282         int page = addr / SPI_FLASH_MMU_PAGE_SIZE;
283         if (page >= 256) {
284             return false; /* invalid address */
285         }
286
287         int idx = page / 32;
288         uint32_t bit = 1 << (page % 32);
289
290         if (mark) {
291             written_pages[idx] |= bit;
292         } else if (written_pages[idx] & bit) {
293             /* it is tempting to write a version of this that only
294                flushes each CPU's cache as needed. However this is
295                tricky because mmaped memory can be used on un-pinned
296                cores, or the pointer passed between CPUs.
297             */
298             Cache_Flush(0);
299 #ifndef CONFIG_FREERTOS_UNICORE
300             Cache_Flush(1);
301 #endif
302             bzero(written_pages, sizeof(written_pages));
303             return true;
304         }
305     }
306     return false;
307 }