xref: /freebsd/stand/efi/loader/bootinfo.c (revision eade2001aa9d91440886de8359a4dec9edcde2a9)
1 /*-
2  * Copyright (c) 1998 Michael Smith <msmith@freebsd.org>
3  * Copyright (c) 2004, 2006 Marcel Moolenaar
4  * Copyright (c) 2014 The FreeBSD Foundation
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 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 AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <stand.h>
30 #include <string.h>
31 #include <sys/param.h>
32 #include <sys/linker.h>
33 #include <sys/reboot.h>
34 #include <sys/boot.h>
35 #include <machine/cpufunc.h>
36 #include <machine/elf.h>
37 #include <machine/metadata.h>
38 #include <machine/psl.h>
39 
40 #ifdef EFI
41 #include <efi.h>
42 #include <efilib.h>
43 #else
44 #include "kboot.h"
45 #endif
46 
47 #include "bootstrap.h"
48 #include "modinfo.h"
49 
50 #if defined(__amd64__)
51 #include <machine/specialreg.h>
52 #endif
53 
54 #ifdef EFI
55 #include "loader_efi.h"
56 #include "gfx_fb.h"
57 #endif
58 
59 #if defined(LOADER_FDT_SUPPORT)
60 #include <fdt_platform.h>
61 #endif
62 
63 #ifdef LOADER_GELI_SUPPORT
64 #include "geliboot.h"
65 #endif
66 
67 int bi_load(char *args, vm_offset_t *modulep, vm_offset_t *kernendp,
68     bool exit_bs);
69 
70 static int
71 bi_getboothowto(char *kargs)
72 {
73 #ifdef EFI
74 	const char *sw, *tmp;
75 	char *opts;
76 	int speed, port;
77 	char buf[50];
78 #endif
79 	char *console;
80 	int howto;
81 
82 	howto = boot_parse_cmdline(kargs);
83 	howto |= boot_env_to_howto();
84 
85 	console = getenv("console");
86 	if (console != NULL) {
87 		if (strcmp(console, "comconsole") == 0)
88 			howto |= RB_SERIAL;
89 		if (strcmp(console, "nullconsole") == 0)
90 			howto |= RB_MUTE;
91 #ifdef EFI
92 #if defined(__i386__) || defined(__amd64__)
93 		if (strcmp(console, "efi") == 0 &&
94 		    getenv("efi_8250_uid") != NULL &&
95 		    getenv("hw.uart.console") == NULL) {
96 			/*
97 			 * If we found a 8250 com port and com speed, we need to
98 			 * tell the kernel where the serial port is, and how
99 			 * fast. Ideally, we'd get the port from ACPI, but that
100 			 * isn't running in the loader. Do the next best thing
101 			 * by allowing it to be set by a loader.conf variable,
102 			 * either a EFI specific one, or the compatible
103 			 * comconsole_port if not. PCI support is needed, but
104 			 * for that we'd ideally refactor the
105 			 * libi386/comconsole.c code to have identical behavior.
106 			 * We only try to set the port for cases where we saw
107 			 * the Serial(x) node when parsing, otherwise
108 			 * specialized hardware that has Uart nodes will have a
109 			 * bogus address set.
110 			 * But if someone specifically setup hw.uart.console,
111 			 * don't override that.
112 			 */
113 			speed = -1;
114 			port = -1;
115 			tmp = getenv("efi_com_speed");
116 			if (tmp != NULL)
117 				speed = strtol(tmp, NULL, 0);
118 			tmp = getenv("efi_com_port");
119 			if (tmp != NULL)
120 				port = strtol(tmp, NULL, 0);
121 			if (port <= 0) {
122 				tmp = getenv("comconsole_port");
123 				if (tmp != NULL)
124 					port = strtol(tmp, NULL, 0);
125 				else {
126 					if (port == 0)
127 						port = 0x3f8;
128 				}
129 			}
130 			if (speed != -1 && port != -1) {
131 				snprintf(buf, sizeof(buf), "io:%d,br:%d", port,
132 				    speed);
133 				env_setenv("hw.uart.console", EV_VOLATILE, buf,
134 				    NULL, NULL);
135 			}
136 		}
137 #endif
138 #endif
139 	}
140 
141 	return (howto);
142 }
143 
144 #ifdef EFI
145 static EFI_STATUS
146 efi_do_vmap(EFI_MEMORY_DESCRIPTOR *mm, UINTN sz, UINTN mmsz, UINT32 mmver)
147 {
148 	EFI_MEMORY_DESCRIPTOR *desc, *viter, *vmap;
149 	EFI_STATUS ret;
150 	int curr, ndesc, nset;
151 
152 	nset = 0;
153 	desc = mm;
154 	ndesc = sz / mmsz;
155 	vmap = malloc(sz);
156 	if (vmap == NULL)
157 		/* This isn't really an EFI error case, but pretend it is */
158 		return (EFI_OUT_OF_RESOURCES);
159 	viter = vmap;
160 	for (curr = 0; curr < ndesc;
161 	    curr++, desc = NextMemoryDescriptor(desc, mmsz)) {
162 		if ((desc->Attribute & EFI_MEMORY_RUNTIME) != 0) {
163 			++nset;
164 			desc->VirtualStart = desc->PhysicalStart;
165 			*viter = *desc;
166 			viter = NextMemoryDescriptor(viter, mmsz);
167 		}
168 	}
169 	ret = RS->SetVirtualAddressMap(nset * mmsz, mmsz, mmver, vmap);
170 	free(vmap);
171 	return (ret);
172 }
173 
174 static int
175 bi_load_efi_data(struct preloaded_file *kfp, bool exit_bs)
176 {
177 	EFI_MEMORY_DESCRIPTOR *mm;
178 	EFI_PHYSICAL_ADDRESS addr = 0;
179 	EFI_STATUS status;
180 	const char *efi_novmap;
181 	size_t efisz;
182 	UINTN efi_mapkey;
183 	UINTN dsz, pages, retry, sz;
184 	UINT32 mmver;
185 	struct efi_map_header *efihdr;
186 	bool do_vmap;
187 
188 #if defined(__amd64__) || defined(__aarch64__) || defined(__i386__)
189 	struct efi_fb efifb;
190 
191 	efifb.fb_addr = gfx_state.tg_fb.fb_addr;
192 	efifb.fb_size = gfx_state.tg_fb.fb_size;
193 	efifb.fb_height = gfx_state.tg_fb.fb_height;
194 	efifb.fb_width = gfx_state.tg_fb.fb_width;
195 	efifb.fb_stride = gfx_state.tg_fb.fb_stride;
196 	efifb.fb_mask_red = gfx_state.tg_fb.fb_mask_red;
197 	efifb.fb_mask_green = gfx_state.tg_fb.fb_mask_green;
198 	efifb.fb_mask_blue = gfx_state.tg_fb.fb_mask_blue;
199 	efifb.fb_mask_reserved = gfx_state.tg_fb.fb_mask_reserved;
200 
201 	if (efifb.fb_addr != 0) {
202 		printf("EFI framebuffer information:\n");
203 		printf("addr, size     0x%jx, 0x%jx\n",
204 		    efifb.fb_addr, efifb.fb_size);
205 		printf("dimensions     %d x %d\n",
206 		    efifb.fb_width, efifb.fb_height);
207 		printf("stride         %d\n", efifb.fb_stride);
208 		printf("masks          0x%08x, 0x%08x, 0x%08x, 0x%08x\n",
209 		    efifb.fb_mask_red, efifb.fb_mask_green, efifb.fb_mask_blue,
210 		    efifb.fb_mask_reserved);
211 
212 		file_addmetadata(kfp, MODINFOMD_EFI_FB, sizeof(efifb), &efifb);
213 	}
214 #endif
215 
216 	do_vmap = true;
217 	efi_novmap = getenv("efi_disable_vmap");
218 	if (efi_novmap != NULL)
219 		do_vmap = strcasecmp(efi_novmap, "YES") != 0;
220 
221 	efisz = (sizeof(struct efi_map_header) + 0xf) & ~0xf;
222 
223 	/*
224 	 * Assign size of EFI_MEMORY_DESCRIPTOR to keep compatible with
225 	 * u-boot which doesn't fill this value when buffer for memory
226 	 * descriptors is too small (eg. 0 to obtain memory map size)
227 	 */
228 	dsz = sizeof(EFI_MEMORY_DESCRIPTOR);
229 
230 	/*
231 	 * Allocate enough pages to hold the bootinfo block and the
232 	 * memory map EFI will return to us. The memory map has an
233 	 * unknown size, so we have to determine that first. Note that
234 	 * the AllocatePages call can itself modify the memory map, so
235 	 * we have to take that into account as well. The changes to
236 	 * the memory map are caused by splitting a range of free
237 	 * memory into two, so that one is marked as being loader
238 	 * data.
239 	 */
240 
241 	sz = 0;
242 	mm = NULL;
243 
244 	/*
245 	 * Matthew Garrett has observed at least one system changing the
246 	 * memory map when calling ExitBootServices, causing it to return an
247 	 * error, probably because callbacks are allocating memory.
248 	 * So we need to retry calling it at least once.
249 	 */
250 	for (retry = 2; retry > 0; retry--) {
251 		for (;;) {
252 			status = BS->GetMemoryMap(&sz, mm, &efi_mapkey, &dsz, &mmver);
253 			if (!EFI_ERROR(status))
254 				break;
255 
256 			if (status != EFI_BUFFER_TOO_SMALL) {
257 				printf("%s: GetMemoryMap error %lu\n", __func__,
258 	                           EFI_ERROR_CODE(status));
259 				return (EINVAL);
260 			}
261 
262 			if (addr != 0)
263 				BS->FreePages(addr, pages);
264 
265 			/* Add 10 descriptors to the size to allow for
266 			 * fragmentation caused by calling AllocatePages */
267 			sz += (10 * dsz);
268 			pages = EFI_SIZE_TO_PAGES(sz + efisz);
269 			status = BS->AllocatePages(AllocateAnyPages, EfiLoaderData,
270 					pages, &addr);
271 			if (EFI_ERROR(status)) {
272 				printf("%s: AllocatePages error %lu\n", __func__,
273 				    EFI_ERROR_CODE(status));
274 				return (ENOMEM);
275 			}
276 
277 			/*
278 			 * Read the memory map and stash it after bootinfo. Align the
279 			 * memory map on a 16-byte boundary (the bootinfo block is page
280 			 * aligned).
281 			 */
282 			efihdr = (struct efi_map_header *)(uintptr_t)addr;
283 			mm = (void *)((uint8_t *)efihdr + efisz);
284 			sz = (EFI_PAGE_SIZE * pages) - efisz;
285 		}
286 
287 		if (!exit_bs)
288 			break;
289 		status = efi_exit_boot_services(efi_mapkey);
290 		if (!EFI_ERROR(status))
291 			break;
292 	}
293 
294 	if (retry == 0) {
295 		BS->FreePages(addr, pages);
296 		printf("ExitBootServices error %lu\n", EFI_ERROR_CODE(status));
297 		return (EINVAL);
298 	}
299 
300 	/*
301 	 * This may be disabled by setting efi_disable_vmap in
302 	 * loader.conf(5). By default we will setup the virtual
303 	 * map entries.
304 	 */
305 
306 	if (do_vmap)
307 		efi_do_vmap(mm, sz, dsz, mmver);
308 	efihdr->memory_size = sz;
309 	efihdr->descriptor_size = dsz;
310 	efihdr->descriptor_version = mmver;
311 	file_addmetadata(kfp, MODINFOMD_EFI_MAP, efisz + sz,
312 	    efihdr);
313 
314 	return (0);
315 }
316 #endif
317 
318 /*
319  * Load the information expected by an amd64 kernel.
320  *
321  * - The 'boothowto' argument is constructed.
322  * - The 'bootdev' argument is constructed.
323  * - The 'bootinfo' struct is constructed, and copied into the kernel space.
324  * - The kernel environment is copied into kernel space.
325  * - Module metadata are formatted and placed in kernel space.
326  */
327 int
328 bi_load(char *args, vm_offset_t *modulep, vm_offset_t *kernendp, bool exit_bs)
329 {
330 	struct preloaded_file *xp, *kfp;
331 	struct devdesc *rootdev;
332 	struct file_metadata *md;
333 	vm_offset_t addr;
334 	uint64_t kernend;
335 #ifdef MODINFOMD_MODULEP
336 	uint64_t module;
337 #endif
338 	uint64_t envp;
339 	vm_offset_t size;
340 	char *rootdevname;
341 	int howto;
342 #ifdef __i386__
343 	/*
344 	 * The 32-bit UEFI loader is used to
345 	 * boot the 64-bit kernel on machines
346 	 * that support it.
347 	 */
348 	bool is64 = true;
349 #else
350 	bool is64 = sizeof(long) == 8;
351 #endif
352 #if defined(LOADER_FDT_SUPPORT)
353 	vm_offset_t dtbp;
354 	int dtb_size;
355 #endif
356 #if defined(__arm__)
357 	vm_offset_t vaddr;
358 	size_t i;
359 	/*
360 	 * These metadata addreses must be converted for kernel after
361 	 * relocation.
362 	 */
363 	uint32_t		mdt[] = {
364 	    MODINFOMD_SSYM, MODINFOMD_ESYM, MODINFOMD_KERNEND,
365 	    MODINFOMD_ENVP, MODINFOMD_FONT,
366 #if defined(LOADER_FDT_SUPPORT)
367 	    MODINFOMD_DTBP
368 #endif
369 	};
370 #endif
371 	howto = bi_getboothowto(args);
372 
373 	/*
374 	 * Allow the environment variable 'rootdev' to override the supplied
375 	 * device. This should perhaps go to MI code and/or have $rootdev
376 	 * tested/set by MI code before launching the kernel.
377 	 */
378 	rootdevname = getenv("rootdev");
379 	archsw.arch_getdev((void**)(&rootdev), rootdevname, NULL);
380 	if (rootdev == NULL) {
381 		printf("Can't determine root device.\n");
382 		return(EINVAL);
383 	}
384 
385 	/* Try reading the /etc/fstab file to select the root device */
386 	getrootmount(devformat(rootdev));
387 
388 	addr = 0;
389 	for (xp = file_findfile(NULL, NULL); xp != NULL; xp = xp->f_next) {
390 		if (addr < xp->f_addr + xp->f_size)
391 			addr = xp->f_addr + xp->f_size;
392 	}
393 
394 	/* Pad to a page boundary. */
395 	addr = roundup(addr, PAGE_SIZE);
396 
397 #ifdef EFI
398 	addr = build_font_module(addr);
399 
400 	/* Pad to a page boundary. */
401 	addr = roundup(addr, PAGE_SIZE);
402 
403 	addr = build_splash_module(addr);
404 
405 	/* Pad to a page boundary. */
406 	addr = roundup(addr, PAGE_SIZE);
407 #endif
408 
409 	/* Copy our environment. */
410 	envp = addr;
411 	addr = md_copyenv(addr);
412 
413 	/* Pad to a page boundary. */
414 	addr = roundup(addr, PAGE_SIZE);
415 
416 #if defined(LOADER_FDT_SUPPORT)
417 	/* Handle device tree blob */
418 	dtbp = addr;
419 	dtb_size = fdt_copy(addr);
420 
421 	/* Pad to a page boundary */
422 	if (dtb_size)
423 		addr += roundup(dtb_size, PAGE_SIZE);
424 #endif
425 
426 	kfp = file_findfile(NULL, "elf kernel");
427 	if (kfp == NULL)
428 		kfp = file_findfile(NULL, "elf64 kernel");
429 	if (kfp == NULL)
430 		panic("can't find kernel file");
431 	kernend = 0;	/* fill it in later */
432 
433 	/* Figure out the size and location of the metadata. */
434 	*modulep = addr;
435 
436 	file_addmetadata(kfp, MODINFOMD_HOWTO, sizeof(howto), &howto);
437 	file_addmetadata(kfp, MODINFOMD_ENVP, sizeof(envp), &envp);
438 #if defined(LOADER_FDT_SUPPORT)
439 	if (dtb_size)
440 		file_addmetadata(kfp, MODINFOMD_DTBP, sizeof(dtbp), &dtbp);
441 	else
442 		printf("WARNING! Trying to fire up the kernel, but no "
443 		    "device tree blob found!\n");
444 #endif
445 	file_addmetadata(kfp, MODINFOMD_KERNEND, sizeof(kernend), &kernend);
446 #ifdef MODINFOMD_MODULEP
447 	module = *modulep;
448 	file_addmetadata(kfp, MODINFOMD_MODULEP, sizeof(module), &module);
449 #endif
450 #ifdef EFI
451 #ifndef __i386__
452 	file_addmetadata(kfp, MODINFOMD_FW_HANDLE, sizeof(ST), &ST);
453 #endif
454 #if defined(__amd64__) || defined(__i386__)
455 	file_addmetadata(kfp, MODINFOMD_EFI_ARCH, sizeof(MACHINE_ARCH),
456 	    MACHINE_ARCH);
457 #endif
458 #endif
459 #ifdef LOADER_GELI_SUPPORT
460 	geli_export_key_metadata(kfp);
461 #endif
462 #ifdef EFI
463 	bi_load_efi_data(kfp, exit_bs);
464 #else
465 	bi_loadsmap(kfp);
466 #endif
467 
468 	size = md_copymodules(0, is64);	/* Find the size of the modules */
469 	kernend = roundup(addr + size, PAGE_SIZE);
470 	*kernendp = kernend;
471 
472 	/* patch MODINFOMD_KERNEND */
473 	md = file_findmetadata(kfp, MODINFOMD_KERNEND);
474 	bcopy(&kernend, md->md_data, sizeof kernend);
475 
476 #if defined(__arm__)
477 	*modulep -= __elfN(relocation_offset);
478 
479 	/* Do relocation fixup on metadata of each module. */
480 	for (xp = file_findfile(NULL, NULL); xp != NULL; xp = xp->f_next) {
481 		for (i = 0; i < nitems(mdt); i++) {
482 			md = file_findmetadata(xp, mdt[i]);
483 			if (md) {
484 				bcopy(md->md_data, &vaddr, sizeof vaddr);
485 				vaddr -= __elfN(relocation_offset);
486 				bcopy(&vaddr, md->md_data, sizeof vaddr);
487 			}
488 		}
489 	}
490 #endif
491 
492 	/* Copy module list and metadata. */
493 	(void)md_copymodules(addr, is64);
494 
495 	return (0);
496 }
497