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