xref: /freebsd/stand/efi/loader/main.c (revision a259b98fa211ed87bfee58c575de4e2de94ee0fa)
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 EFI_STATUS
1277 main(int argc, CHAR16 *argv[])
1278 {
1279 	int howto, i, uhowto;
1280 	bool has_ipxe, has_kbd;
1281 	char *s;
1282 	EFI_DEVICE_PATH *imgpath;
1283 	CHAR16 *text;
1284 	EFI_STATUS rv;
1285 	size_t sz, bisz = 0;
1286 	UINT16 boot_order[100];
1287 	char boot_info[4096];
1288 	char buf[32];
1289 	bool uefi_boot_mgr;
1290 
1291 #if !defined(__arm__)
1292 	efi_smbios_detect();
1293 #endif
1294 
1295         /* Get our loaded image protocol interface structure. */
1296 	(void)OpenProtocolByHandle(IH, &imgid, (void **)&boot_img);
1297 
1298 	/* Report the RSDP early. */
1299 	acpi_detect();
1300 
1301 #ifdef LOADER_VERIEXEC
1302 	/* tell boot_setenv to be careful */
1303 	set_check_restricted(true);
1304 #endif
1305 
1306 	/*
1307 	 * Chicken-and-egg problem; we want to have console output early, but
1308 	 * some console attributes may depend on reading from eg. the boot
1309 	 * device, which we can't do yet.  We can use printf() etc. once this is
1310 	 * done. So, we set it to the efi console, then call console init. This
1311 	 * gets us printf early, but also primes the pump for all future console
1312 	 * changes to take effect, regardless of where they come from.
1313 	 */
1314 	setenv("console", "efi", 1);
1315 	uhowto = parse_uefi_con_out();
1316 #if defined(__riscv)
1317 	/*
1318 	 * This workaround likely is papering over a real issue
1319 	 */
1320 	if ((uhowto & RB_SERIAL) != 0)
1321 		setenv("console", "comconsole", 1);
1322 #endif
1323 	cons_probe();
1324 
1325 	/* Set print_delay variable to have hooks in place. */
1326 	env_setenv("print_delay", EV_VOLATILE, "", setprint_delay, env_nounset);
1327 
1328 	/* Set up currdev variable to have hooks in place. */
1329 	env_setenv("currdev", EV_VOLATILE, "", gen_setcurrdev, env_nounset);
1330 
1331 	/* Init the time source */
1332 	efi_time_init();
1333 
1334 	/*
1335 	 * Initialise the block cache. Set the upper limit.
1336 	 */
1337 	bcache_init(32768, 512);
1338 
1339 	/*
1340 	 * Scan the command line args for memdisk=<url> and download that image
1341 	 * to install as a ramdisk. This needs to be done before we scan the
1342 	 * handles because it installs a handle and creates the right ACPI
1343 	 * tables for the kernel to find it.
1344 	 */
1345 	has_ipxe = maybe_download_ramdisk(argc, argv);
1346 
1347 	/*
1348 	 * Scan the BLOCK IO MEDIA handles then
1349 	 * march through the device switch probing for things.
1350 	 */
1351 	i = efipart_inithandles();
1352 	if (i != 0 && i != ENOENT) {
1353 		printf("efipart_inithandles failed with ERRNO %d, expect "
1354 		    "failures\n", i);
1355 	}
1356 
1357 	/*
1358 	 * Scan all the VirtualDisks, passing them along to the FreeBSD kernel.
1359 	 */
1360 	efiblk_memdisk_preload();
1361 
1362 	devinit();
1363 	if (!has_ipxe)
1364 		maybe_download_initmd();
1365 
1366 	/*
1367 	 * Detect console settings two different ways: one via the command
1368 	 * args (eg -h) or via the UEFI ConOut variable.
1369 	 */
1370 	has_kbd = has_keyboard();
1371 	howto = parse_args(argc, argv);
1372 	if (!has_kbd && (howto & RB_PROBE))
1373 		howto |= RB_SERIAL | RB_MULTIPLE;
1374 	howto &= ~RB_PROBE;
1375 
1376 	/*
1377 	 * Read additional environment variables from the boot device's
1378 	 * "LoaderEnv" file. Any boot loader environment variable may be set
1379 	 * there, which are subtly different than loader.conf variables. Only
1380 	 * the 'simple' ones may be set so things like foo_load="YES" won't work
1381 	 * for two reasons.  First, the parser is simplistic and doesn't grok
1382 	 * quotes.  Second, because the variables that cause an action to happen
1383 	 * are parsed by the lua, 4th or whatever code that's not yet
1384 	 * loaded. This is relative to the root directory when loader.efi is
1385 	 * loaded off the UFS root drive (when chain booted), or from the ESP
1386 	 * when directly loaded by the BIOS.
1387 	 *
1388 	 * We also read in NextLoaderEnv if it was specified. This allows next boot
1389 	 * functionality to be implemented and to override anything in LoaderEnv.
1390 	 */
1391 	read_loader_env("LoaderEnv", "/efi/freebsd/loader.env", false);
1392 	read_loader_env("NextLoaderEnv", NULL, true);
1393 
1394 	set_boot_policy();
1395 
1396 	/*
1397 	 * We now have two notions of console. howto should be viewed as
1398 	 * overrides. If console is already set, don't set it again.
1399 	 */
1400 #define	VIDEO_ONLY	0
1401 #define	SERIAL_ONLY	RB_SERIAL
1402 #define	VID_SER_BOTH	RB_MULTIPLE
1403 #define	SER_VID_BOTH	(RB_SERIAL | RB_MULTIPLE)
1404 #define	CON_MASK	(RB_SERIAL | RB_MULTIPLE)
1405 	if (strcmp(getenv("console"), "efi") == 0) {
1406 		if ((howto & CON_MASK) == 0) {
1407 			/* No override, uhowto is controlling and efi cons is perfect */
1408 			howto = howto | (uhowto & CON_MASK);
1409 		} else if ((howto & CON_MASK) == (uhowto & CON_MASK)) {
1410 			/* override matches what UEFI told us, efi console is perfect */
1411 		} else if ((uhowto & (CON_MASK)) != 0) {
1412 			/*
1413 			 * We detected a serial console on ConOut. All possible
1414 			 * overrides include serial. We can't really override what efi
1415 			 * gives us, so we use it knowing it's the best choice.
1416 			 */
1417 			/* Do nothing */
1418 		} else {
1419 			/*
1420 			 * We detected some kind of serial in the override, but ConOut
1421 			 * has no serial, so we have to sort out which case it really is.
1422 			 */
1423 			switch (howto & CON_MASK) {
1424 			case SERIAL_ONLY:
1425 				setenv("console", "comconsole", 1);
1426 				break;
1427 			case VID_SER_BOTH:
1428 				setenv("console", "efi,comconsole", 1);
1429 				break;
1430 			case SER_VID_BOTH:
1431 				setenv("console", "comconsole,efi", 1);
1432 				break;
1433 				/* case VIDEO_ONLY can't happen -- it's the first if above */
1434 			}
1435 		}
1436 	}
1437 
1438 	/*
1439 	 * howto is set now how we want to export the flags to the kernel, so
1440 	 * set the env based on it.
1441 	 */
1442 	boot_howto_to_env(howto);
1443 
1444 	if (efi_copy_init())
1445 		return (EFI_BUFFER_TOO_SMALL);
1446 
1447 	if ((s = getenv("fail_timeout")) != NULL)
1448 		fail_timeout = strtol(s, NULL, 10);
1449 
1450 	printf("%s\n", bootprog_info);
1451 	printf("   Command line arguments:");
1452 	for (i = 0; i < argc; i++)
1453 		printf(" %S", argv[i]);
1454 	printf("\n");
1455 
1456 	printf("   Image base: 0x%lx\n", (unsigned long)boot_img->ImageBase);
1457 	printf("   EFI version: %d.%02d\n", ST->Hdr.Revision >> 16,
1458 	    ST->Hdr.Revision & 0xffff);
1459 	printf("   EFI Firmware: %S (rev %d.%02d)\n", ST->FirmwareVendor,
1460 	    ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
1461 	printf("   Console: %s (%#x)\n", getenv("console"), howto);
1462 
1463 	/* Determine the devpath of our image so we can prefer it. */
1464 	text = efi_devpath_name(boot_img->FilePath);
1465 	if (text != NULL) {
1466 		printf("   Load Path: %S\n", text);
1467 		efi_setenv_freebsd_wcs("LoaderPath", text);
1468 		efi_free_devpath_name(text);
1469 	}
1470 
1471 	rv = OpenProtocolByHandle(boot_img->DeviceHandle, &devid,
1472 	    (void **)&imgpath);
1473 	if (rv == EFI_SUCCESS) {
1474 		text = efi_devpath_name(imgpath);
1475 		if (text != NULL) {
1476 			printf("   Load Device: %S\n", text);
1477 			efi_setenv_freebsd_wcs("LoaderDev", text);
1478 			efi_free_devpath_name(text);
1479 		}
1480 	}
1481 
1482 	if (getenv("uefi_ignore_boot_mgr") != NULL) {
1483 		printf("    Ignoring UEFI boot manager\n");
1484 		uefi_boot_mgr = false;
1485 	} else {
1486 		uefi_boot_mgr = true;
1487 		boot_current = 0;
1488 		sz = sizeof(boot_current);
1489 		rv = efi_global_getenv("BootCurrent", &boot_current, &sz);
1490 		if (rv == EFI_SUCCESS)
1491 			printf("   BootCurrent: %04x\n", boot_current);
1492 		else {
1493 			boot_current = 0xffff;
1494 			uefi_boot_mgr = false;
1495 		}
1496 
1497 		sz = sizeof(boot_order);
1498 		rv = efi_global_getenv("BootOrder", &boot_order, &sz);
1499 		if (rv == EFI_SUCCESS) {
1500 			printf("   BootOrder:");
1501 			for (i = 0; i < sz / sizeof(boot_order[0]); i++)
1502 				printf(" %04x%s", boot_order[i],
1503 				    boot_order[i] == boot_current ? "[*]" : "");
1504 			printf("\n");
1505 		} else if (uefi_boot_mgr) {
1506 			/*
1507 			 * u-boot doesn't set BootOrder, but otherwise participates in the
1508 			 * boot manager protocol. So we fake it here and don't consider it
1509 			 * a failure.
1510 			 */
1511 			boot_order[0] = boot_current;
1512 		}
1513 	}
1514 
1515 	/*
1516 	 * Next, find the boot info structure the UEFI boot manager is
1517 	 * supposed to setup. We need this so we can walk through it to
1518 	 * find where we are in the booting process and what to try to
1519 	 * boot next.
1520 	 */
1521 	if (uefi_boot_mgr) {
1522 		snprintf(buf, sizeof(buf), "Boot%04X", boot_current);
1523 		sz = sizeof(boot_info);
1524 		rv = efi_global_getenv(buf, &boot_info, &sz);
1525 		if (rv == EFI_SUCCESS)
1526 			bisz = sz;
1527 		else
1528 			uefi_boot_mgr = false;
1529 	}
1530 
1531 	/*
1532 	 * Disable the watchdog timer. By default the boot manager sets
1533 	 * the timer to 5 minutes before invoking a boot option. If we
1534 	 * want to return to the boot manager, we have to disable the
1535 	 * watchdog timer and since we're an interactive program, we don't
1536 	 * want to wait until the user types "quit". The timer may have
1537 	 * fired by then. We don't care if this fails. It does not prevent
1538 	 * normal functioning in any way...
1539 	 */
1540 	BS->SetWatchdogTimer(0, 0, 0, NULL);
1541 
1542 	/*
1543 	 * Initialize the trusted/forbidden certificates from UEFI.
1544 	 * They will be later used to verify the manifest(s),
1545 	 * which should contain hashes of verified files.
1546 	 * This needs to be initialized before any configuration files
1547 	 * are loaded.
1548 	 */
1549 #ifdef EFI_SECUREBOOT
1550 	ve_efi_init();
1551 #endif
1552 
1553 	/*
1554 	 * Try and find a good currdev based on the image that was booted.
1555 	 * It might be desirable here to have a short pause to allow falling
1556 	 * through to the boot loader instead of returning instantly to follow
1557 	 * the boot protocol and also allow an escape hatch for users wishing
1558 	 * to try something different.
1559 	 */
1560 	if (find_currdev(uefi_boot_mgr, boot_info, bisz) != 0)
1561 		if (uefi_boot_mgr &&
1562 		    !interactive_interrupt("Failed to find bootable partition"))
1563 			return (EFI_NOT_FOUND);
1564 
1565 	autoload_font(false);	/* Set up the font list for console. */
1566 	efi_init_environment();
1567 
1568 	interact();			/* doesn't return */
1569 
1570 	return (EFI_SUCCESS);		/* keep compiler happy */
1571 }
1572 
1573 COMMAND_SET(efi_seed_entropy, "efi-seed-entropy", "try to get entropy from the EFI RNG", command_seed_entropy);
1574 
1575 static int
1576 command_seed_entropy(int argc, char *argv[])
1577 {
1578 	EFI_STATUS status;
1579 	EFI_RNG_PROTOCOL *rng;
1580 	unsigned int size_efi = RANDOM_FORTUNA_DEFPOOLSIZE * RANDOM_FORTUNA_NPOOLS;
1581 	unsigned int size = RANDOM_FORTUNA_DEFPOOLSIZE * RANDOM_FORTUNA_NPOOLS;
1582 	void *buf_efi;
1583 	void *buf;
1584 
1585 	if (argc > 1) {
1586 		size_efi = strtol(argv[1], NULL, 0);
1587 
1588 		/* Don't *compress* the entropy we get from EFI. */
1589 		if (size_efi > size)
1590 			size = size_efi;
1591 
1592 		/*
1593 		 * If the amount of entropy we get from EFI is less than the
1594 		 * size of a single Fortuna pool -- i.e. not enough to ensure
1595 		 * that Fortuna is safely seeded -- don't expand it since we
1596 		 * don't want to trick Fortuna into thinking that it has been
1597 		 * safely seeded when it has not.
1598 		 */
1599 		if (size_efi < RANDOM_FORTUNA_DEFPOOLSIZE)
1600 			size = size_efi;
1601 	}
1602 
1603 	status = BS->LocateProtocol(&rng_guid, NULL, (VOID **)&rng);
1604 	if (status != EFI_SUCCESS) {
1605 		command_errmsg = "RNG protocol not found";
1606 		return (CMD_ERROR);
1607 	}
1608 
1609 	if ((buf = malloc(size)) == NULL) {
1610 		command_errmsg = "out of memory";
1611 		return (CMD_ERROR);
1612 	}
1613 
1614 	if ((buf_efi = malloc(size_efi)) == NULL) {
1615 		free(buf);
1616 		command_errmsg = "out of memory";
1617 		return (CMD_ERROR);
1618 	}
1619 
1620 	TSENTER2("rng->GetRNG");
1621 	status = rng->GetRNG(rng, NULL, size_efi, (UINT8 *)buf_efi);
1622 	TSEXIT();
1623 	if (status != EFI_SUCCESS) {
1624 		free(buf_efi);
1625 		free(buf);
1626 		command_errmsg = "GetRNG failed";
1627 		return (CMD_ERROR);
1628 	}
1629 	if (size_efi < size)
1630 		pkcs5v2_genkey_raw(buf, size, "", 0, buf_efi, size_efi, 1);
1631 	else
1632 		memcpy(buf, buf_efi, size);
1633 
1634 	if (file_addbuf("efi_rng_seed", "boot_entropy_platform", size, buf) != 0) {
1635 		free(buf_efi);
1636 		free(buf);
1637 		return (CMD_ERROR);
1638 	}
1639 
1640 	explicit_bzero(buf_efi, size_efi);
1641 	free(buf_efi);
1642 	free(buf);
1643 	return (CMD_OK);
1644 }
1645 
1646 COMMAND_SET(poweroff, "poweroff", "power off the system", command_poweroff);
1647 COMMAND_SET(halt, "halt", "power off the system", command_poweroff);
1648 
1649 static int
1650 command_poweroff(int argc __unused, char *argv[] __unused)
1651 {
1652 	int i;
1653 
1654 	for (i = 0; devsw[i] != NULL; ++i)
1655 		if (devsw[i]->dv_cleanup != NULL)
1656 			(devsw[i]->dv_cleanup)();
1657 
1658 	RS->ResetSystem(EfiResetShutdown, EFI_SUCCESS, 0, NULL);
1659 
1660 	/* NOTREACHED */
1661 	return (CMD_ERROR);
1662 }
1663 
1664 COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot);
1665 
1666 static int
1667 command_reboot(int argc, char *argv[])
1668 {
1669 	int i;
1670 
1671 	for (i = 0; devsw[i] != NULL; ++i)
1672 		if (devsw[i]->dv_cleanup != NULL)
1673 			(devsw[i]->dv_cleanup)();
1674 
1675 	RS->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL);
1676 
1677 	/* NOTREACHED */
1678 	return (CMD_ERROR);
1679 }
1680 
1681 COMMAND_SET(memmap, "memmap", "print memory map", command_memmap);
1682 
1683 static int
1684 command_memmap(int argc __unused, char *argv[] __unused)
1685 {
1686 	UINTN sz;
1687 	EFI_MEMORY_DESCRIPTOR *map, *p;
1688 	UINTN key, dsz;
1689 	UINT32 dver;
1690 	EFI_STATUS status;
1691 	int i, ndesc;
1692 	char line[80];
1693 
1694 	sz = 0;
1695 	status = BS->GetMemoryMap(&sz, 0, &key, &dsz, &dver);
1696 	if (status != EFI_BUFFER_TOO_SMALL) {
1697 		printf("Can't determine memory map size\n");
1698 		return (CMD_ERROR);
1699 	}
1700 	map = malloc(sz);
1701 	status = BS->GetMemoryMap(&sz, map, &key, &dsz, &dver);
1702 	if (EFI_ERROR(status)) {
1703 		printf("Can't read memory map\n");
1704 		return (CMD_ERROR);
1705 	}
1706 
1707 	ndesc = sz / dsz;
1708 	snprintf(line, sizeof(line), "%23s %12s %12s %8s %4s\n",
1709 	    "Type", "Physical", "Virtual", "#Pages", "Attr");
1710 	pager_open();
1711 	if (pager_output(line)) {
1712 		pager_close();
1713 		return (CMD_OK);
1714 	}
1715 
1716 	for (i = 0, p = map; i < ndesc;
1717 	     i++, p = NextMemoryDescriptor(p, dsz)) {
1718 		snprintf(line, sizeof(line), "%23s %012jx %012jx %08jx ",
1719 		    efi_memory_type(p->Type), (uintmax_t)p->PhysicalStart,
1720 		    (uintmax_t)p->VirtualStart, (uintmax_t)p->NumberOfPages);
1721 		if (pager_output(line))
1722 			break;
1723 
1724 		if (p->Attribute & EFI_MEMORY_UC)
1725 			printf("UC ");
1726 		if (p->Attribute & EFI_MEMORY_WC)
1727 			printf("WC ");
1728 		if (p->Attribute & EFI_MEMORY_WT)
1729 			printf("WT ");
1730 		if (p->Attribute & EFI_MEMORY_WB)
1731 			printf("WB ");
1732 		if (p->Attribute & EFI_MEMORY_UCE)
1733 			printf("UCE ");
1734 		if (p->Attribute & EFI_MEMORY_WP)
1735 			printf("WP ");
1736 		if (p->Attribute & EFI_MEMORY_RP)
1737 			printf("RP ");
1738 		if (p->Attribute & EFI_MEMORY_XP)
1739 			printf("XP ");
1740 		if (p->Attribute & EFI_MEMORY_NV)
1741 			printf("NV ");
1742 		if (p->Attribute & EFI_MEMORY_MORE_RELIABLE)
1743 			printf("MR ");
1744 		if (p->Attribute & EFI_MEMORY_RO)
1745 			printf("RO ");
1746 		if (pager_output("\n"))
1747 			break;
1748 	}
1749 
1750 	pager_close();
1751 	return (CMD_OK);
1752 }
1753 
1754 COMMAND_SET(configuration, "configuration", "print configuration tables",
1755     command_configuration);
1756 
1757 static int
1758 command_configuration(int argc, char *argv[])
1759 {
1760 	UINTN i;
1761 	char *name;
1762 
1763 	printf("NumberOfTableEntries=%lu\n",
1764 		(unsigned long)ST->NumberOfTableEntries);
1765 
1766 	for (i = 0; i < ST->NumberOfTableEntries; i++) {
1767 		EFI_GUID *guid;
1768 
1769 		printf("  ");
1770 		guid = &ST->ConfigurationTable[i].VendorGuid;
1771 
1772 		if (efi_guid_to_name(guid, &name) == true) {
1773 			printf(name);
1774 			free(name);
1775 		} else {
1776 			printf("Error while translating UUID to name");
1777 		}
1778 		printf(" at %p\n", ST->ConfigurationTable[i].VendorTable);
1779 	}
1780 
1781 	return (CMD_OK);
1782 }
1783 
1784 
1785 COMMAND_SET(mode, "mode", "change or display EFI text modes", command_mode);
1786 
1787 static int
1788 command_mode(int argc, char *argv[])
1789 {
1790 	UINTN cols, rows;
1791 	unsigned int mode;
1792 	int i;
1793 	char *cp;
1794 	EFI_STATUS status;
1795 	SIMPLE_TEXT_OUTPUT_INTERFACE *conout;
1796 
1797 	conout = ST->ConOut;
1798 
1799 	if (argc > 1) {
1800 		mode = strtol(argv[1], &cp, 0);
1801 		if (cp[0] != '\0') {
1802 			printf("Invalid mode\n");
1803 			return (CMD_ERROR);
1804 		}
1805 		status = conout->QueryMode(conout, mode, &cols, &rows);
1806 		if (EFI_ERROR(status)) {
1807 			printf("invalid mode %d\n", mode);
1808 			return (CMD_ERROR);
1809 		}
1810 		status = conout->SetMode(conout, mode);
1811 		if (EFI_ERROR(status)) {
1812 			printf("couldn't set mode %d\n", mode);
1813 			return (CMD_ERROR);
1814 		}
1815 		(void) cons_update_mode(true);
1816 		return (CMD_OK);
1817 	}
1818 
1819 	printf("Current mode: %d\n", conout->Mode->Mode);
1820 	for (i = 0; i <= conout->Mode->MaxMode; i++) {
1821 		status = conout->QueryMode(conout, i, &cols, &rows);
1822 		if (EFI_ERROR(status))
1823 			continue;
1824 		printf("Mode %d: %u columns, %u rows\n", i, (unsigned)cols,
1825 		    (unsigned)rows);
1826 	}
1827 
1828 	if (i != 0)
1829 		printf("Select a mode with the command \"mode <number>\"\n");
1830 
1831 	return (CMD_OK);
1832 }
1833 
1834 COMMAND_SET(lsefi, "lsefi", "list EFI handles", command_lsefi);
1835 
1836 static void
1837 lsefi_print_handle_info(EFI_HANDLE handle)
1838 {
1839 	EFI_DEVICE_PATH *devpath;
1840 	EFI_DEVICE_PATH *imagepath;
1841 	CHAR16 *dp_name;
1842 
1843 	imagepath = efi_lookup_image_devpath(handle);
1844 	if (imagepath != NULL) {
1845 		dp_name = efi_devpath_name(imagepath);
1846 		printf("Handle for image %S", dp_name);
1847 		efi_free_devpath_name(dp_name);
1848 		return;
1849 	}
1850 	devpath = efi_lookup_devpath(handle);
1851 	if (devpath != NULL) {
1852 		dp_name = efi_devpath_name(devpath);
1853 		printf("Handle for device %S", dp_name);
1854 		efi_free_devpath_name(dp_name);
1855 		return;
1856 	}
1857 	printf("Handle %p", handle);
1858 }
1859 
1860 static int
1861 command_lsefi(int argc __unused, char *argv[] __unused)
1862 {
1863 	char *name;
1864 	EFI_HANDLE *buffer = NULL;
1865 	EFI_HANDLE handle;
1866 	UINTN bufsz = 0, i, j;
1867 	EFI_STATUS status;
1868 	int ret = 0;
1869 
1870 	status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer);
1871 	if (status != EFI_BUFFER_TOO_SMALL) {
1872 		snprintf(command_errbuf, sizeof (command_errbuf),
1873 		    "unexpected error: %lld", (long long)status);
1874 		return (CMD_ERROR);
1875 	}
1876 	if ((buffer = malloc(bufsz)) == NULL) {
1877 		sprintf(command_errbuf, "out of memory");
1878 		return (CMD_ERROR);
1879 	}
1880 
1881 	status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer);
1882 	if (EFI_ERROR(status)) {
1883 		free(buffer);
1884 		snprintf(command_errbuf, sizeof (command_errbuf),
1885 		    "LocateHandle() error: %lld", (long long)status);
1886 		return (CMD_ERROR);
1887 	}
1888 
1889 	pager_open();
1890 	for (i = 0; i < (bufsz / sizeof (EFI_HANDLE)); i++) {
1891 		UINTN nproto = 0;
1892 		EFI_GUID **protocols = NULL;
1893 
1894 		handle = buffer[i];
1895 		lsefi_print_handle_info(handle);
1896 		if (pager_output("\n"))
1897 			break;
1898 		/* device path */
1899 
1900 		status = BS->ProtocolsPerHandle(handle, &protocols, &nproto);
1901 		if (EFI_ERROR(status)) {
1902 			snprintf(command_errbuf, sizeof (command_errbuf),
1903 			    "ProtocolsPerHandle() error: %lld",
1904 			    (long long)status);
1905 			continue;
1906 		}
1907 
1908 		for (j = 0; j < nproto; j++) {
1909 			if (efi_guid_to_name(protocols[j], &name) == true) {
1910 				printf("  %s", name);
1911 				free(name);
1912 			} else {
1913 				printf("Error while translating UUID to name");
1914 			}
1915 			if ((ret = pager_output("\n")) != 0)
1916 				break;
1917 		}
1918 		BS->FreePool(protocols);
1919 		if (ret != 0)
1920 			break;
1921 	}
1922 	pager_close();
1923 	free(buffer);
1924 	return (CMD_OK);
1925 }
1926 
1927 #ifdef LOADER_FDT_SUPPORT
1928 extern int command_fdt_internal(int argc, char *argv[]);
1929 
1930 /*
1931  * Since proper fdt command handling function is defined in fdt_loader_cmd.c,
1932  * and declaring it as extern is in contradiction with COMMAND_SET() macro
1933  * (which uses static pointer), we're defining wrapper function, which
1934  * calls the proper fdt handling routine.
1935  */
1936 static int
1937 command_fdt(int argc, char *argv[])
1938 {
1939 
1940 	return (command_fdt_internal(argc, argv));
1941 }
1942 
1943 COMMAND_SET(fdt, "fdt", "flattened device tree handling", command_fdt);
1944 #endif
1945 
1946 /*
1947  * Chain load another efi loader.
1948  */
1949 static int
1950 command_chain(int argc, char *argv[])
1951 {
1952 	EFI_GUID LoadedImageGUID = LOADED_IMAGE_PROTOCOL;
1953 	EFI_HANDLE loaderhandle;
1954 	EFI_LOADED_IMAGE *loaded_image;
1955 	UINTN ExitDataSize;
1956 	CHAR16 *ExitData = NULL;
1957 	EFI_STATUS status;
1958 	struct stat st;
1959 	struct devdesc *dev;
1960 	char *name, *path;
1961 	void *buf;
1962 	int fd;
1963 
1964 	if (argc < 2) {
1965 		command_errmsg = "wrong number of arguments";
1966 		return (CMD_ERROR);
1967 	}
1968 
1969 	name = argv[1];
1970 
1971 	if ((fd = open(name, O_RDONLY)) < 0) {
1972 		command_errmsg = "no such file";
1973 		return (CMD_ERROR);
1974 	}
1975 
1976 #ifdef LOADER_VERIEXEC
1977 	if (verify_file(fd, name, 0, VE_MUST, __func__) < 0) {
1978 		sprintf(command_errbuf, "can't verify: %s", name);
1979 		close(fd);
1980 		return (CMD_ERROR);
1981 	}
1982 #endif
1983 
1984 	if (fstat(fd, &st) < -1) {
1985 		command_errmsg = "stat failed";
1986 		close(fd);
1987 		return (CMD_ERROR);
1988 	}
1989 
1990 	status = BS->AllocatePool(EfiLoaderCode, (UINTN)st.st_size, &buf);
1991 	if (status != EFI_SUCCESS) {
1992 		command_errmsg = "failed to allocate buffer";
1993 		close(fd);
1994 		return (CMD_ERROR);
1995 	}
1996 	if (read(fd, buf, st.st_size) != st.st_size) {
1997 		command_errmsg = "error while reading the file";
1998 		(void)BS->FreePool(buf);
1999 		close(fd);
2000 		return (CMD_ERROR);
2001 	}
2002 	close(fd);
2003 	status = BS->LoadImage(FALSE, IH, NULL, buf, st.st_size, &loaderhandle);
2004 	(void)BS->FreePool(buf);
2005 	if (status != EFI_SUCCESS) {
2006 		command_errmsg = "LoadImage failed";
2007 		return (CMD_ERROR);
2008 	}
2009 	status = OpenProtocolByHandle(loaderhandle, &LoadedImageGUID,
2010 	    (void **)&loaded_image);
2011 
2012 	if (argc > 2) {
2013 		int i, len = 0;
2014 		CHAR16 *argp;
2015 
2016 		for (i = 2; i < argc; i++)
2017 			len += strlen(argv[i]) + 1;
2018 
2019 		len *= sizeof (*argp);
2020 		loaded_image->LoadOptions = argp = malloc (len);
2021 		loaded_image->LoadOptionsSize = len;
2022 		for (i = 2; i < argc; i++) {
2023 			char *ptr = argv[i];
2024 			while (*ptr)
2025 				*(argp++) = *(ptr++);
2026 			*(argp++) = ' ';
2027 		}
2028 		*(--argv) = 0;
2029 	}
2030 
2031 	if (efi_getdev((void **)&dev, name, (const char **)&path) == 0) {
2032 #ifdef EFI_ZFS_BOOT
2033 		struct zfs_devdesc *z_dev;
2034 #endif
2035 		struct disk_devdesc *d_dev;
2036 		pdinfo_t *hd, *pd;
2037 
2038 		switch (dev->d_dev->dv_type) {
2039 #ifdef EFI_ZFS_BOOT
2040 		case DEVT_ZFS:
2041 			z_dev = (struct zfs_devdesc *)dev;
2042 			loaded_image->DeviceHandle =
2043 			    efizfs_get_handle_by_guid(z_dev->pool_guid);
2044 			break;
2045 #endif
2046 		case DEVT_NET:
2047 			loaded_image->DeviceHandle =
2048 			    efi_find_handle(dev->d_dev, dev->d_unit);
2049 			break;
2050 		default:
2051 			hd = efiblk_get_pdinfo(dev);
2052 			if (STAILQ_EMPTY(&hd->pd_part)) {
2053 				loaded_image->DeviceHandle = hd->pd_handle;
2054 				break;
2055 			}
2056 			d_dev = (struct disk_devdesc *)dev;
2057 			STAILQ_FOREACH(pd, &hd->pd_part, pd_link) {
2058 				/*
2059 				 * d_partition should be 255
2060 				 */
2061 				if (pd->pd_unit == (uint32_t)d_dev->d_slice) {
2062 					loaded_image->DeviceHandle =
2063 					    pd->pd_handle;
2064 					break;
2065 				}
2066 			}
2067 			break;
2068 		}
2069 	}
2070 
2071 	dev_cleanup();
2072 
2073 	status = BS->StartImage(loaderhandle, &ExitDataSize, &ExitData);
2074 	if (status != EFI_SUCCESS) {
2075 		printf("StartImage failed (%lu)", DECODE_ERROR(status));
2076 		if (ExitData != NULL) {
2077 			printf(": %S", ExitData);
2078 			BS->FreePool(ExitData);
2079 		}
2080 		putchar('\n');
2081 		command_errmsg = "";
2082 		free(loaded_image->LoadOptions);
2083 		loaded_image->LoadOptions = NULL;
2084 		status = BS->UnloadImage(loaded_image);
2085 		return (CMD_ERROR);
2086 	}
2087 
2088 	return (CMD_ERROR);	/* not reached */
2089 }
2090 
2091 COMMAND_SET(chain, "chain", "chain load file", command_chain);
2092 
2093 #if defined(LOADER_NET_SUPPORT)
2094 extern struct in_addr servip;
2095 static int
2096 command_netserver(int argc, char *argv[])
2097 {
2098 	char *proto;
2099 	n_long rootaddr;
2100 
2101 	if (argc > 2) {
2102 		command_errmsg = "wrong number of arguments";
2103 		return (CMD_ERROR);
2104 	}
2105 	if (argc < 2) {
2106 		proto = netproto == NET_TFTP ? "tftp://" : "nfs://";
2107 		printf("Netserver URI: %s%s%s\n", proto, intoa(rootip.s_addr),
2108 		    rootpath);
2109 		return (CMD_OK);
2110 	}
2111 	if (argc == 2) {
2112 		strncpy(rootpath, argv[1], sizeof(rootpath));
2113 		rootpath[sizeof(rootpath) -1] = '\0';
2114 		if ((rootaddr = net_parse_rootpath()) != INADDR_NONE)
2115 			servip.s_addr = rootip.s_addr = rootaddr;
2116 		return (CMD_OK);
2117 	}
2118 	return (CMD_ERROR);	/* not reached */
2119 
2120 }
2121 
2122 COMMAND_SET(netserver, "netserver", "change or display netserver URI",
2123     command_netserver);
2124 #endif
2125