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