xref: /freebsd/stand/efi/loader/main.c (revision d904ce8a52e2f73bdcb1b8fba8016eff12128317)
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 
316 	/*
317 	 * FreeBSD encodes it's boot loading path into the boot loader
318 	 * BootXXXX variable. We look for the last one in the path
319 	 * and use that to load the kernel. However, if we only fine
320 	 * one DEVICE_PATH, then there's nothing specific and we should
321 	 * fall back.
322 	 *
323 	 * In an ideal world, we'd look at the image handle we were
324 	 * passed, match up with the loader we are and then return the
325 	 * next one in the path. This would be most flexible and cover
326 	 * many chain booting scenarios where you need to use this
327 	 * boot loader to get to the next boot loader. However, that
328 	 * doesn't work. We rarely have the path to the image booted
329 	 * (just the device) so we can't count on that. So, we do the
330 	 * enxt best thing, we look through the device path(s) passed
331 	 * in the BootXXXX varaible. If there's only one, we return
332 	 * NOT_SPECIFIC. Otherwise, we look at the last one and try to
333 	 * load that. If we can, we return BOOT_INFO_OK. Otherwise we
334 	 * return BAD_CHOICE for the caller to sort out.
335 	 */
336 	if (bisz < sizeof(attr) + sizeof(fplen) + sizeof(CHAR16))
337 		return NOT_SPECIFIC;
338 	walker = boot_info;
339 	ep = walker + bisz;
340 	memcpy(&attr, walker, sizeof(attr));
341 	walker += sizeof(attr);
342 	memcpy(&fplen, walker, sizeof(fplen));
343 	walker += sizeof(fplen);
344 	descr = (CHAR16 *)(intptr_t)walker;
345 	len = ucs2len(descr);
346 	walker += (len + 1) * sizeof(CHAR16);
347 	last_dp = first_dp = dp = (EFI_DEVICE_PATH *)walker;
348 	edp = (EFI_DEVICE_PATH *)(walker + fplen);
349 	if ((char *)edp > ep)
350 		return NOT_SPECIFIC;
351 	while (dp < edp) {
352 		last_dp = dp;
353 		dp = (EFI_DEVICE_PATH *)((char *)dp + efi_devpath_length(dp));
354 	}
355 
356 	/*
357 	 * If there's only one item in the list, then nothing was
358 	 * specified.
359 	 */
360 	if (last_dp == first_dp)
361 		return NOT_SPECIFIC;
362 
363 	/*
364 	 * OK. At this point we either have a good path or a bad one.
365 	 * Let's check.
366 	 */
367 	pp = efiblk_get_pdinfo_by_device_path(last_dp);
368 	if (pp == NULL)
369 		return BAD_CHOICE;
370 	set_currdev_pdinfo(pp);
371 	if (!sanity_check_currdev())
372 		return BAD_CHOICE;
373 
374 	/*
375 	 * OK. We've found a device that matches, next we need to check the last
376 	 * component of the path. If it's a file, then we set the default kernel
377 	 * to that. Otherwise, just use this as the default root.
378 	 *
379 	 * Reminder: we're running very early, before we've parsed the defaults
380 	 * file, so we may need to have a hack override.
381 	 */
382 	dp = efi_devpath_last_node(last_dp);
383 	if (DevicePathType(dp) !=  MEDIA_DEVICE_PATH ||
384 	    DevicePathSubType(dp) != MEDIA_FILEPATH_DP)
385 		return (BOOT_INFO_OK);		/* use currdir, default kernel */
386 	fp = (FILEPATH_DEVICE_PATH *)dp;
387 	ucs2_to_utf8(fp->PathName, &kernel);
388 	if (kernel == NULL)
389 		return (BAD_CHOICE);
390 	if (*kernel == '\\' || isupper(*kernel))
391 		fix_dosisms(kernel);
392 	if (stat(kernel, &st) != 0) {
393 		free(kernel);
394 		return (BAD_CHOICE);
395 	}
396 	setenv("kernel", kernel, 1);
397 	free(kernel);
398 
399 	return (BOOT_INFO_OK);
400 }
401 
402 /*
403  * Look at the passed-in boot_info, if any. If we find it then we need
404  * to see if we can find ourselves in the boot chain. If we can, and
405  * there's another specified thing to boot next, assume that the file
406  * is loaded from / and use that for the root filesystem. If can't
407  * find the specified thing, we must fail the boot. If we're last on
408  * the list, then we fallback to looking for the first available /
409  * candidate (ZFS, if there's a bootable zpool, otherwise a UFS
410  * partition that has either /boot/defaults/loader.conf on it or
411  * /boot/kernel/kernel (the default kernel) that we can use.
412  *
413  * We always fail if we can't find the right thing. However, as
414  * a concession to buggy UEFI implementations, like u-boot, if
415  * we have determined that the host is violating the UEFI boot
416  * manager protocol, we'll signal the rest of the program that
417  * a drop to the OK boot loader prompt is possible.
418  */
419 static int
420 find_currdev(EFI_LOADED_IMAGE *img, bool do_bootmgr, bool is_last,
421     char *boot_info, size_t boot_info_sz)
422 {
423 	pdinfo_t *dp, *pp;
424 	EFI_DEVICE_PATH *devpath, *copy;
425 	EFI_HANDLE h;
426 	CHAR16 *text;
427 	struct devsw *dev;
428 	int unit;
429 	uint64_t extra;
430 	int rv;
431 	char *rootdev;
432 
433 	/*
434 	 * First choice: if rootdev is already set, use that, even if
435 	 * it's wrong.
436 	 */
437 	rootdev = getenv("rootdev");
438 	if (rootdev != NULL) {
439 		printf("Setting currdev to configured rootdev %s\n", rootdev);
440 		set_currdev(rootdev);
441 		return (0);
442 	}
443 
444 	/*
445 	 * Second choice: If we can find out image boot_info, and there's
446 	 * a follow-on boot image in that boot_info, use that. In this
447 	 * case root will be the partition specified in that image and
448 	 * we'll load the kernel specified by the file path. Should there
449 	 * not be a filepath, we use the default. This filepath overrides
450 	 * loader.conf.
451 	 */
452 	if (do_bootmgr) {
453 		rv = match_boot_info(img, boot_info, boot_info_sz);
454 		switch (rv) {
455 		case BOOT_INFO_OK:	/* We found it */
456 			return (0);
457 		case BAD_CHOICE:	/* specified file not found -> error */
458 			/* XXX do we want to have an escape hatch for last in boot order? */
459 			return (ENOENT);
460 		} /* Nothing specified, try normal match */
461 	}
462 
463 #ifdef EFI_ZFS_BOOT
464 	/*
465 	 * Did efi_zfs_probe() detect the boot pool? If so, use the zpool
466 	 * it found, if it's sane. ZFS is the only thing that looks for
467 	 * disks and pools to boot. This may change in the future, however,
468 	 * if we allow specifying which pool to boot from via UEFI variables
469 	 * rather than the bootenv stuff that FreeBSD uses today.
470 	 */
471 	if (pool_guid != 0) {
472 		printf("Trying ZFS pool\n");
473 		if (probe_zfs_currdev(pool_guid))
474 			return (0);
475 	}
476 #endif /* EFI_ZFS_BOOT */
477 
478 	/*
479 	 * Try to find the block device by its handle based on the
480 	 * image we're booting. If we can't find a sane partition,
481 	 * search all the other partitions of the disk. We do not
482 	 * search other disks because it's a violation of the UEFI
483 	 * boot protocol to do so. We fail and let UEFI go on to
484 	 * the next candidate.
485 	 */
486 	dp = efiblk_get_pdinfo_by_handle(img->DeviceHandle);
487 	if (dp != NULL) {
488 		text = efi_devpath_name(dp->pd_devpath);
489 		if (text != NULL) {
490 			printf("Trying ESP: %S\n", text);
491 			efi_free_devpath_name(text);
492 		}
493 		set_currdev_pdinfo(dp);
494 		if (sanity_check_currdev())
495 			return (0);
496 		if (dp->pd_parent != NULL) {
497 			dp = dp->pd_parent;
498 			STAILQ_FOREACH(pp, &dp->pd_part, pd_link) {
499 				/*
500 				 * Roll up the ZFS special case
501 				 * for those partitions that have
502 				 * zpools on them.
503 				 */
504 				if (try_as_currdev(dp, pp))
505 					return (0);
506 			}
507 		}
508 	} else {
509 		printf("Can't find device by handle\n");
510 	}
511 
512 	/*
513 	 * Try the device handle from our loaded image first.  If that
514 	 * fails, use the device path from the loaded image and see if
515 	 * any of the nodes in that path match one of the enumerated
516 	 * handles. Currently, this handle list is only for netboot.
517 	 */
518 	if (efi_handle_lookup(img->DeviceHandle, &dev, &unit, &extra) == 0) {
519 		set_currdev_devsw(dev, unit);
520 		if (sanity_check_currdev())
521 			return (0);
522 	}
523 
524 	copy = NULL;
525 	devpath = efi_lookup_image_devpath(IH);
526 	while (devpath != NULL) {
527 		h = efi_devpath_handle(devpath);
528 		if (h == NULL)
529 			break;
530 
531 		free(copy);
532 		copy = NULL;
533 
534 		if (efi_handle_lookup(h, &dev, &unit, &extra) == 0) {
535 			set_currdev_devsw(dev, unit);
536 			if (sanity_check_currdev())
537 				return (0);
538 		}
539 
540 		devpath = efi_lookup_devpath(h);
541 		if (devpath != NULL) {
542 			copy = efi_devpath_trim(devpath);
543 			devpath = copy;
544 		}
545 	}
546 	free(copy);
547 
548 	return (ENOENT);
549 }
550 
551 static bool
552 interactive_interrupt(const char *msg)
553 {
554 	time_t now, then, last;
555 
556 	last = 0;
557 	now = then = getsecs();
558 	printf("%s\n", msg);
559 	if (fail_timeout == -2)		/* Always break to OK */
560 		return (true);
561 	if (fail_timeout == -1)		/* Never break to OK */
562 		return (false);
563 	do {
564 		if (last != now) {
565 			printf("press any key to interrupt reboot in %d seconds\r",
566 			    fail_timeout - (int)(now - then));
567 			last = now;
568 		}
569 
570 		/* XXX no pause or timeout wait for char */
571 		if (ischar())
572 			return (true);
573 		now = getsecs();
574 	} while (now - then < fail_timeout);
575 	return (false);
576 }
577 
578 static int
579 parse_args(int argc, CHAR16 *argv[])
580 {
581 	int i, j, howto;
582 	bool vargood;
583 	char var[128];
584 
585 	/*
586 	 * Parse the args to set the console settings, etc
587 	 * boot1.efi passes these in, if it can read /boot.config or /boot/config
588 	 * or iPXE may be setup to pass these in. Or the optional argument in the
589 	 * boot environment was used to pass these arguments in (in which case
590 	 * neither /boot.config nor /boot/config are consulted).
591 	 *
592 	 * Loop through the args, and for each one that contains an '=' that is
593 	 * not the first character, add it to the environment.  This allows
594 	 * loader and kernel env vars to be passed on the command line.  Convert
595 	 * args from UCS-2 to ASCII (16 to 8 bit) as they are copied (though this
596 	 * method is flawed for non-ASCII characters).
597 	 */
598 	howto = 0;
599 	for (i = 1; i < argc; i++) {
600 		cpy16to8(argv[i], var, sizeof(var));
601 		howto |= boot_parse_arg(var);
602 	}
603 
604 	return (howto);
605 }
606 
607 /*
608  * Parse ConOut (the list of consoles active) and see if we can find a
609  * serial port and/or a video port. It would be nice to also walk the
610  * ACPI name space to map the UID for the serial port to a port. The
611  * latter is especially hard.
612  */
613 static int
614 parse_uefi_con_out(void)
615 {
616 	int how, rv;
617 	int vid_seen = 0, com_seen = 0, seen = 0;
618 	size_t sz;
619 	char buf[4096], *ep;
620 	EFI_DEVICE_PATH *node;
621 	ACPI_HID_DEVICE_PATH  *acpi;
622 	UART_DEVICE_PATH  *uart;
623 	bool pci_pending;
624 
625 	how = 0;
626 	sz = sizeof(buf);
627 	rv = efi_global_getenv("ConOut", buf, &sz);
628 	if (rv != EFI_SUCCESS)
629 		goto out;
630 	ep = buf + sz;
631 	node = (EFI_DEVICE_PATH *)buf;
632 	while ((char *)node < ep) {
633 		pci_pending = false;
634 		if (DevicePathType(node) == ACPI_DEVICE_PATH &&
635 		    DevicePathSubType(node) == ACPI_DP) {
636 			/* Check for Serial node */
637 			acpi = (void *)node;
638 			if (EISA_ID_TO_NUM(acpi->HID) == 0x501)
639 				com_seen = ++seen;
640 		} else if (DevicePathType(node) == MESSAGING_DEVICE_PATH &&
641 		    DevicePathSubType(node) == MSG_UART_DP) {
642 			char bd[16];
643 
644 			uart = (void *)node;
645 			snprintf(bd, sizeof(bd), "%d", uart->BaudRate);
646 			setenv("efi_com_speed", bd, 1);
647 		} else if (DevicePathType(node) == ACPI_DEVICE_PATH &&
648 		    DevicePathSubType(node) == ACPI_ADR_DP) {
649 			/* Check for AcpiAdr() Node for video */
650 			vid_seen = ++seen;
651 		} else if (DevicePathType(node) == HARDWARE_DEVICE_PATH &&
652 		    DevicePathSubType(node) == HW_PCI_DP) {
653 			/*
654 			 * Note, vmware fusion has a funky console device
655 			 *	PciRoot(0x0)/Pci(0xf,0x0)
656 			 * which we can only detect at the end since we also
657 			 * have to cope with:
658 			 *	PciRoot(0x0)/Pci(0x1f,0x0)/Serial(0x1)
659 			 * so only match it if it's last.
660 			 */
661 			pci_pending = true;
662 		}
663 		node = NextDevicePathNode(node); /* Skip the end node */
664 	}
665 	if (pci_pending && vid_seen == 0)
666 		vid_seen = ++seen;
667 
668 	/*
669 	 * Truth table for RB_MULTIPLE | RB_SERIAL
670 	 * Value		Result
671 	 * 0			Use only video console
672 	 * RB_SERIAL		Use only serial console
673 	 * RB_MULTIPLE		Use both video and serial console
674 	 *			(but video is primary so gets rc messages)
675 	 * both			Use both video and serial console
676 	 *			(but serial is primary so gets rc messages)
677 	 *
678 	 * Try to honor this as best we can. If only one of serial / video
679 	 * found, then use that. Otherwise, use the first one we found.
680 	 * This also implies if we found nothing, default to video.
681 	 */
682 	how = 0;
683 	if (vid_seen && com_seen) {
684 		how |= RB_MULTIPLE;
685 		if (com_seen < vid_seen)
686 			how |= RB_SERIAL;
687 	} else if (com_seen)
688 		how |= RB_SERIAL;
689 out:
690 	return (how);
691 }
692 
693 EFI_STATUS
694 main(int argc, CHAR16 *argv[])
695 {
696 	EFI_GUID *guid;
697 	int howto, i, uhowto;
698 	UINTN k;
699 	bool has_kbd, is_last;
700 	char *s;
701 	EFI_DEVICE_PATH *imgpath;
702 	CHAR16 *text;
703 	EFI_STATUS rv;
704 	size_t sz, bosz = 0, bisz = 0;
705 	UINT16 boot_order[100];
706 	char boot_info[4096];
707 	EFI_LOADED_IMAGE *img;
708 	char buf[32];
709 	bool uefi_boot_mgr;
710 
711 	archsw.arch_autoload = efi_autoload;
712 	archsw.arch_getdev = efi_getdev;
713 	archsw.arch_copyin = efi_copyin;
714 	archsw.arch_copyout = efi_copyout;
715 	archsw.arch_readin = efi_readin;
716 #ifdef EFI_ZFS_BOOT
717 	/* Note this needs to be set before ZFS init. */
718 	archsw.arch_zfs_probe = efi_zfs_probe;
719 #endif
720 
721         /* Get our loaded image protocol interface structure. */
722 	BS->HandleProtocol(IH, &imgid, (VOID**)&img);
723 
724 #ifdef EFI_ZFS_BOOT
725 	/* Tell ZFS probe code where we booted from */
726 	efizfs_set_preferred(img->DeviceHandle);
727 #endif
728 	/* Init the time source */
729 	efi_time_init();
730 
731 	has_kbd = has_keyboard();
732 
733 	/*
734 	 * XXX Chicken-and-egg problem; we want to have console output
735 	 * early, but some console attributes may depend on reading from
736 	 * eg. the boot device, which we can't do yet.  We can use
737 	 * printf() etc. once this is done.
738 	 */
739 	setenv("console", "efi", 1);
740 	cons_probe();
741 
742 	/*
743 	 * Initialise the block cache. Set the upper limit.
744 	 */
745 	bcache_init(32768, 512);
746 
747 	howto = parse_args(argc, argv);
748 	if (!has_kbd && (howto & RB_PROBE))
749 		howto |= RB_SERIAL | RB_MULTIPLE;
750 	howto &= ~RB_PROBE;
751 	uhowto = parse_uefi_con_out();
752 
753 	/*
754 	 * We now have two notions of console. howto should be viewed as
755 	 * overrides. If console is already set, don't set it again.
756 	 */
757 #define	VIDEO_ONLY	0
758 #define	SERIAL_ONLY	RB_SERIAL
759 #define	VID_SER_BOTH	RB_MULTIPLE
760 #define	SER_VID_BOTH	(RB_SERIAL | RB_MULTIPLE)
761 #define	CON_MASK	(RB_SERIAL | RB_MULTIPLE)
762 	if (strcmp(getenv("console"), "efi") == 0) {
763 		if ((howto & CON_MASK) == 0) {
764 			/* No override, uhowto is controlling and efi cons is perfect */
765 			howto = howto | (uhowto & CON_MASK);
766 			setenv("console", "efi", 1);
767 		} else if ((howto & CON_MASK) == (uhowto & CON_MASK)) {
768 			/* override matches what UEFI told us, efi console is perfect */
769 			setenv("console", "efi", 1);
770 		} else if ((uhowto & (CON_MASK)) != 0) {
771 			/*
772 			 * We detected a serial console on ConOut. All possible
773 			 * overrides include serial. We can't really override what efi
774 			 * gives us, so we use it knowing it's the best choice.
775 			 */
776 			setenv("console", "efi", 1);
777 		} else {
778 			/*
779 			 * We detected some kind of serial in the override, but ConOut
780 			 * has no serial, so we have to sort out which case it really is.
781 			 */
782 			switch (howto & CON_MASK) {
783 			case SERIAL_ONLY:
784 				setenv("console", "comconsole", 1);
785 				break;
786 			case VID_SER_BOTH:
787 				setenv("console", "efi comconsole", 1);
788 				break;
789 			case SER_VID_BOTH:
790 				setenv("console", "comconsole efi", 1);
791 				break;
792 				/* case VIDEO_ONLY can't happen -- it's the first if above */
793 			}
794 		}
795 	}
796 	/*
797 	 * howto is set now how we want to export the flags to the kernel, so
798 	 * set the env based on it.
799 	 */
800 	boot_howto_to_env(howto);
801 
802 	if (efi_copy_init()) {
803 		printf("failed to allocate staging area\n");
804 		return (EFI_BUFFER_TOO_SMALL);
805 	}
806 
807 	if ((s = getenv("fail_timeout")) != NULL)
808 		fail_timeout = strtol(s, NULL, 10);
809 
810 	/*
811 	 * Scan the BLOCK IO MEDIA handles then
812 	 * march through the device switch probing for things.
813 	 */
814 	if ((i = efipart_inithandles()) == 0) {
815 		for (i = 0; devsw[i] != NULL; i++)
816 			if (devsw[i]->dv_init != NULL)
817 				(devsw[i]->dv_init)();
818 	} else
819 		printf("efipart_inithandles failed %d, expect failures", i);
820 
821 	printf("%s\n", bootprog_info);
822 	printf("   Command line arguments:");
823 	for (i = 0; i < argc; i++)
824 		printf(" %S", argv[i]);
825 	printf("\n");
826 
827 	printf("   EFI version: %d.%02d\n", ST->Hdr.Revision >> 16,
828 	    ST->Hdr.Revision & 0xffff);
829 	printf("   EFI Firmware: %S (rev %d.%02d)\n", ST->FirmwareVendor,
830 	    ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
831 
832 
833 	/* Determine the devpath of our image so we can prefer it. */
834 	text = efi_devpath_name(img->FilePath);
835 	if (text != NULL) {
836 		printf("   Load Path: %S\n", text);
837 		efi_setenv_freebsd_wcs("LoaderPath", text);
838 		efi_free_devpath_name(text);
839 	}
840 
841 	rv = BS->HandleProtocol(img->DeviceHandle, &devid, (void **)&imgpath);
842 	if (rv == EFI_SUCCESS) {
843 		text = efi_devpath_name(imgpath);
844 		if (text != NULL) {
845 			printf("   Load Device: %S\n", text);
846 			efi_setenv_freebsd_wcs("LoaderDev", text);
847 			efi_free_devpath_name(text);
848 		}
849 	}
850 
851 	uefi_boot_mgr = true;
852 	boot_current = 0;
853 	sz = sizeof(boot_current);
854 	rv = efi_global_getenv("BootCurrent", &boot_current, &sz);
855 	if (rv == EFI_SUCCESS)
856 		printf("   BootCurrent: %04x\n", boot_current);
857 	else {
858 		boot_current = 0xffff;
859 		uefi_boot_mgr = false;
860 	}
861 
862 	sz = sizeof(boot_order);
863 	rv = efi_global_getenv("BootOrder", &boot_order, &sz);
864 	if (rv == EFI_SUCCESS) {
865 		printf("   BootOrder:");
866 		for (i = 0; i < sz / sizeof(boot_order[0]); i++)
867 			printf(" %04x%s", boot_order[i],
868 			    boot_order[i] == boot_current ? "[*]" : "");
869 		printf("\n");
870 		is_last = boot_order[(sz / sizeof(boot_order[0])) - 1] == boot_current;
871 		bosz = sz;
872 	} else if (uefi_boot_mgr) {
873 		/*
874 		 * u-boot doesn't set BootOrder, but otherwise participates in the
875 		 * boot manager protocol. So we fake it here and don't consider it
876 		 * a failure.
877 		 */
878 		bosz = sizeof(boot_order[0]);
879 		boot_order[0] = boot_current;
880 		is_last = true;
881 	}
882 
883 	/*
884 	 * Next, find the boot info structure the UEFI boot manager is
885 	 * supposed to setup. We need this so we can walk through it to
886 	 * find where we are in the booting process and what to try to
887 	 * boot next.
888 	 */
889 	if (uefi_boot_mgr) {
890 		snprintf(buf, sizeof(buf), "Boot%04X", boot_current);
891 		sz = sizeof(boot_info);
892 		rv = efi_global_getenv(buf, &boot_info, &sz);
893 		if (rv == EFI_SUCCESS)
894 			bisz = sz;
895 		else
896 			uefi_boot_mgr = false;
897 	}
898 
899 	/*
900 	 * Disable the watchdog timer. By default the boot manager sets
901 	 * the timer to 5 minutes before invoking a boot option. If we
902 	 * want to return to the boot manager, we have to disable the
903 	 * watchdog timer and since we're an interactive program, we don't
904 	 * want to wait until the user types "quit". The timer may have
905 	 * fired by then. We don't care if this fails. It does not prevent
906 	 * normal functioning in any way...
907 	 */
908 	BS->SetWatchdogTimer(0, 0, 0, NULL);
909 
910 	/*
911 	 * Try and find a good currdev based on the image that was booted.
912 	 * It might be desirable here to have a short pause to allow falling
913 	 * through to the boot loader instead of returning instantly to follow
914 	 * the boot protocol and also allow an escape hatch for users wishing
915 	 * to try something different.
916 	 */
917 	if (find_currdev(img, uefi_boot_mgr, is_last, boot_info, bisz) != 0)
918 		if (!interactive_interrupt("Failed to find bootable partition"))
919 			return (EFI_NOT_FOUND);
920 
921 	efi_init_environment();
922 
923 #if !defined(__arm__)
924 	for (k = 0; k < ST->NumberOfTableEntries; k++) {
925 		guid = &ST->ConfigurationTable[k].VendorGuid;
926 		if (!memcmp(guid, &smbios, sizeof(EFI_GUID))) {
927 			char buf[40];
928 
929 			snprintf(buf, sizeof(buf), "%p",
930 			    ST->ConfigurationTable[k].VendorTable);
931 			setenv("hint.smbios.0.mem", buf, 1);
932 			smbios_detect(ST->ConfigurationTable[k].VendorTable);
933 			break;
934 		}
935 	}
936 #endif
937 
938 	interact();			/* doesn't return */
939 
940 	return (EFI_SUCCESS);		/* keep compiler happy */
941 }
942 
943 COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot);
944 
945 static int
946 command_reboot(int argc, char *argv[])
947 {
948 	int i;
949 
950 	for (i = 0; devsw[i] != NULL; ++i)
951 		if (devsw[i]->dv_cleanup != NULL)
952 			(devsw[i]->dv_cleanup)();
953 
954 	RS->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL);
955 
956 	/* NOTREACHED */
957 	return (CMD_ERROR);
958 }
959 
960 COMMAND_SET(quit, "quit", "exit the loader", command_quit);
961 
962 static int
963 command_quit(int argc, char *argv[])
964 {
965 	exit(0);
966 	return (CMD_OK);
967 }
968 
969 COMMAND_SET(memmap, "memmap", "print memory map", command_memmap);
970 
971 static int
972 command_memmap(int argc, char *argv[])
973 {
974 	UINTN sz;
975 	EFI_MEMORY_DESCRIPTOR *map, *p;
976 	UINTN key, dsz;
977 	UINT32 dver;
978 	EFI_STATUS status;
979 	int i, ndesc;
980 	char line[80];
981 	static char *types[] = {
982 	    "Reserved",
983 	    "LoaderCode",
984 	    "LoaderData",
985 	    "BootServicesCode",
986 	    "BootServicesData",
987 	    "RuntimeServicesCode",
988 	    "RuntimeServicesData",
989 	    "ConventionalMemory",
990 	    "UnusableMemory",
991 	    "ACPIReclaimMemory",
992 	    "ACPIMemoryNVS",
993 	    "MemoryMappedIO",
994 	    "MemoryMappedIOPortSpace",
995 	    "PalCode"
996 	};
997 
998 	sz = 0;
999 	status = BS->GetMemoryMap(&sz, 0, &key, &dsz, &dver);
1000 	if (status != EFI_BUFFER_TOO_SMALL) {
1001 		printf("Can't determine memory map size\n");
1002 		return (CMD_ERROR);
1003 	}
1004 	map = malloc(sz);
1005 	status = BS->GetMemoryMap(&sz, map, &key, &dsz, &dver);
1006 	if (EFI_ERROR(status)) {
1007 		printf("Can't read memory map\n");
1008 		return (CMD_ERROR);
1009 	}
1010 
1011 	ndesc = sz / dsz;
1012 	snprintf(line, sizeof(line), "%23s %12s %12s %8s %4s\n",
1013 	    "Type", "Physical", "Virtual", "#Pages", "Attr");
1014 	pager_open();
1015 	if (pager_output(line)) {
1016 		pager_close();
1017 		return (CMD_OK);
1018 	}
1019 
1020 	for (i = 0, p = map; i < ndesc;
1021 	     i++, p = NextMemoryDescriptor(p, dsz)) {
1022 		printf("%23s %012jx %012jx %08jx ", types[p->Type],
1023 		    (uintmax_t)p->PhysicalStart, (uintmax_t)p->VirtualStart,
1024 		    (uintmax_t)p->NumberOfPages);
1025 		if (p->Attribute & EFI_MEMORY_UC)
1026 			printf("UC ");
1027 		if (p->Attribute & EFI_MEMORY_WC)
1028 			printf("WC ");
1029 		if (p->Attribute & EFI_MEMORY_WT)
1030 			printf("WT ");
1031 		if (p->Attribute & EFI_MEMORY_WB)
1032 			printf("WB ");
1033 		if (p->Attribute & EFI_MEMORY_UCE)
1034 			printf("UCE ");
1035 		if (p->Attribute & EFI_MEMORY_WP)
1036 			printf("WP ");
1037 		if (p->Attribute & EFI_MEMORY_RP)
1038 			printf("RP ");
1039 		if (p->Attribute & EFI_MEMORY_XP)
1040 			printf("XP ");
1041 		if (pager_output("\n"))
1042 			break;
1043 	}
1044 
1045 	pager_close();
1046 	return (CMD_OK);
1047 }
1048 
1049 COMMAND_SET(configuration, "configuration", "print configuration tables",
1050     command_configuration);
1051 
1052 static const char *
1053 guid_to_string(EFI_GUID *guid)
1054 {
1055 	static char buf[40];
1056 
1057 	sprintf(buf, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
1058 	    guid->Data1, guid->Data2, guid->Data3, guid->Data4[0],
1059 	    guid->Data4[1], guid->Data4[2], guid->Data4[3], guid->Data4[4],
1060 	    guid->Data4[5], guid->Data4[6], guid->Data4[7]);
1061 	return (buf);
1062 }
1063 
1064 static int
1065 command_configuration(int argc, char *argv[])
1066 {
1067 	char line[80];
1068 	UINTN i;
1069 
1070 	snprintf(line, sizeof(line), "NumberOfTableEntries=%lu\n",
1071 		(unsigned long)ST->NumberOfTableEntries);
1072 	pager_open();
1073 	if (pager_output(line)) {
1074 		pager_close();
1075 		return (CMD_OK);
1076 	}
1077 
1078 	for (i = 0; i < ST->NumberOfTableEntries; i++) {
1079 		EFI_GUID *guid;
1080 
1081 		printf("  ");
1082 		guid = &ST->ConfigurationTable[i].VendorGuid;
1083 		if (!memcmp(guid, &mps, sizeof(EFI_GUID)))
1084 			printf("MPS Table");
1085 		else if (!memcmp(guid, &acpi, sizeof(EFI_GUID)))
1086 			printf("ACPI Table");
1087 		else if (!memcmp(guid, &acpi20, sizeof(EFI_GUID)))
1088 			printf("ACPI 2.0 Table");
1089 		else if (!memcmp(guid, &smbios, sizeof(EFI_GUID)))
1090 			printf("SMBIOS Table %p",
1091 			    ST->ConfigurationTable[i].VendorTable);
1092 		else if (!memcmp(guid, &smbios3, sizeof(EFI_GUID)))
1093 			printf("SMBIOS3 Table");
1094 		else if (!memcmp(guid, &dxe, sizeof(EFI_GUID)))
1095 			printf("DXE Table");
1096 		else if (!memcmp(guid, &hoblist, sizeof(EFI_GUID)))
1097 			printf("HOB List Table");
1098 		else if (!memcmp(guid, &lzmadecomp, sizeof(EFI_GUID)))
1099 			printf("LZMA Compression");
1100 		else if (!memcmp(guid, &mpcore, sizeof(EFI_GUID)))
1101 			printf("ARM MpCore Information Table");
1102 		else if (!memcmp(guid, &esrt, sizeof(EFI_GUID)))
1103 			printf("ESRT Table");
1104 		else if (!memcmp(guid, &memtype, sizeof(EFI_GUID)))
1105 			printf("Memory Type Information Table");
1106 		else if (!memcmp(guid, &debugimg, sizeof(EFI_GUID)))
1107 			printf("Debug Image Info Table");
1108 		else if (!memcmp(guid, &fdtdtb, sizeof(EFI_GUID)))
1109 			printf("FDT Table");
1110 		else
1111 			printf("Unknown Table (%s)", guid_to_string(guid));
1112 		snprintf(line, sizeof(line), " at %p\n",
1113 		    ST->ConfigurationTable[i].VendorTable);
1114 		if (pager_output(line))
1115 			break;
1116 	}
1117 
1118 	pager_close();
1119 	return (CMD_OK);
1120 }
1121 
1122 
1123 COMMAND_SET(mode, "mode", "change or display EFI text modes", command_mode);
1124 
1125 static int
1126 command_mode(int argc, char *argv[])
1127 {
1128 	UINTN cols, rows;
1129 	unsigned int mode;
1130 	int i;
1131 	char *cp;
1132 	char rowenv[8];
1133 	EFI_STATUS status;
1134 	SIMPLE_TEXT_OUTPUT_INTERFACE *conout;
1135 	extern void HO(void);
1136 
1137 	conout = ST->ConOut;
1138 
1139 	if (argc > 1) {
1140 		mode = strtol(argv[1], &cp, 0);
1141 		if (cp[0] != '\0') {
1142 			printf("Invalid mode\n");
1143 			return (CMD_ERROR);
1144 		}
1145 		status = conout->QueryMode(conout, mode, &cols, &rows);
1146 		if (EFI_ERROR(status)) {
1147 			printf("invalid mode %d\n", mode);
1148 			return (CMD_ERROR);
1149 		}
1150 		status = conout->SetMode(conout, mode);
1151 		if (EFI_ERROR(status)) {
1152 			printf("couldn't set mode %d\n", mode);
1153 			return (CMD_ERROR);
1154 		}
1155 		sprintf(rowenv, "%u", (unsigned)rows);
1156 		setenv("LINES", rowenv, 1);
1157 		HO();		/* set cursor */
1158 		return (CMD_OK);
1159 	}
1160 
1161 	printf("Current mode: %d\n", conout->Mode->Mode);
1162 	for (i = 0; i <= conout->Mode->MaxMode; i++) {
1163 		status = conout->QueryMode(conout, i, &cols, &rows);
1164 		if (EFI_ERROR(status))
1165 			continue;
1166 		printf("Mode %d: %u columns, %u rows\n", i, (unsigned)cols,
1167 		    (unsigned)rows);
1168 	}
1169 
1170 	if (i != 0)
1171 		printf("Select a mode with the command \"mode <number>\"\n");
1172 
1173 	return (CMD_OK);
1174 }
1175 
1176 #ifdef LOADER_FDT_SUPPORT
1177 extern int command_fdt_internal(int argc, char *argv[]);
1178 
1179 /*
1180  * Since proper fdt command handling function is defined in fdt_loader_cmd.c,
1181  * and declaring it as extern is in contradiction with COMMAND_SET() macro
1182  * (which uses static pointer), we're defining wrapper function, which
1183  * calls the proper fdt handling routine.
1184  */
1185 static int
1186 command_fdt(int argc, char *argv[])
1187 {
1188 
1189 	return (command_fdt_internal(argc, argv));
1190 }
1191 
1192 COMMAND_SET(fdt, "fdt", "flattened device tree handling", command_fdt);
1193 #endif
1194 
1195 /*
1196  * Chain load another efi loader.
1197  */
1198 static int
1199 command_chain(int argc, char *argv[])
1200 {
1201 	EFI_GUID LoadedImageGUID = LOADED_IMAGE_PROTOCOL;
1202 	EFI_HANDLE loaderhandle;
1203 	EFI_LOADED_IMAGE *loaded_image;
1204 	EFI_STATUS status;
1205 	struct stat st;
1206 	struct devdesc *dev;
1207 	char *name, *path;
1208 	void *buf;
1209 	int fd;
1210 
1211 	if (argc < 2) {
1212 		command_errmsg = "wrong number of arguments";
1213 		return (CMD_ERROR);
1214 	}
1215 
1216 	name = argv[1];
1217 
1218 	if ((fd = open(name, O_RDONLY)) < 0) {
1219 		command_errmsg = "no such file";
1220 		return (CMD_ERROR);
1221 	}
1222 
1223 	if (fstat(fd, &st) < -1) {
1224 		command_errmsg = "stat failed";
1225 		close(fd);
1226 		return (CMD_ERROR);
1227 	}
1228 
1229 	status = BS->AllocatePool(EfiLoaderCode, (UINTN)st.st_size, &buf);
1230 	if (status != EFI_SUCCESS) {
1231 		command_errmsg = "failed to allocate buffer";
1232 		close(fd);
1233 		return (CMD_ERROR);
1234 	}
1235 	if (read(fd, buf, st.st_size) != st.st_size) {
1236 		command_errmsg = "error while reading the file";
1237 		(void)BS->FreePool(buf);
1238 		close(fd);
1239 		return (CMD_ERROR);
1240 	}
1241 	close(fd);
1242 	status = BS->LoadImage(FALSE, IH, NULL, buf, st.st_size, &loaderhandle);
1243 	(void)BS->FreePool(buf);
1244 	if (status != EFI_SUCCESS) {
1245 		command_errmsg = "LoadImage failed";
1246 		return (CMD_ERROR);
1247 	}
1248 	status = BS->HandleProtocol(loaderhandle, &LoadedImageGUID,
1249 	    (void **)&loaded_image);
1250 
1251 	if (argc > 2) {
1252 		int i, len = 0;
1253 		CHAR16 *argp;
1254 
1255 		for (i = 2; i < argc; i++)
1256 			len += strlen(argv[i]) + 1;
1257 
1258 		len *= sizeof (*argp);
1259 		loaded_image->LoadOptions = argp = malloc (len);
1260 		loaded_image->LoadOptionsSize = len;
1261 		for (i = 2; i < argc; i++) {
1262 			char *ptr = argv[i];
1263 			while (*ptr)
1264 				*(argp++) = *(ptr++);
1265 			*(argp++) = ' ';
1266 		}
1267 		*(--argv) = 0;
1268 	}
1269 
1270 	if (efi_getdev((void **)&dev, name, (const char **)&path) == 0) {
1271 #ifdef EFI_ZFS_BOOT
1272 		struct zfs_devdesc *z_dev;
1273 #endif
1274 		struct disk_devdesc *d_dev;
1275 		pdinfo_t *hd, *pd;
1276 
1277 		switch (dev->d_dev->dv_type) {
1278 #ifdef EFI_ZFS_BOOT
1279 		case DEVT_ZFS:
1280 			z_dev = (struct zfs_devdesc *)dev;
1281 			loaded_image->DeviceHandle =
1282 			    efizfs_get_handle_by_guid(z_dev->pool_guid);
1283 			break;
1284 #endif
1285 		case DEVT_NET:
1286 			loaded_image->DeviceHandle =
1287 			    efi_find_handle(dev->d_dev, dev->d_unit);
1288 			break;
1289 		default:
1290 			hd = efiblk_get_pdinfo(dev);
1291 			if (STAILQ_EMPTY(&hd->pd_part)) {
1292 				loaded_image->DeviceHandle = hd->pd_handle;
1293 				break;
1294 			}
1295 			d_dev = (struct disk_devdesc *)dev;
1296 			STAILQ_FOREACH(pd, &hd->pd_part, pd_link) {
1297 				/*
1298 				 * d_partition should be 255
1299 				 */
1300 				if (pd->pd_unit == (uint32_t)d_dev->d_slice) {
1301 					loaded_image->DeviceHandle =
1302 					    pd->pd_handle;
1303 					break;
1304 				}
1305 			}
1306 			break;
1307 		}
1308 	}
1309 
1310 	dev_cleanup();
1311 	status = BS->StartImage(loaderhandle, NULL, NULL);
1312 	if (status != EFI_SUCCESS) {
1313 		command_errmsg = "StartImage failed";
1314 		free(loaded_image->LoadOptions);
1315 		loaded_image->LoadOptions = NULL;
1316 		status = BS->UnloadImage(loaded_image);
1317 		return (CMD_ERROR);
1318 	}
1319 
1320 	return (CMD_ERROR);	/* not reached */
1321 }
1322 
1323 COMMAND_SET(chain, "chain", "chain load file", command_chain);
1324