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