xref: /freebsd/stand/efi/loader/main.c (revision 1edb7116)
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. Also check for ConIn as well. This will
726  * be enough to determine if we have serial, and if we don't, we default
727  * to video. If there's a dual-console situation with ConIn, this will
728  * currently fail.
729  */
730 int
731 parse_uefi_con_out(void)
732 {
733 	int how, rv;
734 	int vid_seen = 0, com_seen = 0, seen = 0;
735 	size_t sz;
736 	char buf[4096], *ep;
737 	EFI_DEVICE_PATH *node;
738 	ACPI_HID_DEVICE_PATH  *acpi;
739 	UART_DEVICE_PATH  *uart;
740 	bool pci_pending;
741 
742 	how = 0;
743 	sz = sizeof(buf);
744 	rv = efi_global_getenv("ConOut", buf, &sz);
745 	if (rv != EFI_SUCCESS)
746 		rv = efi_global_getenv("ConOutDev", buf, &sz);
747 	if (rv != EFI_SUCCESS)
748 		rv = efi_global_getenv("ConIn", buf, &sz);
749 	if (rv != EFI_SUCCESS) {
750 		/*
751 		 * If we don't have any ConOut default to both. If we have GOP
752 		 * make video primary, otherwise just make serial primary. In
753 		 * either case, try to use both the 'efi' console which will use
754 		 * the GOP, if present and serial. If there's an EFI BIOS that
755 		 * omits this, but has a serial port redirect, we'll
756 		 * unavioidably get doubled characters (but we'll be right in
757 		 * all the other more common cases).
758 		 */
759 		if (efi_has_gop())
760 			how = RB_MULTIPLE;
761 		else
762 			how = RB_MULTIPLE | RB_SERIAL;
763 		setenv("console", "efi,comconsole", 1);
764 		goto out;
765 	}
766 	ep = buf + sz;
767 	node = (EFI_DEVICE_PATH *)buf;
768 	while ((char *)node < ep) {
769 		if (IsDevicePathEndType(node)) {
770 			if (pci_pending && vid_seen == 0)
771 				vid_seen = ++seen;
772 		}
773 		pci_pending = false;
774 		if (DevicePathType(node) == ACPI_DEVICE_PATH &&
775 		    (DevicePathSubType(node) == ACPI_DP ||
776 		    DevicePathSubType(node) == ACPI_EXTENDED_DP)) {
777 			/* Check for Serial node */
778 			acpi = (void *)node;
779 			if (EISA_ID_TO_NUM(acpi->HID) == 0x501) {
780 				setenv_int("efi_8250_uid", acpi->UID);
781 				com_seen = ++seen;
782 			}
783 		} else if (DevicePathType(node) == MESSAGING_DEVICE_PATH &&
784 		    DevicePathSubType(node) == MSG_UART_DP) {
785 			com_seen = ++seen;
786 			uart = (void *)node;
787 			setenv_int("efi_com_speed", uart->BaudRate);
788 		} else if (DevicePathType(node) == ACPI_DEVICE_PATH &&
789 		    DevicePathSubType(node) == ACPI_ADR_DP) {
790 			/* Check for AcpiAdr() Node for video */
791 			vid_seen = ++seen;
792 		} else if (DevicePathType(node) == HARDWARE_DEVICE_PATH &&
793 		    DevicePathSubType(node) == HW_PCI_DP) {
794 			/*
795 			 * Note, vmware fusion has a funky console device
796 			 *	PciRoot(0x0)/Pci(0xf,0x0)
797 			 * which we can only detect at the end since we also
798 			 * have to cope with:
799 			 *	PciRoot(0x0)/Pci(0x1f,0x0)/Serial(0x1)
800 			 * so only match it if it's last.
801 			 */
802 			pci_pending = true;
803 		}
804 		node = NextDevicePathNode(node);
805 	}
806 
807 	/*
808 	 * Truth table for RB_MULTIPLE | RB_SERIAL
809 	 * Value		Result
810 	 * 0			Use only video console
811 	 * RB_SERIAL		Use only serial console
812 	 * RB_MULTIPLE		Use both video and serial console
813 	 *			(but video is primary so gets rc messages)
814 	 * both			Use both video and serial console
815 	 *			(but serial is primary so gets rc messages)
816 	 *
817 	 * Try to honor this as best we can. If only one of serial / video
818 	 * found, then use that. Otherwise, use the first one we found.
819 	 * This also implies if we found nothing, default to video.
820 	 */
821 	how = 0;
822 	if (vid_seen && com_seen) {
823 		how |= RB_MULTIPLE;
824 		if (com_seen < vid_seen)
825 			how |= RB_SERIAL;
826 	} else if (com_seen)
827 		how |= RB_SERIAL;
828 out:
829 	return (how);
830 }
831 
832 void
833 parse_loader_efi_config(EFI_HANDLE h, const char *env_fn)
834 {
835 	pdinfo_t *dp;
836 	struct stat st;
837 	int fd = -1;
838 	char *env = NULL;
839 
840 	dp = efiblk_get_pdinfo_by_handle(h);
841 	if (dp == NULL)
842 		return;
843 	set_currdev_pdinfo(dp);
844 	if (stat(env_fn, &st) != 0)
845 		return;
846 	fd = open(env_fn, O_RDONLY);
847 	if (fd == -1)
848 		return;
849 	env = malloc(st.st_size + 1);
850 	if (env == NULL)
851 		goto out;
852 	if (read(fd, env, st.st_size) != st.st_size)
853 		goto out;
854 	env[st.st_size] = '\0';
855 	boot_parse_cmdline(env);
856 out:
857 	free(env);
858 	close(fd);
859 }
860 
861 static void
862 read_loader_env(const char *name, char *def_fn, bool once)
863 {
864 	UINTN len;
865 	char *fn, *freeme = NULL;
866 
867 	len = 0;
868 	fn = def_fn;
869 	if (efi_freebsd_getenv(name, NULL, &len) == EFI_BUFFER_TOO_SMALL) {
870 		freeme = fn = malloc(len + 1);
871 		if (fn != NULL) {
872 			if (efi_freebsd_getenv(name, fn, &len) != EFI_SUCCESS) {
873 				free(fn);
874 				fn = NULL;
875 				printf(
876 			    "Can't fetch FreeBSD::%s we know is there\n", name);
877 			} else {
878 				/*
879 				 * if tagged as 'once' delete the env variable so we
880 				 * only use it once.
881 				 */
882 				if (once)
883 					efi_freebsd_delenv(name);
884 				/*
885 				 * We malloced 1 more than len above, then redid the call.
886 				 * so now we have room at the end of the string to NUL terminate
887 				 * it here, even if the typical idium would have '- 1' here to
888 				 * not overflow. len should be the same on return both times.
889 				 */
890 				fn[len] = '\0';
891 			}
892 		} else {
893 			printf(
894 		    "Can't allocate %d bytes to fetch FreeBSD::%s env var\n",
895 			    len, name);
896 		}
897 	}
898 	if (fn) {
899 		printf("    Reading loader env vars from %s\n", fn);
900 		parse_loader_efi_config(boot_img->DeviceHandle, fn);
901 	}
902 }
903 
904 caddr_t
905 ptov(uintptr_t x)
906 {
907 	return ((caddr_t)x);
908 }
909 
910 static void
911 acpi_detect(void)
912 {
913 	ACPI_TABLE_RSDP *rsdp;
914 	char buf[24];
915 	int revision;
916 
917 	feature_enable(FEATURE_EARLY_ACPI);
918 	if ((rsdp = efi_get_table(&acpi20)) == NULL)
919 		if ((rsdp = efi_get_table(&acpi)) == NULL)
920 			return;
921 
922 	sprintf(buf, "0x%016llx", (unsigned long long)rsdp);
923 	setenv("acpi.rsdp", buf, 1);
924 	revision = rsdp->Revision;
925 	if (revision == 0)
926 		revision = 1;
927 	sprintf(buf, "%d", revision);
928 	setenv("acpi.revision", buf, 1);
929 	strncpy(buf, rsdp->OemId, sizeof(rsdp->OemId));
930 	buf[sizeof(rsdp->OemId)] = '\0';
931 	setenv("acpi.oem", buf, 1);
932 	sprintf(buf, "0x%016x", rsdp->RsdtPhysicalAddress);
933 	setenv("acpi.rsdt", buf, 1);
934 	if (revision >= 2) {
935 		/* XXX extended checksum? */
936 		sprintf(buf, "0x%016llx",
937 		    (unsigned long long)rsdp->XsdtPhysicalAddress);
938 		setenv("acpi.xsdt", buf, 1);
939 		sprintf(buf, "%d", rsdp->Length);
940 		setenv("acpi.xsdt_length", buf, 1);
941 	}
942 }
943 
944 EFI_STATUS
945 main(int argc, CHAR16 *argv[])
946 {
947 	EFI_GUID *guid;
948 	int howto, i, uhowto;
949 	UINTN k;
950 	bool has_kbd, is_last;
951 	char *s;
952 	EFI_DEVICE_PATH *imgpath;
953 	CHAR16 *text;
954 	EFI_STATUS rv;
955 	size_t sz, bosz = 0, bisz = 0;
956 	UINT16 boot_order[100];
957 	char boot_info[4096];
958 	char buf[32];
959 	bool uefi_boot_mgr;
960 
961 	archsw.arch_autoload = efi_autoload;
962 	archsw.arch_getdev = efi_getdev;
963 	archsw.arch_copyin = efi_copyin;
964 	archsw.arch_copyout = efi_copyout;
965 #ifdef __amd64__
966 	archsw.arch_hypervisor = x86_hypervisor;
967 #endif
968 	archsw.arch_readin = efi_readin;
969 	archsw.arch_zfs_probe = efi_zfs_probe;
970 
971 #if !defined(__arm__)
972 	for (k = 0; k < ST->NumberOfTableEntries; k++) {
973 		guid = &ST->ConfigurationTable[k].VendorGuid;
974 		if (!memcmp(guid, &smbios, sizeof(EFI_GUID)) ||
975 		    !memcmp(guid, &smbios3, sizeof(EFI_GUID))) {
976 			char buf[40];
977 
978 			snprintf(buf, sizeof(buf), "%p",
979 			    ST->ConfigurationTable[k].VendorTable);
980 			setenv("hint.smbios.0.mem", buf, 1);
981 			smbios_detect(ST->ConfigurationTable[k].VendorTable);
982 			break;
983 		}
984 	}
985 #endif
986 
987         /* Get our loaded image protocol interface structure. */
988 	(void) OpenProtocolByHandle(IH, &imgid, (void **)&boot_img);
989 
990 	/* Report the RSDP early. */
991 	acpi_detect();
992 
993 	/*
994 	 * Chicken-and-egg problem; we want to have console output early, but
995 	 * some console attributes may depend on reading from eg. the boot
996 	 * device, which we can't do yet.  We can use printf() etc. once this is
997 	 * done. So, we set it to the efi console, then call console init. This
998 	 * gets us printf early, but also primes the pump for all future console
999 	 * changes to take effect, regardless of where they come from.
1000 	 */
1001 	setenv("console", "efi", 1);
1002 	uhowto = parse_uefi_con_out();
1003 #if defined(__riscv)
1004 	/*
1005 	 * This workaround likely is papering over a real issue
1006 	 */
1007 	if ((uhowto & RB_SERIAL) != 0)
1008 		setenv("console", "comconsole", 1);
1009 #endif
1010 	cons_probe();
1011 
1012 	/* Set up currdev variable to have hooks in place. */
1013 	env_setenv("currdev", EV_VOLATILE, "", gen_setcurrdev, env_nounset);
1014 
1015 	/* Init the time source */
1016 	efi_time_init();
1017 
1018 	/*
1019 	 * Initialise the block cache. Set the upper limit.
1020 	 */
1021 	bcache_init(32768, 512);
1022 
1023 	/*
1024 	 * Scan the BLOCK IO MEDIA handles then
1025 	 * march through the device switch probing for things.
1026 	 */
1027 	i = efipart_inithandles();
1028 	if (i != 0 && i != ENOENT) {
1029 		printf("efipart_inithandles failed with ERRNO %d, expect "
1030 		    "failures\n", i);
1031 	}
1032 
1033 	devinit();
1034 
1035 	/*
1036 	 * Detect console settings two different ways: one via the command
1037 	 * args (eg -h) or via the UEFI ConOut variable.
1038 	 */
1039 	has_kbd = has_keyboard();
1040 	howto = parse_args(argc, argv);
1041 	if (!has_kbd && (howto & RB_PROBE))
1042 		howto |= RB_SERIAL | RB_MULTIPLE;
1043 	howto &= ~RB_PROBE;
1044 
1045 	/*
1046 	 * Read additional environment variables from the boot device's
1047 	 * "LoaderEnv" file. Any boot loader environment variable may be set
1048 	 * there, which are subtly different than loader.conf variables. Only
1049 	 * the 'simple' ones may be set so things like foo_load="YES" won't work
1050 	 * for two reasons.  First, the parser is simplistic and doesn't grok
1051 	 * quotes.  Second, because the variables that cause an action to happen
1052 	 * are parsed by the lua, 4th or whatever code that's not yet
1053 	 * loaded. This is relative to the root directory when loader.efi is
1054 	 * loaded off the UFS root drive (when chain booted), or from the ESP
1055 	 * when directly loaded by the BIOS.
1056 	 *
1057 	 * We also read in NextLoaderEnv if it was specified. This allows next boot
1058 	 * functionality to be implemented and to override anything in LoaderEnv.
1059 	 */
1060 	read_loader_env("LoaderEnv", "/efi/freebsd/loader.env", false);
1061 	read_loader_env("NextLoaderEnv", NULL, true);
1062 
1063 	/*
1064 	 * We now have two notions of console. howto should be viewed as
1065 	 * overrides. If console is already set, don't set it again.
1066 	 */
1067 #define	VIDEO_ONLY	0
1068 #define	SERIAL_ONLY	RB_SERIAL
1069 #define	VID_SER_BOTH	RB_MULTIPLE
1070 #define	SER_VID_BOTH	(RB_SERIAL | RB_MULTIPLE)
1071 #define	CON_MASK	(RB_SERIAL | RB_MULTIPLE)
1072 	if (strcmp(getenv("console"), "efi") == 0) {
1073 		if ((howto & CON_MASK) == 0) {
1074 			/* No override, uhowto is controlling and efi cons is perfect */
1075 			howto = howto | (uhowto & CON_MASK);
1076 		} else if ((howto & CON_MASK) == (uhowto & CON_MASK)) {
1077 			/* override matches what UEFI told us, efi console is perfect */
1078 		} else if ((uhowto & (CON_MASK)) != 0) {
1079 			/*
1080 			 * We detected a serial console on ConOut. All possible
1081 			 * overrides include serial. We can't really override what efi
1082 			 * gives us, so we use it knowing it's the best choice.
1083 			 */
1084 			/* Do nothing */
1085 		} else {
1086 			/*
1087 			 * We detected some kind of serial in the override, but ConOut
1088 			 * has no serial, so we have to sort out which case it really is.
1089 			 */
1090 			switch (howto & CON_MASK) {
1091 			case SERIAL_ONLY:
1092 				setenv("console", "comconsole", 1);
1093 				break;
1094 			case VID_SER_BOTH:
1095 				setenv("console", "efi comconsole", 1);
1096 				break;
1097 			case SER_VID_BOTH:
1098 				setenv("console", "comconsole efi", 1);
1099 				break;
1100 				/* case VIDEO_ONLY can't happen -- it's the first if above */
1101 			}
1102 		}
1103 	}
1104 
1105 	/*
1106 	 * howto is set now how we want to export the flags to the kernel, so
1107 	 * set the env based on it.
1108 	 */
1109 	boot_howto_to_env(howto);
1110 
1111 	if (efi_copy_init())
1112 		return (EFI_BUFFER_TOO_SMALL);
1113 
1114 	if ((s = getenv("fail_timeout")) != NULL)
1115 		fail_timeout = strtol(s, NULL, 10);
1116 
1117 	printf("%s\n", bootprog_info);
1118 	printf("   Command line arguments:");
1119 	for (i = 0; i < argc; i++)
1120 		printf(" %S", argv[i]);
1121 	printf("\n");
1122 
1123 	printf("   Image base: 0x%lx\n", (unsigned long)boot_img->ImageBase);
1124 	printf("   EFI version: %d.%02d\n", ST->Hdr.Revision >> 16,
1125 	    ST->Hdr.Revision & 0xffff);
1126 	printf("   EFI Firmware: %S (rev %d.%02d)\n", ST->FirmwareVendor,
1127 	    ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
1128 	printf("   Console: %s (%#x)\n", getenv("console"), howto);
1129 
1130 	/* Determine the devpath of our image so we can prefer it. */
1131 	text = efi_devpath_name(boot_img->FilePath);
1132 	if (text != NULL) {
1133 		printf("   Load Path: %S\n", text);
1134 		efi_setenv_freebsd_wcs("LoaderPath", text);
1135 		efi_free_devpath_name(text);
1136 	}
1137 
1138 	rv = OpenProtocolByHandle(boot_img->DeviceHandle, &devid,
1139 	    (void **)&imgpath);
1140 	if (rv == EFI_SUCCESS) {
1141 		text = efi_devpath_name(imgpath);
1142 		if (text != NULL) {
1143 			printf("   Load Device: %S\n", text);
1144 			efi_setenv_freebsd_wcs("LoaderDev", text);
1145 			efi_free_devpath_name(text);
1146 		}
1147 	}
1148 
1149 	if (getenv("uefi_ignore_boot_mgr") != NULL) {
1150 		printf("    Ignoring UEFI boot manager\n");
1151 		uefi_boot_mgr = false;
1152 	} else {
1153 		uefi_boot_mgr = true;
1154 		boot_current = 0;
1155 		sz = sizeof(boot_current);
1156 		rv = efi_global_getenv("BootCurrent", &boot_current, &sz);
1157 		if (rv == EFI_SUCCESS)
1158 			printf("   BootCurrent: %04x\n", boot_current);
1159 		else {
1160 			boot_current = 0xffff;
1161 			uefi_boot_mgr = false;
1162 		}
1163 
1164 		sz = sizeof(boot_order);
1165 		rv = efi_global_getenv("BootOrder", &boot_order, &sz);
1166 		if (rv == EFI_SUCCESS) {
1167 			printf("   BootOrder:");
1168 			for (i = 0; i < sz / sizeof(boot_order[0]); i++)
1169 				printf(" %04x%s", boot_order[i],
1170 				    boot_order[i] == boot_current ? "[*]" : "");
1171 			printf("\n");
1172 			is_last = boot_order[(sz / sizeof(boot_order[0])) - 1] == boot_current;
1173 			bosz = sz;
1174 		} else if (uefi_boot_mgr) {
1175 			/*
1176 			 * u-boot doesn't set BootOrder, but otherwise participates in the
1177 			 * boot manager protocol. So we fake it here and don't consider it
1178 			 * a failure.
1179 			 */
1180 			bosz = sizeof(boot_order[0]);
1181 			boot_order[0] = boot_current;
1182 			is_last = true;
1183 		}
1184 	}
1185 
1186 	/*
1187 	 * Next, find the boot info structure the UEFI boot manager is
1188 	 * supposed to setup. We need this so we can walk through it to
1189 	 * find where we are in the booting process and what to try to
1190 	 * boot next.
1191 	 */
1192 	if (uefi_boot_mgr) {
1193 		snprintf(buf, sizeof(buf), "Boot%04X", boot_current);
1194 		sz = sizeof(boot_info);
1195 		rv = efi_global_getenv(buf, &boot_info, &sz);
1196 		if (rv == EFI_SUCCESS)
1197 			bisz = sz;
1198 		else
1199 			uefi_boot_mgr = false;
1200 	}
1201 
1202 	/*
1203 	 * Disable the watchdog timer. By default the boot manager sets
1204 	 * the timer to 5 minutes before invoking a boot option. If we
1205 	 * want to return to the boot manager, we have to disable the
1206 	 * watchdog timer and since we're an interactive program, we don't
1207 	 * want to wait until the user types "quit". The timer may have
1208 	 * fired by then. We don't care if this fails. It does not prevent
1209 	 * normal functioning in any way...
1210 	 */
1211 	BS->SetWatchdogTimer(0, 0, 0, NULL);
1212 
1213 	/*
1214 	 * Initialize the trusted/forbidden certificates from UEFI.
1215 	 * They will be later used to verify the manifest(s),
1216 	 * which should contain hashes of verified files.
1217 	 * This needs to be initialized before any configuration files
1218 	 * are loaded.
1219 	 */
1220 #ifdef EFI_SECUREBOOT
1221 	ve_efi_init();
1222 #endif
1223 
1224 	/*
1225 	 * Try and find a good currdev based on the image that was booted.
1226 	 * It might be desirable here to have a short pause to allow falling
1227 	 * through to the boot loader instead of returning instantly to follow
1228 	 * the boot protocol and also allow an escape hatch for users wishing
1229 	 * to try something different.
1230 	 */
1231 	if (find_currdev(uefi_boot_mgr, is_last, boot_info, bisz) != 0)
1232 		if (uefi_boot_mgr &&
1233 		    !interactive_interrupt("Failed to find bootable partition"))
1234 			return (EFI_NOT_FOUND);
1235 
1236 	autoload_font(false);	/* Set up the font list for console. */
1237 	efi_init_environment();
1238 
1239 	interact();			/* doesn't return */
1240 
1241 	return (EFI_SUCCESS);		/* keep compiler happy */
1242 }
1243 
1244 COMMAND_SET(efi_seed_entropy, "efi-seed-entropy", "try to get entropy from the EFI RNG", command_seed_entropy);
1245 
1246 static int
1247 command_seed_entropy(int argc, char *argv[])
1248 {
1249 	EFI_STATUS status;
1250 	EFI_RNG_PROTOCOL *rng;
1251 	unsigned int size = 2048;
1252 	void *buf;
1253 
1254 	if (argc > 1) {
1255 		size = strtol(argv[1], NULL, 0);
1256 	}
1257 
1258 	status = BS->LocateProtocol(&rng_guid, NULL, (VOID **)&rng);
1259 	if (status != EFI_SUCCESS) {
1260 		command_errmsg = "RNG protocol not found";
1261 		return (CMD_ERROR);
1262 	}
1263 
1264 	if ((buf = malloc(size)) == NULL) {
1265 		command_errmsg = "out of memory";
1266 		return (CMD_ERROR);
1267 	}
1268 
1269 	status = rng->GetRNG(rng, NULL, size, (UINT8 *)buf);
1270 	if (status != EFI_SUCCESS) {
1271 		free(buf);
1272 		command_errmsg = "GetRNG failed";
1273 		return (CMD_ERROR);
1274 	}
1275 
1276 	if (file_addbuf("efi_rng_seed", "boot_entropy_platform", size, buf) != 0) {
1277 		free(buf);
1278 		return (CMD_ERROR);
1279 	}
1280 
1281 	free(buf);
1282 	return (CMD_OK);
1283 }
1284 
1285 COMMAND_SET(poweroff, "poweroff", "power off the system", command_poweroff);
1286 
1287 static int
1288 command_poweroff(int argc __unused, char *argv[] __unused)
1289 {
1290 	int i;
1291 
1292 	for (i = 0; devsw[i] != NULL; ++i)
1293 		if (devsw[i]->dv_cleanup != NULL)
1294 			(devsw[i]->dv_cleanup)();
1295 
1296 	RS->ResetSystem(EfiResetShutdown, EFI_SUCCESS, 0, NULL);
1297 
1298 	/* NOTREACHED */
1299 	return (CMD_ERROR);
1300 }
1301 
1302 COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot);
1303 
1304 static int
1305 command_reboot(int argc, char *argv[])
1306 {
1307 	int i;
1308 
1309 	for (i = 0; devsw[i] != NULL; ++i)
1310 		if (devsw[i]->dv_cleanup != NULL)
1311 			(devsw[i]->dv_cleanup)();
1312 
1313 	RS->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL);
1314 
1315 	/* NOTREACHED */
1316 	return (CMD_ERROR);
1317 }
1318 
1319 COMMAND_SET(memmap, "memmap", "print memory map", command_memmap);
1320 
1321 static int
1322 command_memmap(int argc __unused, char *argv[] __unused)
1323 {
1324 	UINTN sz;
1325 	EFI_MEMORY_DESCRIPTOR *map, *p;
1326 	UINTN key, dsz;
1327 	UINT32 dver;
1328 	EFI_STATUS status;
1329 	int i, ndesc;
1330 	char line[80];
1331 
1332 	sz = 0;
1333 	status = BS->GetMemoryMap(&sz, 0, &key, &dsz, &dver);
1334 	if (status != EFI_BUFFER_TOO_SMALL) {
1335 		printf("Can't determine memory map size\n");
1336 		return (CMD_ERROR);
1337 	}
1338 	map = malloc(sz);
1339 	status = BS->GetMemoryMap(&sz, map, &key, &dsz, &dver);
1340 	if (EFI_ERROR(status)) {
1341 		printf("Can't read memory map\n");
1342 		return (CMD_ERROR);
1343 	}
1344 
1345 	ndesc = sz / dsz;
1346 	snprintf(line, sizeof(line), "%23s %12s %12s %8s %4s\n",
1347 	    "Type", "Physical", "Virtual", "#Pages", "Attr");
1348 	pager_open();
1349 	if (pager_output(line)) {
1350 		pager_close();
1351 		return (CMD_OK);
1352 	}
1353 
1354 	for (i = 0, p = map; i < ndesc;
1355 	     i++, p = NextMemoryDescriptor(p, dsz)) {
1356 		snprintf(line, sizeof(line), "%23s %012jx %012jx %08jx ",
1357 		    efi_memory_type(p->Type), (uintmax_t)p->PhysicalStart,
1358 		    (uintmax_t)p->VirtualStart, (uintmax_t)p->NumberOfPages);
1359 		if (pager_output(line))
1360 			break;
1361 
1362 		if (p->Attribute & EFI_MEMORY_UC)
1363 			printf("UC ");
1364 		if (p->Attribute & EFI_MEMORY_WC)
1365 			printf("WC ");
1366 		if (p->Attribute & EFI_MEMORY_WT)
1367 			printf("WT ");
1368 		if (p->Attribute & EFI_MEMORY_WB)
1369 			printf("WB ");
1370 		if (p->Attribute & EFI_MEMORY_UCE)
1371 			printf("UCE ");
1372 		if (p->Attribute & EFI_MEMORY_WP)
1373 			printf("WP ");
1374 		if (p->Attribute & EFI_MEMORY_RP)
1375 			printf("RP ");
1376 		if (p->Attribute & EFI_MEMORY_XP)
1377 			printf("XP ");
1378 		if (p->Attribute & EFI_MEMORY_NV)
1379 			printf("NV ");
1380 		if (p->Attribute & EFI_MEMORY_MORE_RELIABLE)
1381 			printf("MR ");
1382 		if (p->Attribute & EFI_MEMORY_RO)
1383 			printf("RO ");
1384 		if (pager_output("\n"))
1385 			break;
1386 	}
1387 
1388 	pager_close();
1389 	return (CMD_OK);
1390 }
1391 
1392 COMMAND_SET(configuration, "configuration", "print configuration tables",
1393     command_configuration);
1394 
1395 static int
1396 command_configuration(int argc, char *argv[])
1397 {
1398 	UINTN i;
1399 	char *name;
1400 
1401 	printf("NumberOfTableEntries=%lu\n",
1402 		(unsigned long)ST->NumberOfTableEntries);
1403 
1404 	for (i = 0; i < ST->NumberOfTableEntries; i++) {
1405 		EFI_GUID *guid;
1406 
1407 		printf("  ");
1408 		guid = &ST->ConfigurationTable[i].VendorGuid;
1409 
1410 		if (efi_guid_to_name(guid, &name) == true) {
1411 			printf(name);
1412 			free(name);
1413 		} else {
1414 			printf("Error while translating UUID to name");
1415 		}
1416 		printf(" at %p\n", ST->ConfigurationTable[i].VendorTable);
1417 	}
1418 
1419 	return (CMD_OK);
1420 }
1421 
1422 
1423 COMMAND_SET(mode, "mode", "change or display EFI text modes", command_mode);
1424 
1425 static int
1426 command_mode(int argc, char *argv[])
1427 {
1428 	UINTN cols, rows;
1429 	unsigned int mode;
1430 	int i;
1431 	char *cp;
1432 	EFI_STATUS status;
1433 	SIMPLE_TEXT_OUTPUT_INTERFACE *conout;
1434 
1435 	conout = ST->ConOut;
1436 
1437 	if (argc > 1) {
1438 		mode = strtol(argv[1], &cp, 0);
1439 		if (cp[0] != '\0') {
1440 			printf("Invalid mode\n");
1441 			return (CMD_ERROR);
1442 		}
1443 		status = conout->QueryMode(conout, mode, &cols, &rows);
1444 		if (EFI_ERROR(status)) {
1445 			printf("invalid mode %d\n", mode);
1446 			return (CMD_ERROR);
1447 		}
1448 		status = conout->SetMode(conout, mode);
1449 		if (EFI_ERROR(status)) {
1450 			printf("couldn't set mode %d\n", mode);
1451 			return (CMD_ERROR);
1452 		}
1453 		(void) cons_update_mode(true);
1454 		return (CMD_OK);
1455 	}
1456 
1457 	printf("Current mode: %d\n", conout->Mode->Mode);
1458 	for (i = 0; i <= conout->Mode->MaxMode; i++) {
1459 		status = conout->QueryMode(conout, i, &cols, &rows);
1460 		if (EFI_ERROR(status))
1461 			continue;
1462 		printf("Mode %d: %u columns, %u rows\n", i, (unsigned)cols,
1463 		    (unsigned)rows);
1464 	}
1465 
1466 	if (i != 0)
1467 		printf("Select a mode with the command \"mode <number>\"\n");
1468 
1469 	return (CMD_OK);
1470 }
1471 
1472 COMMAND_SET(lsefi, "lsefi", "list EFI handles", command_lsefi);
1473 
1474 static void
1475 lsefi_print_handle_info(EFI_HANDLE handle)
1476 {
1477 	EFI_DEVICE_PATH *devpath;
1478 	EFI_DEVICE_PATH *imagepath;
1479 	CHAR16 *dp_name;
1480 
1481 	imagepath = efi_lookup_image_devpath(handle);
1482 	if (imagepath != NULL) {
1483 		dp_name = efi_devpath_name(imagepath);
1484 		printf("Handle for image %S", dp_name);
1485 		efi_free_devpath_name(dp_name);
1486 		return;
1487 	}
1488 	devpath = efi_lookup_devpath(handle);
1489 	if (devpath != NULL) {
1490 		dp_name = efi_devpath_name(devpath);
1491 		printf("Handle for device %S", dp_name);
1492 		efi_free_devpath_name(dp_name);
1493 		return;
1494 	}
1495 	printf("Handle %p", handle);
1496 }
1497 
1498 static int
1499 command_lsefi(int argc __unused, char *argv[] __unused)
1500 {
1501 	char *name;
1502 	EFI_HANDLE *buffer = NULL;
1503 	EFI_HANDLE handle;
1504 	UINTN bufsz = 0, i, j;
1505 	EFI_STATUS status;
1506 	int ret = 0;
1507 
1508 	status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer);
1509 	if (status != EFI_BUFFER_TOO_SMALL) {
1510 		snprintf(command_errbuf, sizeof (command_errbuf),
1511 		    "unexpected error: %lld", (long long)status);
1512 		return (CMD_ERROR);
1513 	}
1514 	if ((buffer = malloc(bufsz)) == NULL) {
1515 		sprintf(command_errbuf, "out of memory");
1516 		return (CMD_ERROR);
1517 	}
1518 
1519 	status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer);
1520 	if (EFI_ERROR(status)) {
1521 		free(buffer);
1522 		snprintf(command_errbuf, sizeof (command_errbuf),
1523 		    "LocateHandle() error: %lld", (long long)status);
1524 		return (CMD_ERROR);
1525 	}
1526 
1527 	pager_open();
1528 	for (i = 0; i < (bufsz / sizeof (EFI_HANDLE)); i++) {
1529 		UINTN nproto = 0;
1530 		EFI_GUID **protocols = NULL;
1531 
1532 		handle = buffer[i];
1533 		lsefi_print_handle_info(handle);
1534 		if (pager_output("\n"))
1535 			break;
1536 		/* device path */
1537 
1538 		status = BS->ProtocolsPerHandle(handle, &protocols, &nproto);
1539 		if (EFI_ERROR(status)) {
1540 			snprintf(command_errbuf, sizeof (command_errbuf),
1541 			    "ProtocolsPerHandle() error: %lld",
1542 			    (long long)status);
1543 			continue;
1544 		}
1545 
1546 		for (j = 0; j < nproto; j++) {
1547 			if (efi_guid_to_name(protocols[j], &name) == true) {
1548 				printf("  %s", name);
1549 				free(name);
1550 			} else {
1551 				printf("Error while translating UUID to name");
1552 			}
1553 			if ((ret = pager_output("\n")) != 0)
1554 				break;
1555 		}
1556 		BS->FreePool(protocols);
1557 		if (ret != 0)
1558 			break;
1559 	}
1560 	pager_close();
1561 	free(buffer);
1562 	return (CMD_OK);
1563 }
1564 
1565 #ifdef LOADER_FDT_SUPPORT
1566 extern int command_fdt_internal(int argc, char *argv[]);
1567 
1568 /*
1569  * Since proper fdt command handling function is defined in fdt_loader_cmd.c,
1570  * and declaring it as extern is in contradiction with COMMAND_SET() macro
1571  * (which uses static pointer), we're defining wrapper function, which
1572  * calls the proper fdt handling routine.
1573  */
1574 static int
1575 command_fdt(int argc, char *argv[])
1576 {
1577 
1578 	return (command_fdt_internal(argc, argv));
1579 }
1580 
1581 COMMAND_SET(fdt, "fdt", "flattened device tree handling", command_fdt);
1582 #endif
1583 
1584 /*
1585  * Chain load another efi loader.
1586  */
1587 static int
1588 command_chain(int argc, char *argv[])
1589 {
1590 	EFI_GUID LoadedImageGUID = LOADED_IMAGE_PROTOCOL;
1591 	EFI_HANDLE loaderhandle;
1592 	EFI_LOADED_IMAGE *loaded_image;
1593 	EFI_STATUS status;
1594 	struct stat st;
1595 	struct devdesc *dev;
1596 	char *name, *path;
1597 	void *buf;
1598 	int fd;
1599 
1600 	if (argc < 2) {
1601 		command_errmsg = "wrong number of arguments";
1602 		return (CMD_ERROR);
1603 	}
1604 
1605 	name = argv[1];
1606 
1607 	if ((fd = open(name, O_RDONLY)) < 0) {
1608 		command_errmsg = "no such file";
1609 		return (CMD_ERROR);
1610 	}
1611 
1612 #ifdef LOADER_VERIEXEC
1613 	if (verify_file(fd, name, 0, VE_MUST, __func__) < 0) {
1614 		sprintf(command_errbuf, "can't verify: %s", name);
1615 		close(fd);
1616 		return (CMD_ERROR);
1617 	}
1618 #endif
1619 
1620 	if (fstat(fd, &st) < -1) {
1621 		command_errmsg = "stat failed";
1622 		close(fd);
1623 		return (CMD_ERROR);
1624 	}
1625 
1626 	status = BS->AllocatePool(EfiLoaderCode, (UINTN)st.st_size, &buf);
1627 	if (status != EFI_SUCCESS) {
1628 		command_errmsg = "failed to allocate buffer";
1629 		close(fd);
1630 		return (CMD_ERROR);
1631 	}
1632 	if (read(fd, buf, st.st_size) != st.st_size) {
1633 		command_errmsg = "error while reading the file";
1634 		(void)BS->FreePool(buf);
1635 		close(fd);
1636 		return (CMD_ERROR);
1637 	}
1638 	close(fd);
1639 	status = BS->LoadImage(FALSE, IH, NULL, buf, st.st_size, &loaderhandle);
1640 	(void)BS->FreePool(buf);
1641 	if (status != EFI_SUCCESS) {
1642 		command_errmsg = "LoadImage failed";
1643 		return (CMD_ERROR);
1644 	}
1645 	status = OpenProtocolByHandle(loaderhandle, &LoadedImageGUID,
1646 	    (void **)&loaded_image);
1647 
1648 	if (argc > 2) {
1649 		int i, len = 0;
1650 		CHAR16 *argp;
1651 
1652 		for (i = 2; i < argc; i++)
1653 			len += strlen(argv[i]) + 1;
1654 
1655 		len *= sizeof (*argp);
1656 		loaded_image->LoadOptions = argp = malloc (len);
1657 		loaded_image->LoadOptionsSize = len;
1658 		for (i = 2; i < argc; i++) {
1659 			char *ptr = argv[i];
1660 			while (*ptr)
1661 				*(argp++) = *(ptr++);
1662 			*(argp++) = ' ';
1663 		}
1664 		*(--argv) = 0;
1665 	}
1666 
1667 	if (efi_getdev((void **)&dev, name, (const char **)&path) == 0) {
1668 #ifdef EFI_ZFS_BOOT
1669 		struct zfs_devdesc *z_dev;
1670 #endif
1671 		struct disk_devdesc *d_dev;
1672 		pdinfo_t *hd, *pd;
1673 
1674 		switch (dev->d_dev->dv_type) {
1675 #ifdef EFI_ZFS_BOOT
1676 		case DEVT_ZFS:
1677 			z_dev = (struct zfs_devdesc *)dev;
1678 			loaded_image->DeviceHandle =
1679 			    efizfs_get_handle_by_guid(z_dev->pool_guid);
1680 			break;
1681 #endif
1682 		case DEVT_NET:
1683 			loaded_image->DeviceHandle =
1684 			    efi_find_handle(dev->d_dev, dev->d_unit);
1685 			break;
1686 		default:
1687 			hd = efiblk_get_pdinfo(dev);
1688 			if (STAILQ_EMPTY(&hd->pd_part)) {
1689 				loaded_image->DeviceHandle = hd->pd_handle;
1690 				break;
1691 			}
1692 			d_dev = (struct disk_devdesc *)dev;
1693 			STAILQ_FOREACH(pd, &hd->pd_part, pd_link) {
1694 				/*
1695 				 * d_partition should be 255
1696 				 */
1697 				if (pd->pd_unit == (uint32_t)d_dev->d_slice) {
1698 					loaded_image->DeviceHandle =
1699 					    pd->pd_handle;
1700 					break;
1701 				}
1702 			}
1703 			break;
1704 		}
1705 	}
1706 
1707 	dev_cleanup();
1708 	status = BS->StartImage(loaderhandle, NULL, NULL);
1709 	if (status != EFI_SUCCESS) {
1710 		command_errmsg = "StartImage failed";
1711 		free(loaded_image->LoadOptions);
1712 		loaded_image->LoadOptions = NULL;
1713 		status = BS->UnloadImage(loaded_image);
1714 		return (CMD_ERROR);
1715 	}
1716 
1717 	return (CMD_ERROR);	/* not reached */
1718 }
1719 
1720 COMMAND_SET(chain, "chain", "chain load file", command_chain);
1721 
1722 extern struct in_addr servip;
1723 static int
1724 command_netserver(int argc, char *argv[])
1725 {
1726 	char *proto;
1727 	n_long rootaddr;
1728 
1729 	if (argc > 2) {
1730 		command_errmsg = "wrong number of arguments";
1731 		return (CMD_ERROR);
1732 	}
1733 	if (argc < 2) {
1734 		proto = netproto == NET_TFTP ? "tftp://" : "nfs://";
1735 		printf("Netserver URI: %s%s%s\n", proto, intoa(rootip.s_addr),
1736 		    rootpath);
1737 		return (CMD_OK);
1738 	}
1739 	if (argc == 2) {
1740 		strncpy(rootpath, argv[1], sizeof(rootpath));
1741 		rootpath[sizeof(rootpath) -1] = '\0';
1742 		if ((rootaddr = net_parse_rootpath()) != INADDR_NONE)
1743 			servip.s_addr = rootip.s_addr = rootaddr;
1744 		return (CMD_OK);
1745 	}
1746 	return (CMD_ERROR);	/* not reached */
1747 
1748 }
1749 
1750 COMMAND_SET(netserver, "netserver", "change or display netserver URI",
1751     command_netserver);
1752