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