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