xref: /freebsd/stand/efi/loader/main.c (revision 56970c3c4b0bc61d972837661a31cc2b9e8e8d7c)
1 /*-
2  * Copyright (c) 2008-2010 Rui Paulo
3  * Copyright (c) 2006 Marcel Moolenaar
4  * All rights reserved.
5  *
6  * Copyright (c) 2016-2019 Netflix, Inc. written by M. Warner Losh
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #include <stand.h>
31 
32 #include <sys/disk.h>
33 #include <sys/param.h>
34 #include <sys/reboot.h>
35 #include <sys/boot.h>
36 #ifdef EFI_ZFS_BOOT
37 #include <sys/zfs_bootenv.h>
38 #endif
39 #include <paths.h>
40 #include <netinet/in.h>
41 #include <netinet/in_systm.h>
42 #include <stdint.h>
43 #include <string.h>
44 #include <setjmp.h>
45 #include <disk.h>
46 #include <dev_net.h>
47 #include <net.h>
48 #include <machine/_inttypes.h>
49 
50 #include <efi.h>
51 #include <efilib.h>
52 #include <efichar.h>
53 
54 #include <Guid/DebugImageInfoTable.h>
55 #include <Guid/DxeServices.h>
56 #include <Guid/Mps.h>
57 #include <Guid/SmBios.h>
58 #include <Protocol/Rng.h>
59 #include <Protocol/SimpleNetwork.h>
60 #include <Protocol/SimpleTextIn.h>
61 
62 #include <uuid.h>
63 
64 #include <bootstrap.h>
65 #include <smbios.h>
66 
67 #include <dev/random/fortuna.h>
68 #include <geom/eli/pkcs5v2.h>
69 
70 #include "efizfs.h"
71 #include "framebuffer.h"
72 
73 #include "platform/acfreebsd.h"
74 #include "acconfig.h"
75 #define ACPI_SYSTEM_XFACE
76 #include "actypes.h"
77 #include "actbl.h"
78 
79 #include <acpi_detect.h>
80 
81 #include "loader_efi.h"
82 
83 struct arch_switch archsw = {	/* MI/MD interface boundary */
84 	.arch_autoload = efi_autoload,
85 	.arch_getdev = efi_getdev,
86 	.arch_copyin = efi_copyin,
87 	.arch_copyout = efi_copyout,
88 #if defined(__amd64__) || defined(__i386__)
89 	.arch_hypervisor = x86_hypervisor,
90 #endif
91 	.arch_readin = efi_readin,
92 	.arch_zfs_probe = efi_zfs_probe,
93 };
94 
95 // XXX These are from ???? Maybe ACPI which needs to define them?
96 // XXX EDK2 doesn't (or didn't as of Feb 2025)
97 #define HOB_LIST_TABLE_GUID \
98     { 0x7739f24c, 0x93d7, 0x11d4, {0x9a, 0x3a, 0x0, 0x90, 0x27, 0x3f, 0xc1, 0x4d} }
99 #define LZMA_DECOMPRESSION_GUID \
100 	{ 0xee4e5898, 0x3914, 0x4259, {0x9d, 0x6e, 0xdc, 0x7b, 0xd7, 0x94, 0x3, 0xcf} }
101 #define ARM_MP_CORE_INFO_TABLE_GUID \
102 	{ 0xa4ee0728, 0xe5d7, 0x4ac5, {0xb2, 0x1e, 0x65, 0x8e, 0xd8, 0x57, 0xe8, 0x34} }
103 #define ESRT_TABLE_GUID \
104 	{ 0xb122a263, 0x3661, 0x4f68, {0x99, 0x29, 0x78, 0xf8, 0xb0, 0xd6, 0x21, 0x80} }
105 #define MEMORY_TYPE_INFORMATION_TABLE_GUID \
106     { 0x4c19049f, 0x4137, 0x4dd3, {0x9c, 0x10, 0x8b, 0x97, 0xa8, 0x3f, 0xfd, 0xfa} }
107 #define FDT_TABLE_GUID \
108     { 0xb1b621d5, 0xf19c, 0x41a5, {0x83, 0x0b, 0xd9, 0x15, 0x2c, 0x69, 0xaa, 0xe0} }
109 
110 EFI_GUID devid = DEVICE_PATH_PROTOCOL;
111 EFI_GUID imgid = LOADED_IMAGE_PROTOCOL;
112 EFI_GUID mps = MPS_TABLE_GUID;
113 EFI_GUID netid = EFI_SIMPLE_NETWORK_PROTOCOL_GUID;
114 EFI_GUID smbios = SMBIOS_TABLE_GUID;
115 EFI_GUID smbios3 = SMBIOS3_TABLE_GUID;
116 EFI_GUID dxe = DXE_SERVICES_TABLE_GUID;
117 EFI_GUID hoblist = HOB_LIST_TABLE_GUID;
118 EFI_GUID lzmadecomp = LZMA_DECOMPRESSION_GUID;
119 EFI_GUID mpcore = ARM_MP_CORE_INFO_TABLE_GUID;
120 EFI_GUID esrt = ESRT_TABLE_GUID;
121 EFI_GUID memtype = MEMORY_TYPE_INFORMATION_TABLE_GUID;
122 EFI_GUID debugimg = EFI_DEBUG_IMAGE_INFO_TABLE_GUID;
123 EFI_GUID fdtdtb = FDT_TABLE_GUID;
124 EFI_GUID inputid = EFI_SIMPLE_TEXT_INPUT_PROTOCOL_GUID;
125 EFI_GUID rng_guid = EFI_RNG_PROTOCOL_GUID;
126 
127 /*
128  * Number of seconds to wait for a keystroke before exiting with failure
129  * in the event no currdev is found. -2 means always break, -1 means
130  * never break, 0 means poll once and then reboot, > 0 means wait for
131  * that many seconds. "fail_timeout" can be set in the environment as
132  * well.
133  */
134 static int fail_timeout = 5;
135 
136 /*
137  * Current boot variable
138  */
139 UINT16 boot_current;
140 
141 /*
142  * Image that we booted from.
143  */
144 EFI_LOADED_IMAGE *boot_img;
145 
146 static bool
has_keyboard(void)147 has_keyboard(void)
148 {
149 	EFI_STATUS status;
150 	EFI_DEVICE_PATH *path;
151 	EFI_HANDLE *hin, *hin_end, *walker;
152 	UINTN sz;
153 	bool retval = false;
154 
155 	/*
156 	 * Find all the handles that support the SIMPLE_TEXT_INPUT_PROTOCOL and
157 	 * do the typical dance to get the right sized buffer.
158 	 */
159 	sz = 0;
160 	hin = NULL;
161 	status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz, 0);
162 	if (status == EFI_BUFFER_TOO_SMALL) {
163 		hin = (EFI_HANDLE *)malloc(sz);
164 		status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz,
165 		    hin);
166 		if (EFI_ERROR(status))
167 			free(hin);
168 	}
169 	if (EFI_ERROR(status))
170 		return retval;
171 
172 	/*
173 	 * Look at each of the handles. If it supports the device path protocol,
174 	 * use it to get the device path for this handle. Then see if that
175 	 * device path matches either the USB device path for keyboards or the
176 	 * legacy device path for keyboards.
177 	 */
178 	hin_end = &hin[sz / sizeof(*hin)];
179 	for (walker = hin; walker < hin_end; walker++) {
180 		status = OpenProtocolByHandle(*walker, &devid, (void **)&path);
181 		if (EFI_ERROR(status))
182 			continue;
183 
184 		while (!IsDevicePathEnd(path)) {
185 			/*
186 			 * Check for the ACPI keyboard node. All PNP3xx nodes
187 			 * are keyboards of different flavors. Note: It is
188 			 * unclear of there's always a keyboard node when
189 			 * there's a keyboard controller, or if there's only one
190 			 * when a keyboard is detected at boot.
191 			 */
192 			if (DevicePathType(path) == ACPI_DEVICE_PATH &&
193 			    (DevicePathSubType(path) == ACPI_DP ||
194 				DevicePathSubType(path) == ACPI_EXTENDED_DP)) {
195 				ACPI_HID_DEVICE_PATH  *acpi;
196 
197 				acpi = (ACPI_HID_DEVICE_PATH *)(void *)path;
198 				if ((EISA_ID_TO_NUM(acpi->HID) & 0xff00) == 0x300 &&
199 				    (acpi->HID & 0xffff) == PNP_EISA_ID_CONST) {
200 					retval = true;
201 					goto out;
202 				}
203 			/*
204 			 * Check for USB keyboard node, if present. Unlike a
205 			 * PS/2 keyboard, these definitely only appear when
206 			 * connected to the system.
207 			 */
208 			} else if (DevicePathType(path) == MESSAGING_DEVICE_PATH &&
209 			    DevicePathSubType(path) == MSG_USB_CLASS_DP) {
210 				USB_CLASS_DEVICE_PATH *usb;
211 
212 				usb = (USB_CLASS_DEVICE_PATH *)(void *)path;
213 				if (usb->DeviceClass == 3 && /* HID */
214 				    usb->DeviceSubClass == 1 && /* Boot devices */
215 				    usb->DeviceProtocol == 1) { /* Boot keyboards */
216 					retval = true;
217 					goto out;
218 				}
219 			}
220 			path = NextDevicePathNode(path);
221 		}
222 	}
223 out:
224 	free(hin);
225 	return retval;
226 }
227 
228 static void
set_currdev_devdesc(struct devdesc * currdev)229 set_currdev_devdesc(struct devdesc *currdev)
230 {
231 	const char *devname;
232 
233 	devname = devformat(currdev);
234 	printf("Setting currdev to %s\n", devname);
235 	set_currdev(devname);
236 }
237 
238 static void
set_currdev_devsw(struct devsw * dev,int unit)239 set_currdev_devsw(struct devsw *dev, int unit)
240 {
241 	struct devdesc currdev;
242 
243 	currdev.d_dev = dev;
244 	currdev.d_unit = unit;
245 
246 	set_currdev_devdesc(&currdev);
247 }
248 
249 static void
set_currdev_pdinfo(pdinfo_t * dp)250 set_currdev_pdinfo(pdinfo_t *dp)
251 {
252 
253 	/*
254 	 * Disks are special: they have partitions. if the parent
255 	 * pointer is non-null, we're a partition not a full disk
256 	 * and we need to adjust currdev appropriately.
257 	 */
258 	if (dp->pd_devsw->dv_type == DEVT_DISK) {
259 		struct disk_devdesc currdev;
260 
261 		currdev.dd.d_dev = dp->pd_devsw;
262 		if (dp->pd_parent == NULL) {
263 			currdev.dd.d_unit = dp->pd_unit;
264 			currdev.d_slice = D_SLICENONE;
265 			currdev.d_partition = D_PARTNONE;
266 		} else {
267 			currdev.dd.d_unit = dp->pd_parent->pd_unit;
268 			currdev.d_slice = dp->pd_unit;
269 			currdev.d_partition = D_PARTISGPT; /* XXX Assumes GPT */
270 		}
271 		set_currdev_devdesc((struct devdesc *)&currdev);
272 	} else {
273 		set_currdev_devsw(dp->pd_devsw, dp->pd_unit);
274 	}
275 }
276 
277 static bool
sanity_check_currdev(void)278 sanity_check_currdev(void)
279 {
280 	struct stat st;
281 
282 	return (stat(PATH_DEFAULTS_LOADER_CONF, &st) == 0 ||
283 #ifdef PATH_BOOTABLE_TOKEN
284 	    stat(PATH_BOOTABLE_TOKEN, &st) == 0 || /* non-standard layout */
285 #endif
286 	    stat(PATH_KERNEL, &st) == 0);
287 }
288 
289 #ifdef EFI_ZFS_BOOT
290 static bool
probe_zfs_currdev(uint64_t guid)291 probe_zfs_currdev(uint64_t guid)
292 {
293 	char buf[VDEV_PAD_SIZE];
294 	char *devname;
295 	struct zfs_devdesc currdev;
296 
297 	currdev.dd.d_dev = &zfs_dev;
298 	currdev.dd.d_unit = 0;
299 	currdev.pool_guid = guid;
300 	currdev.root_guid = 0;
301 	devname = devformat(&currdev.dd);
302 	set_currdev(devname);
303 	printf("Setting currdev to %s\n", devname);
304 	init_zfs_boot_options(devname);
305 
306 	if (zfs_get_bootonce(&currdev, OS_BOOTONCE, buf, sizeof(buf)) == 0) {
307 		printf("zfs bootonce: %s\n", buf);
308 		set_currdev(buf);
309 		setenv("zfs-bootonce", buf, 1);
310 	}
311 	(void)zfs_attach_nvstore(&currdev);
312 
313 	return (sanity_check_currdev());
314 }
315 #endif
316 
317 #ifdef MD_IMAGE_SIZE
318 extern struct devsw md_dev;
319 
320 static bool
probe_md_currdev(void)321 probe_md_currdev(void)
322 {
323 	bool rv;
324 
325 	set_currdev_devsw(&md_dev, 0);
326 	rv = sanity_check_currdev();
327 	if (!rv)
328 		printf("MD not present\n");
329 	return (rv);
330 }
331 #endif
332 
333 static bool
try_as_currdev(pdinfo_t * hd,pdinfo_t * pp)334 try_as_currdev(pdinfo_t *hd, pdinfo_t *pp)
335 {
336 #ifdef EFI_ZFS_BOOT
337 	uint64_t guid;
338 
339 	/*
340 	 * If there's a zpool on this device, try it as a ZFS
341 	 * filesystem, which has somewhat different setup than all
342 	 * other types of fs due to imperfect loader integration.
343 	 * This all stems from ZFS being both a device (zpool) and
344 	 * a filesystem, plus the boot env feature.
345 	 */
346 	if (efizfs_get_guid_by_handle(pp->pd_handle, &guid))
347 		return (probe_zfs_currdev(guid));
348 #endif
349 	/*
350 	 * All other filesystems just need the pdinfo
351 	 * initialized in the standard way.
352 	 */
353 	set_currdev_pdinfo(pp);
354 	return (sanity_check_currdev());
355 }
356 
357 /*
358  * Sometimes we get filenames that are all upper case
359  * and/or have backslashes in them. Filter all this out
360  * if it looks like we need to do so.
361  */
362 static void
fix_dosisms(char * p)363 fix_dosisms(char *p)
364 {
365 	while (*p) {
366 		if (isupper(*p))
367 			*p = tolower(*p);
368 		else if (*p == '\\')
369 			*p = '/';
370 		p++;
371 	}
372 }
373 
374 #define SIZE(dp, edp) (size_t)((intptr_t)(void *)edp - (intptr_t)(void *)dp)
375 
376 enum { BOOT_INFO_OK = 0, BAD_CHOICE = 1, NOT_SPECIFIC = 2  };
377 static int
match_boot_info(char * boot_info,size_t bisz)378 match_boot_info(char *boot_info, size_t bisz)
379 {
380 	uint32_t attr;
381 	uint16_t fplen;
382 	size_t len;
383 	char *walker, *ep;
384 	EFI_DEVICE_PATH *dp, *edp, *first_dp, *last_dp;
385 	pdinfo_t *pp;
386 	CHAR16 *descr;
387 	char *kernel = NULL;
388 	FILEPATH_DEVICE_PATH  *fp;
389 	struct stat st;
390 	CHAR16 *text;
391 
392 	/*
393 	 * FreeBSD encodes its boot loading path into the boot loader
394 	 * BootXXXX variable. We look for the last one in the path
395 	 * and use that to load the kernel. However, if we only find
396 	 * one DEVICE_PATH, then there's nothing specific and we should
397 	 * fall back.
398 	 *
399 	 * In an ideal world, we'd look at the image handle we were
400 	 * passed, match up with the loader we are and then return the
401 	 * next one in the path. This would be most flexible and cover
402 	 * many chain booting scenarios where you need to use this
403 	 * boot loader to get to the next boot loader. However, that
404 	 * doesn't work. We rarely have the path to the image booted
405 	 * (just the device) so we can't count on that. So, we do the
406 	 * next best thing: we look through the device path(s) passed
407 	 * in the BootXXXX variable. If there's only one, we return
408 	 * NOT_SPECIFIC. Otherwise, we look at the last one and try to
409 	 * load that. If we can, we return BOOT_INFO_OK. Otherwise we
410 	 * return BAD_CHOICE for the caller to sort out.
411 	 */
412 	if (bisz < sizeof(attr) + sizeof(fplen) + sizeof(CHAR16))
413 		return NOT_SPECIFIC;
414 	walker = boot_info;
415 	ep = walker + bisz;
416 	memcpy(&attr, walker, sizeof(attr));
417 	walker += sizeof(attr);
418 	memcpy(&fplen, walker, sizeof(fplen));
419 	walker += sizeof(fplen);
420 	descr = (CHAR16 *)(intptr_t)walker;
421 	len = ucs2len(descr);
422 	walker += (len + 1) * sizeof(CHAR16);
423 	last_dp = first_dp = dp = (EFI_DEVICE_PATH *)walker;
424 	edp = (EFI_DEVICE_PATH *)(walker + fplen);
425 	if ((char *)edp > ep)
426 		return NOT_SPECIFIC;
427 	while (dp < edp && SIZE(dp, edp) > sizeof(EFI_DEVICE_PATH)) {
428 		text = efi_devpath_name(dp);
429 		if (text != NULL) {
430 			printf("   BootInfo Path: %S\n", text);
431 			efi_free_devpath_name(text);
432 		}
433 		last_dp = dp;
434 		dp = (EFI_DEVICE_PATH *)((char *)dp + efi_devpath_length(dp));
435 	}
436 
437 	/*
438 	 * If there's only one item in the list, then nothing was
439 	 * specified. Or if the last path doesn't have a media
440 	 * path in it. Those show up as various VenHw() nodes
441 	 * which are basically opaque to us. Don't count those
442 	 * as something specifc.
443 	 */
444 	if (last_dp == first_dp) {
445 		printf("Ignoring Boot%04x: Only one DP found\n", boot_current);
446 		return NOT_SPECIFIC;
447 	}
448 	if (efi_devpath_to_media_path(last_dp) == NULL) {
449 		printf("Ignoring Boot%04x: No Media Path\n", boot_current);
450 		return NOT_SPECIFIC;
451 	}
452 
453 	/*
454 	 * OK. At this point we either have a good path or a bad one.
455 	 * Let's check.
456 	 */
457 	pp = efiblk_get_pdinfo_by_device_path(last_dp);
458 	if (pp == NULL) {
459 		printf("Ignoring Boot%04x: Device Path not found\n", boot_current);
460 		return BAD_CHOICE;
461 	}
462 	set_currdev_pdinfo(pp);
463 	if (!sanity_check_currdev()) {
464 		printf("Ignoring Boot%04x: sanity check failed\n", boot_current);
465 		return BAD_CHOICE;
466 	}
467 
468 	/*
469 	 * OK. We've found a device that matches, next we need to check the last
470 	 * component of the path. If it's a file, then we set the default kernel
471 	 * to that. Otherwise, just use this as the default root.
472 	 *
473 	 * Reminder: we're running very early, before we've parsed the defaults
474 	 * file, so we may need to have a hack override.
475 	 */
476 	dp = efi_devpath_last_node(last_dp);
477 	if (DevicePathType(dp) !=  MEDIA_DEVICE_PATH ||
478 	    DevicePathSubType(dp) != MEDIA_FILEPATH_DP) {
479 		printf("Using Boot%04x for root partition\n", boot_current);
480 		return (BOOT_INFO_OK);		/* use currdir, default kernel */
481 	}
482 	fp = (FILEPATH_DEVICE_PATH *)dp;
483 	ucs2_to_utf8(fp->PathName, &kernel);
484 	if (kernel == NULL) {
485 		printf("Not using Boot%04x: can't decode kernel\n", boot_current);
486 		return (BAD_CHOICE);
487 	}
488 	if (*kernel == '\\' || isupper(*kernel))
489 		fix_dosisms(kernel);
490 	if (stat(kernel, &st) != 0) {
491 		free(kernel);
492 		printf("Not using Boot%04x: can't find %s\n", boot_current,
493 		    kernel);
494 		return (BAD_CHOICE);
495 	}
496 	setenv("kernel", kernel, 1);
497 	free(kernel);
498 	text = efi_devpath_name(last_dp);
499 	if (text) {
500 		printf("Using Boot%04x %S + %s\n", boot_current, text,
501 		    kernel);
502 		efi_free_devpath_name(text);
503 	}
504 
505 	return (BOOT_INFO_OK);
506 }
507 
508 /*
509  * Look at the passed-in boot_info, if any. If we find it then we need
510  * to see if we can find ourselves in the boot chain. If we can, and
511  * there's another specified thing to boot next, assume that the file
512  * is loaded from / and use that for the root filesystem. If can't
513  * find the specified thing, we must fail the boot. If we're last on
514  * the list, then we fallback to looking for the first available /
515  * candidate (ZFS, if there's a bootable zpool, otherwise a UFS
516  * partition that has either /boot/defaults/loader.conf on it or
517  * /boot/kernel/kernel (the default kernel) that we can use.
518  *
519  * We always fail if we can't find the right thing. However, as
520  * a concession to buggy UEFI implementations, like u-boot, if
521  * we have determined that the host is violating the UEFI boot
522  * manager protocol, we'll signal the rest of the program that
523  * a drop to the OK boot loader prompt is possible.
524  */
525 static int
find_currdev(bool do_bootmgr,char * boot_info,size_t boot_info_sz)526 find_currdev(bool do_bootmgr, char *boot_info, size_t boot_info_sz)
527 {
528 	pdinfo_t *dp, *pp;
529 	EFI_DEVICE_PATH *devpath, *copy;
530 	EFI_HANDLE h;
531 	CHAR16 *text;
532 	struct devsw *dev;
533 	int unit;
534 	uint64_t extra;
535 	int rv;
536 	char *rootdev;
537 
538 	/*
539 	 * First choice: if rootdev is already set, use that, even if
540 	 * it's wrong.
541 	 */
542 	rootdev = getenv("rootdev");
543 	if (rootdev != NULL && *rootdev != '\0') {
544 		printf("    Setting currdev to configured rootdev %s\n",
545 		    rootdev);
546 		set_currdev(rootdev);
547 		return (0);
548 	}
549 
550 	/*
551 	 * Second choice: If uefi_rootdev is set, translate that UEFI device
552 	 * path to the loader's internal name and use that.
553 	 */
554 	do {
555 		rootdev = getenv("uefi_rootdev");
556 		if (rootdev == NULL)
557 			break;
558 		devpath = efi_name_to_devpath(rootdev);
559 		if (devpath == NULL)
560 			break;
561 		dp = efiblk_get_pdinfo_by_device_path(devpath);
562 		efi_devpath_free(devpath);
563 		if (dp == NULL)
564 			break;
565 		printf("    Setting currdev to UEFI path %s\n",
566 		    rootdev);
567 		set_currdev_pdinfo(dp);
568 		return (0);
569 	} while (0);
570 
571 	/*
572 	 * Third choice: If we can find out image boot_info, and there's
573 	 * a follow-on boot image in that boot_info, use that. In this
574 	 * case root will be the partition specified in that image and
575 	 * we'll load the kernel specified by the file path. Should there
576 	 * not be a filepath, we use the default. This filepath overrides
577 	 * loader.conf.
578 	 */
579 	if (do_bootmgr) {
580 		rv = match_boot_info(boot_info, boot_info_sz);
581 		switch (rv) {
582 		case BOOT_INFO_OK:	/* We found it */
583 			return (0);
584 		case BAD_CHOICE:	/* specified file not found -> error */
585 			/* XXX do we want to have an escape hatch for last in boot order? */
586 			return (ENOENT);
587 		} /* Nothing specified, try normal match */
588 	}
589 
590 #ifdef EFI_ZFS_BOOT
591 	/*
592 	 * Did efi_zfs_probe() detect the boot pool? If so, use the zpool
593 	 * it found, if it's sane. ZFS is the only thing that looks for
594 	 * disks and pools to boot. This may change in the future, however,
595 	 * if we allow specifying which pool to boot from via UEFI variables
596 	 * rather than the bootenv stuff that FreeBSD uses today.
597 	 */
598 	if (pool_guid != 0) {
599 		printf("Trying ZFS pool\n");
600 		if (probe_zfs_currdev(pool_guid))
601 			return (0);
602 	}
603 #endif /* EFI_ZFS_BOOT */
604 
605 #ifdef MD_IMAGE_SIZE
606 	/*
607 	 * If there is an embedded MD, try to use that.
608 	 */
609 	printf("Trying MD\n");
610 	if (probe_md_currdev())
611 		return (0);
612 #endif /* MD_IMAGE_SIZE */
613 
614 	/*
615 	 * Try to find the block device by its handle based on the
616 	 * image we're booting. If we can't find a sane partition,
617 	 * search all the other partitions of the disk. We do not
618 	 * search other disks because it's a violation of the UEFI
619 	 * boot protocol to do so. We fail and let UEFI go on to
620 	 * the next candidate.
621 	 */
622 	dp = efiblk_get_pdinfo_by_handle(boot_img->DeviceHandle);
623 	if (dp != NULL) {
624 		text = efi_devpath_name(dp->pd_devpath);
625 		if (text != NULL) {
626 			printf("Trying ESP: %S\n", text);
627 			efi_free_devpath_name(text);
628 		}
629 		set_currdev_pdinfo(dp);
630 		if (sanity_check_currdev())
631 			return (0);
632 		if (dp->pd_parent != NULL) {
633 			pdinfo_t *espdp = dp;
634 			dp = dp->pd_parent;
635 			STAILQ_FOREACH(pp, &dp->pd_part, pd_link) {
636 				/* Already tried the ESP */
637 				if (espdp == pp)
638 					continue;
639 				/*
640 				 * Roll up the ZFS special case
641 				 * for those partitions that have
642 				 * zpools on them.
643 				 */
644 				text = efi_devpath_name(pp->pd_devpath);
645 				if (text != NULL) {
646 					printf("Trying: %S\n", text);
647 					efi_free_devpath_name(text);
648 				}
649 				if (try_as_currdev(dp, pp))
650 					return (0);
651 			}
652 		}
653 	}
654 
655 	/*
656 	 * Try the device handle from our loaded image first.  If that
657 	 * fails, use the device path from the loaded image and see if
658 	 * any of the nodes in that path match one of the enumerated
659 	 * handles. Currently, this handle list is only for netboot.
660 	 */
661 	if (efi_handle_lookup(boot_img->DeviceHandle, &dev, &unit, &extra) == 0) {
662 		set_currdev_devsw(dev, unit);
663 		if (sanity_check_currdev())
664 			return (0);
665 	}
666 
667 	copy = NULL;
668 	devpath = efi_lookup_image_devpath(IH);
669 	while (devpath != NULL) {
670 		h = efi_devpath_handle(devpath);
671 		if (h == NULL)
672 			break;
673 
674 		free(copy);
675 		copy = NULL;
676 
677 		if (efi_handle_lookup(h, &dev, &unit, &extra) == 0) {
678 			set_currdev_devsw(dev, unit);
679 			if (sanity_check_currdev())
680 				return (0);
681 		}
682 
683 		devpath = efi_lookup_devpath(h);
684 		if (devpath != NULL) {
685 			copy = efi_devpath_trim(devpath);
686 			devpath = copy;
687 		}
688 	}
689 	free(copy);
690 
691 	return (ENOENT);
692 }
693 
694 static bool
interactive_interrupt(const char * msg)695 interactive_interrupt(const char *msg)
696 {
697 	time_t now, then, last;
698 
699 	last = 0;
700 	now = then = getsecs();
701 	printf("%s\n", msg);
702 	if (fail_timeout == -2)		/* Always break to OK */
703 		return (true);
704 	if (fail_timeout == -1)		/* Never break to OK */
705 		return (false);
706 	do {
707 		if (last != now) {
708 			printf("press any key to interrupt reboot in %d seconds\r",
709 			    fail_timeout - (int)(now - then));
710 			last = now;
711 		}
712 
713 		/* XXX no pause or timeout wait for char */
714 		if (ischar())
715 			return (true);
716 		now = getsecs();
717 	} while (now - then < fail_timeout);
718 	return (false);
719 }
720 
721 static int
parse_args(int argc,CHAR16 * argv[])722 parse_args(int argc, CHAR16 *argv[])
723 {
724 	int i, howto;
725 	char var[128];
726 
727 	/*
728 	 * Parse the args to set the console settings, etc
729 	 * boot1.efi passes these in, if it can read /boot.config or /boot/config
730 	 * or iPXE may be setup to pass these in. Or the optional argument in the
731 	 * boot environment was used to pass these arguments in (in which case
732 	 * neither /boot.config nor /boot/config are consulted).
733 	 *
734 	 * Loop through the args, and for each one that contains an '=' that is
735 	 * not the first character, add it to the environment.  This allows
736 	 * loader and kernel env vars to be passed on the command line.  Convert
737 	 * args from UCS-2 to ASCII (16 to 8 bit) as they are copied (though this
738 	 * method is flawed for non-ASCII characters).
739 	 */
740 	howto = 0;
741 	for (i = 0; i < argc; i++) {
742 		cpy16to8(argv[i], var, sizeof(var));
743 		howto |= boot_parse_arg(var);
744 	}
745 
746 	return (howto);
747 }
748 
749 static void
setenv_int(const char * key,int val)750 setenv_int(const char *key, int val)
751 {
752 	char buf[20];
753 
754 	snprintf(buf, sizeof(buf), "%d", val);
755 	setenv(key, buf, 1);
756 }
757 
758 static void *
acpi_map_sdt(vm_offset_t addr)759 acpi_map_sdt(vm_offset_t addr)
760 {
761 	/* PA == VA */
762 	return ((void *)addr);
763 }
764 
765 static int
acpi_checksum(void * p,size_t length)766 acpi_checksum(void *p, size_t length)
767 {
768 	uint8_t *bp;
769 	uint8_t sum;
770 
771 	bp = p;
772 	sum = 0;
773 	while (length--)
774 		sum += *bp++;
775 
776 	return (sum);
777 }
778 
779 static void *
acpi_find_table(uint8_t * sig)780 acpi_find_table(uint8_t *sig)
781 {
782 	int entries, i, addr_size;
783 	ACPI_TABLE_HEADER *sdp;
784 	ACPI_TABLE_RSDT *rsdt;
785 	ACPI_TABLE_XSDT *xsdt;
786 	vm_offset_t addr;
787 
788 	if (rsdp == NULL)
789 		return (NULL);
790 
791 	rsdt = (ACPI_TABLE_RSDT *)(uintptr_t)rsdp->RsdtPhysicalAddress;
792 	xsdt = (ACPI_TABLE_XSDT *)(uintptr_t)rsdp->XsdtPhysicalAddress;
793 	if (rsdp->Revision < 2) {
794 		sdp = (ACPI_TABLE_HEADER *)rsdt;
795 		addr_size = sizeof(uint32_t);
796 	} else {
797 		sdp = (ACPI_TABLE_HEADER *)xsdt;
798 		addr_size = sizeof(uint64_t);
799 	}
800 	entries = (sdp->Length - sizeof(ACPI_TABLE_HEADER)) / addr_size;
801 	for (i = 0; i < entries; i++) {
802 		if (addr_size == 4)
803 			addr = le32toh(rsdt->TableOffsetEntry[i]);
804 		else
805 			addr = le64toh(xsdt->TableOffsetEntry[i]);
806 		if (addr == 0)
807 			continue;
808 		sdp = (ACPI_TABLE_HEADER *)acpi_map_sdt(addr);
809 		if (acpi_checksum(sdp, sdp->Length)) {
810 			printf("RSDT entry %d (sig %.4s) is corrupt", i,
811 			    sdp->Signature);
812 			continue;
813 		}
814 		if (memcmp(sig, sdp->Signature, 4) == 0)
815 			return (sdp);
816 	}
817 	return (NULL);
818 }
819 
820 /*
821  * Convert the InterfaceType in the SPCR. These are encoded the same for DBG2
822  * tables as well (though we don't parse those here).
823  */
824 static const char *
acpi_uart_type(UINT8 t)825 acpi_uart_type(UINT8 t)
826 {
827 	static const char *types[] = {
828 		[0x00] = "ns8250",	/* Full 16550 */
829 		[0x01] = "ns8250",	/* DBGP Rev 1 16550 subset */
830 		[0x03] = "pl011",	/* Arm PL011 */
831 		[0x05] = "ns8250",	/* Nvidia 16550 */
832 		[0x0d] = "pl011",	/* Arm SBSA 32-bit width */
833 		[0x0e] = "pl011",	/* Arm SBSA generic */
834 		[0x12] = "ns8250",	/* 16550 defined in SerialPort */
835 	};
836 
837 	if (t >= nitems(types))
838 		return (NULL);
839 	return (types[t]);
840 }
841 
842 static int
acpi_uart_baud(UINT8 b)843 acpi_uart_baud(UINT8 b)
844 {
845 	static int baud[] = { 0, -1, -1, 9600, 19200, -1, 57600, 115200 };
846 
847 	if (b > 7)
848 		return (-1);
849 	return (baud[b]);
850 }
851 
852 static int
acpi_uart_regionwidth(UINT8 rw)853 acpi_uart_regionwidth(UINT8 rw)
854 {
855 	if (rw == 0)
856 		return (1);
857 	if (rw > 4)
858 		return (-1);
859 	return (1 << (rw - 1));
860 }
861 
862 static const char *
acpi_uart_parity(UINT8 p)863 acpi_uart_parity(UINT8 p)
864 {
865 	/* Some of these SPCR entires get this wrong, hard wire none */
866 	return ("none");
867 }
868 
869 /*
870  * See if we can find an enabled SPCR ACPI table in the static tables. If so,
871  * then it describes the serial console that's been redirected to, so we know
872  * that at least there's a serial console. This is most important for embedded
873  * systems that don't have traidtional PC serial ports.
874  *
875  * All the two letter variables in this function correspond to their usage in
876  * the uart(4) console string. We use io == -1 to select between I/O ports and
877  * memory mapped addresses. Set both hw.uart.console and hw.uart.consol.extra
878  * to communicate settings from SPCR to the kernel.
879  */
880 static int
check_acpi_spcr(void)881 check_acpi_spcr(void)
882 {
883 	ACPI_TABLE_SPCR *spcr;
884 	int br, db, io, rs, rw, xo, pv, pd;
885 	uintmax_t mm;
886 	const char *dt, *pa;
887 	char *val = NULL;
888 
889 	/*
890 	 * The SPCR is enabled when SerialPort is non-zero.  Address being zero
891 	 * should suffice to see if it's disabled.
892 	 */
893 	spcr = acpi_find_table(ACPI_SIG_SPCR);
894 	if (spcr == NULL || spcr->SerialPort.Address == 0)
895 		return (0);
896 	dt = acpi_uart_type(spcr->InterfaceType);
897 	if (dt == NULL)	{ 	/* Kernel can't use unknown types */
898 		printf("UART Type %d not known\n", spcr->InterfaceType);
899 		return (0);
900 	}
901 
902 	/* I/O vs Memory mapped vs PCI device */
903 	io = -1;
904 	pv = spcr->PciVendorId;
905 	pd = spcr->PciDeviceId;
906 	if (pv == 0xffff && pd == 0xffff) {
907 		if (spcr->SerialPort.SpaceId == 1)
908 			io = spcr->SerialPort.Address;
909 		else {
910 			mm = spcr->SerialPort.Address;
911 			rs = ffs(spcr->SerialPort.BitWidth) - 4;
912 			rw = acpi_uart_regionwidth(spcr->SerialPort.AccessWidth);
913 		}
914 	} else {
915 		/* XXX todo: bus:device:function + flags and segment */
916 	}
917 
918 	/* Uart settings */
919 	pa = acpi_uart_parity(spcr->Parity);
920 	db = 8;
921 
922 	/*
923 	 * UartClkFreq is 3 and newer. We always use it then (it's only valid if
924 	 * it isn't 0, but if it is 0, we want to use 0 to have the kernel
925 	 * guess).
926 	 */
927 	if (spcr->Header.Revision <= 2)
928 		xo = 0;
929 	else
930 		xo = spcr->UartClkFreq;
931 
932 	/*
933 	 * PreciseBaudrate, when non-zero, is to be preferred. It's only valid,
934 	 * though, for rev 4 and newer. So when it's 0 or the version is too
935 	 * old, we do the old-style table lookup. Otherwise we believe it.
936 	 */
937 	if (spcr->Header.Revision <= 3 || spcr->PreciseBaudrate == 0)
938 		br = acpi_uart_baud(spcr->BaudRate);
939 	else
940 		br = spcr->PreciseBaudrate;
941 
942 	if (io != -1) {
943 		asprintf(&val, "db:%d,dt:%s,io:%#x,pa:%s,br:%d,xo=%d",
944 		    db, dt, io, pa, br, xo);
945 	} else if (pv != 0xffff && pd != 0xffff) {
946 		asprintf(&val, "db:%d,dt:%s,pv:%#x,pd:%#x,pa:%s,br:%d,xo=%d",
947 		    db, dt, pv, pd, pa, br, xo);
948 	} else {
949 		asprintf(&val, "db:%d,dt:%s,mm:%#jx,rs:%d,rw:%d,pa:%s,br:%d,xo=%d",
950 		    db, dt, mm, rs, rw, pa, br, xo);
951 	}
952 	env_setenv("hw.uart.console", EV_VOLATILE, val, NULL, NULL);
953 	free(val);
954 
955 	return (RB_SERIAL);
956 }
957 
958 
959 /*
960  * Parse ConOut (the list of consoles active) and see if we can find a serial
961  * port and/or a video port. It would be nice to also walk the ACPI DSDT to map
962  * the UID for the serial port to a port since there's no standard mapping. Also
963  * check for ConIn as well. This will be enough to determine if we have serial,
964  * and if we don't, we default to video. If there's a dual-console situation
965  * with only ConIn defined, this will currently fail.
966  */
967 int
parse_uefi_con_out(void)968 parse_uefi_con_out(void)
969 {
970 	int how, rv;
971 	int vid_seen = 0, com_seen = 0, seen = 0;
972 	size_t sz;
973 	char buf[4096], *ep;
974 	EFI_DEVICE_PATH *node;
975 	ACPI_HID_DEVICE_PATH  *acpi;
976 	UART_DEVICE_PATH  *uart;
977 	bool pci_pending;
978 
979 	/*
980 	 * A SPCR in the ACPI fixed tables documents a serial port used for the
981 	 * console. It may mirror a video console, or may be stand alone. If it
982 	 * is present, we return RB_SERIAL and will use it for the kernel.
983 	 */
984 	how = check_acpi_spcr();
985 	sz = sizeof(buf);
986 	rv = efi_global_getenv("ConOut", buf, &sz);
987 	if (rv != EFI_SUCCESS)
988 		rv = efi_global_getenv("ConOutDev", buf, &sz);
989 	if (rv != EFI_SUCCESS)
990 		rv = efi_global_getenv("ConIn", buf, &sz);
991 	if (rv != EFI_SUCCESS) {
992 		/*
993 		 * If we don't have any Con* variable use both. If we have GOP
994 		 * make video primary, otherwise set serial primary. In either
995 		 * case, try to use both the 'efi' console which will use the
996 		 * GOP, if present and serial. If there's an EFI BIOS that omits
997 		 * this, but has a serial port redirect, we'll unavioidably get
998 		 * doubled characters, but we'll be right in all the other more
999 		 * common cases.
1000 		 */
1001 		if (efi_has_gop())
1002 			how |= RB_MULTIPLE;
1003 		else
1004 			how |= RB_MULTIPLE | RB_SERIAL;
1005 		setenv("console", "efi,comconsole", 1);
1006 		goto out;
1007 	}
1008 	ep = buf + sz;
1009 	node = (EFI_DEVICE_PATH *)buf;
1010 	while ((char *)node < ep) {
1011 		if (IsDevicePathEndType(node)) {
1012 			if (pci_pending && vid_seen == 0)
1013 				vid_seen = ++seen;
1014 		}
1015 		pci_pending = false;
1016 		if (DevicePathType(node) == ACPI_DEVICE_PATH &&
1017 		    (DevicePathSubType(node) == ACPI_DP ||
1018 		    DevicePathSubType(node) == ACPI_EXTENDED_DP)) {
1019 			/* Check for Serial node */
1020 			acpi = (void *)node;
1021 			if (EISA_ID_TO_NUM(acpi->HID) == 0x501) {
1022 				setenv_int("efi_8250_uid", acpi->UID);
1023 				com_seen = ++seen;
1024 			}
1025 		} else if (DevicePathType(node) == MESSAGING_DEVICE_PATH &&
1026 		    DevicePathSubType(node) == MSG_UART_DP) {
1027 			com_seen = ++seen;
1028 			uart = (void *)node;
1029 			setenv_int("efi_com_speed", uart->BaudRate);
1030 		} else if (DevicePathType(node) == ACPI_DEVICE_PATH &&
1031 		    DevicePathSubType(node) == ACPI_ADR_DP) {
1032 			/* Check for AcpiAdr() Node for video */
1033 			vid_seen = ++seen;
1034 		} else if (DevicePathType(node) == HARDWARE_DEVICE_PATH &&
1035 		    DevicePathSubType(node) == HW_PCI_DP) {
1036 			/*
1037 			 * Note, vmware fusion has a funky console device
1038 			 *	PciRoot(0x0)/Pci(0xf,0x0)
1039 			 * which we can only detect at the end since we also
1040 			 * have to cope with:
1041 			 *	PciRoot(0x0)/Pci(0x1f,0x0)/Serial(0x1)
1042 			 * so only match it if it's last.
1043 			 */
1044 			pci_pending = true;
1045 		}
1046 		node = NextDevicePathNode(node);
1047 	}
1048 
1049 	/*
1050 	 * Truth table for RB_MULTIPLE | RB_SERIAL
1051 	 * Value		Result
1052 	 * 0			Use only video console
1053 	 * RB_SERIAL		Use only serial console
1054 	 * RB_MULTIPLE		Use both video and serial console
1055 	 *			(but video is primary so gets rc messages)
1056 	 * both			Use both video and serial console
1057 	 *			(but serial is primary so gets rc messages)
1058 	 *
1059 	 * Try to honor this as best we can. If only one of serial / video
1060 	 * found, then use that. Otherwise, use the first one we found.
1061 	 * This also implies if we found nothing, default to video.
1062 	 */
1063 	how = 0;
1064 	if (vid_seen && com_seen) {
1065 		how |= RB_MULTIPLE;
1066 		if (com_seen < vid_seen)
1067 			how |= RB_SERIAL;
1068 	} else if (com_seen)
1069 		how |= RB_SERIAL;
1070 out:
1071 	return (how);
1072 }
1073 
1074 void
parse_loader_efi_config(EFI_HANDLE h,const char * env_fn)1075 parse_loader_efi_config(EFI_HANDLE h, const char *env_fn)
1076 {
1077 	pdinfo_t *dp;
1078 	struct stat st;
1079 	int fd = -1;
1080 	char *env = NULL;
1081 
1082 	dp = efiblk_get_pdinfo_by_handle(h);
1083 	if (dp == NULL)
1084 		return;
1085 	set_currdev_pdinfo(dp);
1086 	if (stat(env_fn, &st) != 0)
1087 		return;
1088 	fd = open(env_fn, O_RDONLY);
1089 	if (fd == -1)
1090 		return;
1091 	env = malloc(st.st_size + 1);
1092 	if (env == NULL)
1093 		goto out;
1094 	if (read(fd, env, st.st_size) != st.st_size)
1095 		goto out;
1096 	env[st.st_size] = '\0';
1097 	boot_parse_cmdline(env);
1098 out:
1099 	free(env);
1100 	close(fd);
1101 }
1102 
1103 static void
read_loader_env(const char * name,char * def_fn,bool once)1104 read_loader_env(const char *name, char *def_fn, bool once)
1105 {
1106 	UINTN len;
1107 	char *fn, *freeme = NULL;
1108 
1109 	len = 0;
1110 	fn = def_fn;
1111 	if (efi_freebsd_getenv(name, NULL, &len) == EFI_BUFFER_TOO_SMALL) {
1112 		freeme = fn = malloc(len + 1);
1113 		if (fn != NULL) {
1114 			if (efi_freebsd_getenv(name, fn, &len) != EFI_SUCCESS) {
1115 				free(fn);
1116 				fn = NULL;
1117 				printf(
1118 			    "Can't fetch FreeBSD::%s we know is there\n", name);
1119 			} else {
1120 				/*
1121 				 * if tagged as 'once' delete the env variable so we
1122 				 * only use it once.
1123 				 */
1124 				if (once)
1125 					efi_freebsd_delenv(name);
1126 				/*
1127 				 * We malloced 1 more than len above, then redid the call.
1128 				 * so now we have room at the end of the string to NUL terminate
1129 				 * it here, even if the typical idium would have '- 1' here to
1130 				 * not overflow. len should be the same on return both times.
1131 				 */
1132 				fn[len] = '\0';
1133 			}
1134 		} else {
1135 			printf(
1136 		    "Can't allocate %d bytes to fetch FreeBSD::%s env var\n",
1137 			    len, name);
1138 		}
1139 	}
1140 	if (fn) {
1141 		printf("    Reading loader env vars from %s\n", fn);
1142 		parse_loader_efi_config(boot_img->DeviceHandle, fn);
1143 	}
1144 
1145 	free(freeme);
1146 }
1147 
1148 caddr_t
ptov(uintptr_t x)1149 ptov(uintptr_t x)
1150 {
1151 	return ((caddr_t)x);
1152 }
1153 
1154 static void
efi_smbios_detect(void)1155 efi_smbios_detect(void)
1156 {
1157 	VOID *smbios_v2_ptr = NULL;
1158 	UINTN k;
1159 
1160 	for (k = 0; k < ST->NumberOfTableEntries; k++) {
1161 		EFI_GUID *guid;
1162 		VOID *const VT = ST->ConfigurationTable[k].VendorTable;
1163 		char buf[40];
1164 		bool is_smbios_v2, is_smbios_v3;
1165 
1166 		guid = &ST->ConfigurationTable[k].VendorGuid;
1167 		is_smbios_v2 = memcmp(guid, &smbios, sizeof(*guid)) == 0;
1168 		is_smbios_v3 = memcmp(guid, &smbios3, sizeof(*guid)) == 0;
1169 
1170 		if (!is_smbios_v2 && !is_smbios_v3)
1171 			continue;
1172 
1173 		snprintf(buf, sizeof(buf), "%p", VT);
1174 		setenv("hint.smbios.0.mem", buf, 1);
1175 		if (is_smbios_v2)
1176 			/*
1177 			 * We will parse a v2 table only if we don't find a v3
1178 			 * table.  In the meantime, store the address.
1179 			 */
1180 			smbios_v2_ptr = VT;
1181 		else if (smbios_detect(VT) != NULL)
1182 			/* v3 parsing succeeded, we are done. */
1183 			return;
1184 	}
1185 	if (smbios_v2_ptr != NULL)
1186 		(void)smbios_detect(smbios_v2_ptr);
1187 }
1188 
1189 EFI_STATUS
main(int argc,CHAR16 * argv[])1190 main(int argc, CHAR16 *argv[])
1191 {
1192 	int howto, i, uhowto;
1193 	bool has_kbd;
1194 	char *s;
1195 	EFI_DEVICE_PATH *imgpath;
1196 	CHAR16 *text;
1197 	EFI_STATUS rv;
1198 	size_t sz, bisz = 0;
1199 	UINT16 boot_order[100];
1200 	char boot_info[4096];
1201 	char buf[32];
1202 	bool uefi_boot_mgr;
1203 
1204 #if !defined(__arm__)
1205 	efi_smbios_detect();
1206 #endif
1207 
1208         /* Get our loaded image protocol interface structure. */
1209 	(void) OpenProtocolByHandle(IH, &imgid, (void **)&boot_img);
1210 
1211 	/* Report the RSDP early. */
1212 	acpi_detect();
1213 
1214 	/*
1215 	 * Chicken-and-egg problem; we want to have console output early, but
1216 	 * some console attributes may depend on reading from eg. the boot
1217 	 * device, which we can't do yet.  We can use printf() etc. once this is
1218 	 * done. So, we set it to the efi console, then call console init. This
1219 	 * gets us printf early, but also primes the pump for all future console
1220 	 * changes to take effect, regardless of where they come from.
1221 	 */
1222 	setenv("console", "efi", 1);
1223 	uhowto = parse_uefi_con_out();
1224 #if defined(__riscv)
1225 	/*
1226 	 * This workaround likely is papering over a real issue
1227 	 */
1228 	if ((uhowto & RB_SERIAL) != 0)
1229 		setenv("console", "comconsole", 1);
1230 #endif
1231 	cons_probe();
1232 
1233 	/* Set print_delay variable to have hooks in place. */
1234 	env_setenv("print_delay", EV_VOLATILE, "", setprint_delay, env_nounset);
1235 
1236 	/* Set up currdev variable to have hooks in place. */
1237 	env_setenv("currdev", EV_VOLATILE, "", gen_setcurrdev, env_nounset);
1238 
1239 	/* Init the time source */
1240 	efi_time_init();
1241 
1242 	/*
1243 	 * Initialise the block cache. Set the upper limit.
1244 	 */
1245 	bcache_init(32768, 512);
1246 
1247 	/*
1248 	 * Scan the BLOCK IO MEDIA handles then
1249 	 * march through the device switch probing for things.
1250 	 */
1251 	i = efipart_inithandles();
1252 	if (i != 0 && i != ENOENT) {
1253 		printf("efipart_inithandles failed with ERRNO %d, expect "
1254 		    "failures\n", i);
1255 	}
1256 
1257 	devinit();
1258 
1259 	/*
1260 	 * Detect console settings two different ways: one via the command
1261 	 * args (eg -h) or via the UEFI ConOut variable.
1262 	 */
1263 	has_kbd = has_keyboard();
1264 	howto = parse_args(argc, argv);
1265 	if (!has_kbd && (howto & RB_PROBE))
1266 		howto |= RB_SERIAL | RB_MULTIPLE;
1267 	howto &= ~RB_PROBE;
1268 
1269 	/*
1270 	 * Read additional environment variables from the boot device's
1271 	 * "LoaderEnv" file. Any boot loader environment variable may be set
1272 	 * there, which are subtly different than loader.conf variables. Only
1273 	 * the 'simple' ones may be set so things like foo_load="YES" won't work
1274 	 * for two reasons.  First, the parser is simplistic and doesn't grok
1275 	 * quotes.  Second, because the variables that cause an action to happen
1276 	 * are parsed by the lua, 4th or whatever code that's not yet
1277 	 * loaded. This is relative to the root directory when loader.efi is
1278 	 * loaded off the UFS root drive (when chain booted), or from the ESP
1279 	 * when directly loaded by the BIOS.
1280 	 *
1281 	 * We also read in NextLoaderEnv if it was specified. This allows next boot
1282 	 * functionality to be implemented and to override anything in LoaderEnv.
1283 	 */
1284 	read_loader_env("LoaderEnv", "/efi/freebsd/loader.env", false);
1285 	read_loader_env("NextLoaderEnv", NULL, true);
1286 
1287 	/*
1288 	 * We now have two notions of console. howto should be viewed as
1289 	 * overrides. If console is already set, don't set it again.
1290 	 */
1291 #define	VIDEO_ONLY	0
1292 #define	SERIAL_ONLY	RB_SERIAL
1293 #define	VID_SER_BOTH	RB_MULTIPLE
1294 #define	SER_VID_BOTH	(RB_SERIAL | RB_MULTIPLE)
1295 #define	CON_MASK	(RB_SERIAL | RB_MULTIPLE)
1296 	if (strcmp(getenv("console"), "efi") == 0) {
1297 		if ((howto & CON_MASK) == 0) {
1298 			/* No override, uhowto is controlling and efi cons is perfect */
1299 			howto = howto | (uhowto & CON_MASK);
1300 		} else if ((howto & CON_MASK) == (uhowto & CON_MASK)) {
1301 			/* override matches what UEFI told us, efi console is perfect */
1302 		} else if ((uhowto & (CON_MASK)) != 0) {
1303 			/*
1304 			 * We detected a serial console on ConOut. All possible
1305 			 * overrides include serial. We can't really override what efi
1306 			 * gives us, so we use it knowing it's the best choice.
1307 			 */
1308 			/* Do nothing */
1309 		} else {
1310 			/*
1311 			 * We detected some kind of serial in the override, but ConOut
1312 			 * has no serial, so we have to sort out which case it really is.
1313 			 */
1314 			switch (howto & CON_MASK) {
1315 			case SERIAL_ONLY:
1316 				setenv("console", "comconsole", 1);
1317 				break;
1318 			case VID_SER_BOTH:
1319 				setenv("console", "efi,comconsole", 1);
1320 				break;
1321 			case SER_VID_BOTH:
1322 				setenv("console", "comconsole,efi", 1);
1323 				break;
1324 				/* case VIDEO_ONLY can't happen -- it's the first if above */
1325 			}
1326 		}
1327 	}
1328 
1329 	/*
1330 	 * howto is set now how we want to export the flags to the kernel, so
1331 	 * set the env based on it.
1332 	 */
1333 	boot_howto_to_env(howto);
1334 
1335 	if (efi_copy_init())
1336 		return (EFI_BUFFER_TOO_SMALL);
1337 
1338 	if ((s = getenv("fail_timeout")) != NULL)
1339 		fail_timeout = strtol(s, NULL, 10);
1340 
1341 	printf("%s\n", bootprog_info);
1342 	printf("   Command line arguments:");
1343 	for (i = 0; i < argc; i++)
1344 		printf(" %S", argv[i]);
1345 	printf("\n");
1346 
1347 	printf("   Image base: 0x%lx\n", (unsigned long)boot_img->ImageBase);
1348 	printf("   EFI version: %d.%02d\n", ST->Hdr.Revision >> 16,
1349 	    ST->Hdr.Revision & 0xffff);
1350 	printf("   EFI Firmware: %S (rev %d.%02d)\n", ST->FirmwareVendor,
1351 	    ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
1352 	printf("   Console: %s (%#x)\n", getenv("console"), howto);
1353 
1354 	/* Determine the devpath of our image so we can prefer it. */
1355 	text = efi_devpath_name(boot_img->FilePath);
1356 	if (text != NULL) {
1357 		printf("   Load Path: %S\n", text);
1358 		efi_setenv_freebsd_wcs("LoaderPath", text);
1359 		efi_free_devpath_name(text);
1360 	}
1361 
1362 	rv = OpenProtocolByHandle(boot_img->DeviceHandle, &devid,
1363 	    (void **)&imgpath);
1364 	if (rv == EFI_SUCCESS) {
1365 		text = efi_devpath_name(imgpath);
1366 		if (text != NULL) {
1367 			printf("   Load Device: %S\n", text);
1368 			efi_setenv_freebsd_wcs("LoaderDev", text);
1369 			efi_free_devpath_name(text);
1370 		}
1371 	}
1372 
1373 	if (getenv("uefi_ignore_boot_mgr") != NULL) {
1374 		printf("    Ignoring UEFI boot manager\n");
1375 		uefi_boot_mgr = false;
1376 	} else {
1377 		uefi_boot_mgr = true;
1378 		boot_current = 0;
1379 		sz = sizeof(boot_current);
1380 		rv = efi_global_getenv("BootCurrent", &boot_current, &sz);
1381 		if (rv == EFI_SUCCESS)
1382 			printf("   BootCurrent: %04x\n", boot_current);
1383 		else {
1384 			boot_current = 0xffff;
1385 			uefi_boot_mgr = false;
1386 		}
1387 
1388 		sz = sizeof(boot_order);
1389 		rv = efi_global_getenv("BootOrder", &boot_order, &sz);
1390 		if (rv == EFI_SUCCESS) {
1391 			printf("   BootOrder:");
1392 			for (i = 0; i < sz / sizeof(boot_order[0]); i++)
1393 				printf(" %04x%s", boot_order[i],
1394 				    boot_order[i] == boot_current ? "[*]" : "");
1395 			printf("\n");
1396 		} else if (uefi_boot_mgr) {
1397 			/*
1398 			 * u-boot doesn't set BootOrder, but otherwise participates in the
1399 			 * boot manager protocol. So we fake it here and don't consider it
1400 			 * a failure.
1401 			 */
1402 			boot_order[0] = boot_current;
1403 		}
1404 	}
1405 
1406 	/*
1407 	 * Next, find the boot info structure the UEFI boot manager is
1408 	 * supposed to setup. We need this so we can walk through it to
1409 	 * find where we are in the booting process and what to try to
1410 	 * boot next.
1411 	 */
1412 	if (uefi_boot_mgr) {
1413 		snprintf(buf, sizeof(buf), "Boot%04X", boot_current);
1414 		sz = sizeof(boot_info);
1415 		rv = efi_global_getenv(buf, &boot_info, &sz);
1416 		if (rv == EFI_SUCCESS)
1417 			bisz = sz;
1418 		else
1419 			uefi_boot_mgr = false;
1420 	}
1421 
1422 	/*
1423 	 * Disable the watchdog timer. By default the boot manager sets
1424 	 * the timer to 5 minutes before invoking a boot option. If we
1425 	 * want to return to the boot manager, we have to disable the
1426 	 * watchdog timer and since we're an interactive program, we don't
1427 	 * want to wait until the user types "quit". The timer may have
1428 	 * fired by then. We don't care if this fails. It does not prevent
1429 	 * normal functioning in any way...
1430 	 */
1431 	BS->SetWatchdogTimer(0, 0, 0, NULL);
1432 
1433 	/*
1434 	 * Initialize the trusted/forbidden certificates from UEFI.
1435 	 * They will be later used to verify the manifest(s),
1436 	 * which should contain hashes of verified files.
1437 	 * This needs to be initialized before any configuration files
1438 	 * are loaded.
1439 	 */
1440 #ifdef EFI_SECUREBOOT
1441 	ve_efi_init();
1442 #endif
1443 
1444 	/*
1445 	 * Try and find a good currdev based on the image that was booted.
1446 	 * It might be desirable here to have a short pause to allow falling
1447 	 * through to the boot loader instead of returning instantly to follow
1448 	 * the boot protocol and also allow an escape hatch for users wishing
1449 	 * to try something different.
1450 	 */
1451 	if (find_currdev(uefi_boot_mgr, boot_info, bisz) != 0)
1452 		if (uefi_boot_mgr &&
1453 		    !interactive_interrupt("Failed to find bootable partition"))
1454 			return (EFI_NOT_FOUND);
1455 
1456 	autoload_font(false);	/* Set up the font list for console. */
1457 	efi_init_environment();
1458 
1459 	interact();			/* doesn't return */
1460 
1461 	return (EFI_SUCCESS);		/* keep compiler happy */
1462 }
1463 
1464 COMMAND_SET(efi_seed_entropy, "efi-seed-entropy", "try to get entropy from the EFI RNG", command_seed_entropy);
1465 
1466 static int
command_seed_entropy(int argc,char * argv[])1467 command_seed_entropy(int argc, char *argv[])
1468 {
1469 	EFI_STATUS status;
1470 	EFI_RNG_PROTOCOL *rng;
1471 	unsigned int size_efi = RANDOM_FORTUNA_DEFPOOLSIZE * RANDOM_FORTUNA_NPOOLS;
1472 	unsigned int size = RANDOM_FORTUNA_DEFPOOLSIZE * RANDOM_FORTUNA_NPOOLS;
1473 	void *buf_efi;
1474 	void *buf;
1475 
1476 	if (argc > 1) {
1477 		size_efi = strtol(argv[1], NULL, 0);
1478 
1479 		/* Don't *compress* the entropy we get from EFI. */
1480 		if (size_efi > size)
1481 			size = size_efi;
1482 
1483 		/*
1484 		 * If the amount of entropy we get from EFI is less than the
1485 		 * size of a single Fortuna pool -- i.e. not enough to ensure
1486 		 * that Fortuna is safely seeded -- don't expand it since we
1487 		 * don't want to trick Fortuna into thinking that it has been
1488 		 * safely seeded when it has not.
1489 		 */
1490 		if (size_efi < RANDOM_FORTUNA_DEFPOOLSIZE)
1491 			size = size_efi;
1492 	}
1493 
1494 	status = BS->LocateProtocol(&rng_guid, NULL, (VOID **)&rng);
1495 	if (status != EFI_SUCCESS) {
1496 		command_errmsg = "RNG protocol not found";
1497 		return (CMD_ERROR);
1498 	}
1499 
1500 	if ((buf = malloc(size)) == NULL) {
1501 		command_errmsg = "out of memory";
1502 		return (CMD_ERROR);
1503 	}
1504 
1505 	if ((buf_efi = malloc(size_efi)) == NULL) {
1506 		free(buf);
1507 		command_errmsg = "out of memory";
1508 		return (CMD_ERROR);
1509 	}
1510 
1511 	TSENTER2("rng->GetRNG");
1512 	status = rng->GetRNG(rng, NULL, size_efi, (UINT8 *)buf_efi);
1513 	TSEXIT();
1514 	if (status != EFI_SUCCESS) {
1515 		free(buf_efi);
1516 		free(buf);
1517 		command_errmsg = "GetRNG failed";
1518 		return (CMD_ERROR);
1519 	}
1520 	if (size_efi < size)
1521 		pkcs5v2_genkey_raw(buf, size, "", 0, buf_efi, size_efi, 1);
1522 	else
1523 		memcpy(buf, buf_efi, size);
1524 
1525 	if (file_addbuf("efi_rng_seed", "boot_entropy_platform", size, buf) != 0) {
1526 		free(buf_efi);
1527 		free(buf);
1528 		return (CMD_ERROR);
1529 	}
1530 
1531 	explicit_bzero(buf_efi, size_efi);
1532 	free(buf_efi);
1533 	free(buf);
1534 	return (CMD_OK);
1535 }
1536 
1537 COMMAND_SET(poweroff, "poweroff", "power off the system", command_poweroff);
1538 COMMAND_SET(halt, "halt", "power off the system", command_poweroff);
1539 
1540 static int
command_poweroff(int argc __unused,char * argv[]__unused)1541 command_poweroff(int argc __unused, char *argv[] __unused)
1542 {
1543 	int i;
1544 
1545 	for (i = 0; devsw[i] != NULL; ++i)
1546 		if (devsw[i]->dv_cleanup != NULL)
1547 			(devsw[i]->dv_cleanup)();
1548 
1549 	RS->ResetSystem(EfiResetShutdown, EFI_SUCCESS, 0, NULL);
1550 
1551 	/* NOTREACHED */
1552 	return (CMD_ERROR);
1553 }
1554 
1555 COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot);
1556 
1557 static int
command_reboot(int argc,char * argv[])1558 command_reboot(int argc, char *argv[])
1559 {
1560 	int i;
1561 
1562 	for (i = 0; devsw[i] != NULL; ++i)
1563 		if (devsw[i]->dv_cleanup != NULL)
1564 			(devsw[i]->dv_cleanup)();
1565 
1566 	RS->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL);
1567 
1568 	/* NOTREACHED */
1569 	return (CMD_ERROR);
1570 }
1571 
1572 COMMAND_SET(memmap, "memmap", "print memory map", command_memmap);
1573 
1574 static int
command_memmap(int argc __unused,char * argv[]__unused)1575 command_memmap(int argc __unused, char *argv[] __unused)
1576 {
1577 	UINTN sz;
1578 	EFI_MEMORY_DESCRIPTOR *map, *p;
1579 	UINTN key, dsz;
1580 	UINT32 dver;
1581 	EFI_STATUS status;
1582 	int i, ndesc;
1583 	char line[80];
1584 
1585 	sz = 0;
1586 	status = BS->GetMemoryMap(&sz, 0, &key, &dsz, &dver);
1587 	if (status != EFI_BUFFER_TOO_SMALL) {
1588 		printf("Can't determine memory map size\n");
1589 		return (CMD_ERROR);
1590 	}
1591 	map = malloc(sz);
1592 	status = BS->GetMemoryMap(&sz, map, &key, &dsz, &dver);
1593 	if (EFI_ERROR(status)) {
1594 		printf("Can't read memory map\n");
1595 		return (CMD_ERROR);
1596 	}
1597 
1598 	ndesc = sz / dsz;
1599 	snprintf(line, sizeof(line), "%23s %12s %12s %8s %4s\n",
1600 	    "Type", "Physical", "Virtual", "#Pages", "Attr");
1601 	pager_open();
1602 	if (pager_output(line)) {
1603 		pager_close();
1604 		return (CMD_OK);
1605 	}
1606 
1607 	for (i = 0, p = map; i < ndesc;
1608 	     i++, p = NextMemoryDescriptor(p, dsz)) {
1609 		snprintf(line, sizeof(line), "%23s %012jx %012jx %08jx ",
1610 		    efi_memory_type(p->Type), (uintmax_t)p->PhysicalStart,
1611 		    (uintmax_t)p->VirtualStart, (uintmax_t)p->NumberOfPages);
1612 		if (pager_output(line))
1613 			break;
1614 
1615 		if (p->Attribute & EFI_MEMORY_UC)
1616 			printf("UC ");
1617 		if (p->Attribute & EFI_MEMORY_WC)
1618 			printf("WC ");
1619 		if (p->Attribute & EFI_MEMORY_WT)
1620 			printf("WT ");
1621 		if (p->Attribute & EFI_MEMORY_WB)
1622 			printf("WB ");
1623 		if (p->Attribute & EFI_MEMORY_UCE)
1624 			printf("UCE ");
1625 		if (p->Attribute & EFI_MEMORY_WP)
1626 			printf("WP ");
1627 		if (p->Attribute & EFI_MEMORY_RP)
1628 			printf("RP ");
1629 		if (p->Attribute & EFI_MEMORY_XP)
1630 			printf("XP ");
1631 		if (p->Attribute & EFI_MEMORY_NV)
1632 			printf("NV ");
1633 		if (p->Attribute & EFI_MEMORY_MORE_RELIABLE)
1634 			printf("MR ");
1635 		if (p->Attribute & EFI_MEMORY_RO)
1636 			printf("RO ");
1637 		if (pager_output("\n"))
1638 			break;
1639 	}
1640 
1641 	pager_close();
1642 	return (CMD_OK);
1643 }
1644 
1645 COMMAND_SET(configuration, "configuration", "print configuration tables",
1646     command_configuration);
1647 
1648 static int
command_configuration(int argc,char * argv[])1649 command_configuration(int argc, char *argv[])
1650 {
1651 	UINTN i;
1652 	char *name;
1653 
1654 	printf("NumberOfTableEntries=%lu\n",
1655 		(unsigned long)ST->NumberOfTableEntries);
1656 
1657 	for (i = 0; i < ST->NumberOfTableEntries; i++) {
1658 		EFI_GUID *guid;
1659 
1660 		printf("  ");
1661 		guid = &ST->ConfigurationTable[i].VendorGuid;
1662 
1663 		if (efi_guid_to_name(guid, &name) == true) {
1664 			printf(name);
1665 			free(name);
1666 		} else {
1667 			printf("Error while translating UUID to name");
1668 		}
1669 		printf(" at %p\n", ST->ConfigurationTable[i].VendorTable);
1670 	}
1671 
1672 	return (CMD_OK);
1673 }
1674 
1675 
1676 COMMAND_SET(mode, "mode", "change or display EFI text modes", command_mode);
1677 
1678 static int
command_mode(int argc,char * argv[])1679 command_mode(int argc, char *argv[])
1680 {
1681 	UINTN cols, rows;
1682 	unsigned int mode;
1683 	int i;
1684 	char *cp;
1685 	EFI_STATUS status;
1686 	SIMPLE_TEXT_OUTPUT_INTERFACE *conout;
1687 
1688 	conout = ST->ConOut;
1689 
1690 	if (argc > 1) {
1691 		mode = strtol(argv[1], &cp, 0);
1692 		if (cp[0] != '\0') {
1693 			printf("Invalid mode\n");
1694 			return (CMD_ERROR);
1695 		}
1696 		status = conout->QueryMode(conout, mode, &cols, &rows);
1697 		if (EFI_ERROR(status)) {
1698 			printf("invalid mode %d\n", mode);
1699 			return (CMD_ERROR);
1700 		}
1701 		status = conout->SetMode(conout, mode);
1702 		if (EFI_ERROR(status)) {
1703 			printf("couldn't set mode %d\n", mode);
1704 			return (CMD_ERROR);
1705 		}
1706 		(void) cons_update_mode(true);
1707 		return (CMD_OK);
1708 	}
1709 
1710 	printf("Current mode: %d\n", conout->Mode->Mode);
1711 	for (i = 0; i <= conout->Mode->MaxMode; i++) {
1712 		status = conout->QueryMode(conout, i, &cols, &rows);
1713 		if (EFI_ERROR(status))
1714 			continue;
1715 		printf("Mode %d: %u columns, %u rows\n", i, (unsigned)cols,
1716 		    (unsigned)rows);
1717 	}
1718 
1719 	if (i != 0)
1720 		printf("Select a mode with the command \"mode <number>\"\n");
1721 
1722 	return (CMD_OK);
1723 }
1724 
1725 COMMAND_SET(lsefi, "lsefi", "list EFI handles", command_lsefi);
1726 
1727 static void
lsefi_print_handle_info(EFI_HANDLE handle)1728 lsefi_print_handle_info(EFI_HANDLE handle)
1729 {
1730 	EFI_DEVICE_PATH *devpath;
1731 	EFI_DEVICE_PATH *imagepath;
1732 	CHAR16 *dp_name;
1733 
1734 	imagepath = efi_lookup_image_devpath(handle);
1735 	if (imagepath != NULL) {
1736 		dp_name = efi_devpath_name(imagepath);
1737 		printf("Handle for image %S", dp_name);
1738 		efi_free_devpath_name(dp_name);
1739 		return;
1740 	}
1741 	devpath = efi_lookup_devpath(handle);
1742 	if (devpath != NULL) {
1743 		dp_name = efi_devpath_name(devpath);
1744 		printf("Handle for device %S", dp_name);
1745 		efi_free_devpath_name(dp_name);
1746 		return;
1747 	}
1748 	printf("Handle %p", handle);
1749 }
1750 
1751 static int
command_lsefi(int argc __unused,char * argv[]__unused)1752 command_lsefi(int argc __unused, char *argv[] __unused)
1753 {
1754 	char *name;
1755 	EFI_HANDLE *buffer = NULL;
1756 	EFI_HANDLE handle;
1757 	UINTN bufsz = 0, i, j;
1758 	EFI_STATUS status;
1759 	int ret = 0;
1760 
1761 	status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer);
1762 	if (status != EFI_BUFFER_TOO_SMALL) {
1763 		snprintf(command_errbuf, sizeof (command_errbuf),
1764 		    "unexpected error: %lld", (long long)status);
1765 		return (CMD_ERROR);
1766 	}
1767 	if ((buffer = malloc(bufsz)) == NULL) {
1768 		sprintf(command_errbuf, "out of memory");
1769 		return (CMD_ERROR);
1770 	}
1771 
1772 	status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer);
1773 	if (EFI_ERROR(status)) {
1774 		free(buffer);
1775 		snprintf(command_errbuf, sizeof (command_errbuf),
1776 		    "LocateHandle() error: %lld", (long long)status);
1777 		return (CMD_ERROR);
1778 	}
1779 
1780 	pager_open();
1781 	for (i = 0; i < (bufsz / sizeof (EFI_HANDLE)); i++) {
1782 		UINTN nproto = 0;
1783 		EFI_GUID **protocols = NULL;
1784 
1785 		handle = buffer[i];
1786 		lsefi_print_handle_info(handle);
1787 		if (pager_output("\n"))
1788 			break;
1789 		/* device path */
1790 
1791 		status = BS->ProtocolsPerHandle(handle, &protocols, &nproto);
1792 		if (EFI_ERROR(status)) {
1793 			snprintf(command_errbuf, sizeof (command_errbuf),
1794 			    "ProtocolsPerHandle() error: %lld",
1795 			    (long long)status);
1796 			continue;
1797 		}
1798 
1799 		for (j = 0; j < nproto; j++) {
1800 			if (efi_guid_to_name(protocols[j], &name) == true) {
1801 				printf("  %s", name);
1802 				free(name);
1803 			} else {
1804 				printf("Error while translating UUID to name");
1805 			}
1806 			if ((ret = pager_output("\n")) != 0)
1807 				break;
1808 		}
1809 		BS->FreePool(protocols);
1810 		if (ret != 0)
1811 			break;
1812 	}
1813 	pager_close();
1814 	free(buffer);
1815 	return (CMD_OK);
1816 }
1817 
1818 #ifdef LOADER_FDT_SUPPORT
1819 extern int command_fdt_internal(int argc, char *argv[]);
1820 
1821 /*
1822  * Since proper fdt command handling function is defined in fdt_loader_cmd.c,
1823  * and declaring it as extern is in contradiction with COMMAND_SET() macro
1824  * (which uses static pointer), we're defining wrapper function, which
1825  * calls the proper fdt handling routine.
1826  */
1827 static int
command_fdt(int argc,char * argv[])1828 command_fdt(int argc, char *argv[])
1829 {
1830 
1831 	return (command_fdt_internal(argc, argv));
1832 }
1833 
1834 COMMAND_SET(fdt, "fdt", "flattened device tree handling", command_fdt);
1835 #endif
1836 
1837 /*
1838  * Chain load another efi loader.
1839  */
1840 static int
command_chain(int argc,char * argv[])1841 command_chain(int argc, char *argv[])
1842 {
1843 	EFI_GUID LoadedImageGUID = LOADED_IMAGE_PROTOCOL;
1844 	EFI_HANDLE loaderhandle;
1845 	EFI_LOADED_IMAGE *loaded_image;
1846 	UINTN ExitDataSize;
1847 	CHAR16 *ExitData = NULL;
1848 	EFI_STATUS status;
1849 	struct stat st;
1850 	struct devdesc *dev;
1851 	char *name, *path;
1852 	void *buf;
1853 	int fd;
1854 
1855 	if (argc < 2) {
1856 		command_errmsg = "wrong number of arguments";
1857 		return (CMD_ERROR);
1858 	}
1859 
1860 	name = argv[1];
1861 
1862 	if ((fd = open(name, O_RDONLY)) < 0) {
1863 		command_errmsg = "no such file";
1864 		return (CMD_ERROR);
1865 	}
1866 
1867 #ifdef LOADER_VERIEXEC
1868 	if (verify_file(fd, name, 0, VE_MUST, __func__) < 0) {
1869 		sprintf(command_errbuf, "can't verify: %s", name);
1870 		close(fd);
1871 		return (CMD_ERROR);
1872 	}
1873 #endif
1874 
1875 	if (fstat(fd, &st) < -1) {
1876 		command_errmsg = "stat failed";
1877 		close(fd);
1878 		return (CMD_ERROR);
1879 	}
1880 
1881 	status = BS->AllocatePool(EfiLoaderCode, (UINTN)st.st_size, &buf);
1882 	if (status != EFI_SUCCESS) {
1883 		command_errmsg = "failed to allocate buffer";
1884 		close(fd);
1885 		return (CMD_ERROR);
1886 	}
1887 	if (read(fd, buf, st.st_size) != st.st_size) {
1888 		command_errmsg = "error while reading the file";
1889 		(void)BS->FreePool(buf);
1890 		close(fd);
1891 		return (CMD_ERROR);
1892 	}
1893 	close(fd);
1894 	status = BS->LoadImage(FALSE, IH, NULL, buf, st.st_size, &loaderhandle);
1895 	(void)BS->FreePool(buf);
1896 	if (status != EFI_SUCCESS) {
1897 		command_errmsg = "LoadImage failed";
1898 		return (CMD_ERROR);
1899 	}
1900 	status = OpenProtocolByHandle(loaderhandle, &LoadedImageGUID,
1901 	    (void **)&loaded_image);
1902 
1903 	if (argc > 2) {
1904 		int i, len = 0;
1905 		CHAR16 *argp;
1906 
1907 		for (i = 2; i < argc; i++)
1908 			len += strlen(argv[i]) + 1;
1909 
1910 		len *= sizeof (*argp);
1911 		loaded_image->LoadOptions = argp = malloc (len);
1912 		loaded_image->LoadOptionsSize = len;
1913 		for (i = 2; i < argc; i++) {
1914 			char *ptr = argv[i];
1915 			while (*ptr)
1916 				*(argp++) = *(ptr++);
1917 			*(argp++) = ' ';
1918 		}
1919 		*(--argv) = 0;
1920 	}
1921 
1922 	if (efi_getdev((void **)&dev, name, (const char **)&path) == 0) {
1923 #ifdef EFI_ZFS_BOOT
1924 		struct zfs_devdesc *z_dev;
1925 #endif
1926 		struct disk_devdesc *d_dev;
1927 		pdinfo_t *hd, *pd;
1928 
1929 		switch (dev->d_dev->dv_type) {
1930 #ifdef EFI_ZFS_BOOT
1931 		case DEVT_ZFS:
1932 			z_dev = (struct zfs_devdesc *)dev;
1933 			loaded_image->DeviceHandle =
1934 			    efizfs_get_handle_by_guid(z_dev->pool_guid);
1935 			break;
1936 #endif
1937 		case DEVT_NET:
1938 			loaded_image->DeviceHandle =
1939 			    efi_find_handle(dev->d_dev, dev->d_unit);
1940 			break;
1941 		default:
1942 			hd = efiblk_get_pdinfo(dev);
1943 			if (STAILQ_EMPTY(&hd->pd_part)) {
1944 				loaded_image->DeviceHandle = hd->pd_handle;
1945 				break;
1946 			}
1947 			d_dev = (struct disk_devdesc *)dev;
1948 			STAILQ_FOREACH(pd, &hd->pd_part, pd_link) {
1949 				/*
1950 				 * d_partition should be 255
1951 				 */
1952 				if (pd->pd_unit == (uint32_t)d_dev->d_slice) {
1953 					loaded_image->DeviceHandle =
1954 					    pd->pd_handle;
1955 					break;
1956 				}
1957 			}
1958 			break;
1959 		}
1960 	}
1961 
1962 	dev_cleanup();
1963 
1964 	status = BS->StartImage(loaderhandle, &ExitDataSize, &ExitData);
1965 	if (status != EFI_SUCCESS) {
1966 		printf("StartImage failed (%lu)", DECODE_ERROR(status));
1967 		if (ExitData != NULL) {
1968 			printf(": %S", ExitData);
1969 			BS->FreePool(ExitData);
1970 		}
1971 		putchar('\n');
1972 		command_errmsg = "";
1973 		free(loaded_image->LoadOptions);
1974 		loaded_image->LoadOptions = NULL;
1975 		status = BS->UnloadImage(loaded_image);
1976 		return (CMD_ERROR);
1977 	}
1978 
1979 	return (CMD_ERROR);	/* not reached */
1980 }
1981 
1982 COMMAND_SET(chain, "chain", "chain load file", command_chain);
1983 
1984 #if defined(LOADER_NET_SUPPORT)
1985 extern struct in_addr servip;
1986 static int
command_netserver(int argc,char * argv[])1987 command_netserver(int argc, char *argv[])
1988 {
1989 	char *proto;
1990 	n_long rootaddr;
1991 
1992 	if (argc > 2) {
1993 		command_errmsg = "wrong number of arguments";
1994 		return (CMD_ERROR);
1995 	}
1996 	if (argc < 2) {
1997 		proto = netproto == NET_TFTP ? "tftp://" : "nfs://";
1998 		printf("Netserver URI: %s%s%s\n", proto, intoa(rootip.s_addr),
1999 		    rootpath);
2000 		return (CMD_OK);
2001 	}
2002 	if (argc == 2) {
2003 		strncpy(rootpath, argv[1], sizeof(rootpath));
2004 		rootpath[sizeof(rootpath) -1] = '\0';
2005 		if ((rootaddr = net_parse_rootpath()) != INADDR_NONE)
2006 			servip.s_addr = rootip.s_addr = rootaddr;
2007 		return (CMD_OK);
2008 	}
2009 	return (CMD_ERROR);	/* not reached */
2010 
2011 }
2012 
2013 COMMAND_SET(netserver, "netserver", "change or display netserver URI",
2014     command_netserver);
2015 #endif
2016