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