xref: /freebsd/stand/efi/loader/main.c (revision 752c1d14e398faab8e6f19f99ee29df87ecb05e1)
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 <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include <stand.h>
34 
35 #include <sys/disk.h>
36 #include <sys/param.h>
37 #include <sys/reboot.h>
38 #include <sys/boot.h>
39 #ifdef EFI_ZFS_BOOT
40 #include <sys/zfs_bootenv.h>
41 #endif
42 #include <paths.h>
43 #include <stdint.h>
44 #include <string.h>
45 #include <setjmp.h>
46 #include <disk.h>
47 
48 #include <efi.h>
49 #include <efilib.h>
50 #include <efichar.h>
51 
52 #include <uuid.h>
53 
54 #include <bootstrap.h>
55 #include <smbios.h>
56 
57 #include "efizfs.h"
58 
59 #include "loader_efi.h"
60 
61 struct arch_switch archsw;	/* MI/MD interface boundary */
62 
63 EFI_GUID acpi = ACPI_TABLE_GUID;
64 EFI_GUID acpi20 = ACPI_20_TABLE_GUID;
65 EFI_GUID devid = DEVICE_PATH_PROTOCOL;
66 EFI_GUID imgid = LOADED_IMAGE_PROTOCOL;
67 EFI_GUID mps = MPS_TABLE_GUID;
68 EFI_GUID netid = EFI_SIMPLE_NETWORK_PROTOCOL;
69 EFI_GUID smbios = SMBIOS_TABLE_GUID;
70 EFI_GUID smbios3 = SMBIOS3_TABLE_GUID;
71 EFI_GUID dxe = DXE_SERVICES_TABLE_GUID;
72 EFI_GUID hoblist = HOB_LIST_TABLE_GUID;
73 EFI_GUID lzmadecomp = LZMA_DECOMPRESSION_GUID;
74 EFI_GUID mpcore = ARM_MP_CORE_INFO_TABLE_GUID;
75 EFI_GUID esrt = ESRT_TABLE_GUID;
76 EFI_GUID memtype = MEMORY_TYPE_INFORMATION_TABLE_GUID;
77 EFI_GUID debugimg = DEBUG_IMAGE_INFO_TABLE_GUID;
78 EFI_GUID fdtdtb = FDT_TABLE_GUID;
79 EFI_GUID inputid = SIMPLE_TEXT_INPUT_PROTOCOL;
80 
81 /*
82  * Number of seconds to wait for a keystroke before exiting with failure
83  * in the event no currdev is found. -2 means always break, -1 means
84  * never break, 0 means poll once and then reboot, > 0 means wait for
85  * that many seconds. "fail_timeout" can be set in the environment as
86  * well.
87  */
88 static int fail_timeout = 5;
89 
90 /*
91  * Current boot variable
92  */
93 UINT16 boot_current;
94 
95 /*
96  * Image that we booted from.
97  */
98 EFI_LOADED_IMAGE *boot_img;
99 
100 static bool
101 has_keyboard(void)
102 {
103 	EFI_STATUS status;
104 	EFI_DEVICE_PATH *path;
105 	EFI_HANDLE *hin, *hin_end, *walker;
106 	UINTN sz;
107 	bool retval = false;
108 
109 	/*
110 	 * Find all the handles that support the SIMPLE_TEXT_INPUT_PROTOCOL and
111 	 * do the typical dance to get the right sized buffer.
112 	 */
113 	sz = 0;
114 	hin = NULL;
115 	status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz, 0);
116 	if (status == EFI_BUFFER_TOO_SMALL) {
117 		hin = (EFI_HANDLE *)malloc(sz);
118 		status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz,
119 		    hin);
120 		if (EFI_ERROR(status))
121 			free(hin);
122 	}
123 	if (EFI_ERROR(status))
124 		return retval;
125 
126 	/*
127 	 * Look at each of the handles. If it supports the device path protocol,
128 	 * use it to get the device path for this handle. Then see if that
129 	 * device path matches either the USB device path for keyboards or the
130 	 * legacy device path for keyboards.
131 	 */
132 	hin_end = &hin[sz / sizeof(*hin)];
133 	for (walker = hin; walker < hin_end; walker++) {
134 		status = OpenProtocolByHandle(*walker, &devid, (void **)&path);
135 		if (EFI_ERROR(status))
136 			continue;
137 
138 		while (!IsDevicePathEnd(path)) {
139 			/*
140 			 * Check for the ACPI keyboard node. All PNP3xx nodes
141 			 * are keyboards of different flavors. Note: It is
142 			 * unclear of there's always a keyboard node when
143 			 * there's a keyboard controller, or if there's only one
144 			 * when a keyboard is detected at boot.
145 			 */
146 			if (DevicePathType(path) == ACPI_DEVICE_PATH &&
147 			    (DevicePathSubType(path) == ACPI_DP ||
148 				DevicePathSubType(path) == ACPI_EXTENDED_DP)) {
149 				ACPI_HID_DEVICE_PATH  *acpi;
150 
151 				acpi = (ACPI_HID_DEVICE_PATH *)(void *)path;
152 				if ((EISA_ID_TO_NUM(acpi->HID) & 0xff00) == 0x300 &&
153 				    (acpi->HID & 0xffff) == PNP_EISA_ID_CONST) {
154 					retval = true;
155 					goto out;
156 				}
157 			/*
158 			 * Check for USB keyboard node, if present. Unlike a
159 			 * PS/2 keyboard, these definitely only appear when
160 			 * connected to the system.
161 			 */
162 			} else if (DevicePathType(path) == MESSAGING_DEVICE_PATH &&
163 			    DevicePathSubType(path) == MSG_USB_CLASS_DP) {
164 				USB_CLASS_DEVICE_PATH *usb;
165 
166 				usb = (USB_CLASS_DEVICE_PATH *)(void *)path;
167 				if (usb->DeviceClass == 3 && /* HID */
168 				    usb->DeviceSubClass == 1 && /* Boot devices */
169 				    usb->DeviceProtocol == 1) { /* Boot keyboards */
170 					retval = true;
171 					goto out;
172 				}
173 			}
174 			path = NextDevicePathNode(path);
175 		}
176 	}
177 out:
178 	free(hin);
179 	return retval;
180 }
181 
182 static void
183 set_currdev(const char *devname)
184 {
185 
186 	/*
187 	 * Don't execute hooks here; we may need to try setting these more than
188 	 * once here if we're probing for the ZFS pool we're supposed to boot.
189 	 * The currdev hook is intended to just validate user input anyways,
190 	 * while the loaddev hook makes it immutable once we've determined what
191 	 * the proper currdev is.
192 	 */
193 	env_setenv("currdev", EV_VOLATILE | EV_NOHOOK, devname, efi_setcurrdev,
194 	    env_nounset);
195 	env_setenv("loaddev", EV_VOLATILE | EV_NOHOOK, devname, env_noset,
196 	    env_nounset);
197 }
198 
199 static void
200 set_currdev_devdesc(struct devdesc *currdev)
201 {
202 	const char *devname;
203 
204 	devname = efi_fmtdev(currdev);
205 	printf("Setting currdev to %s\n", devname);
206 	set_currdev(devname);
207 }
208 
209 static void
210 set_currdev_devsw(struct devsw *dev, int unit)
211 {
212 	struct devdesc currdev;
213 
214 	currdev.d_dev = dev;
215 	currdev.d_unit = unit;
216 
217 	set_currdev_devdesc(&currdev);
218 }
219 
220 static void
221 set_currdev_pdinfo(pdinfo_t *dp)
222 {
223 
224 	/*
225 	 * Disks are special: they have partitions. if the parent
226 	 * pointer is non-null, we're a partition not a full disk
227 	 * and we need to adjust currdev appropriately.
228 	 */
229 	if (dp->pd_devsw->dv_type == DEVT_DISK) {
230 		struct disk_devdesc currdev;
231 
232 		currdev.dd.d_dev = dp->pd_devsw;
233 		if (dp->pd_parent == NULL) {
234 			currdev.dd.d_unit = dp->pd_unit;
235 			currdev.d_slice = D_SLICENONE;
236 			currdev.d_partition = D_PARTNONE;
237 		} else {
238 			currdev.dd.d_unit = dp->pd_parent->pd_unit;
239 			currdev.d_slice = dp->pd_unit;
240 			currdev.d_partition = D_PARTISGPT; /* XXX Assumes GPT */
241 		}
242 		set_currdev_devdesc((struct devdesc *)&currdev);
243 	} else {
244 		set_currdev_devsw(dp->pd_devsw, dp->pd_unit);
245 	}
246 }
247 
248 static bool
249 sanity_check_currdev(void)
250 {
251 	struct stat st;
252 
253 	return (stat(PATH_DEFAULTS_LOADER_CONF, &st) == 0 ||
254 #ifdef PATH_BOOTABLE_TOKEN
255 	    stat(PATH_BOOTABLE_TOKEN, &st) == 0 || /* non-standard layout */
256 #endif
257 	    stat(PATH_KERNEL, &st) == 0);
258 }
259 
260 #ifdef EFI_ZFS_BOOT
261 static bool
262 probe_zfs_currdev(uint64_t guid)
263 {
264 	char *devname;
265 	struct zfs_devdesc currdev;
266 	char *buf = NULL;
267 	bool rv;
268 
269 	currdev.dd.d_dev = &zfs_dev;
270 	currdev.dd.d_unit = 0;
271 	currdev.pool_guid = guid;
272 	currdev.root_guid = 0;
273 	set_currdev_devdesc((struct devdesc *)&currdev);
274 	devname = efi_fmtdev(&currdev);
275 	init_zfs_boot_options(devname);
276 
277 	rv = sanity_check_currdev();
278 	if (rv) {
279 		buf = malloc(VDEV_PAD_SIZE);
280 		if (buf != NULL) {
281 			if (zfs_get_bootonce(&currdev, OS_BOOTONCE, buf,
282 			    VDEV_PAD_SIZE) == 0) {
283 				printf("zfs bootonce: %s\n", buf);
284 				set_currdev(buf);
285 				setenv("zfs-bootonce", buf, 1);
286 			}
287 			free(buf);
288 			(void) zfs_attach_nvstore(&currdev);
289 		}
290 	}
291 	return (rv);
292 }
293 #endif
294 
295 static bool
296 try_as_currdev(pdinfo_t *hd, pdinfo_t *pp)
297 {
298 	uint64_t guid;
299 
300 #ifdef EFI_ZFS_BOOT
301 	/*
302 	 * If there's a zpool on this device, try it as a ZFS
303 	 * filesystem, which has somewhat different setup than all
304 	 * other types of fs due to imperfect loader integration.
305 	 * This all stems from ZFS being both a device (zpool) and
306 	 * a filesystem, plus the boot env feature.
307 	 */
308 	if (efizfs_get_guid_by_handle(pp->pd_handle, &guid))
309 		return (probe_zfs_currdev(guid));
310 #endif
311 	/*
312 	 * All other filesystems just need the pdinfo
313 	 * initialized in the standard way.
314 	 */
315 	set_currdev_pdinfo(pp);
316 	return (sanity_check_currdev());
317 }
318 
319 /*
320  * Sometimes we get filenames that are all upper case
321  * and/or have backslashes in them. Filter all this out
322  * if it looks like we need to do so.
323  */
324 static void
325 fix_dosisms(char *p)
326 {
327 	while (*p) {
328 		if (isupper(*p))
329 			*p = tolower(*p);
330 		else if (*p == '\\')
331 			*p = '/';
332 		p++;
333 	}
334 }
335 
336 #define SIZE(dp, edp) (size_t)((intptr_t)(void *)edp - (intptr_t)(void *)dp)
337 
338 enum { BOOT_INFO_OK = 0, BAD_CHOICE = 1, NOT_SPECIFIC = 2  };
339 static int
340 match_boot_info(char *boot_info, size_t bisz)
341 {
342 	uint32_t attr;
343 	uint16_t fplen;
344 	size_t len;
345 	char *walker, *ep;
346 	EFI_DEVICE_PATH *dp, *edp, *first_dp, *last_dp;
347 	pdinfo_t *pp;
348 	CHAR16 *descr;
349 	char *kernel = NULL;
350 	FILEPATH_DEVICE_PATH  *fp;
351 	struct stat st;
352 	CHAR16 *text;
353 
354 	/*
355 	 * FreeBSD encodes it's boot loading path into the boot loader
356 	 * BootXXXX variable. We look for the last one in the path
357 	 * and use that to load the kernel. However, if we only fine
358 	 * one DEVICE_PATH, then there's nothing specific and we should
359 	 * fall back.
360 	 *
361 	 * In an ideal world, we'd look at the image handle we were
362 	 * passed, match up with the loader we are and then return the
363 	 * next one in the path. This would be most flexible and cover
364 	 * many chain booting scenarios where you need to use this
365 	 * boot loader to get to the next boot loader. However, that
366 	 * doesn't work. We rarely have the path to the image booted
367 	 * (just the device) so we can't count on that. So, we do the
368 	 * enxt best thing, we look through the device path(s) passed
369 	 * in the BootXXXX varaible. If there's only one, we return
370 	 * NOT_SPECIFIC. Otherwise, we look at the last one and try to
371 	 * load that. If we can, we return BOOT_INFO_OK. Otherwise we
372 	 * return BAD_CHOICE for the caller to sort out.
373 	 */
374 	if (bisz < sizeof(attr) + sizeof(fplen) + sizeof(CHAR16))
375 		return NOT_SPECIFIC;
376 	walker = boot_info;
377 	ep = walker + bisz;
378 	memcpy(&attr, walker, sizeof(attr));
379 	walker += sizeof(attr);
380 	memcpy(&fplen, walker, sizeof(fplen));
381 	walker += sizeof(fplen);
382 	descr = (CHAR16 *)(intptr_t)walker;
383 	len = ucs2len(descr);
384 	walker += (len + 1) * sizeof(CHAR16);
385 	last_dp = first_dp = dp = (EFI_DEVICE_PATH *)walker;
386 	edp = (EFI_DEVICE_PATH *)(walker + fplen);
387 	if ((char *)edp > ep)
388 		return NOT_SPECIFIC;
389 	while (dp < edp && SIZE(dp, edp) > sizeof(EFI_DEVICE_PATH)) {
390 		text = efi_devpath_name(dp);
391 		if (text != NULL) {
392 			printf("   BootInfo Path: %S\n", text);
393 			efi_free_devpath_name(text);
394 		}
395 		last_dp = dp;
396 		dp = (EFI_DEVICE_PATH *)((char *)dp + efi_devpath_length(dp));
397 	}
398 
399 	/*
400 	 * If there's only one item in the list, then nothing was
401 	 * specified. Or if the last path doesn't have a media
402 	 * path in it. Those show up as various VenHw() nodes
403 	 * which are basically opaque to us. Don't count those
404 	 * as something specifc.
405 	 */
406 	if (last_dp == first_dp) {
407 		printf("Ignoring Boot%04x: Only one DP found\n", boot_current);
408 		return NOT_SPECIFIC;
409 	}
410 	if (efi_devpath_to_media_path(last_dp) == NULL) {
411 		printf("Ignoring Boot%04x: No Media Path\n", boot_current);
412 		return NOT_SPECIFIC;
413 	}
414 
415 	/*
416 	 * OK. At this point we either have a good path or a bad one.
417 	 * Let's check.
418 	 */
419 	pp = efiblk_get_pdinfo_by_device_path(last_dp);
420 	if (pp == NULL) {
421 		printf("Ignoring Boot%04x: Device Path not found\n", boot_current);
422 		return BAD_CHOICE;
423 	}
424 	set_currdev_pdinfo(pp);
425 	if (!sanity_check_currdev()) {
426 		printf("Ignoring Boot%04x: sanity check failed\n", boot_current);
427 		return BAD_CHOICE;
428 	}
429 
430 	/*
431 	 * OK. We've found a device that matches, next we need to check the last
432 	 * component of the path. If it's a file, then we set the default kernel
433 	 * to that. Otherwise, just use this as the default root.
434 	 *
435 	 * Reminder: we're running very early, before we've parsed the defaults
436 	 * file, so we may need to have a hack override.
437 	 */
438 	dp = efi_devpath_last_node(last_dp);
439 	if (DevicePathType(dp) !=  MEDIA_DEVICE_PATH ||
440 	    DevicePathSubType(dp) != MEDIA_FILEPATH_DP) {
441 		printf("Using Boot%04x for root partition\n", boot_current);
442 		return (BOOT_INFO_OK);		/* use currdir, default kernel */
443 	}
444 	fp = (FILEPATH_DEVICE_PATH *)dp;
445 	ucs2_to_utf8(fp->PathName, &kernel);
446 	if (kernel == NULL) {
447 		printf("Not using Boot%04x: can't decode kernel\n", boot_current);
448 		return (BAD_CHOICE);
449 	}
450 	if (*kernel == '\\' || isupper(*kernel))
451 		fix_dosisms(kernel);
452 	if (stat(kernel, &st) != 0) {
453 		free(kernel);
454 		printf("Not using Boot%04x: can't find %s\n", boot_current,
455 		    kernel);
456 		return (BAD_CHOICE);
457 	}
458 	setenv("kernel", kernel, 1);
459 	free(kernel);
460 	text = efi_devpath_name(last_dp);
461 	if (text) {
462 		printf("Using Boot%04x %S + %s\n", boot_current, text,
463 		    kernel);
464 		efi_free_devpath_name(text);
465 	}
466 
467 	return (BOOT_INFO_OK);
468 }
469 
470 /*
471  * Look at the passed-in boot_info, if any. If we find it then we need
472  * to see if we can find ourselves in the boot chain. If we can, and
473  * there's another specified thing to boot next, assume that the file
474  * is loaded from / and use that for the root filesystem. If can't
475  * find the specified thing, we must fail the boot. If we're last on
476  * the list, then we fallback to looking for the first available /
477  * candidate (ZFS, if there's a bootable zpool, otherwise a UFS
478  * partition that has either /boot/defaults/loader.conf on it or
479  * /boot/kernel/kernel (the default kernel) that we can use.
480  *
481  * We always fail if we can't find the right thing. However, as
482  * a concession to buggy UEFI implementations, like u-boot, if
483  * we have determined that the host is violating the UEFI boot
484  * manager protocol, we'll signal the rest of the program that
485  * a drop to the OK boot loader prompt is possible.
486  */
487 static int
488 find_currdev(bool do_bootmgr, bool is_last,
489     char *boot_info, size_t boot_info_sz)
490 {
491 	pdinfo_t *dp, *pp;
492 	EFI_DEVICE_PATH *devpath, *copy;
493 	EFI_HANDLE h;
494 	CHAR16 *text;
495 	struct devsw *dev;
496 	int unit;
497 	uint64_t extra;
498 	int rv;
499 	char *rootdev;
500 
501 	/*
502 	 * First choice: if rootdev is already set, use that, even if
503 	 * it's wrong.
504 	 */
505 	rootdev = getenv("rootdev");
506 	if (rootdev != NULL) {
507 		printf("    Setting currdev to configured rootdev %s\n",
508 		    rootdev);
509 		set_currdev(rootdev);
510 		return (0);
511 	}
512 
513 	/*
514 	 * Second choice: If uefi_rootdev is set, translate that UEFI device
515 	 * path to the loader's internal name and use that.
516 	 */
517 	do {
518 		rootdev = getenv("uefi_rootdev");
519 		if (rootdev == NULL)
520 			break;
521 		devpath = efi_name_to_devpath(rootdev);
522 		if (devpath == NULL)
523 			break;
524 		dp = efiblk_get_pdinfo_by_device_path(devpath);
525 		efi_devpath_free(devpath);
526 		if (dp == NULL)
527 			break;
528 		printf("    Setting currdev to UEFI path %s\n",
529 		    rootdev);
530 		set_currdev_pdinfo(dp);
531 		return (0);
532 	} while (0);
533 
534 	/*
535 	 * Third choice: If we can find out image boot_info, and there's
536 	 * a follow-on boot image in that boot_info, use that. In this
537 	 * case root will be the partition specified in that image and
538 	 * we'll load the kernel specified by the file path. Should there
539 	 * not be a filepath, we use the default. This filepath overrides
540 	 * loader.conf.
541 	 */
542 	if (do_bootmgr) {
543 		rv = match_boot_info(boot_info, boot_info_sz);
544 		switch (rv) {
545 		case BOOT_INFO_OK:	/* We found it */
546 			return (0);
547 		case BAD_CHOICE:	/* specified file not found -> error */
548 			/* XXX do we want to have an escape hatch for last in boot order? */
549 			return (ENOENT);
550 		} /* Nothing specified, try normal match */
551 	}
552 
553 #ifdef EFI_ZFS_BOOT
554 	/*
555 	 * Did efi_zfs_probe() detect the boot pool? If so, use the zpool
556 	 * it found, if it's sane. ZFS is the only thing that looks for
557 	 * disks and pools to boot. This may change in the future, however,
558 	 * if we allow specifying which pool to boot from via UEFI variables
559 	 * rather than the bootenv stuff that FreeBSD uses today.
560 	 */
561 	if (pool_guid != 0) {
562 		printf("Trying ZFS pool\n");
563 		if (probe_zfs_currdev(pool_guid))
564 			return (0);
565 	}
566 #endif /* EFI_ZFS_BOOT */
567 
568 	/*
569 	 * Try to find the block device by its handle based on the
570 	 * image we're booting. If we can't find a sane partition,
571 	 * search all the other partitions of the disk. We do not
572 	 * search other disks because it's a violation of the UEFI
573 	 * boot protocol to do so. We fail and let UEFI go on to
574 	 * the next candidate.
575 	 */
576 	dp = efiblk_get_pdinfo_by_handle(boot_img->DeviceHandle);
577 	if (dp != NULL) {
578 		text = efi_devpath_name(dp->pd_devpath);
579 		if (text != NULL) {
580 			printf("Trying ESP: %S\n", text);
581 			efi_free_devpath_name(text);
582 		}
583 		set_currdev_pdinfo(dp);
584 		if (sanity_check_currdev())
585 			return (0);
586 		if (dp->pd_parent != NULL) {
587 			pdinfo_t *espdp = dp;
588 			dp = dp->pd_parent;
589 			STAILQ_FOREACH(pp, &dp->pd_part, pd_link) {
590 				/* Already tried the ESP */
591 				if (espdp == pp)
592 					continue;
593 				/*
594 				 * Roll up the ZFS special case
595 				 * for those partitions that have
596 				 * zpools on them.
597 				 */
598 				text = efi_devpath_name(pp->pd_devpath);
599 				if (text != NULL) {
600 					printf("Trying: %S\n", text);
601 					efi_free_devpath_name(text);
602 				}
603 				if (try_as_currdev(dp, pp))
604 					return (0);
605 			}
606 		}
607 	}
608 
609 	/*
610 	 * Try the device handle from our loaded image first.  If that
611 	 * fails, use the device path from the loaded image and see if
612 	 * any of the nodes in that path match one of the enumerated
613 	 * handles. Currently, this handle list is only for netboot.
614 	 */
615 	if (efi_handle_lookup(boot_img->DeviceHandle, &dev, &unit, &extra) == 0) {
616 		set_currdev_devsw(dev, unit);
617 		if (sanity_check_currdev())
618 			return (0);
619 	}
620 
621 	copy = NULL;
622 	devpath = efi_lookup_image_devpath(IH);
623 	while (devpath != NULL) {
624 		h = efi_devpath_handle(devpath);
625 		if (h == NULL)
626 			break;
627 
628 		free(copy);
629 		copy = NULL;
630 
631 		if (efi_handle_lookup(h, &dev, &unit, &extra) == 0) {
632 			set_currdev_devsw(dev, unit);
633 			if (sanity_check_currdev())
634 				return (0);
635 		}
636 
637 		devpath = efi_lookup_devpath(h);
638 		if (devpath != NULL) {
639 			copy = efi_devpath_trim(devpath);
640 			devpath = copy;
641 		}
642 	}
643 	free(copy);
644 
645 	return (ENOENT);
646 }
647 
648 static bool
649 interactive_interrupt(const char *msg)
650 {
651 	time_t now, then, last;
652 
653 	last = 0;
654 	now = then = getsecs();
655 	printf("%s\n", msg);
656 	if (fail_timeout == -2)		/* Always break to OK */
657 		return (true);
658 	if (fail_timeout == -1)		/* Never break to OK */
659 		return (false);
660 	do {
661 		if (last != now) {
662 			printf("press any key to interrupt reboot in %d seconds\r",
663 			    fail_timeout - (int)(now - then));
664 			last = now;
665 		}
666 
667 		/* XXX no pause or timeout wait for char */
668 		if (ischar())
669 			return (true);
670 		now = getsecs();
671 	} while (now - then < fail_timeout);
672 	return (false);
673 }
674 
675 static int
676 parse_args(int argc, CHAR16 *argv[])
677 {
678 	int i, j, howto;
679 	bool vargood;
680 	char var[128];
681 
682 	/*
683 	 * Parse the args to set the console settings, etc
684 	 * boot1.efi passes these in, if it can read /boot.config or /boot/config
685 	 * or iPXE may be setup to pass these in. Or the optional argument in the
686 	 * boot environment was used to pass these arguments in (in which case
687 	 * neither /boot.config nor /boot/config are consulted).
688 	 *
689 	 * Loop through the args, and for each one that contains an '=' that is
690 	 * not the first character, add it to the environment.  This allows
691 	 * loader and kernel env vars to be passed on the command line.  Convert
692 	 * args from UCS-2 to ASCII (16 to 8 bit) as they are copied (though this
693 	 * method is flawed for non-ASCII characters).
694 	 */
695 	howto = 0;
696 	for (i = 1; i < argc; i++) {
697 		cpy16to8(argv[i], var, sizeof(var));
698 		howto |= boot_parse_arg(var);
699 	}
700 
701 	return (howto);
702 }
703 
704 static void
705 setenv_int(const char *key, int val)
706 {
707 	char buf[20];
708 
709 	snprintf(buf, sizeof(buf), "%d", val);
710 	setenv(key, buf, 1);
711 }
712 
713 /*
714  * Parse ConOut (the list of consoles active) and see if we can find a
715  * serial port and/or a video port. It would be nice to also walk the
716  * ACPI name space to map the UID for the serial port to a port. The
717  * latter is especially hard.
718  */
719 int
720 parse_uefi_con_out(void)
721 {
722 	int how, rv;
723 	int vid_seen = 0, com_seen = 0, seen = 0;
724 	size_t sz;
725 	char buf[4096], *ep;
726 	EFI_DEVICE_PATH *node;
727 	ACPI_HID_DEVICE_PATH  *acpi;
728 	UART_DEVICE_PATH  *uart;
729 	bool pci_pending;
730 
731 	how = 0;
732 	sz = sizeof(buf);
733 	rv = efi_global_getenv("ConOut", buf, &sz);
734 	if (rv != EFI_SUCCESS) {
735 		/* If we don't have any ConOut default to serial */
736 		how = RB_SERIAL;
737 		goto out;
738 	}
739 	ep = buf + sz;
740 	node = (EFI_DEVICE_PATH *)buf;
741 	while ((char *)node < ep) {
742 		if (IsDevicePathEndType(node)) {
743 			if (pci_pending && vid_seen == 0)
744 				vid_seen = ++seen;
745 		}
746 		pci_pending = false;
747 		if (DevicePathType(node) == ACPI_DEVICE_PATH &&
748 		    (DevicePathSubType(node) == ACPI_DP ||
749 		    DevicePathSubType(node) == ACPI_EXTENDED_DP)) {
750 			/* Check for Serial node */
751 			acpi = (void *)node;
752 			if (EISA_ID_TO_NUM(acpi->HID) == 0x501) {
753 				setenv_int("efi_8250_uid", acpi->UID);
754 				com_seen = ++seen;
755 			}
756 		} else if (DevicePathType(node) == MESSAGING_DEVICE_PATH &&
757 		    DevicePathSubType(node) == MSG_UART_DP) {
758 			com_seen = ++seen;
759 			uart = (void *)node;
760 			setenv_int("efi_com_speed", uart->BaudRate);
761 		} else if (DevicePathType(node) == ACPI_DEVICE_PATH &&
762 		    DevicePathSubType(node) == ACPI_ADR_DP) {
763 			/* Check for AcpiAdr() Node for video */
764 			vid_seen = ++seen;
765 		} else if (DevicePathType(node) == HARDWARE_DEVICE_PATH &&
766 		    DevicePathSubType(node) == HW_PCI_DP) {
767 			/*
768 			 * Note, vmware fusion has a funky console device
769 			 *	PciRoot(0x0)/Pci(0xf,0x0)
770 			 * which we can only detect at the end since we also
771 			 * have to cope with:
772 			 *	PciRoot(0x0)/Pci(0x1f,0x0)/Serial(0x1)
773 			 * so only match it if it's last.
774 			 */
775 			pci_pending = true;
776 		}
777 		node = NextDevicePathNode(node);
778 	}
779 
780 	/*
781 	 * Truth table for RB_MULTIPLE | RB_SERIAL
782 	 * Value		Result
783 	 * 0			Use only video console
784 	 * RB_SERIAL		Use only serial console
785 	 * RB_MULTIPLE		Use both video and serial console
786 	 *			(but video is primary so gets rc messages)
787 	 * both			Use both video and serial console
788 	 *			(but serial is primary so gets rc messages)
789 	 *
790 	 * Try to honor this as best we can. If only one of serial / video
791 	 * found, then use that. Otherwise, use the first one we found.
792 	 * This also implies if we found nothing, default to video.
793 	 */
794 	how = 0;
795 	if (vid_seen && com_seen) {
796 		how |= RB_MULTIPLE;
797 		if (com_seen < vid_seen)
798 			how |= RB_SERIAL;
799 	} else if (com_seen)
800 		how |= RB_SERIAL;
801 out:
802 	return (how);
803 }
804 
805 void
806 parse_loader_efi_config(EFI_HANDLE h, const char *env_fn)
807 {
808 	pdinfo_t *dp;
809 	struct stat st;
810 	int fd = -1;
811 	char *env = NULL;
812 
813 	dp = efiblk_get_pdinfo_by_handle(h);
814 	if (dp == NULL)
815 		return;
816 	set_currdev_pdinfo(dp);
817 	if (stat(env_fn, &st) != 0)
818 		return;
819 	fd = open(env_fn, O_RDONLY);
820 	if (fd == -1)
821 		return;
822 	env = malloc(st.st_size + 1);
823 	if (env == NULL)
824 		goto out;
825 	if (read(fd, env, st.st_size) != st.st_size)
826 		goto out;
827 	env[st.st_size] = '\0';
828 	boot_parse_cmdline(env);
829 out:
830 	free(env);
831 	close(fd);
832 }
833 
834 static void
835 read_loader_env(const char *name, char *def_fn, bool once)
836 {
837 	UINTN len;
838 	char *fn, *freeme = NULL;
839 
840 	len = 0;
841 	fn = def_fn;
842 	if (efi_freebsd_getenv(name, NULL, &len) == EFI_BUFFER_TOO_SMALL) {
843 		freeme = fn = malloc(len + 1);
844 		if (fn != NULL) {
845 			if (efi_freebsd_getenv(name, fn, &len) != EFI_SUCCESS) {
846 				free(fn);
847 				fn = NULL;
848 				printf(
849 			    "Can't fetch FreeBSD::%s we know is there\n", name);
850 			} else {
851 				/*
852 				 * if tagged as 'once' delete the env variable so we
853 				 * only use it once.
854 				 */
855 				if (once)
856 					efi_freebsd_delenv(name);
857 				/*
858 				 * We malloced 1 more than len above, then redid the call.
859 				 * so now we have room at the end of the string to NUL terminate
860 				 * it here, even if the typical idium would have '- 1' here to
861 				 * not overflow. len should be the same on return both times.
862 				 */
863 				fn[len] = '\0';
864 			}
865 		} else {
866 			printf(
867 		    "Can't allocate %d bytes to fetch FreeBSD::%s env var\n",
868 			    len, name);
869 		}
870 	}
871 	if (fn) {
872 		printf("    Reading loader env vars from %s\n", fn);
873 		parse_loader_efi_config(boot_img->DeviceHandle, fn);
874 	}
875 }
876 
877 caddr_t
878 ptov(uintptr_t x)
879 {
880 	return ((caddr_t)x);
881 }
882 
883 EFI_STATUS
884 main(int argc, CHAR16 *argv[])
885 {
886 	EFI_GUID *guid;
887 	int howto, i, uhowto;
888 	UINTN k;
889 	bool has_kbd, is_last;
890 	char *s;
891 	EFI_DEVICE_PATH *imgpath;
892 	CHAR16 *text;
893 	EFI_STATUS rv;
894 	size_t sz, bosz = 0, bisz = 0;
895 	UINT16 boot_order[100];
896 	char boot_info[4096];
897 	char buf[32];
898 	bool uefi_boot_mgr;
899 
900 	archsw.arch_autoload = efi_autoload;
901 	archsw.arch_getdev = efi_getdev;
902 	archsw.arch_copyin = efi_copyin;
903 	archsw.arch_copyout = efi_copyout;
904 #ifdef __amd64__
905 	archsw.arch_hypervisor = x86_hypervisor;
906 #endif
907 	archsw.arch_readin = efi_readin;
908 	archsw.arch_zfs_probe = efi_zfs_probe;
909 
910         /* Get our loaded image protocol interface structure. */
911 	(void) OpenProtocolByHandle(IH, &imgid, (void **)&boot_img);
912 
913 	/*
914 	 * Chicken-and-egg problem; we want to have console output early, but
915 	 * some console attributes may depend on reading from eg. the boot
916 	 * device, which we can't do yet.  We can use printf() etc. once this is
917 	 * done. So, we set it to the efi console, then call console init. This
918 	 * gets us printf early, but also primes the pump for all future console
919 	 * changes to take effect, regardless of where they come from.
920 	 */
921 	setenv("console", "efi", 1);
922 	uhowto = parse_uefi_con_out();
923 #if defined(__aarch64__) || defined(__arm__) || defined(__riscv)
924 	if ((uhowto & RB_SERIAL) != 0)
925 		setenv("console", "comconsole", 1);
926 #endif
927 	cons_probe();
928 
929 	/* Init the time source */
930 	efi_time_init();
931 
932 	/*
933 	 * Initialise the block cache. Set the upper limit.
934 	 */
935 	bcache_init(32768, 512);
936 
937 	/*
938 	 * Scan the BLOCK IO MEDIA handles then
939 	 * march through the device switch probing for things.
940 	 */
941 	i = efipart_inithandles();
942 	if (i != 0 && i != ENOENT) {
943 		printf("efipart_inithandles failed with ERRNO %d, expect "
944 		    "failures\n", i);
945 	}
946 
947 	for (i = 0; devsw[i] != NULL; i++)
948 		if (devsw[i]->dv_init != NULL)
949 			(devsw[i]->dv_init)();
950 
951 	/*
952 	 * Detect console settings two different ways: one via the command
953 	 * args (eg -h) or via the UEFI ConOut variable.
954 	 */
955 	has_kbd = has_keyboard();
956 	howto = parse_args(argc, argv);
957 	if (!has_kbd && (howto & RB_PROBE))
958 		howto |= RB_SERIAL | RB_MULTIPLE;
959 	howto &= ~RB_PROBE;
960 
961 	/*
962 	 * Read additional environment variables from the boot device's
963 	 * "LoaderEnv" file. Any boot loader environment variable may be set
964 	 * there, which are subtly different than loader.conf variables. Only
965 	 * the 'simple' ones may be set so things like foo_load="YES" won't work
966 	 * for two reasons.  First, the parser is simplistic and doesn't grok
967 	 * quotes.  Second, because the variables that cause an action to happen
968 	 * are parsed by the lua, 4th or whatever code that's not yet
969 	 * loaded. This is relative to the root directory when loader.efi is
970 	 * loaded off the UFS root drive (when chain booted), or from the ESP
971 	 * when directly loaded by the BIOS.
972 	 *
973 	 * We also read in NextLoaderEnv if it was specified. This allows next boot
974 	 * functionality to be implemented and to override anything in LoaderEnv.
975 	 */
976 	read_loader_env("LoaderEnv", "/efi/freebsd/loader.env", false);
977 	read_loader_env("NextLoaderEnv", NULL, true);
978 
979 	/*
980 	 * We now have two notions of console. howto should be viewed as
981 	 * overrides. If console is already set, don't set it again.
982 	 */
983 #define	VIDEO_ONLY	0
984 #define	SERIAL_ONLY	RB_SERIAL
985 #define	VID_SER_BOTH	RB_MULTIPLE
986 #define	SER_VID_BOTH	(RB_SERIAL | RB_MULTIPLE)
987 #define	CON_MASK	(RB_SERIAL | RB_MULTIPLE)
988 	if (strcmp(getenv("console"), "efi") == 0) {
989 		if ((howto & CON_MASK) == 0) {
990 			/* No override, uhowto is controlling and efi cons is perfect */
991 			howto = howto | (uhowto & CON_MASK);
992 		} else if ((howto & CON_MASK) == (uhowto & CON_MASK)) {
993 			/* override matches what UEFI told us, efi console is perfect */
994 		} else if ((uhowto & (CON_MASK)) != 0) {
995 			/*
996 			 * We detected a serial console on ConOut. All possible
997 			 * overrides include serial. We can't really override what efi
998 			 * gives us, so we use it knowing it's the best choice.
999 			 */
1000 			/* Do nothing */
1001 		} else {
1002 			/*
1003 			 * We detected some kind of serial in the override, but ConOut
1004 			 * has no serial, so we have to sort out which case it really is.
1005 			 */
1006 			switch (howto & CON_MASK) {
1007 			case SERIAL_ONLY:
1008 				setenv("console", "comconsole", 1);
1009 				break;
1010 			case VID_SER_BOTH:
1011 				setenv("console", "efi comconsole", 1);
1012 				break;
1013 			case SER_VID_BOTH:
1014 				setenv("console", "comconsole efi", 1);
1015 				break;
1016 				/* case VIDEO_ONLY can't happen -- it's the first if above */
1017 			}
1018 		}
1019 	}
1020 
1021 	/*
1022 	 * howto is set now how we want to export the flags to the kernel, so
1023 	 * set the env based on it.
1024 	 */
1025 	boot_howto_to_env(howto);
1026 
1027 	if (efi_copy_init()) {
1028 		printf("failed to allocate staging area\n");
1029 		return (EFI_BUFFER_TOO_SMALL);
1030 	}
1031 
1032 	if ((s = getenv("fail_timeout")) != NULL)
1033 		fail_timeout = strtol(s, NULL, 10);
1034 
1035 	printf("%s\n", bootprog_info);
1036 	printf("   Command line arguments:");
1037 	for (i = 0; i < argc; i++)
1038 		printf(" %S", argv[i]);
1039 	printf("\n");
1040 
1041 	printf("   Image base: 0x%lx\n", (unsigned long)boot_img->ImageBase);
1042 	printf("   EFI version: %d.%02d\n", ST->Hdr.Revision >> 16,
1043 	    ST->Hdr.Revision & 0xffff);
1044 	printf("   EFI Firmware: %S (rev %d.%02d)\n", ST->FirmwareVendor,
1045 	    ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
1046 	printf("   Console: %s (%#x)\n", getenv("console"), howto);
1047 
1048 	/* Determine the devpath of our image so we can prefer it. */
1049 	text = efi_devpath_name(boot_img->FilePath);
1050 	if (text != NULL) {
1051 		printf("   Load Path: %S\n", text);
1052 		efi_setenv_freebsd_wcs("LoaderPath", text);
1053 		efi_free_devpath_name(text);
1054 	}
1055 
1056 	rv = OpenProtocolByHandle(boot_img->DeviceHandle, &devid,
1057 	    (void **)&imgpath);
1058 	if (rv == EFI_SUCCESS) {
1059 		text = efi_devpath_name(imgpath);
1060 		if (text != NULL) {
1061 			printf("   Load Device: %S\n", text);
1062 			efi_setenv_freebsd_wcs("LoaderDev", text);
1063 			efi_free_devpath_name(text);
1064 		}
1065 	}
1066 
1067 	if (getenv("uefi_ignore_boot_mgr") != NULL) {
1068 		printf("    Ignoring UEFI boot manager\n");
1069 		uefi_boot_mgr = false;
1070 	} else {
1071 		uefi_boot_mgr = true;
1072 		boot_current = 0;
1073 		sz = sizeof(boot_current);
1074 		rv = efi_global_getenv("BootCurrent", &boot_current, &sz);
1075 		if (rv == EFI_SUCCESS)
1076 			printf("   BootCurrent: %04x\n", boot_current);
1077 		else {
1078 			boot_current = 0xffff;
1079 			uefi_boot_mgr = false;
1080 		}
1081 
1082 		sz = sizeof(boot_order);
1083 		rv = efi_global_getenv("BootOrder", &boot_order, &sz);
1084 		if (rv == EFI_SUCCESS) {
1085 			printf("   BootOrder:");
1086 			for (i = 0; i < sz / sizeof(boot_order[0]); i++)
1087 				printf(" %04x%s", boot_order[i],
1088 				    boot_order[i] == boot_current ? "[*]" : "");
1089 			printf("\n");
1090 			is_last = boot_order[(sz / sizeof(boot_order[0])) - 1] == boot_current;
1091 			bosz = sz;
1092 		} else if (uefi_boot_mgr) {
1093 			/*
1094 			 * u-boot doesn't set BootOrder, but otherwise participates in the
1095 			 * boot manager protocol. So we fake it here and don't consider it
1096 			 * a failure.
1097 			 */
1098 			bosz = sizeof(boot_order[0]);
1099 			boot_order[0] = boot_current;
1100 			is_last = true;
1101 		}
1102 	}
1103 
1104 	/*
1105 	 * Next, find the boot info structure the UEFI boot manager is
1106 	 * supposed to setup. We need this so we can walk through it to
1107 	 * find where we are in the booting process and what to try to
1108 	 * boot next.
1109 	 */
1110 	if (uefi_boot_mgr) {
1111 		snprintf(buf, sizeof(buf), "Boot%04X", boot_current);
1112 		sz = sizeof(boot_info);
1113 		rv = efi_global_getenv(buf, &boot_info, &sz);
1114 		if (rv == EFI_SUCCESS)
1115 			bisz = sz;
1116 		else
1117 			uefi_boot_mgr = false;
1118 	}
1119 
1120 	/*
1121 	 * Disable the watchdog timer. By default the boot manager sets
1122 	 * the timer to 5 minutes before invoking a boot option. If we
1123 	 * want to return to the boot manager, we have to disable the
1124 	 * watchdog timer and since we're an interactive program, we don't
1125 	 * want to wait until the user types "quit". The timer may have
1126 	 * fired by then. We don't care if this fails. It does not prevent
1127 	 * normal functioning in any way...
1128 	 */
1129 	BS->SetWatchdogTimer(0, 0, 0, NULL);
1130 
1131 	/*
1132 	 * Initialize the trusted/forbidden certificates from UEFI.
1133 	 * They will be later used to verify the manifest(s),
1134 	 * which should contain hashes of verified files.
1135 	 * This needs to be initialized before any configuration files
1136 	 * are loaded.
1137 	 */
1138 #ifdef EFI_SECUREBOOT
1139 	ve_efi_init();
1140 #endif
1141 
1142 	/*
1143 	 * Try and find a good currdev based on the image that was booted.
1144 	 * It might be desirable here to have a short pause to allow falling
1145 	 * through to the boot loader instead of returning instantly to follow
1146 	 * the boot protocol and also allow an escape hatch for users wishing
1147 	 * to try something different.
1148 	 */
1149 	if (find_currdev(uefi_boot_mgr, is_last, boot_info, bisz) != 0)
1150 		if (uefi_boot_mgr &&
1151 		    !interactive_interrupt("Failed to find bootable partition"))
1152 			return (EFI_NOT_FOUND);
1153 
1154 	efi_init_environment();
1155 
1156 #if !defined(__arm__)
1157 	for (k = 0; k < ST->NumberOfTableEntries; k++) {
1158 		guid = &ST->ConfigurationTable[k].VendorGuid;
1159 		if (!memcmp(guid, &smbios, sizeof(EFI_GUID))) {
1160 			char buf[40];
1161 
1162 			snprintf(buf, sizeof(buf), "%p",
1163 			    ST->ConfigurationTable[k].VendorTable);
1164 			setenv("hint.smbios.0.mem", buf, 1);
1165 			smbios_detect(ST->ConfigurationTable[k].VendorTable);
1166 			break;
1167 		}
1168 	}
1169 #endif
1170 
1171 	interact();			/* doesn't return */
1172 
1173 	return (EFI_SUCCESS);		/* keep compiler happy */
1174 }
1175 
1176 COMMAND_SET(poweroff, "poweroff", "power off the system", command_poweroff);
1177 
1178 static int
1179 command_poweroff(int argc __unused, char *argv[] __unused)
1180 {
1181 	int i;
1182 
1183 	for (i = 0; devsw[i] != NULL; ++i)
1184 		if (devsw[i]->dv_cleanup != NULL)
1185 			(devsw[i]->dv_cleanup)();
1186 
1187 	RS->ResetSystem(EfiResetShutdown, EFI_SUCCESS, 0, NULL);
1188 
1189 	/* NOTREACHED */
1190 	return (CMD_ERROR);
1191 }
1192 
1193 COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot);
1194 
1195 static int
1196 command_reboot(int argc, char *argv[])
1197 {
1198 	int i;
1199 
1200 	for (i = 0; devsw[i] != NULL; ++i)
1201 		if (devsw[i]->dv_cleanup != NULL)
1202 			(devsw[i]->dv_cleanup)();
1203 
1204 	RS->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL);
1205 
1206 	/* NOTREACHED */
1207 	return (CMD_ERROR);
1208 }
1209 
1210 COMMAND_SET(quit, "quit", "exit the loader", command_quit);
1211 
1212 static int
1213 command_quit(int argc, char *argv[])
1214 {
1215 	exit(0);
1216 	return (CMD_OK);
1217 }
1218 
1219 COMMAND_SET(memmap, "memmap", "print memory map", command_memmap);
1220 
1221 static int
1222 command_memmap(int argc __unused, char *argv[] __unused)
1223 {
1224 	UINTN sz;
1225 	EFI_MEMORY_DESCRIPTOR *map, *p;
1226 	UINTN key, dsz;
1227 	UINT32 dver;
1228 	EFI_STATUS status;
1229 	int i, ndesc;
1230 	char line[80];
1231 
1232 	sz = 0;
1233 	status = BS->GetMemoryMap(&sz, 0, &key, &dsz, &dver);
1234 	if (status != EFI_BUFFER_TOO_SMALL) {
1235 		printf("Can't determine memory map size\n");
1236 		return (CMD_ERROR);
1237 	}
1238 	map = malloc(sz);
1239 	status = BS->GetMemoryMap(&sz, map, &key, &dsz, &dver);
1240 	if (EFI_ERROR(status)) {
1241 		printf("Can't read memory map\n");
1242 		return (CMD_ERROR);
1243 	}
1244 
1245 	ndesc = sz / dsz;
1246 	snprintf(line, sizeof(line), "%23s %12s %12s %8s %4s\n",
1247 	    "Type", "Physical", "Virtual", "#Pages", "Attr");
1248 	pager_open();
1249 	if (pager_output(line)) {
1250 		pager_close();
1251 		return (CMD_OK);
1252 	}
1253 
1254 	for (i = 0, p = map; i < ndesc;
1255 	     i++, p = NextMemoryDescriptor(p, dsz)) {
1256 		snprintf(line, sizeof(line), "%23s %012jx %012jx %08jx ",
1257 		    efi_memory_type(p->Type), (uintmax_t)p->PhysicalStart,
1258 		    (uintmax_t)p->VirtualStart, (uintmax_t)p->NumberOfPages);
1259 		if (pager_output(line))
1260 			break;
1261 
1262 		if (p->Attribute & EFI_MEMORY_UC)
1263 			printf("UC ");
1264 		if (p->Attribute & EFI_MEMORY_WC)
1265 			printf("WC ");
1266 		if (p->Attribute & EFI_MEMORY_WT)
1267 			printf("WT ");
1268 		if (p->Attribute & EFI_MEMORY_WB)
1269 			printf("WB ");
1270 		if (p->Attribute & EFI_MEMORY_UCE)
1271 			printf("UCE ");
1272 		if (p->Attribute & EFI_MEMORY_WP)
1273 			printf("WP ");
1274 		if (p->Attribute & EFI_MEMORY_RP)
1275 			printf("RP ");
1276 		if (p->Attribute & EFI_MEMORY_XP)
1277 			printf("XP ");
1278 		if (p->Attribute & EFI_MEMORY_NV)
1279 			printf("NV ");
1280 		if (p->Attribute & EFI_MEMORY_MORE_RELIABLE)
1281 			printf("MR ");
1282 		if (p->Attribute & EFI_MEMORY_RO)
1283 			printf("RO ");
1284 		if (pager_output("\n"))
1285 			break;
1286 	}
1287 
1288 	pager_close();
1289 	return (CMD_OK);
1290 }
1291 
1292 COMMAND_SET(configuration, "configuration", "print configuration tables",
1293     command_configuration);
1294 
1295 static int
1296 command_configuration(int argc, char *argv[])
1297 {
1298 	UINTN i;
1299 	char *name;
1300 
1301 	printf("NumberOfTableEntries=%lu\n",
1302 		(unsigned long)ST->NumberOfTableEntries);
1303 
1304 	for (i = 0; i < ST->NumberOfTableEntries; i++) {
1305 		EFI_GUID *guid;
1306 
1307 		printf("  ");
1308 		guid = &ST->ConfigurationTable[i].VendorGuid;
1309 
1310 		if (efi_guid_to_name(guid, &name) == true) {
1311 			printf(name);
1312 			free(name);
1313 		} else {
1314 			printf("Error while translating UUID to name");
1315 		}
1316 		printf(" at %p\n", ST->ConfigurationTable[i].VendorTable);
1317 	}
1318 
1319 	return (CMD_OK);
1320 }
1321 
1322 
1323 COMMAND_SET(mode, "mode", "change or display EFI text modes", command_mode);
1324 
1325 static int
1326 command_mode(int argc, char *argv[])
1327 {
1328 	UINTN cols, rows;
1329 	unsigned int mode;
1330 	int i;
1331 	char *cp;
1332 	EFI_STATUS status;
1333 	SIMPLE_TEXT_OUTPUT_INTERFACE *conout;
1334 
1335 	conout = ST->ConOut;
1336 
1337 	if (argc > 1) {
1338 		mode = strtol(argv[1], &cp, 0);
1339 		if (cp[0] != '\0') {
1340 			printf("Invalid mode\n");
1341 			return (CMD_ERROR);
1342 		}
1343 		status = conout->QueryMode(conout, mode, &cols, &rows);
1344 		if (EFI_ERROR(status)) {
1345 			printf("invalid mode %d\n", mode);
1346 			return (CMD_ERROR);
1347 		}
1348 		status = conout->SetMode(conout, mode);
1349 		if (EFI_ERROR(status)) {
1350 			printf("couldn't set mode %d\n", mode);
1351 			return (CMD_ERROR);
1352 		}
1353 		(void) efi_cons_update_mode();
1354 		return (CMD_OK);
1355 	}
1356 
1357 	printf("Current mode: %d\n", conout->Mode->Mode);
1358 	for (i = 0; i <= conout->Mode->MaxMode; i++) {
1359 		status = conout->QueryMode(conout, i, &cols, &rows);
1360 		if (EFI_ERROR(status))
1361 			continue;
1362 		printf("Mode %d: %u columns, %u rows\n", i, (unsigned)cols,
1363 		    (unsigned)rows);
1364 	}
1365 
1366 	if (i != 0)
1367 		printf("Select a mode with the command \"mode <number>\"\n");
1368 
1369 	return (CMD_OK);
1370 }
1371 
1372 COMMAND_SET(lsefi, "lsefi", "list EFI handles", command_lsefi);
1373 
1374 static int
1375 command_lsefi(int argc __unused, char *argv[] __unused)
1376 {
1377 	char *name;
1378 	EFI_HANDLE *buffer = NULL;
1379 	EFI_HANDLE handle;
1380 	UINTN bufsz = 0, i, j;
1381 	EFI_STATUS status;
1382 	int ret = 0;
1383 
1384 	status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer);
1385 	if (status != EFI_BUFFER_TOO_SMALL) {
1386 		snprintf(command_errbuf, sizeof (command_errbuf),
1387 		    "unexpected error: %lld", (long long)status);
1388 		return (CMD_ERROR);
1389 	}
1390 	if ((buffer = malloc(bufsz)) == NULL) {
1391 		sprintf(command_errbuf, "out of memory");
1392 		return (CMD_ERROR);
1393 	}
1394 
1395 	status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer);
1396 	if (EFI_ERROR(status)) {
1397 		free(buffer);
1398 		snprintf(command_errbuf, sizeof (command_errbuf),
1399 		    "LocateHandle() error: %lld", (long long)status);
1400 		return (CMD_ERROR);
1401 	}
1402 
1403 	pager_open();
1404 	for (i = 0; i < (bufsz / sizeof (EFI_HANDLE)); i++) {
1405 		UINTN nproto = 0;
1406 		EFI_GUID **protocols = NULL;
1407 
1408 		handle = buffer[i];
1409 		printf("Handle %p", handle);
1410 		if (pager_output("\n"))
1411 			break;
1412 		/* device path */
1413 
1414 		status = BS->ProtocolsPerHandle(handle, &protocols, &nproto);
1415 		if (EFI_ERROR(status)) {
1416 			snprintf(command_errbuf, sizeof (command_errbuf),
1417 			    "ProtocolsPerHandle() error: %lld",
1418 			    (long long)status);
1419 			continue;
1420 		}
1421 
1422 		for (j = 0; j < nproto; j++) {
1423 			if (efi_guid_to_name(protocols[j], &name) == true) {
1424 				printf("  %s", name);
1425 				free(name);
1426 			} else {
1427 				printf("Error while translating UUID to name");
1428 			}
1429 			if ((ret = pager_output("\n")) != 0)
1430 				break;
1431 		}
1432 		BS->FreePool(protocols);
1433 		if (ret != 0)
1434 			break;
1435 	}
1436 	pager_close();
1437 	free(buffer);
1438 	return (CMD_OK);
1439 }
1440 
1441 #ifdef LOADER_FDT_SUPPORT
1442 extern int command_fdt_internal(int argc, char *argv[]);
1443 
1444 /*
1445  * Since proper fdt command handling function is defined in fdt_loader_cmd.c,
1446  * and declaring it as extern is in contradiction with COMMAND_SET() macro
1447  * (which uses static pointer), we're defining wrapper function, which
1448  * calls the proper fdt handling routine.
1449  */
1450 static int
1451 command_fdt(int argc, char *argv[])
1452 {
1453 
1454 	return (command_fdt_internal(argc, argv));
1455 }
1456 
1457 COMMAND_SET(fdt, "fdt", "flattened device tree handling", command_fdt);
1458 #endif
1459 
1460 /*
1461  * Chain load another efi loader.
1462  */
1463 static int
1464 command_chain(int argc, char *argv[])
1465 {
1466 	EFI_GUID LoadedImageGUID = LOADED_IMAGE_PROTOCOL;
1467 	EFI_HANDLE loaderhandle;
1468 	EFI_LOADED_IMAGE *loaded_image;
1469 	EFI_STATUS status;
1470 	struct stat st;
1471 	struct devdesc *dev;
1472 	char *name, *path;
1473 	void *buf;
1474 	int fd;
1475 
1476 	if (argc < 2) {
1477 		command_errmsg = "wrong number of arguments";
1478 		return (CMD_ERROR);
1479 	}
1480 
1481 	name = argv[1];
1482 
1483 	if ((fd = open(name, O_RDONLY)) < 0) {
1484 		command_errmsg = "no such file";
1485 		return (CMD_ERROR);
1486 	}
1487 
1488 #ifdef LOADER_VERIEXEC
1489 	if (verify_file(fd, name, 0, VE_MUST, __func__) < 0) {
1490 		sprintf(command_errbuf, "can't verify: %s", name);
1491 		close(fd);
1492 		return (CMD_ERROR);
1493 	}
1494 #endif
1495 
1496 	if (fstat(fd, &st) < -1) {
1497 		command_errmsg = "stat failed";
1498 		close(fd);
1499 		return (CMD_ERROR);
1500 	}
1501 
1502 	status = BS->AllocatePool(EfiLoaderCode, (UINTN)st.st_size, &buf);
1503 	if (status != EFI_SUCCESS) {
1504 		command_errmsg = "failed to allocate buffer";
1505 		close(fd);
1506 		return (CMD_ERROR);
1507 	}
1508 	if (read(fd, buf, st.st_size) != st.st_size) {
1509 		command_errmsg = "error while reading the file";
1510 		(void)BS->FreePool(buf);
1511 		close(fd);
1512 		return (CMD_ERROR);
1513 	}
1514 	close(fd);
1515 	status = BS->LoadImage(FALSE, IH, NULL, buf, st.st_size, &loaderhandle);
1516 	(void)BS->FreePool(buf);
1517 	if (status != EFI_SUCCESS) {
1518 		command_errmsg = "LoadImage failed";
1519 		return (CMD_ERROR);
1520 	}
1521 	status = OpenProtocolByHandle(loaderhandle, &LoadedImageGUID,
1522 	    (void **)&loaded_image);
1523 
1524 	if (argc > 2) {
1525 		int i, len = 0;
1526 		CHAR16 *argp;
1527 
1528 		for (i = 2; i < argc; i++)
1529 			len += strlen(argv[i]) + 1;
1530 
1531 		len *= sizeof (*argp);
1532 		loaded_image->LoadOptions = argp = malloc (len);
1533 		loaded_image->LoadOptionsSize = len;
1534 		for (i = 2; i < argc; i++) {
1535 			char *ptr = argv[i];
1536 			while (*ptr)
1537 				*(argp++) = *(ptr++);
1538 			*(argp++) = ' ';
1539 		}
1540 		*(--argv) = 0;
1541 	}
1542 
1543 	if (efi_getdev((void **)&dev, name, (const char **)&path) == 0) {
1544 #ifdef EFI_ZFS_BOOT
1545 		struct zfs_devdesc *z_dev;
1546 #endif
1547 		struct disk_devdesc *d_dev;
1548 		pdinfo_t *hd, *pd;
1549 
1550 		switch (dev->d_dev->dv_type) {
1551 #ifdef EFI_ZFS_BOOT
1552 		case DEVT_ZFS:
1553 			z_dev = (struct zfs_devdesc *)dev;
1554 			loaded_image->DeviceHandle =
1555 			    efizfs_get_handle_by_guid(z_dev->pool_guid);
1556 			break;
1557 #endif
1558 		case DEVT_NET:
1559 			loaded_image->DeviceHandle =
1560 			    efi_find_handle(dev->d_dev, dev->d_unit);
1561 			break;
1562 		default:
1563 			hd = efiblk_get_pdinfo(dev);
1564 			if (STAILQ_EMPTY(&hd->pd_part)) {
1565 				loaded_image->DeviceHandle = hd->pd_handle;
1566 				break;
1567 			}
1568 			d_dev = (struct disk_devdesc *)dev;
1569 			STAILQ_FOREACH(pd, &hd->pd_part, pd_link) {
1570 				/*
1571 				 * d_partition should be 255
1572 				 */
1573 				if (pd->pd_unit == (uint32_t)d_dev->d_slice) {
1574 					loaded_image->DeviceHandle =
1575 					    pd->pd_handle;
1576 					break;
1577 				}
1578 			}
1579 			break;
1580 		}
1581 	}
1582 
1583 	dev_cleanup();
1584 	status = BS->StartImage(loaderhandle, NULL, NULL);
1585 	if (status != EFI_SUCCESS) {
1586 		command_errmsg = "StartImage failed";
1587 		free(loaded_image->LoadOptions);
1588 		loaded_image->LoadOptions = NULL;
1589 		status = BS->UnloadImage(loaded_image);
1590 		return (CMD_ERROR);
1591 	}
1592 
1593 	return (CMD_ERROR);	/* not reached */
1594 }
1595 
1596 COMMAND_SET(chain, "chain", "chain load file", command_chain);
1597