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