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