xref: /freebsd/stand/efi/loader/main.c (revision f39bffc62c1395bde25d152c7f68fdf7cbaab414)
1 /*-
2  * Copyright (c) 2008-2010 Rui Paulo
3  * Copyright (c) 2006 Marcel Moolenaar
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include <sys/disk.h>
32 #include <sys/param.h>
33 #include <sys/reboot.h>
34 #include <stdint.h>
35 #include <stand.h>
36 #include <string.h>
37 #include <setjmp.h>
38 #include <disk.h>
39 
40 #include <efi.h>
41 #include <efilib.h>
42 
43 #include <uuid.h>
44 
45 #include <bootstrap.h>
46 #include <smbios.h>
47 
48 #ifdef EFI_ZFS_BOOT
49 #include <libzfs.h>
50 #include "efizfs.h"
51 #endif
52 
53 #include "loader_efi.h"
54 
55 struct arch_switch archsw;	/* MI/MD interface boundary */
56 
57 EFI_GUID acpi = ACPI_TABLE_GUID;
58 EFI_GUID acpi20 = ACPI_20_TABLE_GUID;
59 EFI_GUID devid = DEVICE_PATH_PROTOCOL;
60 EFI_GUID imgid = LOADED_IMAGE_PROTOCOL;
61 EFI_GUID mps = MPS_TABLE_GUID;
62 EFI_GUID netid = EFI_SIMPLE_NETWORK_PROTOCOL;
63 EFI_GUID smbios = SMBIOS_TABLE_GUID;
64 EFI_GUID smbios3 = SMBIOS3_TABLE_GUID;
65 EFI_GUID dxe = DXE_SERVICES_TABLE_GUID;
66 EFI_GUID hoblist = HOB_LIST_TABLE_GUID;
67 EFI_GUID lzmadecomp = LZMA_DECOMPRESSION_GUID;
68 EFI_GUID mpcore = ARM_MP_CORE_INFO_TABLE_GUID;
69 EFI_GUID esrt = ESRT_TABLE_GUID;
70 EFI_GUID memtype = MEMORY_TYPE_INFORMATION_TABLE_GUID;
71 EFI_GUID debugimg = DEBUG_IMAGE_INFO_TABLE_GUID;
72 EFI_GUID fdtdtb = FDT_TABLE_GUID;
73 EFI_GUID inputid = SIMPLE_TEXT_INPUT_PROTOCOL;
74 
75 /*
76  * Number of seconds to wait for a keystroke before exiting with failure
77  * in the event no currdev is found. -2 means always break, -1 means
78  * never break, 0 means poll once and then reboot, > 0 means wait for
79  * that many seconds. "fail_timeout" can be set in the environment as
80  * well.
81  */
82 static int fail_timeout = 5;
83 
84 static bool
85 has_keyboard(void)
86 {
87 	EFI_STATUS status;
88 	EFI_DEVICE_PATH *path;
89 	EFI_HANDLE *hin, *hin_end, *walker;
90 	UINTN sz;
91 	bool retval = false;
92 
93 	/*
94 	 * Find all the handles that support the SIMPLE_TEXT_INPUT_PROTOCOL and
95 	 * do the typical dance to get the right sized buffer.
96 	 */
97 	sz = 0;
98 	hin = NULL;
99 	status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz, 0);
100 	if (status == EFI_BUFFER_TOO_SMALL) {
101 		hin = (EFI_HANDLE *)malloc(sz);
102 		status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz,
103 		    hin);
104 		if (EFI_ERROR(status))
105 			free(hin);
106 	}
107 	if (EFI_ERROR(status))
108 		return retval;
109 
110 	/*
111 	 * Look at each of the handles. If it supports the device path protocol,
112 	 * use it to get the device path for this handle. Then see if that
113 	 * device path matches either the USB device path for keyboards or the
114 	 * legacy device path for keyboards.
115 	 */
116 	hin_end = &hin[sz / sizeof(*hin)];
117 	for (walker = hin; walker < hin_end; walker++) {
118 		status = BS->HandleProtocol(*walker, &devid, (VOID **)&path);
119 		if (EFI_ERROR(status))
120 			continue;
121 
122 		while (!IsDevicePathEnd(path)) {
123 			/*
124 			 * Check for the ACPI keyboard node. All PNP3xx nodes
125 			 * are keyboards of different flavors. Note: It is
126 			 * unclear of there's always a keyboard node when
127 			 * there's a keyboard controller, or if there's only one
128 			 * when a keyboard is detected at boot.
129 			 */
130 			if (DevicePathType(path) == ACPI_DEVICE_PATH &&
131 			    (DevicePathSubType(path) == ACPI_DP ||
132 				DevicePathSubType(path) == ACPI_EXTENDED_DP)) {
133 				ACPI_HID_DEVICE_PATH  *acpi;
134 
135 				acpi = (ACPI_HID_DEVICE_PATH *)(void *)path;
136 				if ((EISA_ID_TO_NUM(acpi->HID) & 0xff00) == 0x300 &&
137 				    (acpi->HID & 0xffff) == PNP_EISA_ID_CONST) {
138 					retval = true;
139 					goto out;
140 				}
141 			/*
142 			 * Check for USB keyboard node, if present. Unlike a
143 			 * PS/2 keyboard, these definitely only appear when
144 			 * connected to the system.
145 			 */
146 			} else if (DevicePathType(path) == MESSAGING_DEVICE_PATH &&
147 			    DevicePathSubType(path) == MSG_USB_CLASS_DP) {
148 				USB_CLASS_DEVICE_PATH *usb;
149 
150 				usb = (USB_CLASS_DEVICE_PATH *)(void *)path;
151 				if (usb->DeviceClass == 3 && /* HID */
152 				    usb->DeviceSubClass == 1 && /* Boot devices */
153 				    usb->DeviceProtocol == 1) { /* Boot keyboards */
154 					retval = true;
155 					goto out;
156 				}
157 			}
158 			path = NextDevicePathNode(path);
159 		}
160 	}
161 out:
162 	free(hin);
163 	return retval;
164 }
165 
166 static void
167 set_currdev_devdesc(struct devdesc *currdev)
168 {
169 	const char *devname;
170 
171 	devname = efi_fmtdev(currdev);
172 
173 	printf("Setting currdev to %s\n", devname);
174 
175 	env_setenv("currdev", EV_VOLATILE, devname, efi_setcurrdev, env_nounset);
176 	env_setenv("loaddev", EV_VOLATILE, devname, env_noset, env_nounset);
177 }
178 
179 static void
180 set_currdev_devsw(struct devsw *dev, int unit)
181 {
182 	struct devdesc currdev;
183 
184 	currdev.d_dev = dev;
185 	currdev.d_unit = unit;
186 
187 	set_currdev_devdesc(&currdev);
188 }
189 
190 static void
191 set_currdev_pdinfo(pdinfo_t *dp)
192 {
193 
194 	/*
195 	 * Disks are special: they have partitions. if the parent
196 	 * pointer is non-null, we're a partition not a full disk
197 	 * and we need to adjust currdev appropriately.
198 	 */
199 	if (dp->pd_devsw->dv_type == DEVT_DISK) {
200 		struct disk_devdesc currdev;
201 
202 		currdev.dd.d_dev = dp->pd_devsw;
203 		if (dp->pd_parent == NULL) {
204 			currdev.dd.d_unit = dp->pd_unit;
205 			currdev.d_slice = -1;
206 			currdev.d_partition = -1;
207 		} else {
208 			currdev.dd.d_unit = dp->pd_parent->pd_unit;
209 			currdev.d_slice = dp->pd_unit;
210 			currdev.d_partition = 255;	/* Assumes GPT */
211 		}
212 		set_currdev_devdesc((struct devdesc *)&currdev);
213 	} else {
214 		set_currdev_devsw(dp->pd_devsw, dp->pd_unit);
215 	}
216 }
217 
218 static bool
219 sanity_check_currdev(void)
220 {
221 	struct stat st;
222 
223 	return (stat("/boot/defaults/loader.conf", &st) == 0);
224 }
225 
226 #ifdef EFI_ZFS_BOOT
227 static bool
228 probe_zfs_currdev(uint64_t guid)
229 {
230 	char *devname;
231 	struct zfs_devdesc currdev;
232 
233 	currdev.dd.d_dev = &zfs_dev;
234 	currdev.dd.d_unit = 0;
235 	currdev.pool_guid = guid;
236 	currdev.root_guid = 0;
237 	set_currdev_devdesc((struct devdesc *)&currdev);
238 	devname = efi_fmtdev(&currdev);
239 	init_zfs_bootenv(devname);
240 
241 	return (sanity_check_currdev());
242 }
243 #endif
244 
245 static bool
246 try_as_currdev(pdinfo_t *hd, pdinfo_t *pp)
247 {
248 	uint64_t guid;
249 
250 #ifdef EFI_ZFS_BOOT
251 	/*
252 	 * If there's a zpool on this device, try it as a ZFS
253 	 * filesystem, which has somewhat different setup than all
254 	 * other types of fs due to imperfect loader integration.
255 	 * This all stems from ZFS being both a device (zpool) and
256 	 * a filesystem, plus the boot env feature.
257 	 */
258 	if (efizfs_get_guid_by_handle(pp->pd_handle, &guid))
259 		return (probe_zfs_currdev(guid));
260 #endif
261 	/*
262 	 * All other filesystems just need the pdinfo
263 	 * initialized in the standard way.
264 	 */
265 	set_currdev_pdinfo(pp);
266 	return (sanity_check_currdev());
267 }
268 
269 static int
270 find_currdev(EFI_LOADED_IMAGE *img)
271 {
272 	pdinfo_t *dp, *pp;
273 	EFI_DEVICE_PATH *devpath, *copy;
274 	EFI_HANDLE h;
275 	CHAR16 *text;
276 	struct devsw *dev;
277 	int unit;
278 	uint64_t extra;
279 
280 #ifdef EFI_ZFS_BOOT
281 	/*
282 	 * Did efi_zfs_probe() detect the boot pool? If so, use the zpool
283 	 * it found, if it's sane. ZFS is the only thing that looks for
284 	 * disks and pools to boot. This may change in the future, however,
285 	 * if we allow specifying which pool to boot from via UEFI variables
286 	 * rather than the bootenv stuff that FreeBSD uses today.
287 	 */
288 	if (pool_guid != 0) {
289 		printf("Trying ZFS pool\n");
290 		if (probe_zfs_currdev(pool_guid))
291 			return (0);
292 	}
293 #endif /* EFI_ZFS_BOOT */
294 
295 	/*
296 	 * Try to find the block device by its handle based on the
297 	 * image we're booting. If we can't find a sane partition,
298 	 * search all the other partitions of the disk. We do not
299 	 * search other disks because it's a violation of the UEFI
300 	 * boot protocol to do so. We fail and let UEFI go on to
301 	 * the next candidate.
302 	 */
303 	dp = efiblk_get_pdinfo_by_handle(img->DeviceHandle);
304 	if (dp != NULL) {
305 		text = efi_devpath_name(dp->pd_devpath);
306 		if (text != NULL) {
307 			printf("Trying ESP: %S\n", text);
308 			efi_free_devpath_name(text);
309 		}
310 		set_currdev_pdinfo(dp);
311 		if (sanity_check_currdev())
312 			return (0);
313 		if (dp->pd_parent != NULL) {
314 			dp = dp->pd_parent;
315 			STAILQ_FOREACH(pp, &dp->pd_part, pd_link) {
316 				text = efi_devpath_name(pp->pd_devpath);
317 				if (text != NULL) {
318 					printf("And now the part: %S\n", text);
319 					efi_free_devpath_name(text);
320 				}
321 				/*
322 				 * Roll up the ZFS special case
323 				 * for those partitions that have
324 				 * zpools on them
325 				 */
326 				if (try_as_currdev(dp, pp))
327 					return (0);
328 			}
329 		}
330 	} else {
331 		printf("Can't find device by handle\n");
332 	}
333 
334 	/*
335 	 * Try the device handle from our loaded image first.  If that
336 	 * fails, use the device path from the loaded image and see if
337 	 * any of the nodes in that path match one of the enumerated
338 	 * handles. Currently, this handle list is only for netboot.
339 	 */
340 	if (efi_handle_lookup(img->DeviceHandle, &dev, &unit, &extra) == 0) {
341 		set_currdev_devsw(dev, unit);
342 		if (sanity_check_currdev())
343 			return (0);
344 	}
345 
346 	copy = NULL;
347 	devpath = efi_lookup_image_devpath(IH);
348 	while (devpath != NULL) {
349 		h = efi_devpath_handle(devpath);
350 		if (h == NULL)
351 			break;
352 
353 		free(copy);
354 		copy = NULL;
355 
356 		if (efi_handle_lookup(h, &dev, &unit, &extra) == 0) {
357 			set_currdev_devsw(dev, unit);
358 			if (sanity_check_currdev())
359 				return (0);
360 		}
361 
362 		devpath = efi_lookup_devpath(h);
363 		if (devpath != NULL) {
364 			copy = efi_devpath_trim(devpath);
365 			devpath = copy;
366 		}
367 	}
368 	free(copy);
369 
370 	return (ENOENT);
371 }
372 
373 static bool
374 interactive_interrupt(const char *msg)
375 {
376 	time_t now, then, last;
377 
378 	last = 0;
379 	now = then = getsecs();
380 	printf("%s\n", msg);
381 	if (fail_timeout == -2)		/* Always break to OK */
382 		return (true);
383 	if (fail_timeout == -1)		/* Never break to OK */
384 		return (false);
385 	do {
386 		if (last != now) {
387 			printf("press any key to interrupt reboot in %d seconds\r",
388 			    fail_timeout - (int)(now - then));
389 			last = now;
390 		}
391 
392 		/* XXX no pause or timeout wait for char */
393 		if (ischar())
394 			return (true);
395 		now = getsecs();
396 	} while (now - then < fail_timeout);
397 	return (false);
398 }
399 
400 int
401 parse_args(int argc, CHAR16 *argv[], bool has_kbd)
402 {
403 	int i, j, howto;
404 	bool vargood;
405 	char var[128];
406 
407 	/*
408 	 * Parse the args to set the console settings, etc
409 	 * boot1.efi passes these in, if it can read /boot.config or /boot/config
410 	 * or iPXE may be setup to pass these in. Or the optional argument in the
411 	 * boot environment was used to pass these arguments in (in which case
412 	 * neither /boot.config nor /boot/config are consulted).
413 	 *
414 	 * Loop through the args, and for each one that contains an '=' that is
415 	 * not the first character, add it to the environment.  This allows
416 	 * loader and kernel env vars to be passed on the command line.  Convert
417 	 * args from UCS-2 to ASCII (16 to 8 bit) as they are copied (though this
418 	 * method is flawed for non-ASCII characters).
419 	 */
420 	howto = 0;
421 	for (i = 1; i < argc; i++) {
422 		if (argv[i][0] == '-') {
423 			for (j = 1; argv[i][j] != 0; j++) {
424 				int ch;
425 
426 				ch = argv[i][j];
427 				switch (ch) {
428 				case 'a':
429 					howto |= RB_ASKNAME;
430 					break;
431 				case 'd':
432 					howto |= RB_KDB;
433 					break;
434 				case 'D':
435 					howto |= RB_MULTIPLE;
436 					break;
437 				case 'h':
438 					howto |= RB_SERIAL;
439 					break;
440 				case 'm':
441 					howto |= RB_MUTE;
442 					break;
443 				case 'p':
444 					howto |= RB_PAUSE;
445 					break;
446 				case 'P':
447 					if (!has_kbd)
448 						howto |= RB_SERIAL | RB_MULTIPLE;
449 					break;
450 				case 'r':
451 					howto |= RB_DFLTROOT;
452 					break;
453 				case 's':
454 					howto |= RB_SINGLE;
455 					break;
456 				case 'S':
457 					if (argv[i][j + 1] == 0) {
458 						if (i + 1 == argc) {
459 							setenv("comconsole_speed", "115200", 1);
460 						} else {
461 							cpy16to8(&argv[i + 1][0], var,
462 							    sizeof(var));
463 							setenv("comconsole_speed", var, 1);
464 						}
465 						i++;
466 						break;
467 					} else {
468 						cpy16to8(&argv[i][j + 1], var,
469 						    sizeof(var));
470 						setenv("comconsole_speed", var, 1);
471 						break;
472 					}
473 				case 'v':
474 					howto |= RB_VERBOSE;
475 					break;
476 				}
477 			}
478 		} else {
479 			vargood = false;
480 			for (j = 0; argv[i][j] != 0; j++) {
481 				if (j == sizeof(var)) {
482 					vargood = false;
483 					break;
484 				}
485 				if (j > 0 && argv[i][j] == '=')
486 					vargood = true;
487 				var[j] = (char)argv[i][j];
488 			}
489 			if (vargood) {
490 				var[j] = 0;
491 				putenv(var);
492 			}
493 		}
494 	}
495 	return (howto);
496 }
497 
498 
499 EFI_STATUS
500 main(int argc, CHAR16 *argv[])
501 {
502 	EFI_GUID *guid;
503 	int howto, i;
504 	UINTN k;
505 	bool has_kbd;
506 	char *s;
507 	EFI_DEVICE_PATH *imgpath;
508 	CHAR16 *text;
509 	EFI_STATUS status;
510 	UINT16 boot_current;
511 	size_t sz;
512 	UINT16 boot_order[100];
513 	EFI_LOADED_IMAGE *img;
514 
515 	archsw.arch_autoload = efi_autoload;
516 	archsw.arch_getdev = efi_getdev;
517 	archsw.arch_copyin = efi_copyin;
518 	archsw.arch_copyout = efi_copyout;
519 	archsw.arch_readin = efi_readin;
520 #ifdef EFI_ZFS_BOOT
521 	/* Note this needs to be set before ZFS init. */
522 	archsw.arch_zfs_probe = efi_zfs_probe;
523 #endif
524 
525         /* Get our loaded image protocol interface structure. */
526 	BS->HandleProtocol(IH, &imgid, (VOID**)&img);
527 
528 #ifdef EFI_ZFS_BOOT
529 	/* Tell ZFS probe code where we booted from */
530 	efizfs_set_preferred(img->DeviceHandle);
531 #endif
532 	/* Init the time source */
533 	efi_time_init();
534 
535 	has_kbd = has_keyboard();
536 
537 	/*
538 	 * XXX Chicken-and-egg problem; we want to have console output
539 	 * early, but some console attributes may depend on reading from
540 	 * eg. the boot device, which we can't do yet.  We can use
541 	 * printf() etc. once this is done.
542 	 */
543 	cons_probe();
544 
545 	/*
546 	 * Initialise the block cache. Set the upper limit.
547 	 */
548 	bcache_init(32768, 512);
549 
550 	howto = parse_args(argc, argv, has_kbd);
551 
552 	bootenv_set(howto);
553 
554 	/*
555 	 * XXX we need fallback to this stuff after looking at the ConIn, ConOut and ConErr variables
556 	 */
557 	if (howto & RB_MULTIPLE) {
558 		if (howto & RB_SERIAL)
559 			setenv("console", "comconsole efi" , 1);
560 		else
561 			setenv("console", "efi comconsole" , 1);
562 	} else if (howto & RB_SERIAL) {
563 		setenv("console", "comconsole" , 1);
564 	} else
565 		setenv("console", "efi", 1);
566 
567 	if (efi_copy_init()) {
568 		printf("failed to allocate staging area\n");
569 		return (EFI_BUFFER_TOO_SMALL);
570 	}
571 
572 	if ((s = getenv("fail_timeout")) != NULL)
573 		fail_timeout = strtol(s, NULL, 10);
574 
575 	/*
576 	 * Scan the BLOCK IO MEDIA handles then
577 	 * march through the device switch probing for things.
578 	 */
579 	if ((i = efipart_inithandles()) == 0) {
580 		for (i = 0; devsw[i] != NULL; i++)
581 			if (devsw[i]->dv_init != NULL)
582 				(devsw[i]->dv_init)();
583 	} else
584 		printf("efipart_inithandles failed %d, expect failures", i);
585 
586 	printf("Command line arguments:");
587 	for (i = 0; i < argc; i++)
588 		printf(" %S", argv[i]);
589 	printf("\n");
590 
591 	printf("Image base: 0x%lx\n", (u_long)img->ImageBase);
592 	printf("EFI version: %d.%02d\n", ST->Hdr.Revision >> 16,
593 	    ST->Hdr.Revision & 0xffff);
594 	printf("EFI Firmware: %S (rev %d.%02d)\n", ST->FirmwareVendor,
595 	    ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
596 
597 	printf("\n%s", bootprog_info);
598 
599 	/* Determine the devpath of our image so we can prefer it. */
600 	text = efi_devpath_name(img->FilePath);
601 	if (text != NULL) {
602 		printf("   Load Path: %S\n", text);
603 		efi_setenv_freebsd_wcs("LoaderPath", text);
604 		efi_free_devpath_name(text);
605 	}
606 
607 	status = BS->HandleProtocol(img->DeviceHandle, &devid, (void **)&imgpath);
608 	if (status == EFI_SUCCESS) {
609 		text = efi_devpath_name(imgpath);
610 		if (text != NULL) {
611 			printf("   Load Device: %S\n", text);
612 			efi_setenv_freebsd_wcs("LoaderDev", text);
613 			efi_free_devpath_name(text);
614 		}
615 	}
616 
617 	boot_current = 0;
618 	sz = sizeof(boot_current);
619 	efi_global_getenv("BootCurrent", &boot_current, &sz);
620 	printf("   BootCurrent: %04x\n", boot_current);
621 
622 	sz = sizeof(boot_order);
623 	efi_global_getenv("BootOrder", &boot_order, &sz);
624 	printf("   BootOrder:");
625 	for (i = 0; i < sz / sizeof(boot_order[0]); i++)
626 		printf(" %04x%s", boot_order[i],
627 		    boot_order[i] == boot_current ? "[*]" : "");
628 	printf("\n");
629 
630 	/*
631 	 * Disable the watchdog timer. By default the boot manager sets
632 	 * the timer to 5 minutes before invoking a boot option. If we
633 	 * want to return to the boot manager, we have to disable the
634 	 * watchdog timer and since we're an interactive program, we don't
635 	 * want to wait until the user types "quit". The timer may have
636 	 * fired by then. We don't care if this fails. It does not prevent
637 	 * normal functioning in any way...
638 	 */
639 	BS->SetWatchdogTimer(0, 0, 0, NULL);
640 
641 	/*
642 	 * Try and find a good currdev based on the image that was booted.
643 	 * It might be desirable here to have a short pause to allow falling
644 	 * through to the boot loader instead of returning instantly to follow
645 	 * the boot protocol and also allow an escape hatch for users wishing
646 	 * to try something different.
647 	 */
648 	if (find_currdev(img) != 0)
649 		if (!interactive_interrupt("Failed to find bootable partition"))
650 			return (EFI_NOT_FOUND);
651 
652 	efi_init_environment();
653 	setenv("LINES", "24", 1);	/* optional */
654 
655 #if !defined(__arm__)
656 	for (k = 0; k < ST->NumberOfTableEntries; k++) {
657 		guid = &ST->ConfigurationTable[k].VendorGuid;
658 		if (!memcmp(guid, &smbios, sizeof(EFI_GUID))) {
659 			char buf[40];
660 
661 			snprintf(buf, sizeof(buf), "%p",
662 			    ST->ConfigurationTable[k].VendorTable);
663 			setenv("hint.smbios.0.mem", buf, 1);
664 			smbios_detect(ST->ConfigurationTable[k].VendorTable);
665 			break;
666 		}
667 	}
668 #endif
669 
670 	interact();			/* doesn't return */
671 
672 	return (EFI_SUCCESS);		/* keep compiler happy */
673 }
674 
675 COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot);
676 
677 static int
678 command_reboot(int argc, char *argv[])
679 {
680 	int i;
681 
682 	for (i = 0; devsw[i] != NULL; ++i)
683 		if (devsw[i]->dv_cleanup != NULL)
684 			(devsw[i]->dv_cleanup)();
685 
686 	RS->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL);
687 
688 	/* NOTREACHED */
689 	return (CMD_ERROR);
690 }
691 
692 COMMAND_SET(quit, "quit", "exit the loader", command_quit);
693 
694 static int
695 command_quit(int argc, char *argv[])
696 {
697 	exit(0);
698 	return (CMD_OK);
699 }
700 
701 COMMAND_SET(memmap, "memmap", "print memory map", command_memmap);
702 
703 static int
704 command_memmap(int argc, char *argv[])
705 {
706 	UINTN sz;
707 	EFI_MEMORY_DESCRIPTOR *map, *p;
708 	UINTN key, dsz;
709 	UINT32 dver;
710 	EFI_STATUS status;
711 	int i, ndesc;
712 	char line[80];
713 	static char *types[] = {
714 	    "Reserved",
715 	    "LoaderCode",
716 	    "LoaderData",
717 	    "BootServicesCode",
718 	    "BootServicesData",
719 	    "RuntimeServicesCode",
720 	    "RuntimeServicesData",
721 	    "ConventionalMemory",
722 	    "UnusableMemory",
723 	    "ACPIReclaimMemory",
724 	    "ACPIMemoryNVS",
725 	    "MemoryMappedIO",
726 	    "MemoryMappedIOPortSpace",
727 	    "PalCode"
728 	};
729 
730 	sz = 0;
731 	status = BS->GetMemoryMap(&sz, 0, &key, &dsz, &dver);
732 	if (status != EFI_BUFFER_TOO_SMALL) {
733 		printf("Can't determine memory map size\n");
734 		return (CMD_ERROR);
735 	}
736 	map = malloc(sz);
737 	status = BS->GetMemoryMap(&sz, map, &key, &dsz, &dver);
738 	if (EFI_ERROR(status)) {
739 		printf("Can't read memory map\n");
740 		return (CMD_ERROR);
741 	}
742 
743 	ndesc = sz / dsz;
744 	snprintf(line, sizeof(line), "%23s %12s %12s %8s %4s\n",
745 	    "Type", "Physical", "Virtual", "#Pages", "Attr");
746 	pager_open();
747 	if (pager_output(line)) {
748 		pager_close();
749 		return (CMD_OK);
750 	}
751 
752 	for (i = 0, p = map; i < ndesc;
753 	     i++, p = NextMemoryDescriptor(p, dsz)) {
754 		printf("%23s %012jx %012jx %08jx ", types[p->Type],
755 		    (uintmax_t)p->PhysicalStart, (uintmax_t)p->VirtualStart,
756 		    (uintmax_t)p->NumberOfPages);
757 		if (p->Attribute & EFI_MEMORY_UC)
758 			printf("UC ");
759 		if (p->Attribute & EFI_MEMORY_WC)
760 			printf("WC ");
761 		if (p->Attribute & EFI_MEMORY_WT)
762 			printf("WT ");
763 		if (p->Attribute & EFI_MEMORY_WB)
764 			printf("WB ");
765 		if (p->Attribute & EFI_MEMORY_UCE)
766 			printf("UCE ");
767 		if (p->Attribute & EFI_MEMORY_WP)
768 			printf("WP ");
769 		if (p->Attribute & EFI_MEMORY_RP)
770 			printf("RP ");
771 		if (p->Attribute & EFI_MEMORY_XP)
772 			printf("XP ");
773 		if (pager_output("\n"))
774 			break;
775 	}
776 
777 	pager_close();
778 	return (CMD_OK);
779 }
780 
781 COMMAND_SET(configuration, "configuration", "print configuration tables",
782     command_configuration);
783 
784 static const char *
785 guid_to_string(EFI_GUID *guid)
786 {
787 	static char buf[40];
788 
789 	sprintf(buf, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
790 	    guid->Data1, guid->Data2, guid->Data3, guid->Data4[0],
791 	    guid->Data4[1], guid->Data4[2], guid->Data4[3], guid->Data4[4],
792 	    guid->Data4[5], guid->Data4[6], guid->Data4[7]);
793 	return (buf);
794 }
795 
796 static int
797 command_configuration(int argc, char *argv[])
798 {
799 	char line[80];
800 	UINTN i;
801 
802 	snprintf(line, sizeof(line), "NumberOfTableEntries=%lu\n",
803 		(unsigned long)ST->NumberOfTableEntries);
804 	pager_open();
805 	if (pager_output(line)) {
806 		pager_close();
807 		return (CMD_OK);
808 	}
809 
810 	for (i = 0; i < ST->NumberOfTableEntries; i++) {
811 		EFI_GUID *guid;
812 
813 		printf("  ");
814 		guid = &ST->ConfigurationTable[i].VendorGuid;
815 		if (!memcmp(guid, &mps, sizeof(EFI_GUID)))
816 			printf("MPS Table");
817 		else if (!memcmp(guid, &acpi, sizeof(EFI_GUID)))
818 			printf("ACPI Table");
819 		else if (!memcmp(guid, &acpi20, sizeof(EFI_GUID)))
820 			printf("ACPI 2.0 Table");
821 		else if (!memcmp(guid, &smbios, sizeof(EFI_GUID)))
822 			printf("SMBIOS Table %p",
823 			    ST->ConfigurationTable[i].VendorTable);
824 		else if (!memcmp(guid, &smbios3, sizeof(EFI_GUID)))
825 			printf("SMBIOS3 Table");
826 		else if (!memcmp(guid, &dxe, sizeof(EFI_GUID)))
827 			printf("DXE Table");
828 		else if (!memcmp(guid, &hoblist, sizeof(EFI_GUID)))
829 			printf("HOB List Table");
830 		else if (!memcmp(guid, &lzmadecomp, sizeof(EFI_GUID)))
831 			printf("LZMA Compression");
832 		else if (!memcmp(guid, &mpcore, sizeof(EFI_GUID)))
833 			printf("ARM MpCore Information Table");
834 		else if (!memcmp(guid, &esrt, sizeof(EFI_GUID)))
835 			printf("ESRT Table");
836 		else if (!memcmp(guid, &memtype, sizeof(EFI_GUID)))
837 			printf("Memory Type Information Table");
838 		else if (!memcmp(guid, &debugimg, sizeof(EFI_GUID)))
839 			printf("Debug Image Info Table");
840 		else if (!memcmp(guid, &fdtdtb, sizeof(EFI_GUID)))
841 			printf("FDT Table");
842 		else
843 			printf("Unknown Table (%s)", guid_to_string(guid));
844 		snprintf(line, sizeof(line), " at %p\n",
845 		    ST->ConfigurationTable[i].VendorTable);
846 		if (pager_output(line))
847 			break;
848 	}
849 
850 	pager_close();
851 	return (CMD_OK);
852 }
853 
854 
855 COMMAND_SET(mode, "mode", "change or display EFI text modes", command_mode);
856 
857 static int
858 command_mode(int argc, char *argv[])
859 {
860 	UINTN cols, rows;
861 	unsigned int mode;
862 	int i;
863 	char *cp;
864 	char rowenv[8];
865 	EFI_STATUS status;
866 	SIMPLE_TEXT_OUTPUT_INTERFACE *conout;
867 	extern void HO(void);
868 
869 	conout = ST->ConOut;
870 
871 	if (argc > 1) {
872 		mode = strtol(argv[1], &cp, 0);
873 		if (cp[0] != '\0') {
874 			printf("Invalid mode\n");
875 			return (CMD_ERROR);
876 		}
877 		status = conout->QueryMode(conout, mode, &cols, &rows);
878 		if (EFI_ERROR(status)) {
879 			printf("invalid mode %d\n", mode);
880 			return (CMD_ERROR);
881 		}
882 		status = conout->SetMode(conout, mode);
883 		if (EFI_ERROR(status)) {
884 			printf("couldn't set mode %d\n", mode);
885 			return (CMD_ERROR);
886 		}
887 		sprintf(rowenv, "%u", (unsigned)rows);
888 		setenv("LINES", rowenv, 1);
889 		HO();		/* set cursor */
890 		return (CMD_OK);
891 	}
892 
893 	printf("Current mode: %d\n", conout->Mode->Mode);
894 	for (i = 0; i <= conout->Mode->MaxMode; i++) {
895 		status = conout->QueryMode(conout, i, &cols, &rows);
896 		if (EFI_ERROR(status))
897 			continue;
898 		printf("Mode %d: %u columns, %u rows\n", i, (unsigned)cols,
899 		    (unsigned)rows);
900 	}
901 
902 	if (i != 0)
903 		printf("Select a mode with the command \"mode <number>\"\n");
904 
905 	return (CMD_OK);
906 }
907 
908 #ifdef LOADER_FDT_SUPPORT
909 extern int command_fdt_internal(int argc, char *argv[]);
910 
911 /*
912  * Since proper fdt command handling function is defined in fdt_loader_cmd.c,
913  * and declaring it as extern is in contradiction with COMMAND_SET() macro
914  * (which uses static pointer), we're defining wrapper function, which
915  * calls the proper fdt handling routine.
916  */
917 static int
918 command_fdt(int argc, char *argv[])
919 {
920 
921 	return (command_fdt_internal(argc, argv));
922 }
923 
924 COMMAND_SET(fdt, "fdt", "flattened device tree handling", command_fdt);
925 #endif
926 
927 /*
928  * Chain load another efi loader.
929  */
930 static int
931 command_chain(int argc, char *argv[])
932 {
933 	EFI_GUID LoadedImageGUID = LOADED_IMAGE_PROTOCOL;
934 	EFI_HANDLE loaderhandle;
935 	EFI_LOADED_IMAGE *loaded_image;
936 	EFI_STATUS status;
937 	struct stat st;
938 	struct devdesc *dev;
939 	char *name, *path;
940 	void *buf;
941 	int fd;
942 
943 	if (argc < 2) {
944 		command_errmsg = "wrong number of arguments";
945 		return (CMD_ERROR);
946 	}
947 
948 	name = argv[1];
949 
950 	if ((fd = open(name, O_RDONLY)) < 0) {
951 		command_errmsg = "no such file";
952 		return (CMD_ERROR);
953 	}
954 
955 	if (fstat(fd, &st) < -1) {
956 		command_errmsg = "stat failed";
957 		close(fd);
958 		return (CMD_ERROR);
959 	}
960 
961 	status = BS->AllocatePool(EfiLoaderCode, (UINTN)st.st_size, &buf);
962 	if (status != EFI_SUCCESS) {
963 		command_errmsg = "failed to allocate buffer";
964 		close(fd);
965 		return (CMD_ERROR);
966 	}
967 	if (read(fd, buf, st.st_size) != st.st_size) {
968 		command_errmsg = "error while reading the file";
969 		(void)BS->FreePool(buf);
970 		close(fd);
971 		return (CMD_ERROR);
972 	}
973 	close(fd);
974 	status = BS->LoadImage(FALSE, IH, NULL, buf, st.st_size, &loaderhandle);
975 	(void)BS->FreePool(buf);
976 	if (status != EFI_SUCCESS) {
977 		command_errmsg = "LoadImage failed";
978 		return (CMD_ERROR);
979 	}
980 	status = BS->HandleProtocol(loaderhandle, &LoadedImageGUID,
981 	    (void **)&loaded_image);
982 
983 	if (argc > 2) {
984 		int i, len = 0;
985 		CHAR16 *argp;
986 
987 		for (i = 2; i < argc; i++)
988 			len += strlen(argv[i]) + 1;
989 
990 		len *= sizeof (*argp);
991 		loaded_image->LoadOptions = argp = malloc (len);
992 		loaded_image->LoadOptionsSize = len;
993 		for (i = 2; i < argc; i++) {
994 			char *ptr = argv[i];
995 			while (*ptr)
996 				*(argp++) = *(ptr++);
997 			*(argp++) = ' ';
998 		}
999 		*(--argv) = 0;
1000 	}
1001 
1002 	if (efi_getdev((void **)&dev, name, (const char **)&path) == 0) {
1003 #ifdef EFI_ZFS_BOOT
1004 		struct zfs_devdesc *z_dev;
1005 #endif
1006 		struct disk_devdesc *d_dev;
1007 		pdinfo_t *hd, *pd;
1008 
1009 		switch (dev->d_dev->dv_type) {
1010 #ifdef EFI_ZFS_BOOT
1011 		case DEVT_ZFS:
1012 			z_dev = (struct zfs_devdesc *)dev;
1013 			loaded_image->DeviceHandle =
1014 			    efizfs_get_handle_by_guid(z_dev->pool_guid);
1015 			break;
1016 #endif
1017 		case DEVT_NET:
1018 			loaded_image->DeviceHandle =
1019 			    efi_find_handle(dev->d_dev, dev->d_unit);
1020 			break;
1021 		default:
1022 			hd = efiblk_get_pdinfo(dev);
1023 			if (STAILQ_EMPTY(&hd->pd_part)) {
1024 				loaded_image->DeviceHandle = hd->pd_handle;
1025 				break;
1026 			}
1027 			d_dev = (struct disk_devdesc *)dev;
1028 			STAILQ_FOREACH(pd, &hd->pd_part, pd_link) {
1029 				/*
1030 				 * d_partition should be 255
1031 				 */
1032 				if (pd->pd_unit == (uint32_t)d_dev->d_slice) {
1033 					loaded_image->DeviceHandle =
1034 					    pd->pd_handle;
1035 					break;
1036 				}
1037 			}
1038 			break;
1039 		}
1040 	}
1041 
1042 	dev_cleanup();
1043 	status = BS->StartImage(loaderhandle, NULL, NULL);
1044 	if (status != EFI_SUCCESS) {
1045 		command_errmsg = "StartImage failed";
1046 		free(loaded_image->LoadOptions);
1047 		loaded_image->LoadOptions = NULL;
1048 		status = BS->UnloadImage(loaded_image);
1049 		return (CMD_ERROR);
1050 	}
1051 
1052 	return (CMD_ERROR);	/* not reached */
1053 }
1054 
1055 COMMAND_SET(chain, "chain", "chain load file", command_chain);
1056