main.c revision 294999
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/10/sys/boot/efi/loader/main.c 294999 2016-01-28 17:24:40Z smh $");
30
31#include <sys/param.h>
32#include <stand.h>
33#include <string.h>
34#include <setjmp.h>
35
36#include <efi.h>
37#include <efilib.h>
38
39#include <bootstrap.h>
40#include <smbios.h>
41
42#ifdef EFI_ZFS_BOOT
43#include <libzfs.h>
44#endif
45
46#include "loader_efi.h"
47
48extern char bootprog_name[];
49extern char bootprog_rev[];
50extern char bootprog_date[];
51extern char bootprog_maker[];
52
53struct arch_switch archsw;	/* MI/MD interface boundary */
54
55EFI_GUID acpi = ACPI_TABLE_GUID;
56EFI_GUID acpi20 = ACPI_20_TABLE_GUID;
57EFI_GUID devid = DEVICE_PATH_PROTOCOL;
58EFI_GUID imgid = LOADED_IMAGE_PROTOCOL;
59EFI_GUID mps = MPS_TABLE_GUID;
60EFI_GUID netid = EFI_SIMPLE_NETWORK_PROTOCOL;
61EFI_GUID smbios = SMBIOS_TABLE_GUID;
62EFI_GUID dxe = DXE_SERVICES_TABLE_GUID;
63EFI_GUID hoblist = HOB_LIST_TABLE_GUID;
64EFI_GUID memtype = MEMORY_TYPE_INFORMATION_TABLE_GUID;
65EFI_GUID debugimg = DEBUG_IMAGE_INFO_TABLE_GUID;
66
67#ifdef EFI_ZFS_BOOT
68static void efi_zfs_probe(void);
69#endif
70
71/*
72 * Need this because EFI uses UTF-16 unicode string constants, but we
73 * use UTF-8. We can't use printf due to the possiblity of \0 and we
74 * don't support support wide characters either.
75 */
76static void
77print_str16(const CHAR16 *str)
78{
79	int i;
80
81	for (i = 0; str[i]; i++)
82		printf("%c", (char)str[i]);
83}
84
85EFI_STATUS
86main(int argc, CHAR16 *argv[])
87{
88	char var[128];
89	EFI_LOADED_IMAGE *img;
90	EFI_GUID *guid;
91	int i, j, vargood, unit;
92	struct devsw *dev;
93	uint64_t pool_guid;
94	UINTN k;
95
96	archsw.arch_autoload = efi_autoload;
97	archsw.arch_getdev = efi_getdev;
98	archsw.arch_copyin = efi_copyin;
99	archsw.arch_copyout = efi_copyout;
100	archsw.arch_readin = efi_readin;
101#ifdef EFI_ZFS_BOOT
102	/* Note this needs to be set before ZFS init. */
103	archsw.arch_zfs_probe = efi_zfs_probe;
104#endif
105
106	/*
107	 * XXX Chicken-and-egg problem; we want to have console output
108	 * early, but some console attributes may depend on reading from
109	 * eg. the boot device, which we can't do yet.  We can use
110	 * printf() etc. once this is done.
111	 */
112	cons_probe();
113
114	/*
115	 * Loop through the args, and for each one that contains an '=' that is
116	 * not the first character, add it to the environment.  This allows
117	 * loader and kernel env vars to be passed on the command line.  Convert
118	 * args from UCS-2 to ASCII (16 to 8 bit) as they are copied.
119	 */
120	for (i = 1; i < argc; i++) {
121		vargood = 0;
122		for (j = 0; argv[i][j] != 0; j++) {
123			if (j == sizeof(var)) {
124				vargood = 0;
125				break;
126			}
127			if (j > 0 && argv[i][j] == '=')
128				vargood = 1;
129			var[j] = (char)argv[i][j];
130		}
131		if (vargood) {
132			var[j] = 0;
133			putenv(var);
134		}
135	}
136
137	if (efi_copy_init()) {
138		printf("failed to allocate staging area\n");
139		return (EFI_BUFFER_TOO_SMALL);
140	}
141
142	/*
143	 * March through the device switch probing for things.
144	 */
145	for (i = 0; devsw[i] != NULL; i++)
146		if (devsw[i]->dv_init != NULL)
147			(devsw[i]->dv_init)();
148
149	/* Get our loaded image protocol interface structure. */
150	BS->HandleProtocol(IH, &imgid, (VOID**)&img);
151
152	printf("Command line arguments:");
153	for (i = 0; i < argc; i++) {
154		printf(" ");
155		print_str16(argv[i]);
156	}
157	printf("\n");
158
159	printf("Image base: 0x%lx\n", (u_long)img->ImageBase);
160	printf("EFI version: %d.%02d\n", ST->Hdr.Revision >> 16,
161	    ST->Hdr.Revision & 0xffff);
162	printf("EFI Firmware: ");
163	/* printf doesn't understand EFI Unicode */
164	ST->ConOut->OutputString(ST->ConOut, ST->FirmwareVendor);
165	printf(" (rev %d.%02d)\n", ST->FirmwareRevision >> 16,
166	    ST->FirmwareRevision & 0xffff);
167
168	printf("\n");
169	printf("%s, Revision %s\n", bootprog_name, bootprog_rev);
170	printf("(%s, %s)\n", bootprog_maker, bootprog_date);
171
172	/*
173	 * Disable the watchdog timer. By default the boot manager sets
174	 * the timer to 5 minutes before invoking a boot option. If we
175	 * want to return to the boot manager, we have to disable the
176	 * watchdog timer and since we're an interactive program, we don't
177	 * want to wait until the user types "quit". The timer may have
178	 * fired by then. We don't care if this fails. It does not prevent
179	 * normal functioning in any way...
180	 */
181	BS->SetWatchdogTimer(0, 0, 0, NULL);
182
183	if (efi_handle_lookup(img->DeviceHandle, &dev, &unit, &pool_guid) != 0)
184		return (EFI_NOT_FOUND);
185
186	switch (dev->dv_type) {
187#ifdef EFI_ZFS_BOOT
188	case DEVT_ZFS: {
189		struct zfs_devdesc currdev;
190
191		currdev.d_dev = dev;
192		currdev.d_unit = unit;
193		currdev.d_type = currdev.d_dev->dv_type;
194		currdev.d_opendata = NULL;
195		currdev.pool_guid = pool_guid;
196		currdev.root_guid = 0;
197		env_setenv("currdev", EV_VOLATILE, efi_fmtdev(&currdev),
198			   efi_setcurrdev, env_nounset);
199		env_setenv("loaddev", EV_VOLATILE, efi_fmtdev(&currdev), env_noset,
200			   env_nounset);
201		break;
202	}
203#endif
204	default: {
205		struct devdesc currdev;
206
207		currdev.d_dev = dev;
208		currdev.d_unit = unit;
209		currdev.d_opendata = NULL;
210		currdev.d_type = currdev.d_dev->dv_type;
211		env_setenv("currdev", EV_VOLATILE, efi_fmtdev(&currdev),
212			   efi_setcurrdev, env_nounset);
213		env_setenv("loaddev", EV_VOLATILE, efi_fmtdev(&currdev), env_noset,
214			   env_nounset);
215		break;
216	}
217	}
218
219	setenv("LINES", "24", 1);	/* optional */
220
221	for (k = 0; k < ST->NumberOfTableEntries; k++) {
222		guid = &ST->ConfigurationTable[k].VendorGuid;
223		if (!memcmp(guid, &smbios, sizeof(EFI_GUID))) {
224			smbios_detect(ST->ConfigurationTable[k].VendorTable);
225			break;
226		}
227	}
228
229	interact();			/* doesn't return */
230
231	return (EFI_SUCCESS);		/* keep compiler happy */
232}
233
234COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot);
235
236static int
237command_reboot(int argc, char *argv[])
238{
239	int i;
240
241	for (i = 0; devsw[i] != NULL; ++i)
242		if (devsw[i]->dv_cleanup != NULL)
243			(devsw[i]->dv_cleanup)();
244
245	RS->ResetSystem(EfiResetCold, EFI_SUCCESS, 23,
246	    (CHAR16 *)"Reboot from the loader");
247
248	/* NOTREACHED */
249	return (CMD_ERROR);
250}
251
252COMMAND_SET(quit, "quit", "exit the loader", command_quit);
253
254static int
255command_quit(int argc, char *argv[])
256{
257	exit(0);
258	return (CMD_OK);
259}
260
261COMMAND_SET(memmap, "memmap", "print memory map", command_memmap);
262
263static int
264command_memmap(int argc, char *argv[])
265{
266	UINTN sz;
267	EFI_MEMORY_DESCRIPTOR *map, *p;
268	UINTN key, dsz;
269	UINT32 dver;
270	EFI_STATUS status;
271	int i, ndesc;
272	static char *types[] = {
273	    "Reserved",
274	    "LoaderCode",
275	    "LoaderData",
276	    "BootServicesCode",
277	    "BootServicesData",
278	    "RuntimeServicesCode",
279	    "RuntimeServicesData",
280	    "ConventionalMemory",
281	    "UnusableMemory",
282	    "ACPIReclaimMemory",
283	    "ACPIMemoryNVS",
284	    "MemoryMappedIO",
285	    "MemoryMappedIOPortSpace",
286	    "PalCode"
287	};
288
289	sz = 0;
290	status = BS->GetMemoryMap(&sz, 0, &key, &dsz, &dver);
291	if (status != EFI_BUFFER_TOO_SMALL) {
292		printf("Can't determine memory map size\n");
293		return (CMD_ERROR);
294	}
295	map = malloc(sz);
296	status = BS->GetMemoryMap(&sz, map, &key, &dsz, &dver);
297	if (EFI_ERROR(status)) {
298		printf("Can't read memory map\n");
299		return (CMD_ERROR);
300	}
301
302	ndesc = sz / dsz;
303	printf("%23s %12s %12s %8s %4s\n",
304	    "Type", "Physical", "Virtual", "#Pages", "Attr");
305
306	for (i = 0, p = map; i < ndesc;
307	     i++, p = NextMemoryDescriptor(p, dsz)) {
308		printf("%23s %012jx %012jx %08jx ", types[p->Type],
309		   (uintmax_t)p->PhysicalStart, (uintmax_t)p->VirtualStart,
310		   (uintmax_t)p->NumberOfPages);
311		if (p->Attribute & EFI_MEMORY_UC)
312			printf("UC ");
313		if (p->Attribute & EFI_MEMORY_WC)
314			printf("WC ");
315		if (p->Attribute & EFI_MEMORY_WT)
316			printf("WT ");
317		if (p->Attribute & EFI_MEMORY_WB)
318			printf("WB ");
319		if (p->Attribute & EFI_MEMORY_UCE)
320			printf("UCE ");
321		if (p->Attribute & EFI_MEMORY_WP)
322			printf("WP ");
323		if (p->Attribute & EFI_MEMORY_RP)
324			printf("RP ");
325		if (p->Attribute & EFI_MEMORY_XP)
326			printf("XP ");
327		printf("\n");
328	}
329
330	return (CMD_OK);
331}
332
333COMMAND_SET(configuration, "configuration", "print configuration tables",
334    command_configuration);
335
336static const char *
337guid_to_string(EFI_GUID *guid)
338{
339	static char buf[40];
340
341	sprintf(buf, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
342	    guid->Data1, guid->Data2, guid->Data3, guid->Data4[0],
343	    guid->Data4[1], guid->Data4[2], guid->Data4[3], guid->Data4[4],
344	    guid->Data4[5], guid->Data4[6], guid->Data4[7]);
345	return (buf);
346}
347
348static int
349command_configuration(int argc, char *argv[])
350{
351	UINTN i;
352
353	printf("NumberOfTableEntries=%lu\n",
354		(unsigned long)ST->NumberOfTableEntries);
355	for (i = 0; i < ST->NumberOfTableEntries; i++) {
356		EFI_GUID *guid;
357
358		printf("  ");
359		guid = &ST->ConfigurationTable[i].VendorGuid;
360		if (!memcmp(guid, &mps, sizeof(EFI_GUID)))
361			printf("MPS Table");
362		else if (!memcmp(guid, &acpi, sizeof(EFI_GUID)))
363			printf("ACPI Table");
364		else if (!memcmp(guid, &acpi20, sizeof(EFI_GUID)))
365			printf("ACPI 2.0 Table");
366		else if (!memcmp(guid, &smbios, sizeof(EFI_GUID)))
367			printf("SMBIOS Table");
368		else if (!memcmp(guid, &dxe, sizeof(EFI_GUID)))
369			printf("DXE Table");
370		else if (!memcmp(guid, &hoblist, sizeof(EFI_GUID)))
371			printf("HOB List Table");
372		else if (!memcmp(guid, &memtype, sizeof(EFI_GUID)))
373			printf("Memory Type Information Table");
374		else if (!memcmp(guid, &debugimg, sizeof(EFI_GUID)))
375			printf("Debug Image Info Table");
376		else
377			printf("Unknown Table (%s)", guid_to_string(guid));
378		printf(" at %p\n", ST->ConfigurationTable[i].VendorTable);
379	}
380
381	return (CMD_OK);
382}
383
384
385COMMAND_SET(mode, "mode", "change or display text modes", command_mode);
386
387static int
388command_mode(int argc, char *argv[])
389{
390	UINTN cols, rows;
391	unsigned int mode;
392	int i;
393	char *cp;
394	char rowenv[8];
395	EFI_STATUS status;
396	SIMPLE_TEXT_OUTPUT_INTERFACE *conout;
397	extern void HO(void);
398
399	conout = ST->ConOut;
400
401	if (argc > 1) {
402		mode = strtol(argv[1], &cp, 0);
403		if (cp[0] != '\0') {
404			printf("Invalid mode\n");
405			return (CMD_ERROR);
406		}
407		status = conout->QueryMode(conout, mode, &cols, &rows);
408		if (EFI_ERROR(status)) {
409			printf("invalid mode %d\n", mode);
410			return (CMD_ERROR);
411		}
412		status = conout->SetMode(conout, mode);
413		if (EFI_ERROR(status)) {
414			printf("couldn't set mode %d\n", mode);
415			return (CMD_ERROR);
416		}
417		sprintf(rowenv, "%u", (unsigned)rows);
418		setenv("LINES", rowenv, 1);
419		HO();		/* set cursor */
420		return (CMD_OK);
421	}
422
423	printf("Current mode: %d\n", conout->Mode->Mode);
424	for (i = 0; i <= conout->Mode->MaxMode; i++) {
425		status = conout->QueryMode(conout, i, &cols, &rows);
426		if (EFI_ERROR(status))
427			continue;
428		printf("Mode %d: %u columns, %u rows\n", i, (unsigned)cols,
429		    (unsigned)rows);
430	}
431
432	if (i != 0)
433		printf("Choose the mode with \"col <mode number>\"\n");
434
435	return (CMD_OK);
436}
437
438
439COMMAND_SET(nvram, "nvram", "get or set NVRAM variables", command_nvram);
440
441static int
442command_nvram(int argc, char *argv[])
443{
444	CHAR16 var[128];
445	CHAR16 *data;
446	EFI_STATUS status;
447	EFI_GUID varguid = { 0,0,0,{0,0,0,0,0,0,0,0} };
448	UINTN varsz, datasz, i;
449	SIMPLE_TEXT_OUTPUT_INTERFACE *conout;
450
451	conout = ST->ConOut;
452
453	/* Initiate the search */
454	status = RS->GetNextVariableName(&varsz, NULL, NULL);
455
456	for (; status != EFI_NOT_FOUND; ) {
457		status = RS->GetNextVariableName(&varsz, var, &varguid);
458		//if (EFI_ERROR(status))
459			//break;
460
461		conout->OutputString(conout, var);
462		printf("=");
463		datasz = 0;
464		status = RS->GetVariable(var, &varguid, NULL, &datasz, NULL);
465		/* XXX: check status */
466		data = malloc(datasz);
467		status = RS->GetVariable(var, &varguid, NULL, &datasz, data);
468		if (EFI_ERROR(status))
469			printf("<error retrieving variable>");
470		else {
471			for (i = 0; i < datasz; i++) {
472				if (isalnum(data[i]) || isspace(data[i]))
473					printf("%c", data[i]);
474				else
475					printf("\\x%02x", data[i]);
476			}
477		}
478		/* XXX */
479		pager_output("\n");
480		free(data);
481	}
482
483	return (CMD_OK);
484}
485
486#ifdef EFI_ZFS_BOOT
487COMMAND_SET(lszfs, "lszfs", "list child datasets of a zfs dataset",
488    command_lszfs);
489
490static int
491command_lszfs(int argc, char *argv[])
492{
493	int err;
494
495	if (argc != 2) {
496		command_errmsg = "wrong number of arguments";
497		return (CMD_ERROR);
498	}
499
500	err = zfs_list(argv[1]);
501	if (err != 0) {
502		command_errmsg = strerror(err);
503		return (CMD_ERROR);
504	}
505	return (CMD_OK);
506}
507#endif
508
509#ifdef EFI_ZFS_BOOT
510static void
511efi_zfs_probe(void)
512{
513	EFI_HANDLE h;
514	u_int unit;
515	int i;
516	char dname[SPECNAMELEN + 1];
517	uint64_t guid;
518
519	unit = 0;
520	h = efi_find_handle(&efipart_dev, 0);
521	for (i = 0; h != NULL; h = efi_find_handle(&efipart_dev, ++i)) {
522		snprintf(dname, sizeof(dname), "%s%d:", efipart_dev.dv_name, i);
523		if (zfs_probe_dev(dname, &guid) == 0)
524			(void)efi_handle_update_dev(h, &zfs_dev, unit++, guid);
525	}
526}
527#endif
528