efi: Split out test init/uninit into functions
[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 <charset.h>
9 #include <common.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/global_data.h>
20 #include <asm-generic/sections.h>
21 #include <asm-generic/unaligned.h>
22 #include <linux/linkage.h>
23
24 #ifdef CONFIG_ARMV7_NONSEC
25 #include <asm/armv7.h>
26 #include <asm/secure.h>
27 #endif
28
29 DECLARE_GLOBAL_DATA_PTR;
30
31 #define OBJ_LIST_NOT_INITIALIZED 1
32
33 static efi_status_t efi_obj_list_initialized = OBJ_LIST_NOT_INITIALIZED;
34
35 static struct efi_device_path *bootefi_image_path;
36 static struct efi_device_path *bootefi_device_path;
37
38 /* Initialize and populate EFI object list */
39 efi_status_t efi_init_obj_list(void)
40 {
41         efi_status_t ret = EFI_SUCCESS;
42
43         /*
44          * On the ARM architecture gd is mapped to a fixed register (r9 or x18).
45          * As this register may be overwritten by an EFI payload we save it here
46          * and restore it on every callback entered.
47          */
48         efi_save_gd();
49
50         /* Initialize once only */
51         if (efi_obj_list_initialized != OBJ_LIST_NOT_INITIALIZED)
52                 return efi_obj_list_initialized;
53
54         /* Initialize system table */
55         ret = efi_initialize_system_table();
56         if (ret != EFI_SUCCESS)
57                 goto out;
58
59         /* Initialize root node */
60         ret = efi_root_node_register();
61         if (ret != EFI_SUCCESS)
62                 goto out;
63
64         /* Initialize EFI driver uclass */
65         ret = efi_driver_init();
66         if (ret != EFI_SUCCESS)
67                 goto out;
68
69         ret = efi_console_register();
70         if (ret != EFI_SUCCESS)
71                 goto out;
72 #ifdef CONFIG_PARTITIONS
73         ret = efi_disk_register();
74         if (ret != EFI_SUCCESS)
75                 goto out;
76 #endif
77 #if defined(CONFIG_LCD) || defined(CONFIG_DM_VIDEO)
78         ret = efi_gop_register();
79         if (ret != EFI_SUCCESS)
80                 goto out;
81 #endif
82 #ifdef CONFIG_NET
83         ret = efi_net_register();
84         if (ret != EFI_SUCCESS)
85                 goto out;
86 #endif
87 #ifdef CONFIG_GENERATE_ACPI_TABLE
88         ret = efi_acpi_register();
89         if (ret != EFI_SUCCESS)
90                 goto out;
91 #endif
92 #ifdef CONFIG_GENERATE_SMBIOS_TABLE
93         ret = efi_smbios_register();
94         if (ret != EFI_SUCCESS)
95                 goto out;
96 #endif
97         ret = efi_watchdog_register();
98         if (ret != EFI_SUCCESS)
99                 goto out;
100
101         /* Initialize EFI runtime services */
102         ret = efi_reset_system_init();
103         if (ret != EFI_SUCCESS)
104                 goto out;
105
106 out:
107         efi_obj_list_initialized = ret;
108         return ret;
109 }
110
111 /*
112  * Allow unaligned memory access.
113  *
114  * This routine is overridden by architectures providing this feature.
115  */
116 void __weak allow_unaligned(void)
117 {
118 }
119
120 /*
121  * Set the load options of an image from an environment variable.
122  *
123  * @loaded_image_info:  the image
124  * @env_var:            name of the environment variable
125  */
126 static void set_load_options(struct efi_loaded_image *loaded_image_info,
127                              const char *env_var)
128 {
129         size_t size;
130         const char *env = env_get(env_var);
131         u16 *pos;
132
133         loaded_image_info->load_options = NULL;
134         loaded_image_info->load_options_size = 0;
135         if (!env)
136                 return;
137         size = utf8_utf16_strlen(env) + 1;
138         loaded_image_info->load_options = calloc(size, sizeof(u16));
139         if (!loaded_image_info->load_options) {
140                 printf("ERROR: Out of memory\n");
141                 return;
142         }
143         pos = loaded_image_info->load_options;
144         utf8_utf16_strcpy(&pos, env);
145         loaded_image_info->load_options_size = size * 2;
146 }
147
148 /**
149  * copy_fdt() - Copy the device tree to a new location available to EFI
150  *
151  * The FDT is relocated into a suitable location within the EFI memory map.
152  * An additional 12KB is added to the space in case the device tree needs to be
153  * expanded later with fdt_open_into().
154  *
155  * @fdt_addr:   On entry, address of start of FDT. On exit, address of relocated
156  *              FDT start
157  * Return:      status code
158  */
159 static efi_status_t copy_fdt(ulong *fdt_addrp)
160 {
161         unsigned long fdt_ram_start = -1L, fdt_pages;
162         efi_status_t ret = 0;
163         void *fdt, *new_fdt;
164         u64 new_fdt_addr;
165         uint fdt_size;
166         int i;
167
168         for (i = 0; i < CONFIG_NR_DRAM_BANKS; i++) {
169                 u64 ram_start = gd->bd->bi_dram[i].start;
170                 u64 ram_size = gd->bd->bi_dram[i].size;
171
172                 if (!ram_size)
173                         continue;
174
175                 if (ram_start < fdt_ram_start)
176                         fdt_ram_start = ram_start;
177         }
178
179         /*
180          * Give us at least 4KB of breathing room in case the device tree needs
181          * to be expanded later. Round up to the nearest EFI page boundary.
182          */
183         fdt = map_sysmem(*fdt_addrp, 0);
184         fdt_size = fdt_totalsize(fdt);
185         fdt_size += 4096 * 3;
186         fdt_size = ALIGN(fdt_size + EFI_PAGE_SIZE - 1, EFI_PAGE_SIZE);
187         fdt_pages = fdt_size >> EFI_PAGE_SHIFT;
188
189         /* Safe fdt location is at 127MB */
190         new_fdt_addr = fdt_ram_start + (127 * 1024 * 1024) + fdt_size;
191         ret = efi_allocate_pages(EFI_ALLOCATE_MAX_ADDRESS,
192                                  EFI_RUNTIME_SERVICES_DATA, fdt_pages,
193                                  &new_fdt_addr);
194         if (ret != EFI_SUCCESS) {
195                 /* If we can't put it there, put it somewhere */
196                 new_fdt_addr = (ulong)memalign(EFI_PAGE_SIZE, fdt_size);
197                 ret = efi_allocate_pages(EFI_ALLOCATE_MAX_ADDRESS,
198                                          EFI_RUNTIME_SERVICES_DATA, fdt_pages,
199                                          &new_fdt_addr);
200                 if (ret != EFI_SUCCESS) {
201                         printf("ERROR: Failed to reserve space for FDT\n");
202                         goto done;
203                 }
204         }
205
206         new_fdt = map_sysmem(new_fdt_addr, fdt_size);
207         memcpy(new_fdt, fdt, fdt_totalsize(fdt));
208         fdt_set_totalsize(new_fdt, fdt_size);
209
210         *fdt_addrp = new_fdt_addr;
211 done:
212         return ret;
213 }
214
215 static efi_status_t efi_do_enter(
216                         efi_handle_t image_handle, struct efi_system_table *st,
217                         EFIAPI efi_status_t (*entry)(
218                                 efi_handle_t image_handle,
219                                 struct efi_system_table *st))
220 {
221         efi_status_t ret = EFI_LOAD_ERROR;
222
223         if (entry)
224                 ret = entry(image_handle, st);
225         st->boottime->exit(image_handle, ret, 0, NULL);
226         return ret;
227 }
228
229 #ifdef CONFIG_ARM64
230 static efi_status_t efi_run_in_el2(EFIAPI efi_status_t (*entry)(
231                         efi_handle_t image_handle, struct efi_system_table *st),
232                         efi_handle_t image_handle, struct efi_system_table *st)
233 {
234         /* Enable caches again */
235         dcache_enable();
236
237         return efi_do_enter(image_handle, st, entry);
238 }
239 #endif
240
241 #ifdef CONFIG_ARMV7_NONSEC
242 static bool is_nonsec;
243
244 static efi_status_t efi_run_in_hyp(EFIAPI efi_status_t (*entry)(
245                         efi_handle_t image_handle, struct efi_system_table *st),
246                         efi_handle_t image_handle, struct efi_system_table *st)
247 {
248         /* Enable caches again */
249         dcache_enable();
250
251         is_nonsec = true;
252
253         return efi_do_enter(image_handle, st, entry);
254 }
255 #endif
256
257 /*
258  * efi_carve_out_dt_rsv() - Carve out DT reserved memory ranges
259  *
260  * The mem_rsv entries of the FDT are added to the memory map. Any failures are
261  * ignored because this is not critical and we would rather continue to try to
262  * boot.
263  *
264  * @fdt: Pointer to device tree
265  */
266 static void efi_carve_out_dt_rsv(void *fdt)
267 {
268         int nr_rsv, i;
269         uint64_t addr, size, pages;
270
271         nr_rsv = fdt_num_mem_rsv(fdt);
272
273         /* Look for an existing entry and add it to the efi mem map. */
274         for (i = 0; i < nr_rsv; i++) {
275                 if (fdt_get_mem_rsv(fdt, i, &addr, &size) != 0)
276                         continue;
277
278                 /*
279                  * Do not carve out the device tree. It is already marked as
280                  * EFI_RUNTIME_SERVICES_DATA
281                  */
282                 if (addr == (uintptr_t)fdt)
283                         continue;
284
285                 pages = ALIGN(size + (addr & EFI_PAGE_MASK), EFI_PAGE_SIZE) >>
286                         EFI_PAGE_SHIFT;
287                 addr &= ~EFI_PAGE_MASK;
288                 if (!efi_add_memory_map(addr, pages, EFI_RESERVED_MEMORY_TYPE,
289                                         false))
290                         printf("FDT memrsv map %d: Failed to add to map\n", i);
291         }
292 }
293
294 static efi_status_t efi_install_fdt(ulong fdt_addr)
295 {
296         bootm_headers_t img = { 0 };
297         efi_status_t ret;
298         void *fdt;
299
300         fdt = map_sysmem(fdt_addr, 0);
301         if (fdt_check_header(fdt)) {
302                 printf("ERROR: invalid device tree\n");
303                 return EFI_INVALID_PARAMETER;
304         }
305
306         /* Prepare fdt for payload */
307         ret = copy_fdt(&fdt_addr);
308         if (ret)
309                 return ret;
310
311         unmap_sysmem(fdt);
312         fdt = map_sysmem(fdt_addr, 0);
313         if (image_setup_libfdt(&img, fdt, 0, NULL)) {
314                 printf("ERROR: failed to process device tree\n");
315                 return EFI_LOAD_ERROR;
316         }
317
318         efi_carve_out_dt_rsv(fdt);
319
320         /* Link to it in the efi tables */
321         ret = efi_install_configuration_table(&efi_guid_fdt, fdt);
322         if (ret != EFI_SUCCESS)
323                 return EFI_OUT_OF_RESOURCES;
324
325         return ret;
326 }
327
328 /**
329  * do_bootefi_exec() - execute EFI binary
330  *
331  * @efi:                address of the binary
332  * @device_path:        path of the device from which the binary was loaded
333  * @image_path:         device path of the binary
334  * Return:              status code
335  *
336  * Load the EFI binary into a newly assigned memory unwinding the relocation
337  * information, install the loaded image protocol, and call the binary.
338  */
339 static efi_status_t do_bootefi_exec(void *efi,
340                                     struct efi_device_path *device_path,
341                                     struct efi_device_path *image_path)
342 {
343         efi_handle_t mem_handle = NULL;
344         struct efi_device_path *memdp = NULL;
345         efi_status_t ret;
346         struct efi_loaded_image_obj *image_obj = NULL;
347         struct efi_loaded_image *loaded_image_info = NULL;
348
349         EFIAPI efi_status_t (*entry)(efi_handle_t image_handle,
350                                      struct efi_system_table *st);
351
352         /*
353          * Special case for efi payload not loaded from disk, such as
354          * 'bootefi hello' or for example payload loaded directly into
355          * memory via JTAG, etc:
356          */
357         if (!device_path && !image_path) {
358                 printf("WARNING: using memory device/image path, this may confuse some payloads!\n");
359                 /* actual addresses filled in after efi_load_pe() */
360                 memdp = efi_dp_from_mem(0, 0, 0);
361                 device_path = image_path = memdp;
362                 /*
363                  * Grub expects that the device path of the loaded image is
364                  * installed on a handle.
365                  */
366                 ret = efi_create_handle(&mem_handle);
367                 if (ret != EFI_SUCCESS)
368                         goto exit;
369                 ret = efi_add_protocol(mem_handle, &efi_guid_device_path,
370                                        device_path);
371                 if (ret != EFI_SUCCESS)
372                         goto exit;
373         } else {
374                 assert(device_path && image_path);
375         }
376
377         ret = efi_setup_loaded_image(device_path, image_path, &image_obj,
378                                      &loaded_image_info);
379         if (ret != EFI_SUCCESS)
380                 goto exit;
381
382         /* Transfer environment variable bootargs as load options */
383         set_load_options(loaded_image_info, "bootargs");
384         /* Load the EFI payload */
385         entry = efi_load_pe(image_obj, efi, loaded_image_info);
386         if (!entry) {
387                 ret = EFI_LOAD_ERROR;
388                 goto exit;
389         }
390
391         if (memdp) {
392                 struct efi_device_path_memory *mdp = (void *)memdp;
393                 mdp->memory_type = loaded_image_info->image_code_type;
394                 mdp->start_address = (uintptr_t)loaded_image_info->image_base;
395                 mdp->end_address = mdp->start_address +
396                                 loaded_image_info->image_size;
397         }
398
399         /* we don't support much: */
400         env_set("efi_8be4df61-93ca-11d2-aa0d-00e098032b8c_OsIndicationsSupported",
401                 "{ro,boot}(blob)0000000000000000");
402
403         /* Call our payload! */
404         debug("%s:%d Jumping to 0x%lx\n", __func__, __LINE__, (long)entry);
405
406         if (setjmp(&image_obj->exit_jmp)) {
407                 ret = image_obj->exit_status;
408                 goto exit;
409         }
410
411 #ifdef CONFIG_ARM64
412         /* On AArch64 we need to make sure we call our payload in < EL3 */
413         if (current_el() == 3) {
414                 smp_kick_all_cpus();
415                 dcache_disable();       /* flush cache before switch to EL2 */
416
417                 /* Move into EL2 and keep running there */
418                 armv8_switch_to_el2((ulong)entry,
419                                     (ulong)&image_obj->header,
420                                     (ulong)&systab, 0, (ulong)efi_run_in_el2,
421                                     ES_TO_AARCH64);
422
423                 /* Should never reach here, efi exits with longjmp */
424                 while (1) { }
425         }
426 #endif
427
428 #ifdef CONFIG_ARMV7_NONSEC
429         if (armv7_boot_nonsec() && !is_nonsec) {
430                 dcache_disable();       /* flush cache before switch to HYP */
431
432                 armv7_init_nonsec();
433                 secure_ram_addr(_do_nonsec_entry)(
434                                         efi_run_in_hyp,
435                                         (uintptr_t)entry,
436                                         (uintptr_t)&image_obj->header,
437                                         (uintptr_t)&systab);
438
439                 /* Should never reach here, efi exits with longjmp */
440                 while (1) { }
441         }
442 #endif
443
444         ret = efi_do_enter(&image_obj->header, &systab, entry);
445
446 exit:
447         /* image has returned, loaded-image obj goes *poof*: */
448         if (image_obj)
449                 efi_delete_handle(&image_obj->header);
450         if (mem_handle)
451                 efi_delete_handle(mem_handle);
452
453         return ret;
454 }
455
456 #ifdef CONFIG_CMD_BOOTEFI_SELFTEST
457 /**
458  * bootefi_test_prepare() - prepare to run an EFI test
459  *
460  * This sets things up so we can call EFI functions. This involves preparing
461  * the 'gd' pointer and setting up the load ed image data structures.
462  *
463  * @image_objp: loaded_image_infop: Pointer to a struct which will hold the
464  *    loaded image object. This struct will be inited by this function before
465  *    use.
466  * @loaded_image_infop: Pointer to a struct which will hold the loaded image
467  *    info. This struct will be inited by this function before use.
468  * @path: File path to the test being run (often just the test name with a
469  *    backslash before it
470  * @test_func: Address of the test function that is being run
471  * @return 0 if OK, -ve on error
472  */
473 static efi_status_t bootefi_test_prepare
474                 (struct efi_loaded_image_obj **image_objp,
475                 struct efi_loaded_image **loaded_image_infop,
476                 const char *path,
477                 ulong test_func)
478 {
479         efi_status_t r;
480
481         /* Construct a dummy device path */
482         bootefi_device_path = efi_dp_from_mem(EFI_RESERVED_MEMORY_TYPE,
483                                               (uintptr_t)test_func,
484                                               (uintptr_t)test_func);
485         if (!bootefi_device_path)
486                 return EFI_OUT_OF_RESOURCES;
487         bootefi_image_path = efi_dp_from_file(NULL, 0, path);
488         if (!bootefi_image_path)
489                 return EFI_OUT_OF_RESOURCES;
490         r = efi_setup_loaded_image(bootefi_device_path, bootefi_image_path,
491                                    image_objp, loaded_image_infop);
492         if (r)
493                 return r;
494
495         /* Transfer environment variable efi_selftest as load options */
496         set_load_options(*loaded_image_infop, "efi_selftest");
497
498         return 0;
499 }
500
501 /**
502  * bootefi_test_finish() - finish up after running an EFI test
503  *
504  * @image_obj: Pointer to a struct which holds the loaded image object
505  * @loaded_image_info: Pointer to a struct which holds the loaded image info
506  */
507 static void bootefi_test_finish(struct efi_loaded_image_obj *image_obj,
508                                 struct efi_loaded_image *loaded_image_info)
509 {
510         efi_restore_gd();
511         free(loaded_image_info->load_options);
512         efi_delete_handle(&image_obj->header);
513 }
514 #endif /* CONFIG_CMD_BOOTEFI_SELFTEST */
515
516 static int do_bootefi_bootmgr_exec(void)
517 {
518         struct efi_device_path *device_path, *file_path;
519         void *addr;
520         efi_status_t r;
521
522         addr = efi_bootmgr_load(&device_path, &file_path);
523         if (!addr)
524                 return 1;
525
526         printf("## Starting EFI application at %p ...\n", addr);
527         r = do_bootefi_exec(addr, device_path, file_path);
528         printf("## Application terminated, r = %lu\n",
529                r & ~EFI_ERROR_MASK);
530
531         if (r != EFI_SUCCESS)
532                 return 1;
533
534         return 0;
535 }
536
537 /* Interpreter command to boot an arbitrary EFI image from memory */
538 static int do_bootefi(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
539 {
540         unsigned long addr;
541         char *saddr;
542         efi_status_t r;
543         unsigned long fdt_addr;
544
545         /* Allow unaligned memory access */
546         allow_unaligned();
547
548         /* Initialize EFI drivers */
549         r = efi_init_obj_list();
550         if (r != EFI_SUCCESS) {
551                 printf("Error: Cannot set up EFI drivers, r = %lu\n",
552                        r & ~EFI_ERROR_MASK);
553                 return CMD_RET_FAILURE;
554         }
555
556         if (argc < 2)
557                 return CMD_RET_USAGE;
558
559         if (argc > 2) {
560                 fdt_addr = simple_strtoul(argv[2], NULL, 16);
561                 if (!fdt_addr && *argv[2] != '0')
562                         return CMD_RET_USAGE;
563                 /* Install device tree */
564                 r = efi_install_fdt(fdt_addr);
565                 if (r != EFI_SUCCESS) {
566                         printf("ERROR: failed to install device tree\n");
567                         return CMD_RET_FAILURE;
568                 }
569         } else {
570                 /* Remove device tree. EFI_NOT_FOUND can be ignored here */
571                 efi_install_configuration_table(&efi_guid_fdt, NULL);
572                 printf("WARNING: booting without device tree\n");
573         }
574 #ifdef CONFIG_CMD_BOOTEFI_HELLO
575         if (!strcmp(argv[1], "hello")) {
576                 ulong size = __efi_helloworld_end - __efi_helloworld_begin;
577
578                 saddr = env_get("loadaddr");
579                 if (saddr)
580                         addr = simple_strtoul(saddr, NULL, 16);
581                 else
582                         addr = CONFIG_SYS_LOAD_ADDR;
583                 memcpy(map_sysmem(addr, size), __efi_helloworld_begin, size);
584         } else
585 #endif
586 #ifdef CONFIG_CMD_BOOTEFI_SELFTEST
587         if (!strcmp(argv[1], "selftest")) {
588                 struct efi_loaded_image_obj *image_obj;
589                 struct efi_loaded_image *loaded_image_info;
590
591                 if (bootefi_test_prepare(&image_obj, &loaded_image_info,
592                                          "\\selftest",
593                                          (uintptr_t)&efi_selftest))
594                         return CMD_RET_FAILURE;
595
596                 /* Execute the test */
597                 r = efi_selftest(&image_obj->header, &systab);
598                 bootefi_test_finish(image_obj, loaded_image_info);
599                 return r != EFI_SUCCESS;
600         } else
601 #endif
602         if (!strcmp(argv[1], "bootmgr")) {
603                 return do_bootefi_bootmgr_exec();
604         } else {
605                 saddr = argv[1];
606
607                 addr = simple_strtoul(saddr, NULL, 16);
608                 /* Check that a numeric value was passed */
609                 if (!addr && *saddr != '0')
610                         return CMD_RET_USAGE;
611
612         }
613
614         printf("## Starting EFI application at %08lx ...\n", addr);
615         r = do_bootefi_exec(map_sysmem(addr, 0), bootefi_device_path,
616                             bootefi_image_path);
617         printf("## Application terminated, r = %lu\n",
618                r & ~EFI_ERROR_MASK);
619
620         if (r != EFI_SUCCESS)
621                 return 1;
622         else
623                 return 0;
624 }
625
626 #ifdef CONFIG_SYS_LONGHELP
627 static char bootefi_help_text[] =
628         "<image address> [fdt address]\n"
629         "  - boot EFI payload stored at address <image address>.\n"
630         "    If specified, the device tree located at <fdt address> gets\n"
631         "    exposed as EFI configuration table.\n"
632 #ifdef CONFIG_CMD_BOOTEFI_HELLO
633         "bootefi hello\n"
634         "  - boot a sample Hello World application stored within U-Boot\n"
635 #endif
636 #ifdef CONFIG_CMD_BOOTEFI_SELFTEST
637         "bootefi selftest [fdt address]\n"
638         "  - boot an EFI selftest application stored within U-Boot\n"
639         "    Use environment variable efi_selftest to select a single test.\n"
640         "    Use 'setenv efi_selftest list' to enumerate all tests.\n"
641 #endif
642         "bootefi bootmgr [fdt addr]\n"
643         "  - load and boot EFI payload based on BootOrder/BootXXXX variables.\n"
644         "\n"
645         "    If specified, the device tree located at <fdt address> gets\n"
646         "    exposed as EFI configuration table.\n";
647 #endif
648
649 U_BOOT_CMD(
650         bootefi, 3, 0, do_bootefi,
651         "Boots an EFI payload from memory",
652         bootefi_help_text
653 );
654
655 void efi_set_bootdev(const char *dev, const char *devnr, const char *path)
656 {
657         struct efi_device_path *device, *image;
658         efi_status_t ret;
659
660         /* efi_set_bootdev is typically called repeatedly, recover memory */
661         efi_free_pool(bootefi_device_path);
662         efi_free_pool(bootefi_image_path);
663
664         ret = efi_dp_from_name(dev, devnr, path, &device, &image);
665         if (ret == EFI_SUCCESS) {
666                 bootefi_device_path = device;
667                 bootefi_image_path = image;
668         } else {
669                 bootefi_device_path = NULL;
670                 bootefi_image_path = NULL;
671         }
672 }