efi_loader: clean up UEFI sub-system initialization
[oweals/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 <charset.h>
10 #include <command.h>
11 #include <dm.h>
12 #include <efi_loader.h>
13 #include <efi_selftest.h>
14 #include <errno.h>
15 #include <linux/libfdt.h>
16 #include <linux/libfdt_env.h>
17 #include <mapmem.h>
18 #include <memalign.h>
19 #include <asm-generic/sections.h>
20 #include <linux/linkage.h>
21
22 DECLARE_GLOBAL_DATA_PTR;
23
24 static struct efi_device_path *bootefi_image_path;
25 static struct efi_device_path *bootefi_device_path;
26
27 /*
28  * Set the load options of an image from an environment variable.
29  *
30  * @handle:     the image handle
31  * @env_var:    name of the environment variable
32  * Return:      status code
33  */
34 static efi_status_t set_load_options(efi_handle_t handle, const char *env_var)
35 {
36         struct efi_loaded_image *loaded_image_info;
37         size_t size;
38         const char *env = env_get(env_var);
39         u16 *pos;
40         efi_status_t ret;
41
42         ret = EFI_CALL(systab.boottime->open_protocol(
43                                         handle,
44                                         &efi_guid_loaded_image,
45                                         (void **)&loaded_image_info,
46                                         efi_root, NULL,
47                                         EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL));
48         if (ret != EFI_SUCCESS)
49                 return EFI_INVALID_PARAMETER;
50
51         loaded_image_info->load_options = NULL;
52         loaded_image_info->load_options_size = 0;
53         if (!env)
54                 goto out;
55
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                 EFI_CALL(systab.boottime->close_protocol(handle,
61                                                          &efi_guid_loaded_image,
62                                                          efi_root, NULL));
63                 return EFI_OUT_OF_RESOURCES;
64         }
65         pos = loaded_image_info->load_options;
66         utf8_utf16_strcpy(&pos, env);
67         loaded_image_info->load_options_size = size * 2;
68
69 out:
70         return EFI_CALL(systab.boottime->close_protocol(handle,
71                                                         &efi_guid_loaded_image,
72                                                         efi_root, NULL));
73 }
74
75 #if !CONFIG_IS_ENABLED(GENERATE_ACPI_TABLE)
76
77 /**
78  * copy_fdt() - Copy the device tree to a new location available to EFI
79  *
80  * The FDT is copied to a suitable location within the EFI memory map.
81  * Additional 12 KiB are added to the space in case the device tree needs to be
82  * expanded later with fdt_open_into().
83  *
84  * @fdtp:       On entry a pointer to the flattened device tree.
85  *              On exit a pointer to the copy of the flattened device tree.
86  *              FDT start
87  * Return:      status code
88  */
89 static efi_status_t copy_fdt(void **fdtp)
90 {
91         unsigned long fdt_ram_start = -1L, fdt_pages;
92         efi_status_t ret = 0;
93         void *fdt, *new_fdt;
94         u64 new_fdt_addr;
95         uint fdt_size;
96         int i;
97
98         for (i = 0; i < CONFIG_NR_DRAM_BANKS; i++) {
99                 u64 ram_start = gd->bd->bi_dram[i].start;
100                 u64 ram_size = gd->bd->bi_dram[i].size;
101
102                 if (!ram_size)
103                         continue;
104
105                 if (ram_start < fdt_ram_start)
106                         fdt_ram_start = ram_start;
107         }
108
109         /*
110          * Give us at least 12 KiB of breathing room in case the device tree
111          * needs to be expanded later.
112          */
113         fdt = *fdtp;
114         fdt_pages = efi_size_in_pages(fdt_totalsize(fdt) + 0x3000);
115         fdt_size = fdt_pages << EFI_PAGE_SHIFT;
116
117         /*
118          * Safe fdt location is at 127 MiB.
119          * On the sandbox convert from the sandbox address space.
120          */
121         new_fdt_addr = (uintptr_t)map_sysmem(fdt_ram_start + 0x7f00000 +
122                                              fdt_size, 0);
123         ret = efi_allocate_pages(EFI_ALLOCATE_MAX_ADDRESS,
124                                  EFI_BOOT_SERVICES_DATA, fdt_pages,
125                                  &new_fdt_addr);
126         if (ret != EFI_SUCCESS) {
127                 /* If we can't put it there, put it somewhere */
128                 new_fdt_addr = (ulong)memalign(EFI_PAGE_SIZE, fdt_size);
129                 ret = efi_allocate_pages(EFI_ALLOCATE_MAX_ADDRESS,
130                                          EFI_BOOT_SERVICES_DATA, fdt_pages,
131                                          &new_fdt_addr);
132                 if (ret != EFI_SUCCESS) {
133                         printf("ERROR: Failed to reserve space for FDT\n");
134                         goto done;
135                 }
136         }
137         new_fdt = (void *)(uintptr_t)new_fdt_addr;
138         memcpy(new_fdt, fdt, fdt_totalsize(fdt));
139         fdt_set_totalsize(new_fdt, fdt_size);
140
141         *fdtp = (void *)(uintptr_t)new_fdt_addr;
142 done:
143         return ret;
144 }
145
146 /*
147  * efi_carve_out_dt_rsv() - Carve out DT reserved memory ranges
148  *
149  * The mem_rsv entries of the FDT are added to the memory map. Any failures are
150  * ignored because this is not critical and we would rather continue to try to
151  * boot.
152  *
153  * @fdt: Pointer to device tree
154  */
155 static void efi_carve_out_dt_rsv(void *fdt)
156 {
157         int nr_rsv, i;
158         uint64_t addr, size, pages;
159
160         nr_rsv = fdt_num_mem_rsv(fdt);
161
162         /* Look for an existing entry and add it to the efi mem map. */
163         for (i = 0; i < nr_rsv; i++) {
164                 if (fdt_get_mem_rsv(fdt, i, &addr, &size) != 0)
165                         continue;
166
167                 /* Convert from sandbox address space. */
168                 addr = (uintptr_t)map_sysmem(addr, 0);
169
170                 pages = efi_size_in_pages(size + (addr & EFI_PAGE_MASK));
171                 addr &= ~EFI_PAGE_MASK;
172                 if (!efi_add_memory_map(addr, pages, EFI_RESERVED_MEMORY_TYPE,
173                                         false))
174                         printf("FDT memrsv map %d: Failed to add to map\n", i);
175         }
176 }
177
178 /**
179  * get_config_table() - get configuration table
180  *
181  * @guid:       GUID of the configuration table
182  * Return:      pointer to configuration table or NULL
183  */
184 static void *get_config_table(const efi_guid_t *guid)
185 {
186         size_t i;
187
188         for (i = 0; i < systab.nr_tables; i++) {
189                 if (!guidcmp(guid, &systab.tables[i].guid))
190                         return systab.tables[i].table;
191         }
192         return NULL;
193 }
194
195 #endif /* !CONFIG_IS_ENABLED(GENERATE_ACPI_TABLE) */
196
197 /**
198  * efi_install_fdt() - install fdt passed by a command argument
199  * @fdt_opt:    pointer to argument
200  * Return:      status code
201  *
202  * If specified, fdt will be installed as configuration table,
203  * otherwise no fdt will be passed.
204  */
205 static efi_status_t efi_install_fdt(const char *fdt_opt)
206 {
207         /*
208          * The EBBR spec requires that we have either an FDT or an ACPI table
209          * but not both.
210          */
211 #if CONFIG_IS_ENABLED(GENERATE_ACPI_TABLE)
212         if (fdt_opt) {
213                 printf("ERROR: can't have ACPI table and device tree.\n");
214                 return EFI_LOAD_ERROR;
215         }
216 #else
217         unsigned long fdt_addr;
218         void *fdt;
219         bootm_headers_t img = { 0 };
220         efi_status_t ret;
221
222         if (fdt_opt) {
223                 fdt_addr = simple_strtoul(fdt_opt, NULL, 16);
224                 if (!fdt_addr)
225                         return EFI_INVALID_PARAMETER;
226         } else {
227                 /* Look for device tree that is already installed */
228                 if (get_config_table(&efi_guid_fdt))
229                         return EFI_SUCCESS;
230                 /* Use our own device tree as default */
231                 fdt_opt = env_get("fdtcontroladdr");
232                 if (!fdt_opt) {
233                         printf("ERROR: need device tree\n");
234                         return EFI_NOT_FOUND;
235                 }
236                 fdt_addr = simple_strtoul(fdt_opt, NULL, 16);
237                 if (!fdt_addr) {
238                         printf("ERROR: invalid $fdtcontroladdr\n");
239                         return EFI_LOAD_ERROR;
240                 }
241         }
242
243         /* Install device tree */
244         fdt = map_sysmem(fdt_addr, 0);
245         if (fdt_check_header(fdt)) {
246                 printf("ERROR: invalid device tree\n");
247                 return EFI_LOAD_ERROR;
248         }
249
250         /* Create memory reservations as indicated by the device tree */
251         efi_carve_out_dt_rsv(fdt);
252
253         /* Prepare device tree for payload */
254         ret = copy_fdt(&fdt);
255         if (ret) {
256                 printf("ERROR: out of memory\n");
257                 return EFI_OUT_OF_RESOURCES;
258         }
259
260         if (image_setup_libfdt(&img, fdt, 0, NULL)) {
261                 printf("ERROR: failed to process device tree\n");
262                 return EFI_LOAD_ERROR;
263         }
264
265         /* Install device tree as UEFI table */
266         ret = efi_install_configuration_table(&efi_guid_fdt, fdt);
267         if (ret != EFI_SUCCESS) {
268                 printf("ERROR: failed to install device tree\n");
269                 return ret;
270         }
271 #endif /* GENERATE_ACPI_TABLE */
272
273         return EFI_SUCCESS;
274 }
275
276 /**
277  * do_bootefi_exec() - execute EFI binary
278  *
279  * @handle:             handle of loaded image
280  * Return:              status code
281  *
282  * Load the EFI binary into a newly assigned memory unwinding the relocation
283  * information, install the loaded image protocol, and call the binary.
284  */
285 static efi_status_t do_bootefi_exec(efi_handle_t handle)
286 {
287         efi_status_t ret;
288         efi_uintn_t exit_data_size = 0;
289         u16 *exit_data = NULL;
290
291         /* Transfer environment variable as load options */
292         ret = set_load_options(handle, "bootargs");
293         if (ret != EFI_SUCCESS)
294                 return ret;
295
296         /* Call our payload! */
297         ret = EFI_CALL(efi_start_image(handle, &exit_data_size, &exit_data));
298         printf("## Application terminated, r = %lu\n", ret & ~EFI_ERROR_MASK);
299         if (ret && exit_data) {
300                 printf("## %ls\n", exit_data);
301                 efi_free_pool(exit_data);
302         }
303
304         efi_restore_gd();
305
306         /*
307          * FIXME: Who is responsible for
308          *      free(loaded_image_info->load_options);
309          * Once efi_exit() is implemented correctly,
310          * handle itself doesn't exist here.
311          */
312
313         return ret;
314 }
315
316 /**
317  * do_efibootmgr() - execute EFI Boot Manager
318  *
319  * @fdt_opt:    string of fdt start address
320  * Return:      status code
321  *
322  * Execute EFI Boot Manager
323  */
324 static int do_efibootmgr(const char *fdt_opt)
325 {
326         efi_handle_t handle;
327         efi_status_t ret;
328
329         /* Initialize EFI drivers */
330         ret = efi_init_obj_list();
331         if (ret != EFI_SUCCESS) {
332                 printf("Error: Cannot initialize UEFI sub-system, r = %lu\n",
333                        ret & ~EFI_ERROR_MASK);
334                 return CMD_RET_FAILURE;
335         }
336
337         ret = efi_install_fdt(fdt_opt);
338         if (ret == EFI_INVALID_PARAMETER)
339                 return CMD_RET_USAGE;
340         else if (ret != EFI_SUCCESS)
341                 return CMD_RET_FAILURE;
342
343         ret = efi_bootmgr_load(&handle);
344         if (ret != EFI_SUCCESS) {
345                 printf("EFI boot manager: Cannot load any image\n");
346                 return CMD_RET_FAILURE;
347         }
348
349         ret = do_bootefi_exec(handle);
350
351         if (ret != EFI_SUCCESS)
352                 return CMD_RET_FAILURE;
353
354         return CMD_RET_SUCCESS;
355 }
356
357 /*
358  * do_bootefi_image() - execute EFI binary from command line
359  *
360  * @image_opt:  string of image start address
361  * @fdt_opt:    string of fdt start address
362  * Return:      status code
363  *
364  * Set up memory image for the binary to be loaded, prepare
365  * device path and then call do_bootefi_exec() to execute it.
366  */
367 static int do_bootefi_image(const char *image_opt, const char *fdt_opt)
368 {
369         void *image_buf;
370         struct efi_device_path *device_path, *image_path;
371         struct efi_device_path *file_path = NULL;
372         unsigned long addr, size;
373         const char *size_str;
374         efi_handle_t mem_handle = NULL, handle;
375         efi_status_t ret;
376
377         /* Initialize EFI drivers */
378         ret = efi_init_obj_list();
379         if (ret != EFI_SUCCESS) {
380                 printf("Error: Cannot initialize UEFI sub-system, r = %lu\n",
381                        ret & ~EFI_ERROR_MASK);
382                 return CMD_RET_FAILURE;
383         }
384
385         ret = efi_install_fdt(fdt_opt);
386         if (ret == EFI_INVALID_PARAMETER)
387                 return CMD_RET_USAGE;
388         else if (ret != EFI_SUCCESS)
389                 return CMD_RET_FAILURE;
390
391 #ifdef CONFIG_CMD_BOOTEFI_HELLO
392         if (!strcmp(image_opt, "hello")) {
393                 char *saddr;
394
395                 saddr = env_get("loadaddr");
396                 size = __efi_helloworld_end - __efi_helloworld_begin;
397
398                 if (saddr)
399                         addr = simple_strtoul(saddr, NULL, 16);
400                 else
401                         addr = CONFIG_SYS_LOAD_ADDR;
402
403                 image_buf = map_sysmem(addr, size);
404                 memcpy(image_buf, __efi_helloworld_begin, size);
405
406                 device_path = NULL;
407                 image_path = NULL;
408         } else
409 #endif
410         {
411                 size_str = env_get("filesize");
412                 if (size_str)
413                         size = simple_strtoul(size_str, NULL, 16);
414                 else
415                         size = 0;
416
417                 addr = simple_strtoul(image_opt, NULL, 16);
418                 /* Check that a numeric value was passed */
419                 if (!addr && *image_opt != '0')
420                         return CMD_RET_USAGE;
421
422                 image_buf = map_sysmem(addr, size);
423
424                 device_path = bootefi_device_path;
425                 image_path = bootefi_image_path;
426         }
427
428         if (!device_path && !image_path) {
429                 /*
430                  * Special case for efi payload not loaded from disk,
431                  * such as 'bootefi hello' or for example payload
432                  * loaded directly into memory via JTAG, etc:
433                  */
434                 file_path = efi_dp_from_mem(EFI_RESERVED_MEMORY_TYPE,
435                                             (uintptr_t)image_buf, size);
436                 /*
437                  * Make sure that device for device_path exist
438                  * in load_image(). Otherwise, shell and grub will fail.
439                  */
440                 ret = efi_create_handle(&mem_handle);
441                 if (ret != EFI_SUCCESS)
442                         goto out;
443
444                 ret = efi_add_protocol(mem_handle, &efi_guid_device_path,
445                                        file_path);
446                 if (ret != EFI_SUCCESS)
447                         goto out;
448         } else {
449                 assert(device_path && image_path);
450                 file_path = efi_dp_append(device_path, image_path);
451         }
452
453         ret = EFI_CALL(efi_load_image(false, efi_root,
454                                       file_path, image_buf, size, &handle));
455         if (ret != EFI_SUCCESS)
456                 goto out;
457
458         ret = do_bootefi_exec(handle);
459
460 out:
461         if (mem_handle)
462                 efi_delete_handle(mem_handle);
463         if (file_path)
464                 efi_free_pool(file_path);
465
466         if (ret != EFI_SUCCESS)
467                 return CMD_RET_FAILURE;
468
469         return CMD_RET_SUCCESS;
470 }
471
472 #ifdef CONFIG_CMD_BOOTEFI_SELFTEST
473 static efi_status_t bootefi_run_prepare(const char *load_options_path,
474                 struct efi_device_path *device_path,
475                 struct efi_device_path *image_path,
476                 struct efi_loaded_image_obj **image_objp,
477                 struct efi_loaded_image **loaded_image_infop)
478 {
479         efi_status_t ret;
480
481         ret = efi_setup_loaded_image(device_path, image_path, image_objp,
482                                      loaded_image_infop);
483         if (ret != EFI_SUCCESS)
484                 return ret;
485
486         /* Transfer environment variable as load options */
487         return set_load_options((efi_handle_t)*image_objp, load_options_path);
488 }
489
490 /**
491  * bootefi_test_prepare() - prepare to run an EFI test
492  *
493  * Prepare to run a test as if it were provided by a loaded image.
494  *
495  * @image_objp:         pointer to be set to the loaded image handle
496  * @loaded_image_infop: pointer to be set to the loaded image protocol
497  * @path:               dummy file path used to construct the device path
498  *                      set in the loaded image protocol
499  * @load_options_path:  name of a U-Boot environment variable. Its value is
500  *                      set as load options in the loaded image protocol.
501  * Return:              status code
502  */
503 static efi_status_t bootefi_test_prepare
504                 (struct efi_loaded_image_obj **image_objp,
505                  struct efi_loaded_image **loaded_image_infop, const char *path,
506                  const char *load_options_path)
507 {
508         efi_status_t ret;
509
510         /* Construct a dummy device path */
511         bootefi_device_path = efi_dp_from_mem(EFI_RESERVED_MEMORY_TYPE, 0, 0);
512         if (!bootefi_device_path)
513                 return EFI_OUT_OF_RESOURCES;
514
515         bootefi_image_path = efi_dp_from_file(NULL, 0, path);
516         if (!bootefi_image_path) {
517                 ret = EFI_OUT_OF_RESOURCES;
518                 goto failure;
519         }
520
521         ret = bootefi_run_prepare(load_options_path, bootefi_device_path,
522                                   bootefi_image_path, image_objp,
523                                   loaded_image_infop);
524         if (ret == EFI_SUCCESS)
525                 return ret;
526
527         efi_free_pool(bootefi_image_path);
528         bootefi_image_path = NULL;
529 failure:
530         efi_free_pool(bootefi_device_path);
531         bootefi_device_path = NULL;
532         return ret;
533 }
534
535 /**
536  * bootefi_run_finish() - finish up after running an EFI test
537  *
538  * @loaded_image_info: Pointer to a struct which holds the loaded image info
539  * @image_obj: Pointer to a struct which holds the loaded image object
540  */
541 static void bootefi_run_finish(struct efi_loaded_image_obj *image_obj,
542                                struct efi_loaded_image *loaded_image_info)
543 {
544         efi_restore_gd();
545         free(loaded_image_info->load_options);
546         efi_delete_handle(&image_obj->header);
547 }
548
549 /**
550  * do_efi_selftest() - execute EFI Selftest
551  *
552  * @fdt_opt:    string of fdt start address
553  * Return:      status code
554  *
555  * Execute EFI Selftest
556  */
557 static int do_efi_selftest(const char *fdt_opt)
558 {
559         struct efi_loaded_image_obj *image_obj;
560         struct efi_loaded_image *loaded_image_info;
561         efi_status_t ret;
562
563         /* Initialize EFI drivers */
564         ret = efi_init_obj_list();
565         if (ret != EFI_SUCCESS) {
566                 printf("Error: Cannot initialize UEFI sub-system, r = %lu\n",
567                        ret & ~EFI_ERROR_MASK);
568                 return CMD_RET_FAILURE;
569         }
570
571         ret = efi_install_fdt(fdt_opt);
572         if (ret == EFI_INVALID_PARAMETER)
573                 return CMD_RET_USAGE;
574         else if (ret != EFI_SUCCESS)
575                 return CMD_RET_FAILURE;
576
577         ret = bootefi_test_prepare(&image_obj, &loaded_image_info,
578                                    "\\selftest", "efi_selftest");
579         if (ret != EFI_SUCCESS)
580                 return CMD_RET_FAILURE;
581
582         /* Execute the test */
583         ret = EFI_CALL(efi_selftest(&image_obj->header, &systab));
584         bootefi_run_finish(image_obj, loaded_image_info);
585
586         return ret != EFI_SUCCESS;
587 }
588 #endif /* CONFIG_CMD_BOOTEFI_SELFTEST */
589
590 /* Interpreter command to boot an arbitrary EFI image from memory */
591 static int do_bootefi(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
592 {
593         if (argc < 2)
594                 return CMD_RET_USAGE;
595
596         if (!strcmp(argv[1], "bootmgr"))
597                 return do_efibootmgr(argc > 2 ? argv[2] : NULL);
598 #ifdef CONFIG_CMD_BOOTEFI_SELFTEST
599         else if (!strcmp(argv[1], "selftest"))
600                 return do_efi_selftest(argc > 2 ? argv[2] : NULL);
601 #endif
602
603         return do_bootefi_image(argv[1], argc > 2 ? argv[2] : NULL);
604 }
605
606 #ifdef CONFIG_SYS_LONGHELP
607 static char bootefi_help_text[] =
608         "<image address> [fdt address]\n"
609         "  - boot EFI payload stored at address <image address>.\n"
610         "    If specified, the device tree located at <fdt address> gets\n"
611         "    exposed as EFI configuration table.\n"
612 #ifdef CONFIG_CMD_BOOTEFI_HELLO
613         "bootefi hello\n"
614         "  - boot a sample Hello World application stored within U-Boot\n"
615 #endif
616 #ifdef CONFIG_CMD_BOOTEFI_SELFTEST
617         "bootefi selftest [fdt address]\n"
618         "  - boot an EFI selftest application stored within U-Boot\n"
619         "    Use environment variable efi_selftest to select a single test.\n"
620         "    Use 'setenv efi_selftest list' to enumerate all tests.\n"
621 #endif
622         "bootefi bootmgr [fdt address]\n"
623         "  - load and boot EFI payload based on BootOrder/BootXXXX variables.\n"
624         "\n"
625         "    If specified, the device tree located at <fdt address> gets\n"
626         "    exposed as EFI configuration table.\n";
627 #endif
628
629 U_BOOT_CMD(
630         bootefi, 3, 0, do_bootefi,
631         "Boots an EFI payload from memory",
632         bootefi_help_text
633 );
634
635 void efi_set_bootdev(const char *dev, const char *devnr, const char *path)
636 {
637         struct efi_device_path *device, *image;
638         efi_status_t ret;
639
640         /* efi_set_bootdev is typically called repeatedly, recover memory */
641         efi_free_pool(bootefi_device_path);
642         efi_free_pool(bootefi_image_path);
643
644         ret = efi_dp_from_name(dev, devnr, path, &device, &image);
645         if (ret == EFI_SUCCESS) {
646                 bootefi_device_path = device;
647                 if (image) {
648                         /* FIXME: image should not contain device */
649                         struct efi_device_path *image_tmp = image;
650
651                         efi_dp_split_file_path(image, &device, &image);
652                         efi_free_pool(image_tmp);
653                 }
654                 bootefi_image_path = image;
655         } else {
656                 bootefi_device_path = NULL;
657                 bootefi_image_path = NULL;
658         }
659 }