xref: /freebsd/stand/efi/loader/bootinfo.c (revision c1d255d3)
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 #include <efi.h>
44 #include <efilib.h>
45 
46 #include "bootstrap.h"
47 #include "loader_efi.h"
48 
49 #if defined(__amd64__)
50 #include <machine/specialreg.h>
51 #endif
52 
53 #include "gfx_fb.h"
54 
55 #if defined(LOADER_FDT_SUPPORT)
56 #include <fdt_platform.h>
57 #endif
58 
59 #ifdef LOADER_GELI_SUPPORT
60 #include "geliboot.h"
61 #endif
62 
63 int bi_load(char *args, vm_offset_t *modulep, vm_offset_t *kernendp,
64     bool exit_bs);
65 
66 extern EFI_SYSTEM_TABLE	*ST;
67 
68 int boot_services_gone;
69 
70 static int
71 bi_getboothowto(char *kargs)
72 {
73 	const char *sw, *tmp;
74 	char *opts;
75 	char *console;
76 	int howto, speed, port;
77 	char buf[50];
78 
79 	howto = boot_parse_cmdline(kargs);
80 	howto |= boot_env_to_howto();
81 
82 	console = getenv("console");
83 	if (console != NULL) {
84 		if (strcmp(console, "comconsole") == 0)
85 			howto |= RB_SERIAL;
86 		if (strcmp(console, "nullconsole") == 0)
87 			howto |= RB_MUTE;
88 #if defined(__i386__) || defined(__amd64__)
89 		if (strcmp(console, "efi") == 0 &&
90 		    getenv("efi_8250_uid") != NULL &&
91 		    getenv("hw.uart.console") == NULL) {
92 			/*
93 			 * If we found a 8250 com port and com speed, we need to
94 			 * tell the kernel where the serial port is, and how
95 			 * fast. Ideally, we'd get the port from ACPI, but that
96 			 * isn't running in the loader. Do the next best thing
97 			 * by allowing it to be set by a loader.conf variable,
98 			 * either a EFI specific one, or the compatible
99 			 * comconsole_port if not. PCI support is needed, but
100 			 * for that we'd ideally refactor the
101 			 * libi386/comconsole.c code to have identical behavior.
102 			 * We only try to set the port for cases where we saw
103 			 * the Serial(x) node when parsing, otherwise
104 			 * specialized hardware that has Uart nodes will have a
105 			 * bogus address set.
106 			 * But if someone specifically setup hw.uart.console,
107 			 * don't override that.
108 			 */
109 			speed = -1;
110 			port = -1;
111 			tmp = getenv("efi_com_speed");
112 			if (tmp != NULL)
113 				speed = strtol(tmp, NULL, 0);
114 			tmp = getenv("efi_com_port");
115 			if (tmp == NULL)
116 				tmp = getenv("comconsole_port");
117 			if (tmp != NULL)
118 				port = strtol(tmp, NULL, 0);
119 			if (speed != -1 && port != -1) {
120 				snprintf(buf, sizeof(buf), "io:%d,br:%d", port,
121 				    speed);
122 				env_setenv("hw.uart.console", EV_VOLATILE, buf,
123 				    NULL, NULL);
124 			}
125 		}
126 #endif
127 	}
128 
129 	return (howto);
130 }
131 
132 /*
133  * Copy the environment into the load area starting at (addr).
134  * Each variable is formatted as <name>=<value>, with a single nul
135  * separating each variable, and a double nul terminating the environment.
136  */
137 static vm_offset_t
138 bi_copyenv(vm_offset_t start)
139 {
140 	struct env_var *ep;
141 	vm_offset_t addr, last;
142 	size_t len;
143 
144 	addr = last = start;
145 
146 	/* Traverse the environment. */
147 	for (ep = environ; ep != NULL; ep = ep->ev_next) {
148 		len = strlen(ep->ev_name);
149 		if ((size_t)archsw.arch_copyin(ep->ev_name, addr, len) != len)
150 			break;
151 		addr += len;
152 		if (archsw.arch_copyin("=", addr, 1) != 1)
153 			break;
154 		addr++;
155 		if (ep->ev_value != NULL) {
156 			len = strlen(ep->ev_value);
157 			if ((size_t)archsw.arch_copyin(ep->ev_value, addr, len) != len)
158 				break;
159 			addr += len;
160 		}
161 		if (archsw.arch_copyin("", addr, 1) != 1)
162 			break;
163 		last = ++addr;
164 	}
165 
166 	if (archsw.arch_copyin("", last++, 1) != 1)
167 		last = start;
168 	return(last);
169 }
170 
171 /*
172  * Copy module-related data into the load area, where it can be
173  * used as a directory for loaded modules.
174  *
175  * Module data is presented in a self-describing format.  Each datum
176  * is preceded by a 32-bit identifier and a 32-bit size field.
177  *
178  * Currently, the following data are saved:
179  *
180  * MOD_NAME	(variable)		module name (string)
181  * MOD_TYPE	(variable)		module type (string)
182  * MOD_ARGS	(variable)		module parameters (string)
183  * MOD_ADDR	sizeof(vm_offset_t)	module load address
184  * MOD_SIZE	sizeof(size_t)		module size
185  * MOD_METADATA	(variable)		type-specific metadata
186  */
187 #define	COPY32(v, a, c) {					\
188 	uint32_t x = (v);					\
189 	if (c)							\
190 		archsw.arch_copyin(&x, a, sizeof(x));		\
191 	a += sizeof(x);						\
192 }
193 
194 #define	MOD_STR(t, a, s, c) {					\
195 	COPY32(t, a, c);					\
196 	COPY32(strlen(s) + 1, a, c);				\
197 	if (c)							\
198 		archsw.arch_copyin(s, a, strlen(s) + 1);	\
199 	a += roundup(strlen(s) + 1, sizeof(u_long));		\
200 }
201 
202 #define	MOD_NAME(a, s, c)	MOD_STR(MODINFO_NAME, a, s, c)
203 #define	MOD_TYPE(a, s, c)	MOD_STR(MODINFO_TYPE, a, s, c)
204 #define	MOD_ARGS(a, s, c)	MOD_STR(MODINFO_ARGS, a, s, c)
205 
206 #define	MOD_VAR(t, a, s, c) {					\
207 	COPY32(t, a, c);					\
208 	COPY32(sizeof(s), a, c);				\
209 	if (c)							\
210 		archsw.arch_copyin(&s, a, sizeof(s));		\
211 	a += roundup(sizeof(s), sizeof(u_long));		\
212 }
213 
214 #define	MOD_ADDR(a, s, c)	MOD_VAR(MODINFO_ADDR, a, s, c)
215 #define	MOD_SIZE(a, s, c)	MOD_VAR(MODINFO_SIZE, a, s, c)
216 
217 #define	MOD_METADATA(a, mm, c) {				\
218 	COPY32(MODINFO_METADATA | mm->md_type, a, c);		\
219 	COPY32(mm->md_size, a, c);				\
220 	if (c)							\
221 		archsw.arch_copyin(mm->md_data, a, mm->md_size);	\
222 	a += roundup(mm->md_size, sizeof(u_long));		\
223 }
224 
225 #define	MOD_END(a, c) {						\
226 	COPY32(MODINFO_END, a, c);				\
227 	COPY32(0, a, c);					\
228 }
229 
230 static vm_offset_t
231 bi_copymodules(vm_offset_t addr)
232 {
233 	struct preloaded_file *fp;
234 	struct file_metadata *md;
235 	int c;
236 	uint64_t v;
237 
238 	c = addr != 0;
239 	/* Start with the first module on the list, should be the kernel. */
240 	for (fp = file_findfile(NULL, NULL); fp != NULL; fp = fp->f_next) {
241 		MOD_NAME(addr, fp->f_name, c); /* This must come first. */
242 		MOD_TYPE(addr, fp->f_type, c);
243 		if (fp->f_args)
244 			MOD_ARGS(addr, fp->f_args, c);
245 		v = fp->f_addr;
246 #if defined(__arm__)
247 		v -= __elfN(relocation_offset);
248 #endif
249 		MOD_ADDR(addr, v, c);
250 		v = fp->f_size;
251 		MOD_SIZE(addr, v, c);
252 		for (md = fp->f_metadata; md != NULL; md = md->md_next)
253 			if (!(md->md_type & MODINFOMD_NOCOPY))
254 				MOD_METADATA(addr, md, c);
255 	}
256 	MOD_END(addr, c);
257 	return(addr);
258 }
259 
260 static EFI_STATUS
261 efi_do_vmap(EFI_MEMORY_DESCRIPTOR *mm, UINTN sz, UINTN mmsz, UINT32 mmver)
262 {
263 	EFI_MEMORY_DESCRIPTOR *desc, *viter, *vmap;
264 	EFI_STATUS ret;
265 	int curr, ndesc, nset;
266 
267 	nset = 0;
268 	desc = mm;
269 	ndesc = sz / mmsz;
270 	vmap = malloc(sz);
271 	if (vmap == NULL)
272 		/* This isn't really an EFI error case, but pretend it is */
273 		return (EFI_OUT_OF_RESOURCES);
274 	viter = vmap;
275 	for (curr = 0; curr < ndesc;
276 	    curr++, desc = NextMemoryDescriptor(desc, mmsz)) {
277 		if ((desc->Attribute & EFI_MEMORY_RUNTIME) != 0) {
278 			++nset;
279 			desc->VirtualStart = desc->PhysicalStart;
280 			*viter = *desc;
281 			viter = NextMemoryDescriptor(viter, mmsz);
282 		}
283 	}
284 	ret = RS->SetVirtualAddressMap(nset * mmsz, mmsz, mmver, vmap);
285 	free(vmap);
286 	return (ret);
287 }
288 
289 static int
290 bi_load_efi_data(struct preloaded_file *kfp, bool exit_bs)
291 {
292 	EFI_MEMORY_DESCRIPTOR *mm;
293 	EFI_PHYSICAL_ADDRESS addr = 0;
294 	EFI_STATUS status;
295 	const char *efi_novmap;
296 	size_t efisz;
297 	UINTN efi_mapkey;
298 	UINTN dsz, pages, retry, sz;
299 	UINT32 mmver;
300 	struct efi_map_header *efihdr;
301 	bool do_vmap;
302 
303 #if defined(__amd64__) || defined(__aarch64__)
304 	struct efi_fb efifb;
305 
306 	efifb.fb_addr = gfx_state.tg_fb.fb_addr;
307 	efifb.fb_size = gfx_state.tg_fb.fb_size;
308 	efifb.fb_height = gfx_state.tg_fb.fb_height;
309 	efifb.fb_width = gfx_state.tg_fb.fb_width;
310 	efifb.fb_stride = gfx_state.tg_fb.fb_stride;
311 	efifb.fb_mask_red = gfx_state.tg_fb.fb_mask_red;
312 	efifb.fb_mask_green = gfx_state.tg_fb.fb_mask_green;
313 	efifb.fb_mask_blue = gfx_state.tg_fb.fb_mask_blue;
314 	efifb.fb_mask_reserved = gfx_state.tg_fb.fb_mask_reserved;
315 
316 	printf("EFI framebuffer information:\n");
317 	printf("addr, size     0x%jx, 0x%jx\n", efifb.fb_addr, efifb.fb_size);
318 	printf("dimensions     %d x %d\n", efifb.fb_width, efifb.fb_height);
319 	printf("stride         %d\n", efifb.fb_stride);
320 	printf("masks          0x%08x, 0x%08x, 0x%08x, 0x%08x\n",
321 	    efifb.fb_mask_red, efifb.fb_mask_green, efifb.fb_mask_blue,
322 	    efifb.fb_mask_reserved);
323 
324 	if (efifb.fb_addr != 0)
325 		file_addmetadata(kfp, MODINFOMD_EFI_FB, sizeof(efifb), &efifb);
326 #endif
327 
328 	do_vmap = true;
329 	efi_novmap = getenv("efi_disable_vmap");
330 	if (efi_novmap != NULL)
331 		do_vmap = strcasecmp(efi_novmap, "YES") != 0;
332 
333 	efisz = (sizeof(struct efi_map_header) + 0xf) & ~0xf;
334 
335 	/*
336 	 * Assign size of EFI_MEMORY_DESCRIPTOR to keep compatible with
337 	 * u-boot which doesn't fill this value when buffer for memory
338 	 * descriptors is too small (eg. 0 to obtain memory map size)
339 	 */
340 	dsz = sizeof(EFI_MEMORY_DESCRIPTOR);
341 
342 	/*
343 	 * Allocate enough pages to hold the bootinfo block and the
344 	 * memory map EFI will return to us. The memory map has an
345 	 * unknown size, so we have to determine that first. Note that
346 	 * the AllocatePages call can itself modify the memory map, so
347 	 * we have to take that into account as well. The changes to
348 	 * the memory map are caused by splitting a range of free
349 	 * memory into two, so that one is marked as being loader
350 	 * data.
351 	 */
352 
353 	sz = 0;
354 
355 	/*
356 	 * Matthew Garrett has observed at least one system changing the
357 	 * memory map when calling ExitBootServices, causing it to return an
358 	 * error, probably because callbacks are allocating memory.
359 	 * So we need to retry calling it at least once.
360 	 */
361 	for (retry = 2; retry > 0; retry--) {
362 		for (;;) {
363 			status = BS->GetMemoryMap(&sz, mm, &efi_mapkey, &dsz, &mmver);
364 			if (!EFI_ERROR(status))
365 				break;
366 
367 			if (status != EFI_BUFFER_TOO_SMALL) {
368 				printf("%s: GetMemoryMap error %lu\n", __func__,
369 	                           EFI_ERROR_CODE(status));
370 				return (EINVAL);
371 			}
372 
373 			if (addr != 0)
374 				BS->FreePages(addr, pages);
375 
376 			/* Add 10 descriptors to the size to allow for
377 			 * fragmentation caused by calling AllocatePages */
378 			sz += (10 * dsz);
379 			pages = EFI_SIZE_TO_PAGES(sz + efisz);
380 			status = BS->AllocatePages(AllocateAnyPages, EfiLoaderData,
381 					pages, &addr);
382 			if (EFI_ERROR(status)) {
383 				printf("%s: AllocatePages error %lu\n", __func__,
384 				    EFI_ERROR_CODE(status));
385 				return (ENOMEM);
386 			}
387 
388 			/*
389 			 * Read the memory map and stash it after bootinfo. Align the
390 			 * memory map on a 16-byte boundary (the bootinfo block is page
391 			 * aligned).
392 			 */
393 			efihdr = (struct efi_map_header *)(uintptr_t)addr;
394 			mm = (void *)((uint8_t *)efihdr + efisz);
395 			sz = (EFI_PAGE_SIZE * pages) - efisz;
396 		}
397 
398 		if (!exit_bs)
399 			break;
400 		status = BS->ExitBootServices(IH, efi_mapkey);
401 		if (!EFI_ERROR(status)) {
402 			boot_services_gone = 1;
403 			break;
404 		}
405 	}
406 
407 	if (retry == 0) {
408 		BS->FreePages(addr, pages);
409 		printf("ExitBootServices error %lu\n", EFI_ERROR_CODE(status));
410 		return (EINVAL);
411 	}
412 
413 	/*
414 	 * This may be disabled by setting efi_disable_vmap in
415 	 * loader.conf(5). By default we will setup the virtual
416 	 * map entries.
417 	 */
418 
419 	if (do_vmap)
420 		efi_do_vmap(mm, sz, dsz, mmver);
421 	efihdr->memory_size = sz;
422 	efihdr->descriptor_size = dsz;
423 	efihdr->descriptor_version = mmver;
424 	file_addmetadata(kfp, MODINFOMD_EFI_MAP, efisz + sz,
425 	    efihdr);
426 
427 	return (0);
428 }
429 
430 /*
431  * Load the information expected by an amd64 kernel.
432  *
433  * - The 'boothowto' argument is constructed.
434  * - The 'bootdev' argument is constructed.
435  * - The 'bootinfo' struct is constructed, and copied into the kernel space.
436  * - The kernel environment is copied into kernel space.
437  * - Module metadata are formatted and placed in kernel space.
438  */
439 int
440 bi_load(char *args, vm_offset_t *modulep, vm_offset_t *kernendp, bool exit_bs)
441 {
442 	struct preloaded_file *xp, *kfp;
443 	struct devdesc *rootdev;
444 	struct file_metadata *md;
445 	vm_offset_t addr;
446 	uint64_t kernend, module;
447 	uint64_t envp;
448 	vm_offset_t size;
449 	char *rootdevname;
450 	int howto;
451 #if defined(LOADER_FDT_SUPPORT)
452 	vm_offset_t dtbp;
453 	int dtb_size;
454 #endif
455 #if defined(__arm__)
456 	vm_offset_t vaddr;
457 	size_t i;
458 	/*
459 	 * These metadata addreses must be converted for kernel after
460 	 * relocation.
461 	 */
462 	uint32_t		mdt[] = {
463 	    MODINFOMD_SSYM, MODINFOMD_ESYM, MODINFOMD_KERNEND,
464 	    MODINFOMD_ENVP, MODINFOMD_FONT,
465 #if defined(LOADER_FDT_SUPPORT)
466 	    MODINFOMD_DTBP
467 #endif
468 	};
469 #endif
470 
471 	howto = bi_getboothowto(args);
472 
473 	/*
474 	 * Allow the environment variable 'rootdev' to override the supplied
475 	 * device. This should perhaps go to MI code and/or have $rootdev
476 	 * tested/set by MI code before launching the kernel.
477 	 */
478 	rootdevname = getenv("rootdev");
479 	archsw.arch_getdev((void**)(&rootdev), rootdevname, NULL);
480 	if (rootdev == NULL) {
481 		printf("Can't determine root device.\n");
482 		return(EINVAL);
483 	}
484 
485 	/* Try reading the /etc/fstab file to select the root device */
486 	getrootmount(efi_fmtdev((void *)rootdev));
487 
488 	addr = 0;
489 	for (xp = file_findfile(NULL, NULL); xp != NULL; xp = xp->f_next) {
490 		if (addr < (xp->f_addr + xp->f_size))
491 			addr = xp->f_addr + xp->f_size;
492 	}
493 
494 	/* Pad to a page boundary. */
495 	addr = roundup(addr, PAGE_SIZE);
496 
497 	addr = build_font_module(addr);
498 
499 	/* Pad to a page boundary. */
500 	addr = roundup(addr, PAGE_SIZE);
501 
502 	/* Copy our environment. */
503 	envp = addr;
504 	addr = bi_copyenv(addr);
505 
506 	/* Pad to a page boundary. */
507 	addr = roundup(addr, PAGE_SIZE);
508 
509 #if defined(LOADER_FDT_SUPPORT)
510 	/* Handle device tree blob */
511 	dtbp = addr;
512 	dtb_size = fdt_copy(addr);
513 
514 	/* Pad to a page boundary */
515 	if (dtb_size)
516 		addr += roundup(dtb_size, PAGE_SIZE);
517 #endif
518 
519 	kfp = file_findfile(NULL, "elf kernel");
520 	if (kfp == NULL)
521 		kfp = file_findfile(NULL, "elf64 kernel");
522 	if (kfp == NULL)
523 		panic("can't find kernel file");
524 	kernend = 0;	/* fill it in later */
525 
526 	/* Figure out the size and location of the metadata. */
527 	module = *modulep = addr;
528 
529 	file_addmetadata(kfp, MODINFOMD_HOWTO, sizeof(howto), &howto);
530 	file_addmetadata(kfp, MODINFOMD_ENVP, sizeof(envp), &envp);
531 #if defined(LOADER_FDT_SUPPORT)
532 	if (dtb_size)
533 		file_addmetadata(kfp, MODINFOMD_DTBP, sizeof(dtbp), &dtbp);
534 	else
535 		printf("WARNING! Trying to fire up the kernel, but no "
536 		    "device tree blob found!\n");
537 #endif
538 	file_addmetadata(kfp, MODINFOMD_KERNEND, sizeof(kernend), &kernend);
539 #ifdef MODINFOMD_MODULEP
540 	file_addmetadata(kfp, MODINFOMD_MODULEP, sizeof(module), &module);
541 #endif
542 	file_addmetadata(kfp, MODINFOMD_FW_HANDLE, sizeof(ST), &ST);
543 #ifdef LOADER_GELI_SUPPORT
544 	geli_export_key_metadata(kfp);
545 #endif
546 	bi_load_efi_data(kfp, exit_bs);
547 
548 	size = bi_copymodules(0);
549 	kernend = roundup(addr + size, PAGE_SIZE);
550 	*kernendp = kernend;
551 
552 	/* patch MODINFOMD_KERNEND */
553 	md = file_findmetadata(kfp, MODINFOMD_KERNEND);
554 	bcopy(&kernend, md->md_data, sizeof kernend);
555 
556 #if defined(__arm__)
557 	*modulep -= __elfN(relocation_offset);
558 
559 	/* Do relocation fixup on metadata of each module. */
560 	for (xp = file_findfile(NULL, NULL); xp != NULL; xp = xp->f_next) {
561 		for (i = 0; i < nitems(mdt); i++) {
562 			md = file_findmetadata(xp, mdt[i]);
563 			if (md) {
564 				bcopy(md->md_data, &vaddr, sizeof vaddr);
565 				vaddr -= __elfN(relocation_offset);
566 				bcopy(&vaddr, md->md_data, sizeof vaddr);
567 			}
568 		}
569 	}
570 #endif
571 
572 	/* Copy module list and metadata. */
573 	(void)bi_copymodules(addr);
574 
575 	return (0);
576 }
577