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