xref: /freebsd/stand/efi/loader/bootinfo.c (revision 6e66bb9fc3d026765113fa1258cd12292da9309a)
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__)
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 	bool is64 = sizeof(long) == 8;
343 #if defined(LOADER_FDT_SUPPORT)
344 	vm_offset_t dtbp;
345 	int dtb_size;
346 #endif
347 #if defined(__arm__)
348 	vm_offset_t vaddr;
349 	size_t i;
350 	/*
351 	 * These metadata addreses must be converted for kernel after
352 	 * relocation.
353 	 */
354 	uint32_t		mdt[] = {
355 	    MODINFOMD_SSYM, MODINFOMD_ESYM, MODINFOMD_KERNEND,
356 	    MODINFOMD_ENVP, MODINFOMD_FONT,
357 #if defined(LOADER_FDT_SUPPORT)
358 	    MODINFOMD_DTBP
359 #endif
360 	};
361 #endif
362 	howto = bi_getboothowto(args);
363 
364 	/*
365 	 * Allow the environment variable 'rootdev' to override the supplied
366 	 * device. This should perhaps go to MI code and/or have $rootdev
367 	 * tested/set by MI code before launching the kernel.
368 	 */
369 	rootdevname = getenv("rootdev");
370 	archsw.arch_getdev((void**)(&rootdev), rootdevname, NULL);
371 	if (rootdev == NULL) {
372 		printf("Can't determine root device.\n");
373 		return(EINVAL);
374 	}
375 
376 	/* Try reading the /etc/fstab file to select the root device */
377 	getrootmount(devformat(rootdev));
378 
379 	addr = 0;
380 	for (xp = file_findfile(NULL, NULL); xp != NULL; xp = xp->f_next) {
381 		if (addr < xp->f_addr + xp->f_size)
382 			addr = xp->f_addr + xp->f_size;
383 	}
384 
385 	/* Pad to a page boundary. */
386 	addr = roundup(addr, PAGE_SIZE);
387 
388 #ifdef EFI
389 	addr = build_font_module(addr);
390 
391 	/* Pad to a page boundary. */
392 	addr = roundup(addr, PAGE_SIZE);
393 #endif
394 
395 	/* Copy our environment. */
396 	envp = addr;
397 	addr = md_copyenv(addr);
398 
399 	/* Pad to a page boundary. */
400 	addr = roundup(addr, PAGE_SIZE);
401 
402 #if defined(LOADER_FDT_SUPPORT)
403 	/* Handle device tree blob */
404 	dtbp = addr;
405 	dtb_size = fdt_copy(addr);
406 
407 	/* Pad to a page boundary */
408 	if (dtb_size)
409 		addr += roundup(dtb_size, PAGE_SIZE);
410 #endif
411 
412 	kfp = file_findfile(NULL, "elf kernel");
413 	if (kfp == NULL)
414 		kfp = file_findfile(NULL, "elf64 kernel");
415 	if (kfp == NULL)
416 		panic("can't find kernel file");
417 	kernend = 0;	/* fill it in later */
418 
419 	/* Figure out the size and location of the metadata. */
420 	*modulep = addr;
421 
422 	file_addmetadata(kfp, MODINFOMD_HOWTO, sizeof(howto), &howto);
423 	file_addmetadata(kfp, MODINFOMD_ENVP, sizeof(envp), &envp);
424 #if defined(LOADER_FDT_SUPPORT)
425 	if (dtb_size)
426 		file_addmetadata(kfp, MODINFOMD_DTBP, sizeof(dtbp), &dtbp);
427 	else
428 		printf("WARNING! Trying to fire up the kernel, but no "
429 		    "device tree blob found!\n");
430 #endif
431 	file_addmetadata(kfp, MODINFOMD_KERNEND, sizeof(kernend), &kernend);
432 #ifdef MODINFOMD_MODULEP
433 	module = *modulep;
434 	file_addmetadata(kfp, MODINFOMD_MODULEP, sizeof(module), &module);
435 #endif
436 #ifdef EFI
437 	file_addmetadata(kfp, MODINFOMD_FW_HANDLE, sizeof(ST), &ST);
438 #endif
439 #ifdef LOADER_GELI_SUPPORT
440 	geli_export_key_metadata(kfp);
441 #endif
442 #ifdef EFI
443 	bi_load_efi_data(kfp, exit_bs);
444 #else
445 	bi_loadsmap(kfp);
446 #endif
447 
448 	size = md_copymodules(0, is64);	/* Find the size of the modules */
449 	kernend = roundup(addr + size, PAGE_SIZE);
450 	*kernendp = kernend;
451 
452 	/* patch MODINFOMD_KERNEND */
453 	md = file_findmetadata(kfp, MODINFOMD_KERNEND);
454 	bcopy(&kernend, md->md_data, sizeof kernend);
455 
456 #if defined(__arm__)
457 	*modulep -= __elfN(relocation_offset);
458 
459 	/* Do relocation fixup on metadata of each module. */
460 	for (xp = file_findfile(NULL, NULL); xp != NULL; xp = xp->f_next) {
461 		for (i = 0; i < nitems(mdt); i++) {
462 			md = file_findmetadata(xp, mdt[i]);
463 			if (md) {
464 				bcopy(md->md_data, &vaddr, sizeof vaddr);
465 				vaddr -= __elfN(relocation_offset);
466 				bcopy(&vaddr, md->md_data, sizeof vaddr);
467 			}
468 		}
469 	}
470 #endif
471 
472 	/* Copy module list and metadata. */
473 	(void)md_copymodules(addr, is64);
474 
475 	return (0);
476 }
477