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