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