xref: /titanic_54/usr/src/boot/sys/boot/efi/loader/main.c (revision cf7dd858456bdf14e1356d8b4338c2e9b5fadd58)
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 
30 #include <sys/disk.h>
31 #include <sys/param.h>
32 #include <sys/reboot.h>
33 #include <sys/boot.h>
34 #include <stand.h>
35 #include <string.h>
36 #include <setjmp.h>
37 
38 #include <efi.h>
39 #include <efilib.h>
40 #include <efigpt.h>
41 
42 #include <bootstrap.h>
43 #include <smbios.h>
44 
45 #ifdef EFI_ZFS_BOOT
46 #include <libzfs.h>
47 #endif
48 
49 #include "loader_efi.h"
50 
51 extern char bootprog_info[];
52 
53 struct arch_switch archsw;	/* MI/MD interface boundary */
54 
55 EFI_GUID acpi = ACPI_TABLE_GUID;
56 EFI_GUID acpi20 = ACPI_20_TABLE_GUID;
57 EFI_GUID devid = DEVICE_PATH_PROTOCOL;
58 EFI_GUID imgid = LOADED_IMAGE_PROTOCOL;
59 EFI_GUID mps = MPS_TABLE_GUID;
60 EFI_GUID netid = EFI_SIMPLE_NETWORK_PROTOCOL;
61 EFI_GUID smbios = SMBIOS_TABLE_GUID;
62 EFI_GUID smbios3 = SMBIOS3_TABLE_GUID;
63 EFI_GUID dxe = DXE_SERVICES_TABLE_GUID;
64 EFI_GUID hoblist = HOB_LIST_TABLE_GUID;
65 EFI_GUID memtype = MEMORY_TYPE_INFORMATION_TABLE_GUID;
66 EFI_GUID debugimg = DEBUG_IMAGE_INFO_TABLE_GUID;
67 EFI_GUID fdtdtb = FDT_TABLE_GUID;
68 EFI_GUID inputid = SIMPLE_TEXT_INPUT_PROTOCOL;
69 EFI_GUID serial_io = SERIAL_IO_PROTOCOL;
70 
71 extern void acpi_detect(void);
72 void efi_serial_init(void);
73 #ifdef EFI_ZFS_BOOT
74 static void efi_zfs_probe(void);
75 #endif
76 
77 /*
78  * Need this because EFI uses UTF-16 unicode string constants, but we
79  * use UTF-8. We can't use printf due to the possibility of \0 and we
80  * don't support wide characters either.
81  */
82 static void
83 print_str16(const CHAR16 *str)
84 {
85 	int i;
86 
87 	for (i = 0; str[i]; i++)
88 		printf("%c", (char)str[i]);
89 }
90 
91 static void
92 cp16to8(const CHAR16 *src, char *dst, size_t len)
93 {
94 	size_t i;
95 
96 	for (i = 0; i < len && src[i]; i++)
97 		dst[i] = (char)src[i];
98 }
99 
100 static int
101 has_keyboard(void)
102 {
103 	EFI_STATUS status;
104 	EFI_DEVICE_PATH *path;
105 	EFI_HANDLE *hin, *hin_end, *walker;
106 	UINTN sz;
107 	int retval = 0;
108 
109 	/*
110 	 * Find all the handles that support the SIMPLE_TEXT_INPUT_PROTOCOL and
111 	 * do the typical dance to get the right sized buffer.
112 	 */
113 	sz = 0;
114 	hin = NULL;
115 	status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz, 0);
116 	if (status == EFI_BUFFER_TOO_SMALL) {
117 		hin = (EFI_HANDLE *)malloc(sz);
118 		status = BS->LocateHandle(ByProtocol, &inputid, 0, &sz,
119 		    hin);
120 		if (EFI_ERROR(status))
121 			free(hin);
122 	}
123 	if (EFI_ERROR(status))
124 		return retval;
125 
126 	/*
127 	 * Look at each of the handles. If it supports the device path protocol,
128 	 * use it to get the device path for this handle. Then see if that
129 	 * device path matches either the USB device path for keyboards or the
130 	 * legacy device path for keyboards.
131 	 */
132 	hin_end = &hin[sz / sizeof(*hin)];
133 	for (walker = hin; walker < hin_end; walker++) {
134 		status = BS->HandleProtocol(*walker, &devid, (VOID **)&path);
135 		if (EFI_ERROR(status))
136 			continue;
137 
138 		while (!IsDevicePathEnd(path)) {
139 			/*
140 			 * Check for the ACPI keyboard node. All PNP3xx nodes
141 			 * are keyboards of different flavors. Note: It is
142 			 * unclear of there's always a keyboard node when
143 			 * there's a keyboard controller, or if there's only one
144 			 * when a keyboard is detected at boot.
145 			 */
146 			if (DevicePathType(path) == ACPI_DEVICE_PATH &&
147 			    (DevicePathSubType(path) == ACPI_DP ||
148 				DevicePathSubType(path) == ACPI_EXTENDED_DP)) {
149 				ACPI_HID_DEVICE_PATH  *acpi;
150 
151 				acpi = (ACPI_HID_DEVICE_PATH *)(void *)path;
152 				if ((EISA_ID_TO_NUM(acpi->HID) & 0xff00) == 0x300 &&
153 				    (acpi->HID & 0xffff) == PNP_EISA_ID_CONST) {
154 					retval = 1;
155 					goto out;
156 				}
157 			/*
158 			 * Check for USB keyboard node, if present. Unlike a
159 			 * PS/2 keyboard, these definitely only appear when
160 			 * connected to the system.
161 			 */
162 			} else if (DevicePathType(path) == MESSAGING_DEVICE_PATH &&
163 			    DevicePathSubType(path) == MSG_USB_CLASS_DP) {
164 				USB_CLASS_DEVICE_PATH *usb;
165 
166 				usb = (USB_CLASS_DEVICE_PATH *)(void *)path;
167 				if (usb->DeviceClass == 3 && /* HID */
168 				    usb->DeviceSubClass == 1 && /* Boot devices */
169 				    usb->DeviceProtocol == 1) { /* Boot keyboards */
170 					retval = 1;
171 					goto out;
172 				}
173 			}
174 			path = NextDevicePathNode(path);
175 		}
176 	}
177 out:
178 	free(hin);
179 	return retval;
180 }
181 
182 static int
183 find_currdev(EFI_LOADED_IMAGE *img, struct devsw **dev, int *unit,
184     uint64_t *extra)
185 {
186 	EFI_DEVICE_PATH *devpath, *copy;
187 	EFI_HANDLE h;
188 
189 	/*
190 	 * Try the device handle from our loaded image first.  If that
191 	 * fails, use the device path from the loaded image and see if
192 	 * any of the nodes in that path match one of the enumerated
193 	 * handles.
194 	 */
195 	if (efi_handle_lookup(img->DeviceHandle, dev, unit, extra) == 0)
196 		return (0);
197 
198 	copy = NULL;
199 	devpath = efi_lookup_image_devpath(IH);
200 	while (devpath != NULL) {
201 		h = efi_devpath_handle(devpath);
202 		if (h == NULL)
203 			break;
204 
205 		free(copy);
206 		copy = NULL;
207 
208 		if (efi_handle_lookup(h, dev, unit, extra) == 0)
209 			return (0);
210 
211 		devpath = efi_lookup_devpath(h);
212 		if (devpath != NULL) {
213 			copy = efi_devpath_trim(devpath);
214 			devpath = copy;
215 		}
216 	}
217 	free(copy);
218 
219 	return (ENOENT);
220 }
221 
222 EFI_STATUS
223 main(int argc, CHAR16 *argv[])
224 {
225 	char var[128];
226 	EFI_LOADED_IMAGE *img;
227 	EFI_GUID *guid;
228 	int i, j, vargood, unit, howto;
229 	struct devsw *dev;
230 	uint64_t pool_guid;
231 	void *ptr;
232 	UINTN k;
233 	int has_kbd;
234 
235 	archsw.arch_autoload = efi_autoload;
236 	archsw.arch_getdev = efi_getdev;
237 	archsw.arch_copyin = efi_copyin;
238 	archsw.arch_copyout = efi_copyout;
239 	archsw.arch_readin = efi_readin;
240 #ifdef EFI_ZFS_BOOT
241 	/* Note this needs to be set before ZFS init. */
242 	archsw.arch_zfs_probe = efi_zfs_probe;
243 #endif
244 
245 	/* Init the time source */
246 	efi_time_init();
247 
248 	has_kbd = has_keyboard();
249 
250 	/*
251 	 * XXX Chicken-and-egg problem; we want to have console output
252 	 * early, but some console attributes may depend on reading from
253 	 * eg. the boot device, which we can't do yet.  We can use
254 	 * printf() etc. once this is done.
255 	 */
256 	cons_probe();
257 
258 	/*
259 	 * Initialise the block cache. Set the upper limit.
260 	 */
261 	bcache_init(32768, 512);
262 
263 	/*
264 	 * Parse the args to set the console settings, etc
265 	 * boot1.efi passes these in, if it can read /boot.config or /boot/config
266 	 * or iPXE may be setup to pass these in.
267 	 *
268 	 * Loop through the args, and for each one that contains an '=' that is
269 	 * not the first character, add it to the environment.  This allows
270 	 * loader and kernel env vars to be passed on the command line.  Convert
271 	 * args from UCS-2 to ASCII (16 to 8 bit) as they are copied.
272 	 */
273 	howto = 0;
274 	for (i = 1; i < argc; i++) {
275 		if (argv[i][0] == '-') {
276 			for (j = 1; argv[i][j] != 0; j++) {
277 				int ch;
278 
279 				ch = argv[i][j];
280 				switch (ch) {
281 				case 'a':
282 					howto |= RB_ASKNAME;
283 					break;
284 				case 'd':
285 					howto |= RB_KDB;
286 					break;
287 				case 'D':
288 					howto |= RB_MULTIPLE;
289 					break;
290 				case 'h':
291 					howto |= RB_SERIAL;
292 					break;
293 				case 'm':
294 					howto |= RB_MUTE;
295 					break;
296 				case 'p':
297 					howto |= RB_PAUSE;
298 					break;
299 				case 'P':
300 					if (!has_kbd)
301 						howto |= RB_SERIAL | RB_MULTIPLE;
302 					break;
303 				case 'r':
304 					howto |= RB_DFLTROOT;
305 					break;
306 				case 's':
307 					howto |= RB_SINGLE;
308 					break;
309 				case 'S':
310 					if (argv[i][j + 1] == 0) {
311 						if (i + 1 == argc) {
312 							setenv("comconsole_speed", "115200", 1);
313 						} else {
314 							cp16to8(&argv[i + 1][0], var,
315 							    sizeof(var));
316 							setenv("comconsole_speedspeed", var, 1);
317 						}
318 						i++;
319 						break;
320 					} else {
321 						cp16to8(&argv[i][j + 1], var,
322 						    sizeof(var));
323 						setenv("comconsole_speed", var, 1);
324 						break;
325 					}
326 				case 'v':
327 					howto |= RB_VERBOSE;
328 					break;
329 				}
330 			}
331 		} else {
332 			vargood = 0;
333 			for (j = 0; argv[i][j] != 0; j++) {
334 				if (j == sizeof(var)) {
335 					vargood = 0;
336 					break;
337 				}
338 				if (j > 0 && argv[i][j] == '=')
339 					vargood = 1;
340 				var[j] = (char)argv[i][j];
341 			}
342 			if (vargood) {
343 				var[j] = 0;
344 				putenv(var);
345 			}
346 		}
347 	}
348 	for (i = 0; howto_names[i].ev != NULL; i++)
349 		if (howto & howto_names[i].mask)
350 			setenv(howto_names[i].ev, "YES", 1);
351 	if (howto & RB_MULTIPLE) {
352 		if (howto & RB_SERIAL)
353 			setenv("console", "ttya text" , 1);
354 		else
355 			setenv("console", "text ttya" , 1);
356 	} else if (howto & RB_SERIAL) {
357 		setenv("console", "ttya" , 1);
358 	}
359 
360 	if (efi_copy_init()) {
361 		printf("failed to allocate staging area\n");
362 		return (EFI_BUFFER_TOO_SMALL);
363 	}
364 
365 	/*
366 	 * March through the device switch probing for things.
367 	 */
368 	for (i = 0; devsw[i] != NULL; i++)
369 		if (devsw[i]->dv_init != NULL)
370 			(devsw[i]->dv_init)();
371 
372 	/* Get our loaded image protocol interface structure. */
373 	BS->HandleProtocol(IH, &imgid, (VOID**)&img);
374 
375 	printf("Command line arguments:");
376 	for (i = 0; i < argc; i++) {
377 		printf(" ");
378 		print_str16(argv[i]);
379 	}
380 	printf("\n");
381 
382 	printf("Image base: 0x%lx\n", (u_long)img->ImageBase);
383 	printf("EFI version: %d.%02d\n", ST->Hdr.Revision >> 16,
384 	    ST->Hdr.Revision & 0xffff);
385 	printf("EFI Firmware: ");
386 	/* printf doesn't understand EFI Unicode */
387 	ST->ConOut->OutputString(ST->ConOut, ST->FirmwareVendor);
388 	printf(" (rev %d.%02d)\n", ST->FirmwareRevision >> 16,
389 	    ST->FirmwareRevision & 0xffff);
390 
391 	printf("\n%s", bootprog_info);
392 
393 	/*
394 	 * Disable the watchdog timer. By default the boot manager sets
395 	 * the timer to 5 minutes before invoking a boot option. If we
396 	 * want to return to the boot manager, we have to disable the
397 	 * watchdog timer and since we're an interactive program, we don't
398 	 * want to wait until the user types "quit". The timer may have
399 	 * fired by then. We don't care if this fails. It does not prevent
400 	 * normal functioning in any way...
401 	 */
402 	BS->SetWatchdogTimer(0, 0, 0, NULL);
403 
404 	if (find_currdev(img, &dev, &unit, &pool_guid) != 0)
405 		return (EFI_NOT_FOUND);
406 
407 	switch (dev->dv_type) {
408 #ifdef EFI_ZFS_BOOT
409 	case DEVT_ZFS: {
410 		struct zfs_devdesc currdev;
411 
412 		currdev.d_dev = dev;
413 		currdev.d_unit = unit;
414 		currdev.d_type = currdev.d_dev->dv_type;
415 		currdev.d_opendata = NULL;
416 		currdev.pool_guid = pool_guid;
417 		currdev.root_guid = 0;
418 		env_setenv("currdev", EV_VOLATILE, efi_fmtdev(&currdev),
419 			   efi_setcurrdev, env_nounset);
420 		env_setenv("loaddev", EV_VOLATILE, efi_fmtdev(&currdev), env_noset,
421 			   env_nounset);
422 #ifdef __FreeBSD__
423 		init_zfs_bootenv(zfs_fmtdev(&currdev));
424 #endif
425 		break;
426 	}
427 #endif
428 	default: {
429 		struct devdesc currdev;
430 
431 		currdev.d_dev = dev;
432 		currdev.d_unit = unit;
433 		currdev.d_opendata = NULL;
434 		currdev.d_type = currdev.d_dev->dv_type;
435 		env_setenv("currdev", EV_VOLATILE, efi_fmtdev(&currdev),
436 			   efi_setcurrdev, env_nounset);
437 		env_setenv("loaddev", EV_VOLATILE, efi_fmtdev(&currdev), env_noset,
438 			   env_nounset);
439 		break;
440 	}
441 	}
442 
443 	setenv("LINES", "24", 1);	/* optional */
444 	setenv("COLUMNS", "80", 1);	/* optional */
445 	setenv("ISADIR", "amd64", 1);	/* we only build 64bit */
446 	acpi_detect();
447 
448 	if ((ptr = efi_get_table(&smbios3)) == NULL)
449 		ptr = efi_get_table(&smbios);
450 	smbios_detect(ptr);
451 
452 	efi_serial_init();		/* detect and set up serial ports */
453 	interact(NULL);			/* doesn't return */
454 
455 	return (EFI_SUCCESS);		/* keep compiler happy */
456 }
457 
458 COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot);
459 
460 static int
461 command_reboot(int argc __attribute((unused)),
462     char *argv[] __attribute((unused)))
463 {
464 	int i;
465 
466 	for (i = 0; devsw[i] != NULL; ++i)
467 		if (devsw[i]->dv_cleanup != NULL)
468 			(devsw[i]->dv_cleanup)();
469 
470 	RS->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL);
471 
472 	/* NOTREACHED */
473 	return (CMD_ERROR);
474 }
475 
476 COMMAND_SET(memmap, "memmap", "print memory map", command_memmap);
477 
478 static int
479 command_memmap(int argc __attribute((unused)),
480     char *argv[] __attribute((unused)))
481 {
482 	UINTN sz;
483 	EFI_MEMORY_DESCRIPTOR *map, *p;
484 	UINTN key, dsz;
485 	UINT32 dver;
486 	EFI_STATUS status;
487 	int i, ndesc;
488 	int rv = 0;
489 	char line[80];
490 	static const char *types[] = {
491 	    "Reserved",
492 	    "LoaderCode",
493 	    "LoaderData",
494 	    "BootServicesCode",
495 	    "BootServicesData",
496 	    "RuntimeServicesCode",
497 	    "RuntimeServicesData",
498 	    "ConventionalMemory",
499 	    "UnusableMemory",
500 	    "ACPIReclaimMemory",
501 	    "ACPIMemoryNVS",
502 	    "MemoryMappedIO",
503 	    "MemoryMappedIOPortSpace",
504 	    "PalCode"
505 	};
506 
507 	sz = 0;
508 	status = BS->GetMemoryMap(&sz, 0, &key, &dsz, &dver);
509 	if (status != EFI_BUFFER_TOO_SMALL) {
510 		printf("Can't determine memory map size\n");
511 		return (CMD_ERROR);
512 	}
513 	map = malloc(sz);
514 	status = BS->GetMemoryMap(&sz, map, &key, &dsz, &dver);
515 	if (EFI_ERROR(status)) {
516 		printf("Can't read memory map\n");
517 		return (CMD_ERROR);
518 	}
519 
520 	ndesc = sz / dsz;
521 	snprintf(line, 80, "%23s %12s %12s %8s %4s\n",
522 	       "Type", "Physical", "Virtual", "#Pages", "Attr");
523 	pager_open();
524 	rv = pager_output(line);
525 	if (rv) {
526 		pager_close();
527 		return (CMD_OK);
528 	}
529 
530 	for (i = 0, p = map; i < ndesc;
531 	     i++, p = NextMemoryDescriptor(p, dsz)) {
532 		snprintf(line, 80, "%23s %012lx %012lx %08lx ",
533 		    types[p->Type],
534 		    p->PhysicalStart,
535 		    p->VirtualStart,
536 		    p->NumberOfPages);
537 		rv = pager_output(line);
538 		if (rv)
539 			break;
540 
541 		if (p->Attribute & EFI_MEMORY_UC)
542 			printf("UC ");
543 		if (p->Attribute & EFI_MEMORY_WC)
544 			printf("WC ");
545 		if (p->Attribute & EFI_MEMORY_WT)
546 			printf("WT ");
547 		if (p->Attribute & EFI_MEMORY_WB)
548 			printf("WB ");
549 		if (p->Attribute & EFI_MEMORY_UCE)
550 			printf("UCE ");
551 		if (p->Attribute & EFI_MEMORY_WP)
552 			printf("WP ");
553 		if (p->Attribute & EFI_MEMORY_RP)
554 			printf("RP ");
555 		if (p->Attribute & EFI_MEMORY_XP)
556 			printf("XP ");
557 		rv = pager_output("\n");
558 		if (rv)
559 			break;
560 	}
561 
562 	pager_close();
563 	return (CMD_OK);
564 }
565 
566 COMMAND_SET(configuration, "configuration", "print configuration tables",
567     command_configuration);
568 
569 static const char *
570 guid_to_string(EFI_GUID *guid)
571 {
572 	static char buf[40];
573 
574 	sprintf(buf, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
575 	    guid->Data1, guid->Data2, guid->Data3, guid->Data4[0],
576 	    guid->Data4[1], guid->Data4[2], guid->Data4[3], guid->Data4[4],
577 	    guid->Data4[5], guid->Data4[6], guid->Data4[7]);
578 	return (buf);
579 }
580 
581 static int
582 command_configuration(int argc __attribute((unused)),
583     char *argv[] __attribute((unused)))
584 {
585 	UINTN i;
586 
587 	printf("NumberOfTableEntries=%lu\n",
588 		(unsigned long)ST->NumberOfTableEntries);
589 	for (i = 0; i < ST->NumberOfTableEntries; i++) {
590 		EFI_GUID *guid;
591 
592 		printf("  ");
593 		guid = &ST->ConfigurationTable[i].VendorGuid;
594 		if (!memcmp(guid, &mps, sizeof(EFI_GUID)))
595 			printf("MPS Table");
596 		else if (!memcmp(guid, &acpi, sizeof(EFI_GUID)))
597 			printf("ACPI Table");
598 		else if (!memcmp(guid, &acpi20, sizeof(EFI_GUID)))
599 			printf("ACPI 2.0 Table");
600 		else if (!memcmp(guid, &smbios, sizeof(EFI_GUID)))
601 			printf("SMBIOS Table");
602 		else if (!memcmp(guid, &smbios3, sizeof(EFI_GUID)))
603 			printf("SMBIOS3 Table");
604 		else if (!memcmp(guid, &dxe, sizeof(EFI_GUID)))
605 			printf("DXE Table");
606 		else if (!memcmp(guid, &hoblist, sizeof(EFI_GUID)))
607 			printf("HOB List Table");
608 		else if (!memcmp(guid, &memtype, sizeof(EFI_GUID)))
609 			printf("Memory Type Information Table");
610 		else if (!memcmp(guid, &debugimg, sizeof(EFI_GUID)))
611 			printf("Debug Image Info Table");
612 		else if (!memcmp(guid, &fdtdtb, sizeof(EFI_GUID)))
613 			printf("FDT Table");
614 		else
615 			printf("Unknown Table (%s)", guid_to_string(guid));
616 		printf(" at %p\n", ST->ConfigurationTable[i].VendorTable);
617 	}
618 
619 	return (CMD_OK);
620 }
621 
622 
623 COMMAND_SET(mode, "mode", "change or display EFI text modes", command_mode);
624 
625 static int
626 command_mode(int argc, char *argv[])
627 {
628 	UINTN cols, rows;
629 	unsigned int mode;
630 	int i;
631 	char *cp;
632 	char rowenv[8];
633 	EFI_STATUS status;
634 	SIMPLE_TEXT_OUTPUT_INTERFACE *conout;
635 	extern void HO(void);
636 
637 	conout = ST->ConOut;
638 
639 	if (argc > 1) {
640 		mode = strtol(argv[1], &cp, 0);
641 		if (cp[0] != '\0') {
642 			printf("Invalid mode\n");
643 			return (CMD_ERROR);
644 		}
645 		status = conout->QueryMode(conout, mode, &cols, &rows);
646 		if (EFI_ERROR(status)) {
647 			printf("invalid mode %d\n", mode);
648 			return (CMD_ERROR);
649 		}
650 		status = conout->SetMode(conout, mode);
651 		if (EFI_ERROR(status)) {
652 			printf("couldn't set mode %d\n", mode);
653 			return (CMD_ERROR);
654 		}
655 		sprintf(rowenv, "%u", (unsigned)rows);
656 		setenv("LINES", rowenv, 1);
657 		sprintf(rowenv, "%u", (unsigned)cols);
658 		setenv("COLUMNS", rowenv, 1);
659 		HO();		/* set cursor */
660 		return (CMD_OK);
661 	}
662 
663 	printf("Current mode: %d\n", conout->Mode->Mode);
664 	for (i = 0; i <= conout->Mode->MaxMode; i++) {
665 		status = conout->QueryMode(conout, i, &cols, &rows);
666 		if (EFI_ERROR(status))
667 			continue;
668 		printf("Mode %d: %u columns, %u rows\n", i, (unsigned)cols,
669 		    (unsigned)rows);
670 	}
671 
672 	if (i != 0)
673 		printf("Select a mode with the command \"mode <number>\"\n");
674 
675 	return (CMD_OK);
676 }
677 
678 
679 COMMAND_SET(nvram, "nvram", "get NVRAM variables", command_nvram);
680 
681 static int
682 command_nvram(int argc __attribute((unused)),
683     char *argv[] __attribute((unused)))
684 {
685 	CHAR16 var[128];
686 	UINT8 *data;		/* value is in bytes */
687 	EFI_STATUS status;
688 	EFI_GUID varguid = { 0,0,0,{0,0,0,0,0,0,0,0} };
689 	UINTN varsz, datasz, i;
690 	UINT32 attr;
691 	SIMPLE_TEXT_OUTPUT_INTERFACE *conout;
692 
693 	conout = ST->ConOut;
694 
695 	pager_open();
696 	var[0] = 0;		/* Initiate the enumeration */
697 	varsz = 128;
698 
699 	for (status = RS->GetNextVariableName(&varsz, var, &varguid);
700 	    status != EFI_NOT_FOUND;
701 	    status = RS->GetNextVariableName(&varsz, var, &varguid)) {
702 
703 		/*
704 		 * as term emu is keeping track on cursor, use putchar().
705 		 */
706 		for (i = 0; var[i] != 0; i++)
707 			putchar(var[i]);
708 		varsz = 128;    /* GetNextVariableName() did change it. */
709 
710 		printf(": Attributes:");
711 		datasz = 0;
712 		status = RS->GetVariable(var, &varguid, &attr, &datasz, NULL);
713 		if ((data = malloc(datasz)) == NULL)
714 			break;
715 		status = RS->GetVariable(var, &varguid, &attr, &datasz, data);
716 		if (EFI_ERROR(status))
717 			printf("<error retrieving variable>");
718 		else {
719 			if (attr & EFI_VARIABLE_NON_VOLATILE)
720 				printf(" NV");
721 			if (attr & EFI_VARIABLE_BOOTSERVICE_ACCESS)
722 				printf(" BS");
723 			if (attr & EFI_VARIABLE_RUNTIME_ACCESS)
724 				printf(" RS");
725 			if (attr & EFI_VARIABLE_HARDWARE_ERROR_RECORD)
726 				printf(" HR");
727 			if (attr & EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS)
728 				printf(" AW");
729 			if (attr &
730 			    EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS)
731 				printf(" TW");
732 
733 			printf(": DataLength: %lld", (long long)datasz);
734 		}
735 		free(data);
736 		if (pager_output("\n"))
737 			break;
738 	}
739 
740 	pager_close();
741 	return (CMD_OK);
742 }
743 
744 struct protocol_name {
745 	EFI_GUID guid;
746 	const char *name;
747 } proto_names[] = {
748 	{ DEVICE_PATH_PROTOCOL, "device path" },
749 	{ BLOCK_IO_PROTOCOL, "block io" },
750 	{ DISK_IO_PROTOCOL, "disk io" },
751 	{ EFI_DISK_INFO_PROTOCOL_GUID, "disk info" },
752 	{ SIMPLE_FILE_SYSTEM_PROTOCOL, "simple fs" },
753 	{ LOAD_FILE_PROTOCOL, "load file" },
754 	{ DEVICE_IO_PROTOCOL, "device io" },
755 	{ UNICODE_COLLATION_PROTOCOL, "unicode collation" },
756 	{ EFI_UNICODE_COLLATION2_PROTOCOL_GUID, "unicode collation2" },
757 	{ EFI_SIMPLE_NETWORK_PROTOCOL, "simple network" },
758 	{ SIMPLE_TEXT_OUTPUT_PROTOCOL, "simple text output" },
759 	{ SIMPLE_TEXT_INPUT_PROTOCOL, "simple text input" },
760 	{ EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL_GUID, "simple text ex input" },
761 	{ EFI_CONSOLE_CONTROL_PROTOCOL_GUID, "console control" },
762 	{ EFI_CONSOLE_IN_DEVICE_GUID, "stdin" },
763 	{ EFI_CONSOLE_OUT_DEVICE_GUID, "stdout" },
764 	{ EFI_STANDARD_ERROR_DEVICE_GUID, "stderr" },
765 	{ EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID, "GOP" },
766 	{ EFI_UGA_DRAW_PROTOCOL_GUID, "UGA draw" },
767 	{ EFI_PXE_BASE_CODE_PROTOCOL, "PXE base code" },
768 	{ EFI_PXE_BASE_CODE_CALLBACK_PROTOCOL, "PXE base code callback" },
769 	{ SERIAL_IO_PROTOCOL, "serial io" },
770 	{ LOADED_IMAGE_PROTOCOL, "loaded image" },
771 	{ EFI_LOADED_IMAGE_DEVICE_PATH_PROTOCOL_GUID,
772 	    "loaded image device path" },
773 	{ EFI_ISA_IO_PROTOCOL_GUID, "ISA io" },
774 	{ EFI_IDE_CONTROLLER_INIT_PROTOCOL_GUID, "IDE controller init" },
775 	{ EFI_ISA_ACPI_PROTOCOL_GUID, "ISA ACPI" },
776 	{ EFI_PCI_IO_PROTOCOL_GUID, "PCI" },
777 	{ EFI_PCI_ROOT_IO_GUID, "PCI root" },
778 	{ EFI_PCI_ENUMERATION_COMPLETE_GUID, "PCI enumeration" },
779 	{ EFI_DRIVER_DIAGNOSTICS_PROTOCOL_GUID, "Driver diagnostics" },
780 	{ EFI_DRIVER_DIAGNOSTICS2_PROTOCOL_GUID, "Driver diagnostics2" },
781 	{ EFI_SIMPLE_POINTER_PROTOCOL_GUID, "simple pointer" },
782 	{ EFI_ABSOLUTE_POINTER_PROTOCOL_GUID, "absolute pointer" },
783 	{ EFI_VLAN_CONFIG_PROTOCOL_GUID, "VLAN config" },
784 	{ EFI_ARP_SERVICE_BINDING_PROTOCOL_GUID, "ARP service binding" },
785 	{ EFI_ARP_PROTOCOL_GUID, "ARP" },
786 	{ EFI_IP4_SERVICE_BINDING_PROTOCOL, "IPv4 service binding" },
787 	{ EFI_IP4_PROTOCOL, "IPv4" },
788 	{ EFI_IP4_CONFIG_PROTOCOL_GUID, "IPv4 config" },
789 	{ EFI_IP6_SERVICE_BINDING_PROTOCOL, "IPv6 service binding" },
790 	{ EFI_IP6_PROTOCOL, "IPv6" },
791 	{ EFI_IP6_CONFIG_PROTOCOL_GUID, "IPv6 config" },
792 	{ EFI_UDP4_PROTOCOL, "UDPv4" },
793 	{ EFI_UDP4_SERVICE_BINDING_PROTOCOL, "UDPv4 service binding" },
794 	{ EFI_UDP6_PROTOCOL, "UDPv6" },
795 	{ EFI_UDP6_SERVICE_BINDING_PROTOCOL, "UDPv6 service binding" },
796 	{ EFI_TCP4_PROTOCOL, "TCPv4" },
797 	{ EFI_TCP4_SERVICE_BINDING_PROTOCOL, "TCPv4 service binding" },
798 	{ EFI_TCP6_PROTOCOL, "TCPv6" },
799 	{ EFI_TCP6_SERVICE_BINDING_PROTOCOL, "TCPv6 service binding" },
800 	{ EFI_PART_TYPE_EFI_SYSTEM_PART_GUID, "EFI System partition" },
801 	{ EFI_PART_TYPE_LEGACY_MBR_GUID, "MBR legacy" },
802 	{ EFI_DEVICE_TREE_GUID, "device tree" },
803 	{ EFI_USB_IO_PROTOCOL_GUID, "USB io" },
804 	{ EFI_USB2_HC_PROTOCOL_GUID, "USB2 HC" },
805 	{ EFI_COMPONENT_NAME_PROTOCOL_GUID, "component name" },
806 	{ EFI_COMPONENT_NAME2_PROTOCOL_GUID, "component name2" },
807 	{ EFI_DRIVER_BINDING_PROTOCOL_GUID, "driver binding" },
808 	{ EFI_DRIVER_CONFIGURATION_PROTOCOL_GUID, "driver configuration" },
809 	{ EFI_DRIVER_CONFIGURATION2_PROTOCOL_GUID, "driver configuration2" },
810 	{ EFI_DECOMPRESS_PROTOCOL_GUID, "decompress" },
811 	{ EFI_EBC_INTERPRETER_PROTOCOL_GUID, "ebc interpreter" },
812 	{ EFI_NETWORK_INTERFACE_IDENTIFIER_PROTOCOL,
813 	    "network interface identifier" },
814 	{ EFI_NETWORK_INTERFACE_IDENTIFIER_PROTOCOL_31,
815 	    "network interface identifier_31" },
816 	{ EFI_MANAGED_NETWORK_SERVICE_BINDING_PROTOCOL_GUID,
817 	    "managed network service binding" },
818 	{ EFI_MANAGED_NETWORK_PROTOCOL_GUID, "managed network" },
819 	{ EFI_FORM_BROWSER2_PROTOCOL_GUID, "form browser" },
820 	{ EFI_HII_CONFIG_ROUTING_PROTOCOL_GUID, "HII config routing" },
821 	{ EFI_HII_DATABASE_PROTOCOL_GUID, "HII database" },
822 	{ EFI_HII_STRING_PROTOCOL_GUID, "HII string" },
823 	{ EFI_HII_IMAGE_PROTOCOL_GUID, "HII image" },
824 	{ EFI_HII_FONT_PROTOCOL_GUID, "HII font" },
825 	{ EFI_HII_CONFIGURATION_ACCESS_PROTOCOL_GUID, "HII config" },
826 	{ EFI_MTFTP4_SERVICE_BINDING_PROTOCOL_GUID, "MTFTP4 service binding" },
827 	{ EFI_MTFTP4_PROTOCOL_GUID, "MTFTP4" },
828 	{ EFI_MTFTP6_SERVICE_BINDING_PROTOCOL_GUID, "MTFTP6 service binding" },
829 	{ EFI_MTFTP6_PROTOCOL_GUID, "MTFTP6" },
830 	{ EFI_DHCP4_SERVICE_BINDING_PROTOCOL_GUID, "DHCP4 service binding" },
831 	{ EFI_DHCP4_PROTOCOL_GUID, "DHCP4" },
832 	{ EFI_DHCP6_SERVICE_BINDING_PROTOCOL_GUID, "DHCP6 service binding" },
833 	{ EFI_DHCP6_PROTOCOL_GUID, "DHCP6" },
834 	{ EFI_SCSI_IO_PROTOCOL_GUID, "SCSI io" },
835 	{ EFI_SCSI_PASS_THRU_PROTOCOL_GUID, "SCSI pass thru" },
836 	{ EFI_EXT_SCSI_PASS_THRU_PROTOCOL_GUID, "SCSI pass thru ext" },
837 	{ EFI_CAPSULE_ARCH_PROTOCOL_GUID, "Capsule arch" },
838 	{ EFI_MONOTONIC_COUNTER_ARCH_PROTOCOL_GUID, "monotonic counter arch" },
839 	{ EFI_REALTIME_CLOCK_ARCH_PROTOCOL_GUID, "realtime clock arch" },
840 	{ EFI_VARIABLE_ARCH_PROTOCOL_GUID, "variable arch" },
841 	{ EFI_VARIABLE_WRITE_ARCH_PROTOCOL_GUID, "variable write arch" },
842 	{ EFI_WATCHDOG_TIMER_ARCH_PROTOCOL_GUID, "watchdog timer arch" },
843 	{ EFI_MP_SERVICES_PROTOCOL_GUID, "MP services" },
844 	{ EFI_ACPI_SUPPORT_PROTOCOL_GUID, "ACPI support" },
845 	{ EFI_BDS_ARCH_PROTOCOL_GUID, "BDS arch" },
846 	{ EFI_METRONOME_ARCH_PROTOCOL_GUID, "metronome arch" },
847 	{ EFI_TIMER_ARCH_PROTOCOL_GUID, "timer arch" },
848 	{ EFI_DPC_PROTOCOL_GUID, "DPC" },
849 	{ EFI_PRINT2_PROTOCOL_GUID, "print2" },
850 	{ EFI_DEVICE_PATH_TO_TEXT_PROTOCOL_GUID, "device path to text" },
851 	{ EFI_RESET_ARCH_PROTOCOL_GUID, "reset arch" },
852 	{ EFI_CPU_ARCH_PROTOCOL_GUID, "CPU arch" },
853 	{ EFI_CPU_IO2_PROTOCOL_GUID, "CPU IO2" },
854 	{ EFI_LEGACY_8259_PROTOCOL_GUID, "Legacy 8259" },
855 	{ EFI_SECURITY_ARCH_PROTOCOL_GUID, "Security arch" },
856 	{ EFI_SECURITY2_ARCH_PROTOCOL_GUID, "Security2 arch" },
857 	{ EFI_RUNTIME_ARCH_PROTOCOL_GUID, "Runtime arch" },
858 	{ EFI_STATUS_CODE_RUNTIME_PROTOCOL_GUID, "status code runtime" },
859 	{ EFI_DATA_HUB_PROTOCOL_GUID, "data hub" },
860 	{ PCD_PROTOCOL_GUID, "PCD" },
861 	{ EFI_PCD_PROTOCOL_GUID, "EFI PCD" },
862 	{ EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL_GUID, "firmware volume block" },
863 	{ EFI_FIRMWARE_VOLUME2_PROTOCOL_GUID, "firmware volume2" },
864 	{ EFI_FIRMWARE_VOLUME_DISPATCH_PROTOCOL_GUID,
865 	    "firmware volume dispatch" },
866 	{ LZMA_COMPRESS_GUID, "lzma compress" },
867 	{ { 0,0,0,{0,0,0,0,0,0,0,0} }, NULL }	/* must be last entry */
868 };
869 
870 COMMAND_SET(lsefi, "lsefi", "list EFI handles", command_lsefi);
871 
872 static int
873 command_lsefi(int argc __attribute((unused)),
874     char *argv[] __attribute((unused)))
875 {
876 	EFI_HANDLE *buffer = NULL;
877 	EFI_HANDLE handle;
878 	UINTN bufsz = 0, i, j;
879 	EFI_STATUS status;
880 	int k, ret;
881 
882 	status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer);
883 	if (status != EFI_BUFFER_TOO_SMALL) {
884 		snprintf(command_errbuf, sizeof (command_errbuf),
885 		    "unexpected error: %lld", (long long)status);
886 		return (CMD_ERROR);
887 	}
888 	if ((buffer = malloc(bufsz)) == NULL) {
889 		sprintf(command_errbuf, "out of memory");
890 		return (CMD_ERROR);
891 	}
892 
893 	status = BS->LocateHandle(AllHandles, NULL, NULL, &bufsz, buffer);
894 	if (EFI_ERROR(status)) {
895 		free(buffer);
896 		snprintf(command_errbuf, sizeof (command_errbuf),
897 		    "LocateHandle() error: %lld", (long long)status);
898 		return (CMD_ERROR);
899 	}
900 
901 	pager_open();
902 	for (i = 0; i < (bufsz / sizeof (EFI_HANDLE)); i++) {
903 		UINTN nproto = 0;
904 		EFI_GUID **protocols = NULL;
905 
906 		handle = buffer[i];
907 		printf("Handle %p", handle);
908 		if (pager_output("\n"))
909 			break;
910 		/* device path */
911 
912 		status = BS->ProtocolsPerHandle(handle, &protocols, &nproto);
913 		if (EFI_ERROR(status)) {
914 			snprintf(command_errbuf, sizeof (command_errbuf),
915 			    "ProtocolsPerHandle() error: %lld",
916 			    (long long)status);
917 			continue;
918 		}
919 		for (j = 0; j < nproto; j++) {
920 			for (k = 0; proto_names[k].name != NULL; k++)
921 				if (memcmp(protocols[j], &proto_names[k].guid,
922 				    sizeof (proto_names[k].guid)) == 0)
923 					break;
924 			if (proto_names[k].name != NULL)
925 				printf("  %s", proto_names[k].name);
926 			else
927 				printf("  %s", guid_to_string(protocols[j]));
928 			ret = pager_output("\n");
929 			if (ret)
930 				break;
931 		}
932 		BS->FreePool(protocols);
933 		if (ret)
934 			break;
935 	}
936 	pager_close();
937 	free(buffer);
938 	return (CMD_OK);
939 }
940 
941 #ifdef EFI_ZFS_BOOT
942 COMMAND_SET(lszfs, "lszfs", "list child datasets of a zfs dataset",
943     command_lszfs);
944 
945 static int
946 command_lszfs(int argc, char *argv[])
947 {
948 	int err;
949 
950 	if (argc != 2) {
951 		command_errmsg = "wrong number of arguments";
952 		return (CMD_ERROR);
953 	}
954 
955 	err = zfs_list(argv[1]);
956 	if (err != 0) {
957 		command_errmsg = strerror(err);
958 		return (CMD_ERROR);
959 	}
960 	return (CMD_OK);
961 }
962 
963 #ifdef __FreeBSD__
964 COMMAND_SET(reloadbe, "reloadbe", "refresh the list of ZFS Boot Environments",
965 	    command_reloadbe);
966 
967 static int
968 command_reloadbe(int argc, char *argv[])
969 {
970 	int err;
971 	char *root;
972 
973 	if (argc > 2) {
974 		command_errmsg = "wrong number of arguments";
975 		return (CMD_ERROR);
976 	}
977 
978 	if (argc == 2) {
979 		err = zfs_bootenv(argv[1]);
980 	} else {
981 		root = getenv("zfs_be_root");
982 		if (root == NULL) {
983 			return (CMD_OK);
984 		}
985 		err = zfs_bootenv(root);
986 	}
987 
988 	if (err != 0) {
989 		command_errmsg = strerror(err);
990 		return (CMD_ERROR);
991 	}
992 
993 	return (CMD_OK);
994 }
995 #endif /* __FreeBSD__ */
996 #endif
997 
998 void
999 efi_serial_init(void)
1000 {
1001 	EFI_HANDLE *buffer = NULL;
1002 	UINTN bufsz = 0, i;
1003 	EFI_STATUS status;
1004 	int serial = 0;
1005 
1006 	/*
1007 	 * get buffer size
1008 	 */
1009 	status = BS->LocateHandle(ByProtocol, &serial_io, NULL, &bufsz, buffer);
1010 	if (status != EFI_BUFFER_TOO_SMALL) {
1011 		snprintf(command_errbuf, sizeof (command_errbuf),
1012 		    "unexpected error: %lld", (long long)status);
1013 		return;
1014 	}
1015 	if ((buffer = malloc(bufsz)) == NULL) {
1016 		sprintf(command_errbuf, "out of memory");
1017 		return;
1018 	}
1019 
1020 	/*
1021 	 * get handle array
1022 	 */
1023 	status = BS->LocateHandle(ByProtocol, &serial_io, NULL, &bufsz, buffer);
1024 	if (EFI_ERROR(status)) {
1025 		free(buffer);
1026 		snprintf(command_errbuf, sizeof (command_errbuf),
1027 		    "LocateHandle() error: %lld", (long long)status);
1028 		return;
1029 	}
1030 
1031 	for (i = 0; i < (bufsz / sizeof (EFI_HANDLE)); i++) {
1032 		SERIAL_IO_INTERFACE *sio;
1033 		status = BS->OpenProtocol(buffer[i], &serial_io, (void**)&sio,
1034 		    IH, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL);
1035 		if (EFI_ERROR(status)) {
1036 			snprintf(command_errbuf, sizeof (command_errbuf),
1037 			    "OpenProtocol() error: %lld", (long long)status);
1038 		}
1039 		printf("serial# %d\n", serial++);
1040 	}
1041 
1042 	free(buffer);
1043 }
1044 
1045 #ifdef LOADER_FDT_SUPPORT
1046 extern int command_fdt_internal(int argc, char *argv[]);
1047 
1048 /*
1049  * Since proper fdt command handling function is defined in fdt_loader_cmd.c,
1050  * and declaring it as extern is in contradiction with COMMAND_SET() macro
1051  * (which uses static pointer), we're defining wrapper function, which
1052  * calls the proper fdt handling routine.
1053  */
1054 static int
1055 command_fdt(int argc, char *argv[])
1056 {
1057 	return (command_fdt_internal(argc, argv));
1058 }
1059 
1060 COMMAND_SET(fdt, "fdt", "flattened device tree handling", command_fdt);
1061 #endif
1062 
1063 #ifdef EFI_ZFS_BOOT
1064 static void
1065 efi_zfs_probe(void)
1066 {
1067 	EFI_HANDLE h;
1068 	u_int unit;
1069 	int i;
1070 	char dname[SPECNAMELEN + 1];
1071 	uint64_t guid;
1072 
1073 	unit = 0;
1074 	h = efi_find_handle(&efipart_dev, 0);
1075 	for (i = 0; h != NULL; h = efi_find_handle(&efipart_dev, ++i)) {
1076 		snprintf(dname, sizeof(dname), "%s%d:", efipart_dev.dv_name, i);
1077 		if (zfs_probe_dev(dname, &guid) == 0)
1078 			(void)efi_handle_update_dev(h, &zfs_dev, unit++, guid);
1079 	}
1080 }
1081 
1082 uint64_t
1083 ldi_get_size(void *priv)
1084 {
1085 	int fd = (uintptr_t) priv;
1086 	uint64_t size;
1087 
1088 	ioctl(fd, DIOCGMEDIASIZE, &size);
1089 	return (size);
1090 }
1091 #endif
1092