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