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