bad87042695c25dfd7945a48e000da690b12d760
[oweals/u-boot.git] / lib / efi_loader / efi_memory.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  *  EFI application memory management
4  *
5  *  Copyright (c) 2016 Alexander Graf
6  */
7
8 #include <common.h>
9 #include <efi_loader.h>
10 #include <inttypes.h>
11 #include <malloc.h>
12 #include <mapmem.h>
13 #include <watchdog.h>
14 #include <linux/list_sort.h>
15
16 DECLARE_GLOBAL_DATA_PTR;
17
18 struct efi_mem_list {
19         struct list_head link;
20         struct efi_mem_desc desc;
21 };
22
23 #define EFI_CARVE_NO_OVERLAP            -1
24 #define EFI_CARVE_LOOP_AGAIN            -2
25 #define EFI_CARVE_OVERLAPS_NONRAM       -3
26
27 /* This list contains all memory map items */
28 LIST_HEAD(efi_mem);
29
30 #ifdef CONFIG_EFI_LOADER_BOUNCE_BUFFER
31 void *efi_bounce_buffer;
32 #endif
33
34 /*
35  * U-Boot services each EFI AllocatePool request as a separate
36  * (multiple) page allocation.  We have to track the number of pages
37  * to be able to free the correct amount later.
38  * EFI requires 8 byte alignment for pool allocations, so we can
39  * prepend each allocation with an 64 bit header tracking the
40  * allocation size, and hand out the remainder to the caller.
41  */
42 struct efi_pool_allocation {
43         u64 num_pages;
44         char data[] __aligned(ARCH_DMA_MINALIGN);
45 };
46
47 /*
48  * Sorts the memory list from highest address to lowest address
49  *
50  * When allocating memory we should always start from the highest
51  * address chunk, so sort the memory list such that the first list
52  * iterator gets the highest address and goes lower from there.
53  */
54 static int efi_mem_cmp(void *priv, struct list_head *a, struct list_head *b)
55 {
56         struct efi_mem_list *mema = list_entry(a, struct efi_mem_list, link);
57         struct efi_mem_list *memb = list_entry(b, struct efi_mem_list, link);
58
59         if (mema->desc.physical_start == memb->desc.physical_start)
60                 return 0;
61         else if (mema->desc.physical_start < memb->desc.physical_start)
62                 return 1;
63         else
64                 return -1;
65 }
66
67 static void efi_mem_sort(void)
68 {
69         list_sort(NULL, &efi_mem, efi_mem_cmp);
70 }
71
72 /** efi_mem_carve_out - unmap memory region
73  *
74  * @map:                memory map
75  * @carve_desc:         memory region to unmap
76  * @overlap_only_ram:   the carved out region may only overlap RAM
77  * Return Value:        the number of overlapping pages which have been
78  *                      removed from the map,
79  *                      EFI_CARVE_NO_OVERLAP, if the regions don't overlap,
80  *                      EFI_CARVE_OVERLAPS_NONRAM, if the carve and map overlap,
81  *                      and the map contains anything but free ram
82  *                      (only when overlap_only_ram is true),
83  *                      EFI_CARVE_LOOP_AGAIN, if the mapping list should be
84  *                      traversed again, as it has been altered.
85  *
86  * Unmaps all memory occupied by the carve_desc region from the list entry
87  * pointed to by map.
88  *
89  * In case of EFI_CARVE_OVERLAPS_NONRAM it is the callers responsibility
90  * to re-add the already carved out pages to the mapping.
91  */
92 static s64 efi_mem_carve_out(struct efi_mem_list *map,
93                              struct efi_mem_desc *carve_desc,
94                              bool overlap_only_ram)
95 {
96         struct efi_mem_list *newmap;
97         struct efi_mem_desc *map_desc = &map->desc;
98         uint64_t map_start = map_desc->physical_start;
99         uint64_t map_end = map_start + (map_desc->num_pages << EFI_PAGE_SHIFT);
100         uint64_t carve_start = carve_desc->physical_start;
101         uint64_t carve_end = carve_start +
102                              (carve_desc->num_pages << EFI_PAGE_SHIFT);
103
104         /* check whether we're overlapping */
105         if ((carve_end <= map_start) || (carve_start >= map_end))
106                 return EFI_CARVE_NO_OVERLAP;
107
108         /* We're overlapping with non-RAM, warn the caller if desired */
109         if (overlap_only_ram && (map_desc->type != EFI_CONVENTIONAL_MEMORY))
110                 return EFI_CARVE_OVERLAPS_NONRAM;
111
112         /* Sanitize carve_start and carve_end to lie within our bounds */
113         carve_start = max(carve_start, map_start);
114         carve_end = min(carve_end, map_end);
115
116         /* Carving at the beginning of our map? Just move it! */
117         if (carve_start == map_start) {
118                 if (map_end == carve_end) {
119                         /* Full overlap, just remove map */
120                         list_del(&map->link);
121                         free(map);
122                 } else {
123                         map->desc.physical_start = carve_end;
124                         map->desc.num_pages = (map_end - carve_end)
125                                               >> EFI_PAGE_SHIFT;
126                 }
127
128                 return (carve_end - carve_start) >> EFI_PAGE_SHIFT;
129         }
130
131         /*
132          * Overlapping maps, just split the list map at carve_start,
133          * it will get moved or removed in the next iteration.
134          *
135          * [ map_desc |__carve_start__| newmap ]
136          */
137
138         /* Create a new map from [ carve_start ... map_end ] */
139         newmap = calloc(1, sizeof(*newmap));
140         newmap->desc = map->desc;
141         newmap->desc.physical_start = carve_start;
142         newmap->desc.num_pages = (map_end - carve_start) >> EFI_PAGE_SHIFT;
143         /* Insert before current entry (descending address order) */
144         list_add_tail(&newmap->link, &map->link);
145
146         /* Shrink the map to [ map_start ... carve_start ] */
147         map_desc->num_pages = (carve_start - map_start) >> EFI_PAGE_SHIFT;
148
149         return EFI_CARVE_LOOP_AGAIN;
150 }
151
152 uint64_t efi_add_memory_map(uint64_t start, uint64_t pages, int memory_type,
153                             bool overlap_only_ram)
154 {
155         struct list_head *lhandle;
156         struct efi_mem_list *newlist;
157         bool carve_again;
158         uint64_t carved_pages = 0;
159
160         debug("%s: 0x%" PRIx64 " 0x%" PRIx64 " %d %s\n", __func__,
161               start, pages, memory_type, overlap_only_ram ? "yes" : "no");
162
163         if (!pages)
164                 return start;
165
166         newlist = calloc(1, sizeof(*newlist));
167         newlist->desc.type = memory_type;
168         newlist->desc.physical_start = start;
169         newlist->desc.virtual_start = start;
170         newlist->desc.num_pages = pages;
171
172         switch (memory_type) {
173         case EFI_RUNTIME_SERVICES_CODE:
174         case EFI_RUNTIME_SERVICES_DATA:
175                 newlist->desc.attribute = (1 << EFI_MEMORY_WB_SHIFT) |
176                                           (1ULL << EFI_MEMORY_RUNTIME_SHIFT);
177                 break;
178         case EFI_MMAP_IO:
179                 newlist->desc.attribute = 1ULL << EFI_MEMORY_RUNTIME_SHIFT;
180                 break;
181         default:
182                 newlist->desc.attribute = 1 << EFI_MEMORY_WB_SHIFT;
183                 break;
184         }
185
186         /* Add our new map */
187         do {
188                 carve_again = false;
189                 list_for_each(lhandle, &efi_mem) {
190                         struct efi_mem_list *lmem;
191                         s64 r;
192
193                         lmem = list_entry(lhandle, struct efi_mem_list, link);
194                         r = efi_mem_carve_out(lmem, &newlist->desc,
195                                               overlap_only_ram);
196                         switch (r) {
197                         case EFI_CARVE_OVERLAPS_NONRAM:
198                                 /*
199                                  * The user requested to only have RAM overlaps,
200                                  * but we hit a non-RAM region. Error out.
201                                  */
202                                 return 0;
203                         case EFI_CARVE_NO_OVERLAP:
204                                 /* Just ignore this list entry */
205                                 break;
206                         case EFI_CARVE_LOOP_AGAIN:
207                                 /*
208                                  * We split an entry, but need to loop through
209                                  * the list again to actually carve it.
210                                  */
211                                 carve_again = true;
212                                 break;
213                         default:
214                                 /* We carved a number of pages */
215                                 carved_pages += r;
216                                 carve_again = true;
217                                 break;
218                         }
219
220                         if (carve_again) {
221                                 /* The list changed, we need to start over */
222                                 break;
223                         }
224                 }
225         } while (carve_again);
226
227         if (overlap_only_ram && (carved_pages != pages)) {
228                 /*
229                  * The payload wanted to have RAM overlaps, but we overlapped
230                  * with an unallocated region. Error out.
231                  */
232                 return 0;
233         }
234
235         /* Add our new map */
236         list_add_tail(&newlist->link, &efi_mem);
237
238         /* And make sure memory is listed in descending order */
239         efi_mem_sort();
240
241         return start;
242 }
243
244 static uint64_t efi_find_free_memory(uint64_t len, uint64_t max_addr)
245 {
246         struct list_head *lhandle;
247
248         list_for_each(lhandle, &efi_mem) {
249                 struct efi_mem_list *lmem = list_entry(lhandle,
250                         struct efi_mem_list, link);
251                 struct efi_mem_desc *desc = &lmem->desc;
252                 uint64_t desc_len = desc->num_pages << EFI_PAGE_SHIFT;
253                 uint64_t desc_end = desc->physical_start + desc_len;
254                 uint64_t curmax = min(max_addr, desc_end);
255                 uint64_t ret = curmax - len;
256
257                 /* We only take memory from free RAM */
258                 if (desc->type != EFI_CONVENTIONAL_MEMORY)
259                         continue;
260
261                 /* Out of bounds for max_addr */
262                 if ((ret + len) > max_addr)
263                         continue;
264
265                 /* Out of bounds for upper map limit */
266                 if ((ret + len) > desc_end)
267                         continue;
268
269                 /* Out of bounds for lower map limit */
270                 if (ret < desc->physical_start)
271                         continue;
272
273                 /* Return the highest address in this map within bounds */
274                 return ret;
275         }
276
277         return 0;
278 }
279
280 /*
281  * Allocate memory pages.
282  *
283  * @type                type of allocation to be performed
284  * @memory_type         usage type of the allocated memory
285  * @pages               number of pages to be allocated
286  * @memory              allocated memory
287  * @return              status code
288  */
289 efi_status_t efi_allocate_pages(int type, int memory_type,
290                                 efi_uintn_t pages, uint64_t *memory)
291 {
292         u64 len = pages << EFI_PAGE_SHIFT;
293         efi_status_t r = EFI_SUCCESS;
294         uint64_t addr;
295
296         if (!memory)
297                 return EFI_INVALID_PARAMETER;
298
299         switch (type) {
300         case EFI_ALLOCATE_ANY_PAGES:
301                 /* Any page */
302                 addr = efi_find_free_memory(len, -1ULL);
303                 if (!addr) {
304                         r = EFI_NOT_FOUND;
305                         break;
306                 }
307                 break;
308         case EFI_ALLOCATE_MAX_ADDRESS:
309                 /* Max address */
310                 addr = efi_find_free_memory(len, *memory);
311                 if (!addr) {
312                         r = EFI_NOT_FOUND;
313                         break;
314                 }
315                 break;
316         case EFI_ALLOCATE_ADDRESS:
317                 /* Exact address, reserve it. The addr is already in *memory. */
318                 addr = *memory;
319                 break;
320         default:
321                 /* UEFI doesn't specify other allocation types */
322                 r = EFI_INVALID_PARAMETER;
323                 break;
324         }
325
326         if (r == EFI_SUCCESS) {
327                 uint64_t ret;
328
329                 /* Reserve that map in our memory maps */
330                 ret = efi_add_memory_map(addr, pages, memory_type, true);
331                 if (ret == addr) {
332                         *memory = (uintptr_t)map_sysmem(addr, len);
333                 } else {
334                         /* Map would overlap, bail out */
335                         r = EFI_OUT_OF_RESOURCES;
336                 }
337         }
338
339         return r;
340 }
341
342 void *efi_alloc(uint64_t len, int memory_type)
343 {
344         uint64_t ret = 0;
345         uint64_t pages = (len + EFI_PAGE_MASK) >> EFI_PAGE_SHIFT;
346         efi_status_t r;
347
348         r = efi_allocate_pages(EFI_ALLOCATE_ANY_PAGES, memory_type, pages,
349                                &ret);
350         if (r == EFI_SUCCESS)
351                 return (void*)(uintptr_t)ret;
352
353         return NULL;
354 }
355
356 /*
357  * Free memory pages.
358  *
359  * @memory      start of the memory area to be freed
360  * @pages       number of pages to be freed
361  * @return      status code
362  */
363 efi_status_t efi_free_pages(uint64_t memory, efi_uintn_t pages)
364 {
365         uint64_t r = 0;
366         uint64_t addr = map_to_sysmem((void *)(uintptr_t)memory);
367
368         r = efi_add_memory_map(addr, pages, EFI_CONVENTIONAL_MEMORY, false);
369         /* Merging of adjacent free regions is missing */
370
371         if (r == addr)
372                 return EFI_SUCCESS;
373
374         return EFI_NOT_FOUND;
375 }
376
377 /*
378  * Allocate memory from pool.
379  *
380  * @pool_type   type of the pool from which memory is to be allocated
381  * @size        number of bytes to be allocated
382  * @buffer      allocated memory
383  * @return      status code
384  */
385 efi_status_t efi_allocate_pool(int pool_type, efi_uintn_t size, void **buffer)
386 {
387         efi_status_t r;
388         struct efi_pool_allocation *alloc;
389         u64 num_pages = (size + sizeof(struct efi_pool_allocation) +
390                          EFI_PAGE_MASK) >> EFI_PAGE_SHIFT;
391
392         if (!buffer)
393                 return EFI_INVALID_PARAMETER;
394
395         if (size == 0) {
396                 *buffer = NULL;
397                 return EFI_SUCCESS;
398         }
399
400         r = efi_allocate_pages(EFI_ALLOCATE_ANY_PAGES, pool_type, num_pages,
401                                (uint64_t *)&alloc);
402
403         if (r == EFI_SUCCESS) {
404                 alloc->num_pages = num_pages;
405                 *buffer = alloc->data;
406         }
407
408         return r;
409 }
410
411 /*
412  * Free memory from pool.
413  *
414  * @buffer      start of memory to be freed
415  * @return      status code
416  */
417 efi_status_t efi_free_pool(void *buffer)
418 {
419         efi_status_t r;
420         struct efi_pool_allocation *alloc;
421
422         if (buffer == NULL)
423                 return EFI_INVALID_PARAMETER;
424
425         alloc = container_of(buffer, struct efi_pool_allocation, data);
426         /* Sanity check, was the supplied address returned by allocate_pool */
427         assert(((uintptr_t)alloc & EFI_PAGE_MASK) == 0);
428
429         r = efi_free_pages((uintptr_t)alloc, alloc->num_pages);
430
431         return r;
432 }
433
434 /*
435  * Get map describing memory usage.
436  *
437  * @memory_map_size     on entry the size, in bytes, of the memory map buffer,
438  *                      on exit the size of the copied memory map
439  * @memory_map          buffer to which the memory map is written
440  * @map_key             key for the memory map
441  * @descriptor_size     size of an individual memory descriptor
442  * @descriptor_version  version number of the memory descriptor structure
443  * @return              status code
444  */
445 efi_status_t efi_get_memory_map(efi_uintn_t *memory_map_size,
446                                 struct efi_mem_desc *memory_map,
447                                 efi_uintn_t *map_key,
448                                 efi_uintn_t *descriptor_size,
449                                 uint32_t *descriptor_version)
450 {
451         efi_uintn_t map_size = 0;
452         int map_entries = 0;
453         struct list_head *lhandle;
454         efi_uintn_t provided_map_size = *memory_map_size;
455
456         if (!memory_map_size)
457                 return EFI_INVALID_PARAMETER;
458
459         list_for_each(lhandle, &efi_mem)
460                 map_entries++;
461
462         map_size = map_entries * sizeof(struct efi_mem_desc);
463
464         *memory_map_size = map_size;
465
466         if (provided_map_size < map_size)
467                 return EFI_BUFFER_TOO_SMALL;
468
469         if (!memory_map)
470                 return EFI_INVALID_PARAMETER;
471
472         if (descriptor_size)
473                 *descriptor_size = sizeof(struct efi_mem_desc);
474
475         if (descriptor_version)
476                 *descriptor_version = EFI_MEMORY_DESCRIPTOR_VERSION;
477
478         /* Copy list into array */
479         /* Return the list in ascending order */
480         memory_map = &memory_map[map_entries - 1];
481         list_for_each(lhandle, &efi_mem) {
482                 struct efi_mem_list *lmem;
483
484                 lmem = list_entry(lhandle, struct efi_mem_list, link);
485                 *memory_map = lmem->desc;
486                 memory_map--;
487         }
488
489         if (map_key)
490                 *map_key = 0;
491
492         return EFI_SUCCESS;
493 }
494
495 __weak void efi_add_known_memory(void)
496 {
497         int i;
498
499         /* Add RAM */
500         for (i = 0; i < CONFIG_NR_DRAM_BANKS; i++) {
501                 u64 ram_start = gd->bd->bi_dram[i].start;
502                 u64 ram_size = gd->bd->bi_dram[i].size;
503                 u64 start = (ram_start + EFI_PAGE_MASK) & ~EFI_PAGE_MASK;
504                 u64 pages = (ram_size + EFI_PAGE_MASK) >> EFI_PAGE_SHIFT;
505
506                 efi_add_memory_map(start, pages, EFI_CONVENTIONAL_MEMORY,
507                                    false);
508         }
509 }
510
511 /* Add memory regions for U-Boot's memory and for the runtime services code */
512 static void add_u_boot_and_runtime(void)
513 {
514         unsigned long runtime_start, runtime_end, runtime_pages;
515         unsigned long uboot_start, uboot_pages;
516         unsigned long uboot_stack_size = 16 * 1024 * 1024;
517
518         /* Add U-Boot */
519         uboot_start = (gd->start_addr_sp - uboot_stack_size) & ~EFI_PAGE_MASK;
520         uboot_pages = (gd->ram_top - uboot_start) >> EFI_PAGE_SHIFT;
521         efi_add_memory_map(uboot_start, uboot_pages, EFI_LOADER_DATA, false);
522
523         /* Add Runtime Services */
524         runtime_start = (ulong)&__efi_runtime_start & ~EFI_PAGE_MASK;
525         runtime_end = (ulong)&__efi_runtime_stop;
526         runtime_end = (runtime_end + EFI_PAGE_MASK) & ~EFI_PAGE_MASK;
527         runtime_pages = (runtime_end - runtime_start) >> EFI_PAGE_SHIFT;
528         efi_add_memory_map(runtime_start, runtime_pages,
529                            EFI_RUNTIME_SERVICES_CODE, false);
530 }
531
532 int efi_memory_init(void)
533 {
534         efi_add_known_memory();
535
536         if (!IS_ENABLED(CONFIG_SANDBOX))
537                 add_u_boot_and_runtime();
538
539 #ifdef CONFIG_EFI_LOADER_BOUNCE_BUFFER
540         /* Request a 32bit 64MB bounce buffer region */
541         uint64_t efi_bounce_buffer_addr = 0xffffffff;
542
543         if (efi_allocate_pages(EFI_ALLOCATE_MAX_ADDRESS, EFI_LOADER_DATA,
544                                (64 * 1024 * 1024) >> EFI_PAGE_SHIFT,
545                                &efi_bounce_buffer_addr) != EFI_SUCCESS)
546                 return -1;
547
548         efi_bounce_buffer = (void*)(uintptr_t)efi_bounce_buffer_addr;
549 #endif
550
551         return 0;
552 }