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