efi_loader: Expose U-Boot addresses in memory map for sandbox
[platform/kernel/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         switch (type) {
297         case EFI_ALLOCATE_ANY_PAGES:
298                 /* Any page */
299                 addr = efi_find_free_memory(len, -1ULL);
300                 if (!addr) {
301                         r = EFI_NOT_FOUND;
302                         break;
303                 }
304                 break;
305         case EFI_ALLOCATE_MAX_ADDRESS:
306                 /* Max address */
307                 addr = efi_find_free_memory(len, *memory);
308                 if (!addr) {
309                         r = EFI_NOT_FOUND;
310                         break;
311                 }
312                 break;
313         case EFI_ALLOCATE_ADDRESS:
314                 /* Exact address, reserve it. The addr is already in *memory. */
315                 addr = *memory;
316                 break;
317         default:
318                 /* UEFI doesn't specify other allocation types */
319                 r = EFI_INVALID_PARAMETER;
320                 break;
321         }
322
323         if (r == EFI_SUCCESS) {
324                 uint64_t ret;
325
326                 /* Reserve that map in our memory maps */
327                 ret = efi_add_memory_map(addr, pages, memory_type, true);
328                 if (ret == addr) {
329                         *memory = (uintptr_t)map_sysmem(addr, len);
330                 } else {
331                         /* Map would overlap, bail out */
332                         r = EFI_OUT_OF_RESOURCES;
333                 }
334         }
335
336         return r;
337 }
338
339 void *efi_alloc(uint64_t len, int memory_type)
340 {
341         uint64_t ret = 0;
342         uint64_t pages = (len + EFI_PAGE_MASK) >> EFI_PAGE_SHIFT;
343         efi_status_t r;
344
345         r = efi_allocate_pages(EFI_ALLOCATE_ANY_PAGES, memory_type, pages,
346                                &ret);
347         if (r == EFI_SUCCESS)
348                 return (void*)(uintptr_t)ret;
349
350         return NULL;
351 }
352
353 /*
354  * Free memory pages.
355  *
356  * @memory      start of the memory area to be freed
357  * @pages       number of pages to be freed
358  * @return      status code
359  */
360 efi_status_t efi_free_pages(uint64_t memory, efi_uintn_t pages)
361 {
362         uint64_t r = 0;
363         uint64_t addr = map_to_sysmem((void *)(uintptr_t)memory);
364
365         r = efi_add_memory_map(addr, pages, EFI_CONVENTIONAL_MEMORY, false);
366         /* Merging of adjacent free regions is missing */
367
368         if (r == addr)
369                 return EFI_SUCCESS;
370
371         return EFI_NOT_FOUND;
372 }
373
374 /*
375  * Allocate memory from pool.
376  *
377  * @pool_type   type of the pool from which memory is to be allocated
378  * @size        number of bytes to be allocated
379  * @buffer      allocated memory
380  * @return      status code
381  */
382 efi_status_t efi_allocate_pool(int pool_type, efi_uintn_t size, void **buffer)
383 {
384         efi_status_t r;
385         struct efi_pool_allocation *alloc;
386         u64 num_pages = (size + sizeof(struct efi_pool_allocation) +
387                          EFI_PAGE_MASK) >> EFI_PAGE_SHIFT;
388
389         if (size == 0) {
390                 *buffer = NULL;
391                 return EFI_SUCCESS;
392         }
393
394         r = efi_allocate_pages(EFI_ALLOCATE_ANY_PAGES, pool_type, num_pages,
395                                (uint64_t *)&alloc);
396
397         if (r == EFI_SUCCESS) {
398                 alloc->num_pages = num_pages;
399                 *buffer = alloc->data;
400         }
401
402         return r;
403 }
404
405 /*
406  * Free memory from pool.
407  *
408  * @buffer      start of memory to be freed
409  * @return      status code
410  */
411 efi_status_t efi_free_pool(void *buffer)
412 {
413         efi_status_t r;
414         struct efi_pool_allocation *alloc;
415
416         if (buffer == NULL)
417                 return EFI_INVALID_PARAMETER;
418
419         alloc = container_of(buffer, struct efi_pool_allocation, data);
420         /* Sanity check, was the supplied address returned by allocate_pool */
421         assert(((uintptr_t)alloc & EFI_PAGE_MASK) == 0);
422
423         r = efi_free_pages((uintptr_t)alloc, alloc->num_pages);
424
425         return r;
426 }
427
428 /*
429  * Get map describing memory usage.
430  *
431  * @memory_map_size     on entry the size, in bytes, of the memory map buffer,
432  *                      on exit the size of the copied memory map
433  * @memory_map          buffer to which the memory map is written
434  * @map_key             key for the memory map
435  * @descriptor_size     size of an individual memory descriptor
436  * @descriptor_version  version number of the memory descriptor structure
437  * @return              status code
438  */
439 efi_status_t efi_get_memory_map(efi_uintn_t *memory_map_size,
440                                 struct efi_mem_desc *memory_map,
441                                 efi_uintn_t *map_key,
442                                 efi_uintn_t *descriptor_size,
443                                 uint32_t *descriptor_version)
444 {
445         efi_uintn_t map_size = 0;
446         int map_entries = 0;
447         struct list_head *lhandle;
448         efi_uintn_t provided_map_size = *memory_map_size;
449
450         list_for_each(lhandle, &efi_mem)
451                 map_entries++;
452
453         map_size = map_entries * sizeof(struct efi_mem_desc);
454
455         *memory_map_size = map_size;
456
457         if (provided_map_size < map_size)
458                 return EFI_BUFFER_TOO_SMALL;
459
460         if (descriptor_size)
461                 *descriptor_size = sizeof(struct efi_mem_desc);
462
463         if (descriptor_version)
464                 *descriptor_version = EFI_MEMORY_DESCRIPTOR_VERSION;
465
466         /* Copy list into array */
467         if (memory_map) {
468                 /* Return the list in ascending order */
469                 memory_map = &memory_map[map_entries - 1];
470                 list_for_each(lhandle, &efi_mem) {
471                         struct efi_mem_list *lmem;
472
473                         lmem = list_entry(lhandle, struct efi_mem_list, link);
474                         *memory_map = lmem->desc;
475                         memory_map--;
476                 }
477         }
478
479         *map_key = 0;
480
481         return EFI_SUCCESS;
482 }
483
484 __weak void efi_add_known_memory(void)
485 {
486         int i;
487
488         /* Add RAM */
489         for (i = 0; i < CONFIG_NR_DRAM_BANKS; i++) {
490                 u64 ram_start = gd->bd->bi_dram[i].start;
491                 u64 ram_size = gd->bd->bi_dram[i].size;
492                 u64 start = (ram_start + EFI_PAGE_MASK) & ~EFI_PAGE_MASK;
493                 u64 pages = (ram_size + EFI_PAGE_MASK) >> EFI_PAGE_SHIFT;
494
495                 efi_add_memory_map(start, pages, EFI_CONVENTIONAL_MEMORY,
496                                    false);
497         }
498 }
499
500 /* Add memory regions for U-Boot's memory and for the runtime services code */
501 static void add_u_boot_and_runtime(void)
502 {
503         unsigned long runtime_start, runtime_end, runtime_pages;
504         unsigned long uboot_start, uboot_pages;
505         unsigned long uboot_stack_size = 16 * 1024 * 1024;
506
507         /* Add U-Boot */
508         uboot_start = (gd->start_addr_sp - uboot_stack_size) & ~EFI_PAGE_MASK;
509         uboot_pages = (gd->ram_top - uboot_start) >> EFI_PAGE_SHIFT;
510         efi_add_memory_map(uboot_start, uboot_pages, EFI_LOADER_DATA, false);
511
512         /* Add Runtime Services */
513         runtime_start = (ulong)&__efi_runtime_start & ~EFI_PAGE_MASK;
514         runtime_end = (ulong)&__efi_runtime_stop;
515         runtime_end = (runtime_end + EFI_PAGE_MASK) & ~EFI_PAGE_MASK;
516         runtime_pages = (runtime_end - runtime_start) >> EFI_PAGE_SHIFT;
517         efi_add_memory_map(runtime_start, runtime_pages,
518                            EFI_RUNTIME_SERVICES_CODE, false);
519 }
520
521 int efi_memory_init(void)
522 {
523         efi_add_known_memory();
524
525         if (!IS_ENABLED(CONFIG_SANDBOX))
526                 add_u_boot_and_runtime();
527
528 #ifdef CONFIG_EFI_LOADER_BOUNCE_BUFFER
529         /* Request a 32bit 64MB bounce buffer region */
530         uint64_t efi_bounce_buffer_addr = 0xffffffff;
531
532         if (efi_allocate_pages(EFI_ALLOCATE_MAX_ADDRESS, EFI_LOADER_DATA,
533                                (64 * 1024 * 1024) >> EFI_PAGE_SHIFT,
534                                &efi_bounce_buffer_addr) != EFI_SUCCESS)
535                 return -1;
536
537         efi_bounce_buffer = (void*)(uintptr_t)efi_bounce_buffer_addr;
538 #endif
539
540         return 0;
541 }