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