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