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