xref: /freebsd/stand/efi/loader/main.c (revision f9bc005b8ef3b507a5ecbc2d7fe4411ef70eff38)
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 	 * Parse command line arguments before any operation that may configure
1387 	 * the network so DHCP overrides are available on the first attempt.
1388 	 */
1389 	howto = parse_args(argc, argv);
1390 
1391 	/*
1392 	 * If we didn't find a ipxe image, and we're netbooting, try to
1393 	 * download an initmd that the dhcp server tells us about.
1394 	 */
1395 	if (!has_ipxe && is_efi_netboot())
1396 		maybe_download_initmd();
1397 
1398 	/*
1399 	 * Detect console settings two different ways: one via the command
1400 	 * args (eg -h) or via the UEFI ConOut variable.
1401 	 */
1402 	has_kbd = has_keyboard();
1403 	if (!has_kbd && (howto & RB_PROBE))
1404 		howto |= RB_SERIAL | RB_MULTIPLE;
1405 	howto &= ~RB_PROBE;
1406 
1407 	/*
1408 	 * Read additional environment variables from the boot device's
1409 	 * "LoaderEnv" file. Any boot loader environment variable may be set
1410 	 * there, which are subtly different than loader.conf variables. Only
1411 	 * the 'simple' ones may be set so things like foo_load="YES" won't work
1412 	 * for two reasons.  First, the parser is simplistic and doesn't grok
1413 	 * quotes.  Second, because the variables that cause an action to happen
1414 	 * are parsed by the lua, 4th or whatever code that's not yet
1415 	 * loaded. This is relative to the root directory when loader.efi is
1416 	 * loaded off the UFS root drive (when chain booted), or from the ESP
1417 	 * when directly loaded by the BIOS.
1418 	 *
1419 	 * We also read in NextLoaderEnv if it was specified. This allows next boot
1420 	 * functionality to be implemented and to override anything in LoaderEnv.
1421 	 */
1422 	read_loader_env("LoaderEnv", "/efi/freebsd/loader.env", false);
1423 	read_loader_env("NextLoaderEnv", NULL, true);
1424 
1425 	set_boot_policy();
1426 
1427 	/*
1428 	 * We now have two notions of console. howto should be viewed as
1429 	 * overrides. If console is already set, don't set it again.
1430 	 */
1431 #define	VIDEO_ONLY	0
1432 #define	SERIAL_ONLY	RB_SERIAL
1433 #define	VID_SER_BOTH	RB_MULTIPLE
1434 #define	SER_VID_BOTH	(RB_SERIAL | RB_MULTIPLE)
1435 #define	CON_MASK	(RB_SERIAL | RB_MULTIPLE)
1436 	if (strcmp(getenv("console"), "efi") == 0) {
1437 		if ((howto & CON_MASK) == 0) {
1438 			/* No override, uhowto is controlling and efi cons is perfect */
1439 			howto = howto | (uhowto & CON_MASK);
1440 		} else if ((howto & CON_MASK) == (uhowto & CON_MASK)) {
1441 			/* override matches what UEFI told us, efi console is perfect */
1442 		} else if ((uhowto & (CON_MASK)) != 0) {
1443 			/*
1444 			 * We detected a serial console on ConOut. All possible
1445 			 * overrides include serial. We can't really override what efi
1446 			 * gives us, so we use it knowing it's the best choice.
1447 			 */
1448 			/* Do nothing */
1449 		} else {
1450 			/*
1451 			 * We detected some kind of serial in the override, but ConOut
1452 			 * has no serial, so we have to sort out which case it really is.
1453 			 */
1454 			switch (howto & CON_MASK) {
1455 			case SERIAL_ONLY:
1456 				setenv("console", "comconsole", 1);
1457 				break;
1458 			case VID_SER_BOTH:
1459 				setenv("console", "efi,comconsole", 1);
1460 				break;
1461 			case SER_VID_BOTH:
1462 				setenv("console", "comconsole,efi", 1);
1463 				break;
1464 				/* case VIDEO_ONLY can't happen -- it's the first if above */
1465 			}
1466 		}
1467 	}
1468 
1469 	/*
1470 	 * howto is set now how we want to export the flags to the kernel, so
1471 	 * set the env based on it.
1472 	 */
1473 	boot_howto_to_env(howto);
1474 
1475 	if (efi_copy_init())
1476 		return (EFI_BUFFER_TOO_SMALL);
1477 
1478 	if ((s = getenv("fail_timeout")) != NULL)
1479 		fail_timeout = strtol(s, NULL, 10);
1480 
1481 	printf("%s\n", bootprog_info);
1482 	printf("   Command line arguments:");
1483 	for (i = 0; i < argc; i++)
1484 		printf(" %S", argv[i]);
1485 	printf("\n");
1486 
1487 	printf("   Image base: 0x%lx\n", (unsigned long)boot_img->ImageBase);
1488 	printf("   EFI version: %d.%02d\n", ST->Hdr.Revision >> 16,
1489 	    ST->Hdr.Revision & 0xffff);
1490 	printf("   EFI Firmware: %S (rev %d.%02d)\n", ST->FirmwareVendor,
1491 	    ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
1492 	printf("   Console: %s (%#x)\n", getenv("console"), howto);
1493 
1494 	/* Determine the devpath of our image so we can prefer it. */
1495 	text = efi_devpath_name(boot_img->FilePath);
1496 	if (text != NULL) {
1497 		printf("   Load Path: %S\n", text);
1498 		efi_setenv_freebsd_wcs("LoaderPath", text);
1499 		efi_free_devpath_name(text);
1500 	}
1501 
1502 	rv = OpenProtocolByHandle(boot_img->DeviceHandle, &devid,
1503 	    (void **)&imgpath);
1504 	if (rv == EFI_SUCCESS) {
1505 		text = efi_devpath_name(imgpath);
1506 		if (text != NULL) {
1507 			printf("   Load Device: %S\n", text);
1508 			efi_setenv_freebsd_wcs("LoaderDev", text);
1509 			efi_free_devpath_name(text);
1510 		}
1511 	}
1512 
1513 	if (getenv("uefi_ignore_boot_mgr") != NULL) {
1514 		printf("    Ignoring UEFI boot manager\n");
1515 		uefi_boot_mgr = false;
1516 	} else {
1517 		uefi_boot_mgr = true;
1518 		boot_current = 0;
1519 		sz = sizeof(boot_current);
1520 		rv = efi_global_getenv("BootCurrent", &boot_current, &sz);
1521 		if (rv == EFI_SUCCESS)
1522 			printf("   BootCurrent: %04x\n", boot_current);
1523 		else {
1524 			boot_current = 0xffff;
1525 			uefi_boot_mgr = false;
1526 		}
1527 
1528 		sz = sizeof(boot_order);
1529 		rv = efi_global_getenv("BootOrder", &boot_order, &sz);
1530 		if (rv == EFI_SUCCESS) {
1531 			printf("   BootOrder:");
1532 			for (i = 0; i < sz / sizeof(boot_order[0]); i++)
1533 				printf(" %04x%s", boot_order[i],
1534 				    boot_order[i] == boot_current ? "[*]" : "");
1535 			printf("\n");
1536 		} else if (uefi_boot_mgr) {
1537 			/*
1538 			 * u-boot doesn't set BootOrder, but otherwise participates in the
1539 			 * boot manager protocol. So we fake it here and don't consider it
1540 			 * a failure.
1541 			 */
1542 			boot_order[0] = boot_current;
1543 		}
1544 	}
1545 
1546 	/*
1547 	 * Next, find the boot info structure the UEFI boot manager is
1548 	 * supposed to setup. We need this so we can walk through it to
1549 	 * find where we are in the booting process and what to try to
1550 	 * boot next.
1551 	 */
1552 	if (uefi_boot_mgr) {
1553 		snprintf(buf, sizeof(buf), "Boot%04X", boot_current);
1554 		sz = sizeof(boot_info);
1555 		rv = efi_global_getenv(buf, &boot_info, &sz);
1556 		if (rv == EFI_SUCCESS)
1557 			bisz = sz;
1558 		else
1559 			uefi_boot_mgr = false;
1560 	}
1561 
1562 	/*
1563 	 * Disable the watchdog timer. By default the boot manager sets
1564 	 * the timer to 5 minutes before invoking a boot option. If we
1565 	 * want to return to the boot manager, we have to disable the
1566 	 * watchdog timer and since we're an interactive program, we don't
1567 	 * want to wait until the user types "quit". The timer may have
1568 	 * fired by then. We don't care if this fails. It does not prevent
1569 	 * normal functioning in any way...
1570 	 */
1571 	BS->SetWatchdogTimer(0, 0, 0, NULL);
1572 
1573 	/*
1574 	 * Initialize the trusted/forbidden certificates from UEFI.
1575 	 * They will be later used to verify the manifest(s),
1576 	 * which should contain hashes of verified files.
1577 	 * This needs to be initialized before any configuration files
1578 	 * are loaded.
1579 	 */
1580 #ifdef EFI_SECUREBOOT
1581 	ve_efi_init();
1582 #endif
1583 
1584 	/*
1585 	 * Try and find a good currdev based on the image that was booted.
1586 	 * It might be desirable here to have a short pause to allow falling
1587 	 * through to the boot loader instead of returning instantly to follow
1588 	 * the boot protocol and also allow an escape hatch for users wishing
1589 	 * to try something different.
1590 	 */
1591 	if (find_currdev(uefi_boot_mgr, boot_info, bisz) != 0)
1592 		if (uefi_boot_mgr &&
1593 		    !interactive_interrupt("Failed to find bootable partition"))
1594 			return (EFI_NOT_FOUND);
1595 
1596 	autoload_font(false);	/* Set up the font list for console. */
1597 	efi_init_environment();
1598 
1599 	interact();			/* doesn't return */
1600 
1601 	return (EFI_SUCCESS);		/* keep compiler happy */
1602 }
1603 
1604 COMMAND_SET(efi_seed_entropy, "efi-seed-entropy", "try to get entropy from the EFI RNG", command_seed_entropy);
1605 
1606 static int
1607 command_seed_entropy(int argc, char *argv[])
1608 {
1609 	EFI_STATUS status;
1610 	EFI_RNG_PROTOCOL *rng;
1611 	unsigned int size_efi = RANDOM_FORTUNA_DEFPOOLSIZE * RANDOM_FORTUNA_NPOOLS;
1612 	unsigned int size = RANDOM_FORTUNA_DEFPOOLSIZE * RANDOM_FORTUNA_NPOOLS;
1613 	void *buf_efi;
1614 	void *buf;
1615 
1616 	if (argc > 1) {
1617 		size_efi = strtol(argv[1], NULL, 0);
1618 
1619 		/* Don't *compress* the entropy we get from EFI. */
1620 		if (size_efi > size)
1621 			size = size_efi;
1622 
1623 		/*
1624 		 * If the amount of entropy we get from EFI is less than the
1625 		 * size of a single Fortuna pool -- i.e. not enough to ensure
1626 		 * that Fortuna is safely seeded -- don't expand it since we
1627 		 * don't want to trick Fortuna into thinking that it has been
1628 		 * safely seeded when it has not.
1629 		 */
1630 		if (size_efi < RANDOM_FORTUNA_DEFPOOLSIZE)
1631 			size = size_efi;
1632 	}
1633 
1634 	status = BS->LocateProtocol(&rng_guid, NULL, (VOID **)&rng);
1635 	if (status != EFI_SUCCESS) {
1636 		command_errmsg = "RNG protocol not found";
1637 		return (CMD_ERROR);
1638 	}
1639 
1640 	if ((buf = malloc(size)) == NULL) {
1641 		command_errmsg = "out of memory";
1642 		return (CMD_ERROR);
1643 	}
1644 
1645 	if ((buf_efi = malloc(size_efi)) == NULL) {
1646 		free(buf);
1647 		command_errmsg = "out of memory";
1648 		return (CMD_ERROR);
1649 	}
1650 
1651 	TSENTER2("rng->GetRNG");
1652 	status = rng->GetRNG(rng, NULL, size_efi, (UINT8 *)buf_efi);
1653 	TSEXIT();
1654 	if (status != EFI_SUCCESS) {
1655 		free(buf_efi);
1656 		free(buf);
1657 		command_errmsg = "GetRNG failed";
1658 		return (CMD_ERROR);
1659 	}
1660 	if (size_efi < size)
1661 		pkcs5v2_genkey_raw(buf, size, "", 0, buf_efi, size_efi, 1);
1662 	else
1663 		memcpy(buf, buf_efi, size);
1664 
1665 	if (file_addbuf("efi_rng_seed", "boot_entropy_platform", size, buf) != 0) {
1666 		free(buf_efi);
1667 		free(buf);
1668 		return (CMD_ERROR);
1669 	}
1670 
1671 	explicit_bzero(buf_efi, size_efi);
1672 	free(buf_efi);
1673 	free(buf);
1674 	return (CMD_OK);
1675 }
1676 
1677 COMMAND_SET(poweroff, "poweroff", "power off the system", command_poweroff);
1678 COMMAND_SET(halt, "halt", "power off the system", command_poweroff);
1679 
1680 static int
1681 command_poweroff(int argc __unused, char *argv[] __unused)
1682 {
1683 	int i;
1684 
1685 	for (i = 0; devsw[i] != NULL; ++i)
1686 		if (devsw[i]->dv_cleanup != NULL)
1687 			(devsw[i]->dv_cleanup)();
1688 
1689 	RS->ResetSystem(EfiResetShutdown, EFI_SUCCESS, 0, NULL);
1690 
1691 	/* NOTREACHED */
1692 	return (CMD_ERROR);
1693 }
1694 
1695 COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot);
1696 
1697 static int
1698 command_reboot(int argc, char *argv[])
1699 {
1700 	int i;
1701 
1702 	for (i = 0; devsw[i] != NULL; ++i)
1703 		if (devsw[i]->dv_cleanup != NULL)
1704 			(devsw[i]->dv_cleanup)();
1705 
1706 	RS->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL);
1707 
1708 	/* NOTREACHED */
1709 	return (CMD_ERROR);
1710 }
1711 
1712 COMMAND_SET(memmap, "memmap", "print memory map", command_memmap);
1713 
1714 static int
1715 command_memmap(int argc __unused, char *argv[] __unused)
1716 {
1717 	UINTN sz;
1718 	EFI_MEMORY_DESCRIPTOR *map, *p;
1719 	UINTN key, dsz;
1720 	UINT32 dver;
1721 	EFI_STATUS status;
1722 	int i, ndesc;
1723 	char line[80];
1724 
1725 	sz = 0;
1726 	status = BS->GetMemoryMap(&sz, 0, &key, &dsz, &dver);
1727 	if (status != EFI_BUFFER_TOO_SMALL) {
1728 		printf("Can't determine memory map size\n");
1729 		return (CMD_ERROR);
1730 	}
1731 	map = malloc(sz);
1732 	status = BS->GetMemoryMap(&sz, map, &key, &dsz, &dver);
1733 	if (EFI_ERROR(status)) {
1734 		printf("Can't read memory map\n");
1735 		return (CMD_ERROR);
1736 	}
1737 
1738 	ndesc = sz / dsz;
1739 	snprintf(line, sizeof(line), "%23s %12s %12s %8s %4s\n",
1740 	    "Type", "Physical", "Virtual", "#Pages", "Attr");
1741 	pager_open();
1742 	if (pager_output(line)) {
1743 		pager_close();
1744 		return (CMD_OK);
1745 	}
1746 
1747 	for (i = 0, p = map; i < ndesc;
1748 	     i++, p = NextMemoryDescriptor(p, dsz)) {
1749 		snprintf(line, sizeof(line), "%23s %012jx %012jx %08jx ",
1750 		    efi_memory_type(p->Type), (uintmax_t)p->PhysicalStart,
1751 		    (uintmax_t)p->VirtualStart, (uintmax_t)p->NumberOfPages);
1752 		if (pager_output(line))
1753 			break;
1754 
1755 		if (p->Attribute & EFI_MEMORY_UC)
1756 			printf("UC ");
1757 		if (p->Attribute & EFI_MEMORY_WC)
1758 			printf("WC ");
1759 		if (p->Attribute & EFI_MEMORY_WT)
1760 			printf("WT ");
1761 		if (p->Attribute & EFI_MEMORY_WB)
1762 			printf("WB ");
1763 		if (p->Attribute & EFI_MEMORY_UCE)
1764 			printf("UCE ");
1765 		if (p->Attribute & EFI_MEMORY_WP)
1766 			printf("WP ");
1767 		if (p->Attribute & EFI_MEMORY_RP)
1768 			printf("RP ");
1769 		if (p->Attribute & EFI_MEMORY_XP)
1770 			printf("XP ");
1771 		if (p->Attribute & EFI_MEMORY_NV)
1772 			printf("NV ");
1773 		if (p->Attribute & EFI_MEMORY_MORE_RELIABLE)
1774 			printf("MR ");
1775 		if (p->Attribute & EFI_MEMORY_RO)
1776 			printf("RO ");
1777 		if (pager_output("\n"))
1778 			break;
1779 	}
1780 
1781 	pager_close();
1782 	return (CMD_OK);
1783 }
1784 
1785 COMMAND_SET(configuration, "configuration", "print configuration tables",
1786     command_configuration);
1787 
1788 static int
1789 command_configuration(int argc, char *argv[])
1790 {
1791 	UINTN i;
1792 	char *name;
1793 
1794 	printf("NumberOfTableEntries=%lu\n",
1795 		(unsigned long)ST->NumberOfTableEntries);
1796 
1797 	for (i = 0; i < ST->NumberOfTableEntries; i++) {
1798 		EFI_GUID *guid;
1799 
1800 		printf("  ");
1801 		guid = &ST->ConfigurationTable[i].VendorGuid;
1802 
1803 		if (efi_guid_to_name(guid, &name) == true) {
1804 			printf(name);
1805 			free(name);
1806 		} else {
1807 			printf("Error while translating UUID to name");
1808 		}
1809 		printf(" at %p\n", ST->ConfigurationTable[i].VendorTable);
1810 	}
1811 
1812 	return (CMD_OK);
1813 }
1814 
1815 
1816 COMMAND_SET(mode, "mode", "change or display EFI text modes", command_mode);
1817 
1818 static int
1819 command_mode(int argc, char *argv[])
1820 {
1821 	UINTN cols, rows;
1822 	unsigned int mode;
1823 	int i;
1824 	char *cp;
1825 	EFI_STATUS status;
1826 	SIMPLE_TEXT_OUTPUT_INTERFACE *conout;
1827 
1828 	conout = ST->ConOut;
1829 
1830 	if (argc > 1) {
1831 		mode = strtol(argv[1], &cp, 0);
1832 		if (cp[0] != '\0') {
1833 			printf("Invalid mode\n");
1834 			return (CMD_ERROR);
1835 		}
1836 		status = conout->QueryMode(conout, mode, &cols, &rows);
1837 		if (EFI_ERROR(status)) {
1838 			printf("invalid mode %d\n", mode);
1839 			return (CMD_ERROR);
1840 		}
1841 		status = conout->SetMode(conout, mode);
1842 		if (EFI_ERROR(status)) {
1843 			printf("couldn't set mode %d\n", mode);
1844 			return (CMD_ERROR);
1845 		}
1846 		(void) cons_update_mode(true);
1847 		return (CMD_OK);
1848 	}
1849 
1850 	printf("Current mode: %d\n", conout->Mode->Mode);
1851 	for (i = 0; i <= conout->Mode->MaxMode; i++) {
1852 		status = conout->QueryMode(conout, i, &cols, &rows);
1853 		if (EFI_ERROR(status))
1854 			continue;
1855 		printf("Mode %d: %u columns, %u rows\n", i, (unsigned)cols,
1856 		    (unsigned)rows);
1857 	}
1858 
1859 	if (i != 0)
1860 		printf("Select a mode with the command \"mode <number>\"\n");
1861 
1862 	return (CMD_OK);
1863 }
1864 
1865 COMMAND_SET(lsefi, "lsefi", "list EFI handles", command_lsefi);
1866 
1867 static void
1868 lsefi_print_handle_info(EFI_HANDLE handle)
1869 {
1870 	EFI_DEVICE_PATH *devpath;
1871 	EFI_DEVICE_PATH *imagepath;
1872 	CHAR16 *dp_name;
1873 
1874 	imagepath = efi_lookup_image_devpath(handle);
1875 	if (imagepath != NULL) {
1876 		dp_name = efi_devpath_name(imagepath);
1877 		printf("Handle for image %S", dp_name);
1878 		efi_free_devpath_name(dp_name);
1879 		return;
1880 	}
1881 	devpath = efi_lookup_devpath(handle);
1882 	if (devpath != NULL) {
1883 		dp_name = efi_devpath_name(devpath);
1884 		printf("Handle for device %S", dp_name);
1885 		efi_free_devpath_name(dp_name);
1886 		return;
1887 	}
1888 	printf("Handle %p", handle);
1889 }
1890 
1891 static int
1892 command_lsefi(int argc __unused, char *argv[] __unused)
1893 {
1894 	char *name;
1895 	EFI_HANDLE *buffer = NULL;
1896 	EFI_HANDLE handle;
1897 	UINTN bufsz = 0, i, j;
1898 	EFI_STATUS status;
1899 	int ret = 0;
1900 
1901 	status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer);
1902 	if (status != EFI_BUFFER_TOO_SMALL) {
1903 		snprintf(command_errbuf, sizeof (command_errbuf),
1904 		    "unexpected error: %lld", (long long)status);
1905 		return (CMD_ERROR);
1906 	}
1907 	if ((buffer = malloc(bufsz)) == NULL) {
1908 		sprintf(command_errbuf, "out of memory");
1909 		return (CMD_ERROR);
1910 	}
1911 
1912 	status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer);
1913 	if (EFI_ERROR(status)) {
1914 		free(buffer);
1915 		snprintf(command_errbuf, sizeof (command_errbuf),
1916 		    "LocateHandle() error: %lld", (long long)status);
1917 		return (CMD_ERROR);
1918 	}
1919 
1920 	pager_open();
1921 	for (i = 0; i < (bufsz / sizeof (EFI_HANDLE)); i++) {
1922 		UINTN nproto = 0;
1923 		EFI_GUID **protocols = NULL;
1924 
1925 		handle = buffer[i];
1926 		lsefi_print_handle_info(handle);
1927 		if (pager_output("\n"))
1928 			break;
1929 		/* device path */
1930 
1931 		status = BS->ProtocolsPerHandle(handle, &protocols, &nproto);
1932 		if (EFI_ERROR(status)) {
1933 			snprintf(command_errbuf, sizeof (command_errbuf),
1934 			    "ProtocolsPerHandle() error: %lld",
1935 			    (long long)status);
1936 			continue;
1937 		}
1938 
1939 		for (j = 0; j < nproto; j++) {
1940 			if (efi_guid_to_name(protocols[j], &name) == true) {
1941 				printf("  %s", name);
1942 				free(name);
1943 			} else {
1944 				printf("Error while translating UUID to name");
1945 			}
1946 			if ((ret = pager_output("\n")) != 0)
1947 				break;
1948 		}
1949 		BS->FreePool(protocols);
1950 		if (ret != 0)
1951 			break;
1952 	}
1953 	pager_close();
1954 	free(buffer);
1955 	return (CMD_OK);
1956 }
1957 
1958 #ifdef LOADER_FDT_SUPPORT
1959 extern int command_fdt_internal(int argc, char *argv[]);
1960 
1961 /*
1962  * Since proper fdt command handling function is defined in fdt_loader_cmd.c,
1963  * and declaring it as extern is in contradiction with COMMAND_SET() macro
1964  * (which uses static pointer), we're defining wrapper function, which
1965  * calls the proper fdt handling routine.
1966  */
1967 static int
1968 command_fdt(int argc, char *argv[])
1969 {
1970 
1971 	return (command_fdt_internal(argc, argv));
1972 }
1973 
1974 COMMAND_SET(fdt, "fdt", "flattened device tree handling", command_fdt);
1975 #endif
1976 
1977 /*
1978  * Chain load another efi loader.
1979  */
1980 static int
1981 command_chain(int argc, char *argv[])
1982 {
1983 	EFI_GUID LoadedImageGUID = LOADED_IMAGE_PROTOCOL;
1984 	EFI_HANDLE loaderhandle;
1985 	EFI_LOADED_IMAGE *loaded_image;
1986 	UINTN ExitDataSize;
1987 	CHAR16 *ExitData = NULL;
1988 	EFI_STATUS status;
1989 	struct stat st;
1990 	struct devdesc *dev;
1991 	char *name, *path;
1992 	void *buf;
1993 	int fd;
1994 
1995 	if (argc < 2) {
1996 		command_errmsg = "wrong number of arguments";
1997 		return (CMD_ERROR);
1998 	}
1999 
2000 	name = argv[1];
2001 
2002 	if ((fd = open(name, O_RDONLY)) < 0) {
2003 		command_errmsg = "no such file";
2004 		return (CMD_ERROR);
2005 	}
2006 
2007 #ifdef LOADER_VERIEXEC
2008 	if (verify_file(fd, name, 0, VE_MUST, __func__) < 0) {
2009 		sprintf(command_errbuf, "can't verify: %s", name);
2010 		close(fd);
2011 		return (CMD_ERROR);
2012 	}
2013 #endif
2014 
2015 	if (fstat(fd, &st) < -1) {
2016 		command_errmsg = "stat failed";
2017 		close(fd);
2018 		return (CMD_ERROR);
2019 	}
2020 
2021 	status = BS->AllocatePool(EfiLoaderCode, (UINTN)st.st_size, &buf);
2022 	if (status != EFI_SUCCESS) {
2023 		command_errmsg = "failed to allocate buffer";
2024 		close(fd);
2025 		return (CMD_ERROR);
2026 	}
2027 	if (read(fd, buf, st.st_size) != st.st_size) {
2028 		command_errmsg = "error while reading the file";
2029 		(void)BS->FreePool(buf);
2030 		close(fd);
2031 		return (CMD_ERROR);
2032 	}
2033 	close(fd);
2034 	status = BS->LoadImage(FALSE, IH, NULL, buf, st.st_size, &loaderhandle);
2035 	(void)BS->FreePool(buf);
2036 	if (status != EFI_SUCCESS) {
2037 		command_errmsg = "LoadImage failed";
2038 		return (CMD_ERROR);
2039 	}
2040 	status = OpenProtocolByHandle(loaderhandle, &LoadedImageGUID,
2041 	    (void **)&loaded_image);
2042 
2043 	if (argc > 2) {
2044 		int i, len = 0;
2045 		CHAR16 *argp;
2046 
2047 		for (i = 2; i < argc; i++)
2048 			len += strlen(argv[i]) + 1;
2049 
2050 		len *= sizeof (*argp);
2051 		loaded_image->LoadOptions = argp = malloc (len);
2052 		loaded_image->LoadOptionsSize = len;
2053 		for (i = 2; i < argc; i++) {
2054 			char *ptr = argv[i];
2055 			while (*ptr)
2056 				*(argp++) = *(ptr++);
2057 			*(argp++) = ' ';
2058 		}
2059 		*(--argv) = 0;
2060 	}
2061 
2062 	if (efi_getdev((void **)&dev, name, (const char **)&path) == 0) {
2063 #ifdef EFI_ZFS_BOOT
2064 		struct zfs_devdesc *z_dev;
2065 #endif
2066 		struct disk_devdesc *d_dev;
2067 		pdinfo_t *hd, *pd;
2068 
2069 		switch (dev->d_dev->dv_type) {
2070 #ifdef EFI_ZFS_BOOT
2071 		case DEVT_ZFS:
2072 			z_dev = (struct zfs_devdesc *)dev;
2073 			loaded_image->DeviceHandle =
2074 			    efizfs_get_handle_by_guid(z_dev->pool_guid);
2075 			break;
2076 #endif
2077 		case DEVT_NET:
2078 			loaded_image->DeviceHandle =
2079 			    efi_find_handle(dev->d_dev, dev->d_unit);
2080 			break;
2081 		default:
2082 			hd = efiblk_get_pdinfo(dev);
2083 			if (STAILQ_EMPTY(&hd->pd_part)) {
2084 				loaded_image->DeviceHandle = hd->pd_handle;
2085 				break;
2086 			}
2087 			d_dev = (struct disk_devdesc *)dev;
2088 			STAILQ_FOREACH(pd, &hd->pd_part, pd_link) {
2089 				/*
2090 				 * d_partition should be 255
2091 				 */
2092 				if (pd->pd_unit == (uint32_t)d_dev->d_slice) {
2093 					loaded_image->DeviceHandle =
2094 					    pd->pd_handle;
2095 					break;
2096 				}
2097 			}
2098 			break;
2099 		}
2100 	}
2101 
2102 	dev_cleanup();
2103 
2104 	status = BS->StartImage(loaderhandle, &ExitDataSize, &ExitData);
2105 	if (status != EFI_SUCCESS) {
2106 		printf("StartImage failed (%lu)", DECODE_ERROR(status));
2107 		if (ExitData != NULL) {
2108 			printf(": %S", ExitData);
2109 			BS->FreePool(ExitData);
2110 		}
2111 		putchar('\n');
2112 		command_errmsg = "";
2113 		free(loaded_image->LoadOptions);
2114 		loaded_image->LoadOptions = NULL;
2115 		status = BS->UnloadImage(loaded_image);
2116 		return (CMD_ERROR);
2117 	}
2118 
2119 	return (CMD_ERROR);	/* not reached */
2120 }
2121 
2122 COMMAND_SET(chain, "chain", "chain load file", command_chain);
2123 
2124 #if defined(LOADER_NET_SUPPORT)
2125 extern struct in_addr servip;
2126 static int
2127 command_netserver(int argc, char *argv[])
2128 {
2129 	char *proto;
2130 	n_long rootaddr;
2131 
2132 	if (argc > 2) {
2133 		command_errmsg = "wrong number of arguments";
2134 		return (CMD_ERROR);
2135 	}
2136 	if (argc < 2) {
2137 		proto = netproto == NET_TFTP ? "tftp://" : "nfs://";
2138 		printf("Netserver URI: %s%s%s\n", proto, intoa(rootip.s_addr),
2139 		    rootpath);
2140 		return (CMD_OK);
2141 	}
2142 	if (argc == 2) {
2143 		strncpy(rootpath, argv[1], sizeof(rootpath));
2144 		rootpath[sizeof(rootpath) -1] = '\0';
2145 		if ((rootaddr = net_parse_rootpath()) != INADDR_NONE)
2146 			servip.s_addr = rootip.s_addr = rootaddr;
2147 		return (CMD_OK);
2148 	}
2149 	return (CMD_ERROR);	/* not reached */
2150 
2151 }
2152 
2153 COMMAND_SET(netserver, "netserver", "change or display netserver URI",
2154     command_netserver);
2155 #endif
2156