main.c revision 332127
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: stable/11/stand/efi/loader/main.c 332127 2018-04-06 18:38:25Z kevans $");
30
31#include <sys/disk.h>
32#include <sys/param.h>
33#include <sys/reboot.h>
34#include <sys/boot.h>
35#include <stdint.h>
36#include <stand.h>
37#include <string.h>
38#include <setjmp.h>
39#include <disk.h>
40
41#include <efi.h>
42#include <efilib.h>
43
44#include <uuid.h>
45
46#include <bootstrap.h>
47#include <smbios.h>
48
49#ifdef EFI_ZFS_BOOT
50#include <libzfs.h>
51
52#include "efizfs.h"
53#endif
54
55#include "loader_efi.h"
56
57extern char bootprog_info[];
58
59struct arch_switch archsw;	/* MI/MD interface boundary */
60
61EFI_GUID acpi = ACPI_TABLE_GUID;
62EFI_GUID acpi20 = ACPI_20_TABLE_GUID;
63EFI_GUID devid = DEVICE_PATH_PROTOCOL;
64EFI_GUID imgid = LOADED_IMAGE_PROTOCOL;
65EFI_GUID mps = MPS_TABLE_GUID;
66EFI_GUID netid = EFI_SIMPLE_NETWORK_PROTOCOL;
67EFI_GUID smbios = SMBIOS_TABLE_GUID;
68EFI_GUID smbios3 = SMBIOS3_TABLE_GUID;
69EFI_GUID dxe = DXE_SERVICES_TABLE_GUID;
70EFI_GUID hoblist = HOB_LIST_TABLE_GUID;
71EFI_GUID lzmadecomp = LZMA_DECOMPRESSION_GUID;
72EFI_GUID mpcore = ARM_MP_CORE_INFO_TABLE_GUID;
73EFI_GUID esrt = ESRT_TABLE_GUID;
74EFI_GUID memtype = MEMORY_TYPE_INFORMATION_TABLE_GUID;
75EFI_GUID debugimg = DEBUG_IMAGE_INFO_TABLE_GUID;
76EFI_GUID fdtdtb = FDT_TABLE_GUID;
77EFI_GUID inputid = SIMPLE_TEXT_INPUT_PROTOCOL;
78
79static EFI_LOADED_IMAGE *img;
80
81#ifdef	EFI_ZFS_BOOT
82bool
83efi_zfs_is_preferred(EFI_HANDLE *h)
84{
85        return (h == img->DeviceHandle);
86}
87#endif
88
89static int
90has_keyboard(void)
91{
92	EFI_STATUS status;
93	EFI_DEVICE_PATH *path;
94	EFI_HANDLE *hin, *hin_end, *walker;
95	UINTN sz;
96	int retval = 0;
97
98	/*
99	 * Find all the handles that support the SIMPLE_TEXT_INPUT_PROTOCOL and
100	 * do the typical dance to get the right sized buffer.
101	 */
102	sz = 0;
103	hin = NULL;
104	status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz, 0);
105	if (status == EFI_BUFFER_TOO_SMALL) {
106		hin = (EFI_HANDLE *)malloc(sz);
107		status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz,
108		    hin);
109		if (EFI_ERROR(status))
110			free(hin);
111	}
112	if (EFI_ERROR(status))
113		return retval;
114
115	/*
116	 * Look at each of the handles. If it supports the device path protocol,
117	 * use it to get the device path for this handle. Then see if that
118	 * device path matches either the USB device path for keyboards or the
119	 * legacy device path for keyboards.
120	 */
121	hin_end = &hin[sz / sizeof(*hin)];
122	for (walker = hin; walker < hin_end; walker++) {
123		status = BS->HandleProtocol(*walker, &devid, (VOID **)&path);
124		if (EFI_ERROR(status))
125			continue;
126
127		while (!IsDevicePathEnd(path)) {
128			/*
129			 * Check for the ACPI keyboard node. All PNP3xx nodes
130			 * are keyboards of different flavors. Note: It is
131			 * unclear of there's always a keyboard node when
132			 * there's a keyboard controller, or if there's only one
133			 * when a keyboard is detected at boot.
134			 */
135			if (DevicePathType(path) == ACPI_DEVICE_PATH &&
136			    (DevicePathSubType(path) == ACPI_DP ||
137				DevicePathSubType(path) == ACPI_EXTENDED_DP)) {
138				ACPI_HID_DEVICE_PATH  *acpi;
139
140				acpi = (ACPI_HID_DEVICE_PATH *)(void *)path;
141				if ((EISA_ID_TO_NUM(acpi->HID) & 0xff00) == 0x300 &&
142				    (acpi->HID & 0xffff) == PNP_EISA_ID_CONST) {
143					retval = 1;
144					goto out;
145				}
146			/*
147			 * Check for USB keyboard node, if present. Unlike a
148			 * PS/2 keyboard, these definitely only appear when
149			 * connected to the system.
150			 */
151			} else if (DevicePathType(path) == MESSAGING_DEVICE_PATH &&
152			    DevicePathSubType(path) == MSG_USB_CLASS_DP) {
153				USB_CLASS_DEVICE_PATH *usb;
154
155				usb = (USB_CLASS_DEVICE_PATH *)(void *)path;
156				if (usb->DeviceClass == 3 && /* HID */
157				    usb->DeviceSubClass == 1 && /* Boot devices */
158				    usb->DeviceProtocol == 1) { /* Boot keyboards */
159					retval = 1;
160					goto out;
161				}
162			}
163			path = NextDevicePathNode(path);
164		}
165	}
166out:
167	free(hin);
168	return retval;
169}
170
171static void
172set_devdesc_currdev(struct devsw *dev, int unit)
173{
174	struct devdesc currdev;
175	char *devname;
176
177	currdev.d_dev = dev;
178	currdev.d_type = currdev.d_dev->dv_type;
179	currdev.d_unit = unit;
180	currdev.d_opendata = NULL;
181	devname = efi_fmtdev(&currdev);
182
183	env_setenv("currdev", EV_VOLATILE, devname, efi_setcurrdev,
184	    env_nounset);
185	env_setenv("loaddev", EV_VOLATILE, devname, env_noset, env_nounset);
186}
187
188static int
189find_currdev(EFI_LOADED_IMAGE *img)
190{
191	pdinfo_list_t *pdi_list;
192	pdinfo_t *dp, *pp;
193	EFI_DEVICE_PATH *devpath, *copy;
194	EFI_HANDLE h;
195	char *devname;
196	struct devsw *dev;
197	int unit;
198	uint64_t extra;
199
200#ifdef EFI_ZFS_BOOT
201	/* Did efi_zfs_probe() detect the boot pool? */
202	if (pool_guid != 0) {
203		struct zfs_devdesc currdev;
204
205		currdev.d_dev = &zfs_dev;
206		currdev.d_unit = 0;
207		currdev.d_type = currdev.d_dev->dv_type;
208		currdev.d_opendata = NULL;
209		currdev.pool_guid = pool_guid;
210		currdev.root_guid = 0;
211		devname = efi_fmtdev(&currdev);
212
213		env_setenv("currdev", EV_VOLATILE, devname, efi_setcurrdev,
214		    env_nounset);
215		env_setenv("loaddev", EV_VOLATILE, devname, env_noset,
216		    env_nounset);
217		init_zfs_bootenv(devname);
218		return (0);
219	}
220#endif /* EFI_ZFS_BOOT */
221
222	/* We have device lists for hd, cd, fd, walk them all. */
223	pdi_list = efiblk_get_pdinfo_list(&efipart_hddev);
224	STAILQ_FOREACH(dp, pdi_list, pd_link) {
225		struct disk_devdesc currdev;
226
227		currdev.d_dev = &efipart_hddev;
228		currdev.d_type = currdev.d_dev->dv_type;
229		currdev.d_unit = dp->pd_unit;
230		currdev.d_opendata = NULL;
231		currdev.d_slice = -1;
232		currdev.d_partition = -1;
233
234		if (dp->pd_handle == img->DeviceHandle) {
235			devname = efi_fmtdev(&currdev);
236
237			env_setenv("currdev", EV_VOLATILE, devname,
238			    efi_setcurrdev, env_nounset);
239			env_setenv("loaddev", EV_VOLATILE, devname,
240			    env_noset, env_nounset);
241			return (0);
242		}
243		/* Assuming GPT partitioning. */
244		STAILQ_FOREACH(pp, &dp->pd_part, pd_link) {
245			if (pp->pd_handle == img->DeviceHandle) {
246				currdev.d_slice = pp->pd_unit;
247				currdev.d_partition = 255;
248				devname = efi_fmtdev(&currdev);
249
250				env_setenv("currdev", EV_VOLATILE, devname,
251				    efi_setcurrdev, env_nounset);
252				env_setenv("loaddev", EV_VOLATILE, devname,
253				    env_noset, env_nounset);
254				return (0);
255			}
256		}
257	}
258
259	pdi_list = efiblk_get_pdinfo_list(&efipart_cddev);
260	STAILQ_FOREACH(dp, pdi_list, pd_link) {
261		if (dp->pd_handle == img->DeviceHandle ||
262		    dp->pd_alias == img->DeviceHandle) {
263			set_devdesc_currdev(&efipart_cddev, dp->pd_unit);
264			return (0);
265		}
266	}
267
268	pdi_list = efiblk_get_pdinfo_list(&efipart_fddev);
269	STAILQ_FOREACH(dp, pdi_list, pd_link) {
270		if (dp->pd_handle == img->DeviceHandle) {
271			set_devdesc_currdev(&efipart_fddev, dp->pd_unit);
272			return (0);
273		}
274	}
275
276	/*
277	 * Try the device handle from our loaded image first.  If that
278	 * fails, use the device path from the loaded image and see if
279	 * any of the nodes in that path match one of the enumerated
280	 * handles.
281	 */
282	if (efi_handle_lookup(img->DeviceHandle, &dev, &unit, &extra) == 0) {
283		set_devdesc_currdev(dev, unit);
284		return (0);
285	}
286
287	copy = NULL;
288	devpath = efi_lookup_image_devpath(IH);
289	while (devpath != NULL) {
290		h = efi_devpath_handle(devpath);
291		if (h == NULL)
292			break;
293
294		free(copy);
295		copy = NULL;
296
297		if (efi_handle_lookup(h, &dev, &unit, &extra) == 0) {
298			set_devdesc_currdev(dev, unit);
299			return (0);
300		}
301
302		devpath = efi_lookup_devpath(h);
303		if (devpath != NULL) {
304			copy = efi_devpath_trim(devpath);
305			devpath = copy;
306		}
307	}
308	free(copy);
309
310	return (ENOENT);
311}
312
313EFI_STATUS
314main(int argc, CHAR16 *argv[])
315{
316	char var[128];
317	EFI_GUID *guid;
318	int i, j, vargood, howto;
319	UINTN k;
320	int has_kbd;
321#if !defined(__arm__)
322	char buf[40];
323#endif
324
325	archsw.arch_autoload = efi_autoload;
326	archsw.arch_getdev = efi_getdev;
327	archsw.arch_copyin = efi_copyin;
328	archsw.arch_copyout = efi_copyout;
329	archsw.arch_readin = efi_readin;
330#ifdef EFI_ZFS_BOOT
331	/* Note this needs to be set before ZFS init. */
332	archsw.arch_zfs_probe = efi_zfs_probe;
333#endif
334
335        /* Get our loaded image protocol interface structure. */
336	BS->HandleProtocol(IH, &imgid, (VOID**)&img);
337
338	/* Init the time source */
339	efi_time_init();
340
341	has_kbd = has_keyboard();
342
343	/*
344	 * XXX Chicken-and-egg problem; we want to have console output
345	 * early, but some console attributes may depend on reading from
346	 * eg. the boot device, which we can't do yet.  We can use
347	 * printf() etc. once this is done.
348	 */
349	cons_probe();
350
351	/*
352	 * Initialise the block cache. Set the upper limit.
353	 */
354	bcache_init(32768, 512);
355
356	/*
357	 * Parse the args to set the console settings, etc
358	 * boot1.efi passes these in, if it can read /boot.config or /boot/config
359	 * or iPXE may be setup to pass these in.
360	 *
361	 * Loop through the args, and for each one that contains an '=' that is
362	 * not the first character, add it to the environment.  This allows
363	 * loader and kernel env vars to be passed on the command line.  Convert
364	 * args from UCS-2 to ASCII (16 to 8 bit) as they are copied.
365	 */
366	howto = 0;
367	for (i = 1; i < argc; i++) {
368		if (argv[i][0] == '-') {
369			for (j = 1; argv[i][j] != 0; j++) {
370				int ch;
371
372				ch = argv[i][j];
373				switch (ch) {
374				case 'a':
375					howto |= RB_ASKNAME;
376					break;
377				case 'd':
378					howto |= RB_KDB;
379					break;
380				case 'D':
381					howto |= RB_MULTIPLE;
382					break;
383				case 'h':
384					howto |= RB_SERIAL;
385					break;
386				case 'm':
387					howto |= RB_MUTE;
388					break;
389				case 'p':
390					howto |= RB_PAUSE;
391					break;
392				case 'P':
393					if (!has_kbd)
394						howto |= RB_SERIAL | RB_MULTIPLE;
395					break;
396				case 'r':
397					howto |= RB_DFLTROOT;
398					break;
399				case 's':
400					howto |= RB_SINGLE;
401					break;
402				case 'S':
403					if (argv[i][j + 1] == 0) {
404						if (i + 1 == argc) {
405							setenv("comconsole_speed", "115200", 1);
406						} else {
407							cpy16to8(&argv[i + 1][0], var,
408							    sizeof(var));
409							setenv("comconsole_speed", var, 1);
410						}
411						i++;
412						break;
413					} else {
414						cpy16to8(&argv[i][j + 1], var,
415						    sizeof(var));
416						setenv("comconsole_speed", var, 1);
417						break;
418					}
419				case 'v':
420					howto |= RB_VERBOSE;
421					break;
422				}
423			}
424		} else {
425			vargood = 0;
426			for (j = 0; argv[i][j] != 0; j++) {
427				if (j == sizeof(var)) {
428					vargood = 0;
429					break;
430				}
431				if (j > 0 && argv[i][j] == '=')
432					vargood = 1;
433				var[j] = (char)argv[i][j];
434			}
435			if (vargood) {
436				var[j] = 0;
437				putenv(var);
438			}
439		}
440	}
441	for (i = 0; howto_names[i].ev != NULL; i++)
442		if (howto & howto_names[i].mask)
443			setenv(howto_names[i].ev, "YES", 1);
444	if (howto & RB_MULTIPLE) {
445		if (howto & RB_SERIAL)
446			setenv("console", "comconsole efi" , 1);
447		else
448			setenv("console", "efi comconsole" , 1);
449	} else if (howto & RB_SERIAL) {
450		setenv("console", "comconsole" , 1);
451	}
452
453	if (efi_copy_init()) {
454		printf("failed to allocate staging area\n");
455		return (EFI_BUFFER_TOO_SMALL);
456	}
457
458	/*
459	 * Scan the BLOCK IO MEDIA handles then
460	 * march through the device switch probing for things.
461	 */
462	if ((i = efipart_inithandles()) == 0) {
463		for (i = 0; devsw[i] != NULL; i++)
464			if (devsw[i]->dv_init != NULL)
465				(devsw[i]->dv_init)();
466	} else
467		printf("efipart_inithandles failed %d, expect failures", i);
468
469	printf("Command line arguments:");
470	for (i = 0; i < argc; i++)
471		printf(" %S", argv[i]);
472	printf("\n");
473
474	printf("Image base: 0x%lx\n", (u_long)img->ImageBase);
475	printf("EFI version: %d.%02d\n", ST->Hdr.Revision >> 16,
476	    ST->Hdr.Revision & 0xffff);
477	printf("EFI Firmware: %S (rev %d.%02d)\n", ST->FirmwareVendor,
478	    ST->FirmwareRevision >> 16, ST->FirmwareRevision & 0xffff);
479
480	printf("\n%s", bootprog_info);
481
482	/*
483	 * Disable the watchdog timer. By default the boot manager sets
484	 * the timer to 5 minutes before invoking a boot option. If we
485	 * want to return to the boot manager, we have to disable the
486	 * watchdog timer and since we're an interactive program, we don't
487	 * want to wait until the user types "quit". The timer may have
488	 * fired by then. We don't care if this fails. It does not prevent
489	 * normal functioning in any way...
490	 */
491	BS->SetWatchdogTimer(0, 0, 0, NULL);
492
493	if (find_currdev(img) != 0)
494		return (EFI_NOT_FOUND);
495
496	efi_init_environment();
497	setenv("LINES", "24", 1);	/* optional */
498
499	for (k = 0; k < ST->NumberOfTableEntries; k++) {
500		guid = &ST->ConfigurationTable[k].VendorGuid;
501#if !defined(__arm__)
502		if (!memcmp(guid, &smbios, sizeof(EFI_GUID))) {
503			snprintf(buf, sizeof(buf), "%p",
504			    ST->ConfigurationTable[k].VendorTable);
505			setenv("hint.smbios.0.mem", buf, 1);
506			smbios_detect(ST->ConfigurationTable[k].VendorTable);
507			break;
508		}
509#endif
510	}
511
512	interact();			/* doesn't return */
513
514	return (EFI_SUCCESS);		/* keep compiler happy */
515}
516
517COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot);
518
519static int
520command_reboot(int argc, char *argv[])
521{
522	int i;
523
524	for (i = 0; devsw[i] != NULL; ++i)
525		if (devsw[i]->dv_cleanup != NULL)
526			(devsw[i]->dv_cleanup)();
527
528	RS->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL);
529
530	/* NOTREACHED */
531	return (CMD_ERROR);
532}
533
534COMMAND_SET(quit, "quit", "exit the loader", command_quit);
535
536static int
537command_quit(int argc, char *argv[])
538{
539	exit(0);
540	return (CMD_OK);
541}
542
543COMMAND_SET(memmap, "memmap", "print memory map", command_memmap);
544
545static int
546command_memmap(int argc, char *argv[])
547{
548	UINTN sz;
549	EFI_MEMORY_DESCRIPTOR *map, *p;
550	UINTN key, dsz;
551	UINT32 dver;
552	EFI_STATUS status;
553	int i, ndesc;
554	char line[80];
555	static char *types[] = {
556	    "Reserved",
557	    "LoaderCode",
558	    "LoaderData",
559	    "BootServicesCode",
560	    "BootServicesData",
561	    "RuntimeServicesCode",
562	    "RuntimeServicesData",
563	    "ConventionalMemory",
564	    "UnusableMemory",
565	    "ACPIReclaimMemory",
566	    "ACPIMemoryNVS",
567	    "MemoryMappedIO",
568	    "MemoryMappedIOPortSpace",
569	    "PalCode"
570	};
571
572	sz = 0;
573	status = BS->GetMemoryMap(&sz, 0, &key, &dsz, &dver);
574	if (status != EFI_BUFFER_TOO_SMALL) {
575		printf("Can't determine memory map size\n");
576		return (CMD_ERROR);
577	}
578	map = malloc(sz);
579	status = BS->GetMemoryMap(&sz, map, &key, &dsz, &dver);
580	if (EFI_ERROR(status)) {
581		printf("Can't read memory map\n");
582		return (CMD_ERROR);
583	}
584
585	ndesc = sz / dsz;
586	snprintf(line, sizeof(line), "%23s %12s %12s %8s %4s\n",
587	    "Type", "Physical", "Virtual", "#Pages", "Attr");
588	pager_open();
589	if (pager_output(line)) {
590		pager_close();
591		return (CMD_OK);
592	}
593
594	for (i = 0, p = map; i < ndesc;
595	     i++, p = NextMemoryDescriptor(p, dsz)) {
596		printf("%23s %012jx %012jx %08jx ", types[p->Type],
597		    (uintmax_t)p->PhysicalStart, (uintmax_t)p->VirtualStart,
598		    (uintmax_t)p->NumberOfPages);
599		if (p->Attribute & EFI_MEMORY_UC)
600			printf("UC ");
601		if (p->Attribute & EFI_MEMORY_WC)
602			printf("WC ");
603		if (p->Attribute & EFI_MEMORY_WT)
604			printf("WT ");
605		if (p->Attribute & EFI_MEMORY_WB)
606			printf("WB ");
607		if (p->Attribute & EFI_MEMORY_UCE)
608			printf("UCE ");
609		if (p->Attribute & EFI_MEMORY_WP)
610			printf("WP ");
611		if (p->Attribute & EFI_MEMORY_RP)
612			printf("RP ");
613		if (p->Attribute & EFI_MEMORY_XP)
614			printf("XP ");
615		if (pager_output("\n"))
616			break;
617	}
618
619	pager_close();
620	return (CMD_OK);
621}
622
623COMMAND_SET(configuration, "configuration", "print configuration tables",
624    command_configuration);
625
626static const char *
627guid_to_string(EFI_GUID *guid)
628{
629	static char buf[40];
630
631	sprintf(buf, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
632	    guid->Data1, guid->Data2, guid->Data3, guid->Data4[0],
633	    guid->Data4[1], guid->Data4[2], guid->Data4[3], guid->Data4[4],
634	    guid->Data4[5], guid->Data4[6], guid->Data4[7]);
635	return (buf);
636}
637
638static int
639command_configuration(int argc, char *argv[])
640{
641	char line[80];
642	UINTN i;
643
644	snprintf(line, sizeof(line), "NumberOfTableEntries=%lu\n",
645		(unsigned long)ST->NumberOfTableEntries);
646	pager_open();
647	if (pager_output(line)) {
648		pager_close();
649		return (CMD_OK);
650	}
651
652	for (i = 0; i < ST->NumberOfTableEntries; i++) {
653		EFI_GUID *guid;
654
655		printf("  ");
656		guid = &ST->ConfigurationTable[i].VendorGuid;
657		if (!memcmp(guid, &mps, sizeof(EFI_GUID)))
658			printf("MPS Table");
659		else if (!memcmp(guid, &acpi, sizeof(EFI_GUID)))
660			printf("ACPI Table");
661		else if (!memcmp(guid, &acpi20, sizeof(EFI_GUID)))
662			printf("ACPI 2.0 Table");
663		else if (!memcmp(guid, &smbios, sizeof(EFI_GUID)))
664			printf("SMBIOS Table %p",
665			    ST->ConfigurationTable[i].VendorTable);
666		else if (!memcmp(guid, &smbios3, sizeof(EFI_GUID)))
667			printf("SMBIOS3 Table");
668		else if (!memcmp(guid, &dxe, sizeof(EFI_GUID)))
669			printf("DXE Table");
670		else if (!memcmp(guid, &hoblist, sizeof(EFI_GUID)))
671			printf("HOB List Table");
672		else if (!memcmp(guid, &lzmadecomp, sizeof(EFI_GUID)))
673			printf("LZMA Compression");
674		else if (!memcmp(guid, &mpcore, sizeof(EFI_GUID)))
675			printf("ARM MpCore Information Table");
676		else if (!memcmp(guid, &esrt, sizeof(EFI_GUID)))
677			printf("ESRT Table");
678		else if (!memcmp(guid, &memtype, sizeof(EFI_GUID)))
679			printf("Memory Type Information Table");
680		else if (!memcmp(guid, &debugimg, sizeof(EFI_GUID)))
681			printf("Debug Image Info Table");
682		else if (!memcmp(guid, &fdtdtb, sizeof(EFI_GUID)))
683			printf("FDT Table");
684		else
685			printf("Unknown Table (%s)", guid_to_string(guid));
686		snprintf(line, sizeof(line), " at %p\n",
687		    ST->ConfigurationTable[i].VendorTable);
688		if (pager_output(line))
689			break;
690	}
691
692	pager_close();
693	return (CMD_OK);
694}
695
696
697COMMAND_SET(mode, "mode", "change or display EFI text modes", command_mode);
698
699static int
700command_mode(int argc, char *argv[])
701{
702	UINTN cols, rows;
703	unsigned int mode;
704	int i;
705	char *cp;
706	char rowenv[8];
707	EFI_STATUS status;
708	SIMPLE_TEXT_OUTPUT_INTERFACE *conout;
709	extern void HO(void);
710
711	conout = ST->ConOut;
712
713	if (argc > 1) {
714		mode = strtol(argv[1], &cp, 0);
715		if (cp[0] != '\0') {
716			printf("Invalid mode\n");
717			return (CMD_ERROR);
718		}
719		status = conout->QueryMode(conout, mode, &cols, &rows);
720		if (EFI_ERROR(status)) {
721			printf("invalid mode %d\n", mode);
722			return (CMD_ERROR);
723		}
724		status = conout->SetMode(conout, mode);
725		if (EFI_ERROR(status)) {
726			printf("couldn't set mode %d\n", mode);
727			return (CMD_ERROR);
728		}
729		sprintf(rowenv, "%u", (unsigned)rows);
730		setenv("LINES", rowenv, 1);
731		HO();		/* set cursor */
732		return (CMD_OK);
733	}
734
735	printf("Current mode: %d\n", conout->Mode->Mode);
736	for (i = 0; i <= conout->Mode->MaxMode; i++) {
737		status = conout->QueryMode(conout, i, &cols, &rows);
738		if (EFI_ERROR(status))
739			continue;
740		printf("Mode %d: %u columns, %u rows\n", i, (unsigned)cols,
741		    (unsigned)rows);
742	}
743
744	if (i != 0)
745		printf("Select a mode with the command \"mode <number>\"\n");
746
747	return (CMD_OK);
748}
749
750#ifdef EFI_ZFS_BOOT
751COMMAND_SET(lszfs, "lszfs", "list child datasets of a zfs dataset",
752    command_lszfs);
753
754static int
755command_lszfs(int argc, char *argv[])
756{
757	int err;
758
759	if (argc != 2) {
760		command_errmsg = "wrong number of arguments";
761		return (CMD_ERROR);
762	}
763
764	err = zfs_list(argv[1]);
765	if (err != 0) {
766		command_errmsg = strerror(err);
767		return (CMD_ERROR);
768	}
769	return (CMD_OK);
770}
771
772COMMAND_SET(reloadbe, "reloadbe", "refresh the list of ZFS Boot Environments",
773	    command_reloadbe);
774
775static int
776command_reloadbe(int argc, char *argv[])
777{
778	int err;
779	char *root;
780
781	if (argc > 2) {
782		command_errmsg = "wrong number of arguments";
783		return (CMD_ERROR);
784	}
785
786	if (argc == 2) {
787		err = zfs_bootenv(argv[1]);
788	} else {
789		root = getenv("zfs_be_root");
790		if (root == NULL) {
791			return (CMD_OK);
792		}
793		err = zfs_bootenv(root);
794	}
795
796	if (err != 0) {
797		command_errmsg = strerror(err);
798		return (CMD_ERROR);
799	}
800
801	return (CMD_OK);
802}
803#endif
804
805#ifdef LOADER_FDT_SUPPORT
806extern int command_fdt_internal(int argc, char *argv[]);
807
808/*
809 * Since proper fdt command handling function is defined in fdt_loader_cmd.c,
810 * and declaring it as extern is in contradiction with COMMAND_SET() macro
811 * (which uses static pointer), we're defining wrapper function, which
812 * calls the proper fdt handling routine.
813 */
814static int
815command_fdt(int argc, char *argv[])
816{
817
818	return (command_fdt_internal(argc, argv));
819}
820
821COMMAND_SET(fdt, "fdt", "flattened device tree handling", command_fdt);
822#endif
823
824/*
825 * Chain load another efi loader.
826 */
827static int
828command_chain(int argc, char *argv[])
829{
830	EFI_GUID LoadedImageGUID = LOADED_IMAGE_PROTOCOL;
831	EFI_HANDLE loaderhandle;
832	EFI_LOADED_IMAGE *loaded_image;
833	EFI_STATUS status;
834	struct stat st;
835	struct devdesc *dev;
836	char *name, *path;
837	void *buf;
838	int fd;
839
840	if (argc < 2) {
841		command_errmsg = "wrong number of arguments";
842		return (CMD_ERROR);
843	}
844
845	name = argv[1];
846
847	if ((fd = open(name, O_RDONLY)) < 0) {
848		command_errmsg = "no such file";
849		return (CMD_ERROR);
850	}
851
852	if (fstat(fd, &st) < -1) {
853		command_errmsg = "stat failed";
854		close(fd);
855		return (CMD_ERROR);
856	}
857
858	status = BS->AllocatePool(EfiLoaderCode, (UINTN)st.st_size, &buf);
859	if (status != EFI_SUCCESS) {
860		command_errmsg = "failed to allocate buffer";
861		close(fd);
862		return (CMD_ERROR);
863	}
864	if (read(fd, buf, st.st_size) != st.st_size) {
865		command_errmsg = "error while reading the file";
866		(void)BS->FreePool(buf);
867		close(fd);
868		return (CMD_ERROR);
869	}
870	close(fd);
871	status = BS->LoadImage(FALSE, IH, NULL, buf, st.st_size, &loaderhandle);
872	(void)BS->FreePool(buf);
873	if (status != EFI_SUCCESS) {
874		command_errmsg = "LoadImage failed";
875		return (CMD_ERROR);
876	}
877	status = BS->HandleProtocol(loaderhandle, &LoadedImageGUID,
878	    (void **)&loaded_image);
879
880	if (argc > 2) {
881		int i, len = 0;
882		CHAR16 *argp;
883
884		for (i = 2; i < argc; i++)
885			len += strlen(argv[i]) + 1;
886
887		len *= sizeof (*argp);
888		loaded_image->LoadOptions = argp = malloc (len);
889		loaded_image->LoadOptionsSize = len;
890		for (i = 2; i < argc; i++) {
891			char *ptr = argv[i];
892			while (*ptr)
893				*(argp++) = *(ptr++);
894			*(argp++) = ' ';
895		}
896		*(--argv) = 0;
897	}
898
899	if (efi_getdev((void **)&dev, name, (const char **)&path) == 0) {
900#ifdef EFI_ZFS_BOOT
901		struct zfs_devdesc *z_dev;
902#endif
903		struct disk_devdesc *d_dev;
904		pdinfo_t *hd, *pd;
905
906		switch (dev->d_type) {
907#ifdef EFI_ZFS_BOOT
908		case DEVT_ZFS:
909			z_dev = (struct zfs_devdesc *)dev;
910			loaded_image->DeviceHandle =
911			    efizfs_get_handle_by_guid(z_dev->pool_guid);
912			break;
913#endif
914		case DEVT_NET:
915			loaded_image->DeviceHandle =
916			    efi_find_handle(dev->d_dev, dev->d_unit);
917			break;
918		default:
919			hd = efiblk_get_pdinfo(dev);
920			if (STAILQ_EMPTY(&hd->pd_part)) {
921				loaded_image->DeviceHandle = hd->pd_handle;
922				break;
923			}
924			d_dev = (struct disk_devdesc *)dev;
925			STAILQ_FOREACH(pd, &hd->pd_part, pd_link) {
926				/*
927				 * d_partition should be 255
928				 */
929				if (pd->pd_unit == (uint32_t)d_dev->d_slice) {
930					loaded_image->DeviceHandle =
931					    pd->pd_handle;
932					break;
933				}
934			}
935			break;
936		}
937	}
938
939	dev_cleanup();
940	status = BS->StartImage(loaderhandle, NULL, NULL);
941	if (status != EFI_SUCCESS) {
942		command_errmsg = "StartImage failed";
943		free(loaded_image->LoadOptions);
944		loaded_image->LoadOptions = NULL;
945		status = BS->UnloadImage(loaded_image);
946		return (CMD_ERROR);
947	}
948
949	return (CMD_ERROR);	/* not reached */
950}
951
952COMMAND_SET(chain, "chain", "chain load file", command_chain);
953