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