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