7f9913c0ee03e55aa888dde34be919f8787f0626
[platform/kernel/u-boot.git] / cmd / bootefi.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  *  EFI application loader
4  *
5  *  Copyright (c) 2016 Alexander Graf
6  */
7
8 #include <common.h>
9 #include <bootm.h>
10 #include <charset.h>
11 #include <command.h>
12 #include <dm.h>
13 #include <efi_loader.h>
14 #include <efi_selftest.h>
15 #include <errno.h>
16 #include <linux/libfdt.h>
17 #include <linux/libfdt_env.h>
18 #include <mapmem.h>
19 #include <memalign.h>
20 #include <asm/global_data.h>
21 #include <asm-generic/sections.h>
22 #include <asm-generic/unaligned.h>
23 #include <linux/linkage.h>
24
25 DECLARE_GLOBAL_DATA_PTR;
26
27 static struct efi_device_path *bootefi_image_path;
28 static struct efi_device_path *bootefi_device_path;
29
30 /*
31  * Allow unaligned memory access.
32  *
33  * This routine is overridden by architectures providing this feature.
34  */
35 void __weak allow_unaligned(void)
36 {
37 }
38
39 /*
40  * Set the load options of an image from an environment variable.
41  *
42  * @loaded_image_info:  the image
43  * @env_var:            name of the environment variable
44  */
45 static void set_load_options(struct efi_loaded_image *loaded_image_info,
46                              const char *env_var)
47 {
48         size_t size;
49         const char *env = env_get(env_var);
50         u16 *pos;
51
52         loaded_image_info->load_options = NULL;
53         loaded_image_info->load_options_size = 0;
54         if (!env)
55                 return;
56         size = utf8_utf16_strlen(env) + 1;
57         loaded_image_info->load_options = calloc(size, sizeof(u16));
58         if (!loaded_image_info->load_options) {
59                 printf("ERROR: Out of memory\n");
60                 return;
61         }
62         pos = loaded_image_info->load_options;
63         utf8_utf16_strcpy(&pos, env);
64         loaded_image_info->load_options_size = size * 2;
65 }
66
67 /**
68  * copy_fdt() - Copy the device tree to a new location available to EFI
69  *
70  * The FDT is copied to a suitable location within the EFI memory map.
71  * Additional 12 KiB are added to the space in case the device tree needs to be
72  * expanded later with fdt_open_into().
73  *
74  * @fdtp:       On entry a pointer to the flattened device tree.
75  *              On exit a pointer to the copy of the flattened device tree.
76  *              FDT start
77  * Return:      status code
78  */
79 static efi_status_t copy_fdt(void **fdtp)
80 {
81         unsigned long fdt_ram_start = -1L, fdt_pages;
82         efi_status_t ret = 0;
83         void *fdt, *new_fdt;
84         u64 new_fdt_addr;
85         uint fdt_size;
86         int i;
87
88         for (i = 0; i < CONFIG_NR_DRAM_BANKS; i++) {
89                 u64 ram_start = gd->bd->bi_dram[i].start;
90                 u64 ram_size = gd->bd->bi_dram[i].size;
91
92                 if (!ram_size)
93                         continue;
94
95                 if (ram_start < fdt_ram_start)
96                         fdt_ram_start = ram_start;
97         }
98
99         /*
100          * Give us at least 12 KiB of breathing room in case the device tree
101          * needs to be expanded later.
102          */
103         fdt = *fdtp;
104         fdt_pages = efi_size_in_pages(fdt_totalsize(fdt) + 0x3000);
105         fdt_size = fdt_pages << EFI_PAGE_SHIFT;
106
107         /*
108          * Safe fdt location is at 127 MiB.
109          * On the sandbox convert from the sandbox address space.
110          */
111         new_fdt_addr = (uintptr_t)map_sysmem(fdt_ram_start + 0x7f00000 +
112                                              fdt_size, 0);
113         ret = efi_allocate_pages(EFI_ALLOCATE_MAX_ADDRESS,
114                                  EFI_RUNTIME_SERVICES_DATA, fdt_pages,
115                                  &new_fdt_addr);
116         if (ret != EFI_SUCCESS) {
117                 /* If we can't put it there, put it somewhere */
118                 new_fdt_addr = (ulong)memalign(EFI_PAGE_SIZE, fdt_size);
119                 ret = efi_allocate_pages(EFI_ALLOCATE_MAX_ADDRESS,
120                                          EFI_RUNTIME_SERVICES_DATA, fdt_pages,
121                                          &new_fdt_addr);
122                 if (ret != EFI_SUCCESS) {
123                         printf("ERROR: Failed to reserve space for FDT\n");
124                         goto done;
125                 }
126         }
127         new_fdt = (void *)(uintptr_t)new_fdt_addr;
128         memcpy(new_fdt, fdt, fdt_totalsize(fdt));
129         fdt_set_totalsize(new_fdt, fdt_size);
130
131         *fdtp = (void *)(uintptr_t)new_fdt_addr;
132 done:
133         return ret;
134 }
135
136 static efi_status_t efi_do_enter(
137                         efi_handle_t image_handle, struct efi_system_table *st,
138                         EFIAPI efi_status_t (*entry)(
139                                 efi_handle_t image_handle,
140                                 struct efi_system_table *st))
141 {
142         efi_status_t ret = EFI_LOAD_ERROR;
143
144         if (entry)
145                 ret = entry(image_handle, st);
146         st->boottime->exit(image_handle, ret, 0, NULL);
147         return ret;
148 }
149
150 /*
151  * efi_carve_out_dt_rsv() - Carve out DT reserved memory ranges
152  *
153  * The mem_rsv entries of the FDT are added to the memory map. Any failures are
154  * ignored because this is not critical and we would rather continue to try to
155  * boot.
156  *
157  * @fdt: Pointer to device tree
158  */
159 static void efi_carve_out_dt_rsv(void *fdt)
160 {
161         int nr_rsv, i;
162         uint64_t addr, size, pages;
163
164         nr_rsv = fdt_num_mem_rsv(fdt);
165
166         /* Look for an existing entry and add it to the efi mem map. */
167         for (i = 0; i < nr_rsv; i++) {
168                 if (fdt_get_mem_rsv(fdt, i, &addr, &size) != 0)
169                         continue;
170
171                 /* Convert from sandbox address space. */
172                 addr = (uintptr_t)map_sysmem(addr, 0);
173
174                 pages = efi_size_in_pages(size + (addr & EFI_PAGE_MASK));
175                 addr &= ~EFI_PAGE_MASK;
176                 if (!efi_add_memory_map(addr, pages, EFI_RESERVED_MEMORY_TYPE,
177                                         false))
178                         printf("FDT memrsv map %d: Failed to add to map\n", i);
179         }
180 }
181
182 static efi_status_t efi_install_fdt(ulong fdt_addr)
183 {
184         bootm_headers_t img = { 0 };
185         efi_status_t ret;
186         void *fdt;
187
188         fdt = map_sysmem(fdt_addr, 0);
189         if (fdt_check_header(fdt)) {
190                 printf("ERROR: invalid device tree\n");
191                 return EFI_INVALID_PARAMETER;
192         }
193
194         /* Create memory reservation as indicated by the device tree */
195         efi_carve_out_dt_rsv(fdt);
196
197         /* Prepare fdt for payload */
198         ret = copy_fdt(&fdt);
199         if (ret)
200                 return ret;
201
202         if (image_setup_libfdt(&img, fdt, 0, NULL)) {
203                 printf("ERROR: failed to process device tree\n");
204                 return EFI_LOAD_ERROR;
205         }
206
207         /* Link to it in the efi tables */
208         ret = efi_install_configuration_table(&efi_guid_fdt, fdt);
209         if (ret != EFI_SUCCESS)
210                 return EFI_OUT_OF_RESOURCES;
211
212         return ret;
213 }
214
215 static efi_status_t bootefi_run_prepare(const char *load_options_path,
216                 struct efi_device_path *device_path,
217                 struct efi_device_path *image_path,
218                 struct efi_loaded_image_obj **image_objp,
219                 struct efi_loaded_image **loaded_image_infop)
220 {
221         efi_status_t ret;
222
223         ret = efi_setup_loaded_image(device_path, image_path, image_objp,
224                                      loaded_image_infop);
225         if (ret != EFI_SUCCESS)
226                 return ret;
227
228         /* Transfer environment variable as load options */
229         set_load_options(*loaded_image_infop, load_options_path);
230
231         return 0;
232 }
233
234 /**
235  * bootefi_run_finish() - finish up after running an EFI test
236  *
237  * @loaded_image_info: Pointer to a struct which holds the loaded image info
238  * @image_objj: Pointer to a struct which holds the loaded image object
239  */
240 static void bootefi_run_finish(struct efi_loaded_image_obj *image_obj,
241                                struct efi_loaded_image *loaded_image_info)
242 {
243         efi_restore_gd();
244         free(loaded_image_info->load_options);
245         efi_delete_handle(&image_obj->header);
246 }
247
248 /**
249  * do_bootefi_exec() - execute EFI binary
250  *
251  * @efi:                address of the binary
252  * @device_path:        path of the device from which the binary was loaded
253  * @image_path:         device path of the binary
254  * Return:              status code
255  *
256  * Load the EFI binary into a newly assigned memory unwinding the relocation
257  * information, install the loaded image protocol, and call the binary.
258  */
259 static efi_status_t do_bootefi_exec(void *efi,
260                                     struct efi_device_path *device_path,
261                                     struct efi_device_path *image_path)
262 {
263         efi_handle_t mem_handle = NULL;
264         struct efi_device_path *memdp = NULL;
265         efi_status_t ret;
266         struct efi_loaded_image_obj *image_obj = NULL;
267         struct efi_loaded_image *loaded_image_info = NULL;
268
269         /*
270          * Special case for efi payload not loaded from disk, such as
271          * 'bootefi hello' or for example payload loaded directly into
272          * memory via JTAG, etc:
273          */
274         if (!device_path && !image_path) {
275                 printf("WARNING: using memory device/image path, this may confuse some payloads!\n");
276                 /* actual addresses filled in after efi_load_pe() */
277                 memdp = efi_dp_from_mem(EFI_RESERVED_MEMORY_TYPE, 0, 0);
278                 device_path = image_path = memdp;
279                 /*
280                  * Grub expects that the device path of the loaded image is
281                  * installed on a handle.
282                  */
283                 ret = efi_create_handle(&mem_handle);
284                 if (ret != EFI_SUCCESS)
285                         return ret; /* TODO: leaks device_path */
286                 ret = efi_add_protocol(mem_handle, &efi_guid_device_path,
287                                        device_path);
288                 if (ret != EFI_SUCCESS)
289                         goto err_add_protocol;
290         } else {
291                 assert(device_path && image_path);
292         }
293
294         ret = bootefi_run_prepare("bootargs", device_path, image_path,
295                                   &image_obj, &loaded_image_info);
296         if (ret)
297                 goto err_prepare;
298
299         /* Load the EFI payload */
300         ret = efi_load_pe(image_obj, efi, loaded_image_info);
301         if (ret != EFI_SUCCESS)
302                 goto err_prepare;
303
304         if (memdp) {
305                 struct efi_device_path_memory *mdp = (void *)memdp;
306                 mdp->memory_type = loaded_image_info->image_code_type;
307                 mdp->start_address = (uintptr_t)loaded_image_info->image_base;
308                 mdp->end_address = mdp->start_address +
309                                 loaded_image_info->image_size;
310         }
311
312         /* we don't support much: */
313         env_set("efi_8be4df61-93ca-11d2-aa0d-00e098032b8c_OsIndicationsSupported",
314                 "{ro,boot}(blob)0000000000000000");
315
316         /* Call our payload! */
317         debug("%s: Jumping to 0x%p\n", __func__, image_obj->entry);
318
319         if (setjmp(&image_obj->exit_jmp)) {
320                 ret = image_obj->exit_status;
321                 goto err_prepare;
322         }
323
324         ret = efi_do_enter(&image_obj->header, &systab, image_obj->entry);
325
326 err_prepare:
327         /* image has returned, loaded-image obj goes *poof*: */
328         bootefi_run_finish(image_obj, loaded_image_info);
329
330 err_add_protocol:
331         if (mem_handle)
332                 efi_delete_handle(mem_handle);
333
334         return ret;
335 }
336
337 #ifdef CONFIG_CMD_BOOTEFI_SELFTEST
338 /**
339  * bootefi_test_prepare() - prepare to run an EFI test
340  *
341  * This sets things up so we can call EFI functions. This involves preparing
342  * the 'gd' pointer and setting up the load ed image data structures.
343  *
344  * @image_objp: loaded_image_infop: Pointer to a struct which will hold the
345  *    loaded image object. This struct will be inited by this function before
346  *    use.
347  * @loaded_image_infop: Pointer to a struct which will hold the loaded image
348  *    info. This struct will be inited by this function before use.
349  * @path: File path to the test being run (often just the test name with a
350  *    backslash before it
351  * @test_func: Address of the test function that is being run
352  * @load_options_path: U-Boot environment variable to use as load options
353  * @return 0 if OK, -ve on error
354  */
355 static efi_status_t bootefi_test_prepare
356                 (struct efi_loaded_image_obj **image_objp,
357                 struct efi_loaded_image **loaded_image_infop, const char *path,
358                 ulong test_func, const char *load_options_path)
359 {
360         /* Construct a dummy device path */
361         bootefi_device_path = efi_dp_from_mem(EFI_RESERVED_MEMORY_TYPE,
362                                               (uintptr_t)test_func,
363                                               (uintptr_t)test_func);
364         if (!bootefi_device_path)
365                 return EFI_OUT_OF_RESOURCES;
366         bootefi_image_path = efi_dp_from_file(NULL, 0, path);
367         if (!bootefi_image_path)
368                 return EFI_OUT_OF_RESOURCES;
369
370         return bootefi_run_prepare(load_options_path, bootefi_device_path,
371                                    bootefi_image_path, image_objp,
372                                    loaded_image_infop);
373 }
374
375 #endif /* CONFIG_CMD_BOOTEFI_SELFTEST */
376
377 static int do_bootefi_bootmgr_exec(void)
378 {
379         struct efi_device_path *device_path, *file_path;
380         void *addr;
381         efi_status_t r;
382
383         addr = efi_bootmgr_load(&device_path, &file_path);
384         if (!addr)
385                 return 1;
386
387         printf("## Starting EFI application at %p ...\n", addr);
388         r = do_bootefi_exec(addr, device_path, file_path);
389         printf("## Application terminated, r = %lu\n",
390                r & ~EFI_ERROR_MASK);
391
392         if (r != EFI_SUCCESS)
393                 return 1;
394
395         return 0;
396 }
397
398 /* Interpreter command to boot an arbitrary EFI image from memory */
399 static int do_bootefi(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
400 {
401         unsigned long addr;
402         char *saddr;
403         efi_status_t r;
404         unsigned long fdt_addr;
405
406         /* Allow unaligned memory access */
407         allow_unaligned();
408
409         switch_to_non_secure_mode();
410
411         /* Initialize EFI drivers */
412         r = efi_init_obj_list();
413         if (r != EFI_SUCCESS) {
414                 printf("Error: Cannot set up EFI drivers, r = %lu\n",
415                        r & ~EFI_ERROR_MASK);
416                 return CMD_RET_FAILURE;
417         }
418
419         if (argc < 2)
420                 return CMD_RET_USAGE;
421
422         if (argc > 2) {
423                 fdt_addr = simple_strtoul(argv[2], NULL, 16);
424                 if (!fdt_addr && *argv[2] != '0')
425                         return CMD_RET_USAGE;
426                 /* Install device tree */
427                 r = efi_install_fdt(fdt_addr);
428                 if (r != EFI_SUCCESS) {
429                         printf("ERROR: failed to install device tree\n");
430                         return CMD_RET_FAILURE;
431                 }
432         } else {
433                 /* Remove device tree. EFI_NOT_FOUND can be ignored here */
434                 efi_install_configuration_table(&efi_guid_fdt, NULL);
435                 printf("WARNING: booting without device tree\n");
436         }
437 #ifdef CONFIG_CMD_BOOTEFI_HELLO
438         if (!strcmp(argv[1], "hello")) {
439                 ulong size = __efi_helloworld_end - __efi_helloworld_begin;
440
441                 saddr = env_get("loadaddr");
442                 if (saddr)
443                         addr = simple_strtoul(saddr, NULL, 16);
444                 else
445                         addr = CONFIG_SYS_LOAD_ADDR;
446                 memcpy(map_sysmem(addr, size), __efi_helloworld_begin, size);
447         } else
448 #endif
449 #ifdef CONFIG_CMD_BOOTEFI_SELFTEST
450         if (!strcmp(argv[1], "selftest")) {
451                 struct efi_loaded_image_obj *image_obj;
452                 struct efi_loaded_image *loaded_image_info;
453
454                 if (bootefi_test_prepare(&image_obj, &loaded_image_info,
455                                          "\\selftest", (uintptr_t)&efi_selftest,
456                                          "efi_selftest"))
457                         return CMD_RET_FAILURE;
458
459                 /* Execute the test */
460                 r = efi_selftest(&image_obj->header, &systab);
461                 bootefi_run_finish(image_obj, loaded_image_info);
462                 return r != EFI_SUCCESS;
463         } else
464 #endif
465         if (!strcmp(argv[1], "bootmgr")) {
466                 return do_bootefi_bootmgr_exec();
467         } else {
468                 saddr = argv[1];
469
470                 addr = simple_strtoul(saddr, NULL, 16);
471                 /* Check that a numeric value was passed */
472                 if (!addr && *saddr != '0')
473                         return CMD_RET_USAGE;
474
475         }
476
477         printf("## Starting EFI application at %08lx ...\n", addr);
478         r = do_bootefi_exec(map_sysmem(addr, 0), bootefi_device_path,
479                             bootefi_image_path);
480         printf("## Application terminated, r = %lu\n",
481                r & ~EFI_ERROR_MASK);
482
483         if (r != EFI_SUCCESS)
484                 return 1;
485         else
486                 return 0;
487 }
488
489 #ifdef CONFIG_SYS_LONGHELP
490 static char bootefi_help_text[] =
491         "<image address> [fdt address]\n"
492         "  - boot EFI payload stored at address <image address>.\n"
493         "    If specified, the device tree located at <fdt address> gets\n"
494         "    exposed as EFI configuration table.\n"
495 #ifdef CONFIG_CMD_BOOTEFI_HELLO
496         "bootefi hello\n"
497         "  - boot a sample Hello World application stored within U-Boot\n"
498 #endif
499 #ifdef CONFIG_CMD_BOOTEFI_SELFTEST
500         "bootefi selftest [fdt address]\n"
501         "  - boot an EFI selftest application stored within U-Boot\n"
502         "    Use environment variable efi_selftest to select a single test.\n"
503         "    Use 'setenv efi_selftest list' to enumerate all tests.\n"
504 #endif
505         "bootefi bootmgr [fdt addr]\n"
506         "  - load and boot EFI payload based on BootOrder/BootXXXX variables.\n"
507         "\n"
508         "    If specified, the device tree located at <fdt address> gets\n"
509         "    exposed as EFI configuration table.\n";
510 #endif
511
512 U_BOOT_CMD(
513         bootefi, 3, 0, do_bootefi,
514         "Boots an EFI payload from memory",
515         bootefi_help_text
516 );
517
518 void efi_set_bootdev(const char *dev, const char *devnr, const char *path)
519 {
520         struct efi_device_path *device, *image;
521         efi_status_t ret;
522
523         /* efi_set_bootdev is typically called repeatedly, recover memory */
524         efi_free_pool(bootefi_device_path);
525         efi_free_pool(bootefi_image_path);
526
527         ret = efi_dp_from_name(dev, devnr, path, &device, &image);
528         if (ret == EFI_SUCCESS) {
529                 bootefi_device_path = device;
530                 bootefi_image_path = image;
531         } else {
532                 bootefi_device_path = NULL;
533                 bootefi_image_path = NULL;
534         }
535 }