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