xref: /freebsd/stand/efi/loader/bootinfo.c (revision f0cfa1b168014f56c02b83e5f28412cc5f78d117)
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/reboot.h>
36 #include <sys/linker.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 "framebuffer.h"
54 
55 #if defined(LOADER_FDT_SUPPORT)
56 #include <fdt_platform.h>
57 #endif
58 
59 int bi_load(char *args, vm_offset_t *modulep, vm_offset_t *kernendp);
60 
61 extern EFI_SYSTEM_TABLE	*ST;
62 
63 static const char howto_switches[] = "aCdrgDmphsv";
64 static int howto_masks[] = {
65 	RB_ASKNAME, RB_CDROM, RB_KDB, RB_DFLTROOT, RB_GDB, RB_MULTIPLE,
66 	RB_MUTE, RB_PAUSE, RB_SERIAL, RB_SINGLE, RB_VERBOSE
67 };
68 
69 static int
70 bi_getboothowto(char *kargs)
71 {
72 	const char *sw;
73 	char *opts;
74 	char *console;
75 	int howto, i;
76 
77 	howto = 0;
78 
79 	/* Get the boot options from the environment first. */
80 	for (i = 0; howto_names[i].ev != NULL; i++) {
81 		if (getenv(howto_names[i].ev) != NULL)
82 			howto |= howto_names[i].mask;
83 	}
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 	}
92 
93 	/* Parse kargs */
94 	if (kargs == NULL)
95 		return (howto);
96 
97 	opts = strchr(kargs, '-');
98 	while (opts != NULL) {
99 		while (*(++opts) != '\0') {
100 			sw = strchr(howto_switches, *opts);
101 			if (sw == NULL)
102 				break;
103 			howto |= howto_masks[sw - howto_switches];
104 		}
105 		opts = strchr(opts, '-');
106 	}
107 
108 	return (howto);
109 }
110 
111 /*
112  * Copy the environment into the load area starting at (addr).
113  * Each variable is formatted as <name>=<value>, with a single nul
114  * separating each variable, and a double nul terminating the environment.
115  */
116 static vm_offset_t
117 bi_copyenv(vm_offset_t start)
118 {
119 	struct env_var *ep;
120 	vm_offset_t addr, last;
121 	size_t len;
122 
123 	addr = last = start;
124 
125 	/* Traverse the environment. */
126 	for (ep = environ; ep != NULL; ep = ep->ev_next) {
127 		len = strlen(ep->ev_name);
128 		if ((size_t)archsw.arch_copyin(ep->ev_name, addr, len) != len)
129 			break;
130 		addr += len;
131 		if (archsw.arch_copyin("=", addr, 1) != 1)
132 			break;
133 		addr++;
134 		if (ep->ev_value != NULL) {
135 			len = strlen(ep->ev_value);
136 			if ((size_t)archsw.arch_copyin(ep->ev_value, addr, len) != len)
137 				break;
138 			addr += len;
139 		}
140 		if (archsw.arch_copyin("", addr, 1) != 1)
141 			break;
142 		last = ++addr;
143 	}
144 
145 	if (archsw.arch_copyin("", last++, 1) != 1)
146 		last = start;
147 	return(last);
148 }
149 
150 /*
151  * Copy module-related data into the load area, where it can be
152  * used as a directory for loaded modules.
153  *
154  * Module data is presented in a self-describing format.  Each datum
155  * is preceded by a 32-bit identifier and a 32-bit size field.
156  *
157  * Currently, the following data are saved:
158  *
159  * MOD_NAME	(variable)		module name (string)
160  * MOD_TYPE	(variable)		module type (string)
161  * MOD_ARGS	(variable)		module parameters (string)
162  * MOD_ADDR	sizeof(vm_offset_t)	module load address
163  * MOD_SIZE	sizeof(size_t)		module size
164  * MOD_METADATA	(variable)		type-specific metadata
165  */
166 #define	COPY32(v, a, c) {					\
167 	uint32_t x = (v);					\
168 	if (c)							\
169 		archsw.arch_copyin(&x, a, sizeof(x));		\
170 	a += sizeof(x);						\
171 }
172 
173 #define	MOD_STR(t, a, s, c) {					\
174 	COPY32(t, a, c);					\
175 	COPY32(strlen(s) + 1, a, c);				\
176 	if (c)							\
177 		archsw.arch_copyin(s, a, strlen(s) + 1);	\
178 	a += roundup(strlen(s) + 1, sizeof(u_long));		\
179 }
180 
181 #define	MOD_NAME(a, s, c)	MOD_STR(MODINFO_NAME, a, s, c)
182 #define	MOD_TYPE(a, s, c)	MOD_STR(MODINFO_TYPE, a, s, c)
183 #define	MOD_ARGS(a, s, c)	MOD_STR(MODINFO_ARGS, a, s, c)
184 
185 #define	MOD_VAR(t, a, s, c) {					\
186 	COPY32(t, a, c);					\
187 	COPY32(sizeof(s), a, c);				\
188 	if (c)							\
189 		archsw.arch_copyin(&s, a, sizeof(s));		\
190 	a += roundup(sizeof(s), sizeof(u_long));		\
191 }
192 
193 #define	MOD_ADDR(a, s, c)	MOD_VAR(MODINFO_ADDR, a, s, c)
194 #define	MOD_SIZE(a, s, c)	MOD_VAR(MODINFO_SIZE, a, s, c)
195 
196 #define	MOD_METADATA(a, mm, c) {				\
197 	COPY32(MODINFO_METADATA | mm->md_type, a, c);		\
198 	COPY32(mm->md_size, a, c);				\
199 	if (c)							\
200 		archsw.arch_copyin(mm->md_data, a, mm->md_size);	\
201 	a += roundup(mm->md_size, sizeof(u_long));		\
202 }
203 
204 #define	MOD_END(a, c) {						\
205 	COPY32(MODINFO_END, a, c);				\
206 	COPY32(0, a, c);					\
207 }
208 
209 static vm_offset_t
210 bi_copymodules(vm_offset_t addr)
211 {
212 	struct preloaded_file *fp;
213 	struct file_metadata *md;
214 	int c;
215 	uint64_t v;
216 
217 	c = addr != 0;
218 	/* Start with the first module on the list, should be the kernel. */
219 	for (fp = file_findfile(NULL, NULL); fp != NULL; fp = fp->f_next) {
220 		MOD_NAME(addr, fp->f_name, c); /* This must come first. */
221 		MOD_TYPE(addr, fp->f_type, c);
222 		if (fp->f_args)
223 			MOD_ARGS(addr, fp->f_args, c);
224 		v = fp->f_addr;
225 #if defined(__arm__)
226 		v -= __elfN(relocation_offset);
227 #endif
228 		MOD_ADDR(addr, v, c);
229 		v = fp->f_size;
230 		MOD_SIZE(addr, v, c);
231 		for (md = fp->f_metadata; md != NULL; md = md->md_next)
232 			if (!(md->md_type & MODINFOMD_NOCOPY))
233 				MOD_METADATA(addr, md, c);
234 	}
235 	MOD_END(addr, c);
236 	return(addr);
237 }
238 
239 static int
240 bi_load_efi_data(struct preloaded_file *kfp)
241 {
242 	EFI_MEMORY_DESCRIPTOR *mm;
243 	EFI_PHYSICAL_ADDRESS addr;
244 	EFI_STATUS status;
245 	size_t efisz;
246 	UINTN efi_mapkey;
247 	UINTN mmsz, pages, retry, sz;
248 	UINT32 mmver;
249 	struct efi_map_header *efihdr;
250 
251 #if defined(__amd64__) || defined(__aarch64__)
252 	struct efi_fb efifb;
253 
254 	if (efi_find_framebuffer(&efifb) == 0) {
255 		printf("EFI framebuffer information:\n");
256 		printf("addr, size     0x%jx, 0x%jx\n", efifb.fb_addr,
257 		    efifb.fb_size);
258 		printf("dimensions     %d x %d\n", efifb.fb_width,
259 		    efifb.fb_height);
260 		printf("stride         %d\n", efifb.fb_stride);
261 		printf("masks          0x%08x, 0x%08x, 0x%08x, 0x%08x\n",
262 		    efifb.fb_mask_red, efifb.fb_mask_green, efifb.fb_mask_blue,
263 		    efifb.fb_mask_reserved);
264 
265 		file_addmetadata(kfp, MODINFOMD_EFI_FB, sizeof(efifb), &efifb);
266 	}
267 #endif
268 
269 	efisz = (sizeof(struct efi_map_header) + 0xf) & ~0xf;
270 
271 	/*
272 	 * Assgin size of EFI_MEMORY_DESCRIPTOR to keep compatible with
273 	 * u-boot which doesn't fill this value when buffer for memory
274 	 * descriptors is too small (eg. 0 to obtain memory map size)
275 	 */
276 	mmsz = sizeof(EFI_MEMORY_DESCRIPTOR);
277 
278 	/*
279 	 * It is possible that the first call to ExitBootServices may change
280 	 * the map key. Fetch a new map key and retry ExitBootServices in that
281 	 * case.
282 	 */
283 	for (retry = 2; retry > 0; retry--) {
284 		/*
285 		 * Allocate enough pages to hold the bootinfo block and the
286 		 * memory map EFI will return to us. The memory map has an
287 		 * unknown size, so we have to determine that first. Note that
288 		 * the AllocatePages call can itself modify the memory map, so
289 		 * we have to take that into account as well. The changes to
290 		 * the memory map are caused by splitting a range of free
291 		 * memory into two (AFAICT), so that one is marked as being
292 		 * loader data.
293 		 */
294 		sz = 0;
295 		BS->GetMemoryMap(&sz, NULL, &efi_mapkey, &mmsz, &mmver);
296 		sz += mmsz;
297 		sz = (sz + 0xf) & ~0xf;
298 		pages = EFI_SIZE_TO_PAGES(sz + efisz);
299 		status = BS->AllocatePages(AllocateAnyPages, EfiLoaderData,
300 		     pages, &addr);
301 		if (EFI_ERROR(status)) {
302 			printf("%s: AllocatePages error %lu\n", __func__,
303 			    EFI_ERROR_CODE(status));
304 			return (ENOMEM);
305 		}
306 
307 		/*
308 		 * Read the memory map and stash it after bootinfo. Align the
309 		 * memory map on a 16-byte boundary (the bootinfo block is page
310 		 * aligned).
311 		 */
312 		efihdr = (struct efi_map_header *)addr;
313 		mm = (void *)((uint8_t *)efihdr + efisz);
314 		sz = (EFI_PAGE_SIZE * pages) - efisz;
315 
316 		status = BS->GetMemoryMap(&sz, mm, &efi_mapkey, &mmsz, &mmver);
317 		if (EFI_ERROR(status)) {
318 			printf("%s: GetMemoryMap error %lu\n", __func__,
319 			    EFI_ERROR_CODE(status));
320 			return (EINVAL);
321 		}
322 		status = BS->ExitBootServices(IH, efi_mapkey);
323 		if (EFI_ERROR(status) == 0) {
324 			efihdr->memory_size = sz;
325 			efihdr->descriptor_size = mmsz;
326 			efihdr->descriptor_version = mmver;
327 			file_addmetadata(kfp, MODINFOMD_EFI_MAP, efisz + sz,
328 			    efihdr);
329 			return (0);
330 		}
331 		BS->FreePages(addr, pages);
332 	}
333 	printf("ExitBootServices error %lu\n", EFI_ERROR_CODE(status));
334 	return (EINVAL);
335 }
336 
337 /*
338  * Load the information expected by an amd64 kernel.
339  *
340  * - The 'boothowto' argument is constructed.
341  * - The 'bootdev' argument is constructed.
342  * - The 'bootinfo' struct is constructed, and copied into the kernel space.
343  * - The kernel environment is copied into kernel space.
344  * - Module metadata are formatted and placed in kernel space.
345  */
346 int
347 bi_load(char *args, vm_offset_t *modulep, vm_offset_t *kernendp)
348 {
349 	struct preloaded_file *xp, *kfp;
350 	struct devdesc *rootdev;
351 	struct file_metadata *md;
352 	vm_offset_t addr;
353 	uint64_t kernend;
354 	uint64_t envp;
355 	vm_offset_t size;
356 	char *rootdevname;
357 	int howto;
358 #if defined(LOADER_FDT_SUPPORT)
359 	vm_offset_t dtbp;
360 	int dtb_size;
361 #endif
362 #if defined(__arm__)
363 	vm_offset_t vaddr;
364 	size_t i;
365 	/*
366 	 * These metadata addreses must be converted for kernel after
367 	 * relocation.
368 	 */
369 	uint32_t		mdt[] = {
370 	    MODINFOMD_SSYM, MODINFOMD_ESYM, MODINFOMD_KERNEND,
371 	    MODINFOMD_ENVP,
372 #if defined(LOADER_FDT_SUPPORT)
373 	    MODINFOMD_DTBP
374 #endif
375 	};
376 #endif
377 
378 	howto = bi_getboothowto(args);
379 
380 	/*
381 	 * Allow the environment variable 'rootdev' to override the supplied
382 	 * device. This should perhaps go to MI code and/or have $rootdev
383 	 * tested/set by MI code before launching the kernel.
384 	 */
385 	rootdevname = getenv("rootdev");
386 	archsw.arch_getdev((void**)(&rootdev), rootdevname, NULL);
387 	if (rootdev == NULL) {
388 		printf("Can't determine root device.\n");
389 		return(EINVAL);
390 	}
391 
392 	/* Try reading the /etc/fstab file to select the root device */
393 	getrootmount(efi_fmtdev((void *)rootdev));
394 
395 	addr = 0;
396 	for (xp = file_findfile(NULL, NULL); xp != NULL; xp = xp->f_next) {
397 		if (addr < (xp->f_addr + xp->f_size))
398 			addr = xp->f_addr + xp->f_size;
399 	}
400 
401 	/* Pad to a page boundary. */
402 	addr = roundup(addr, PAGE_SIZE);
403 
404 	/* Copy our environment. */
405 	envp = addr;
406 	addr = bi_copyenv(addr);
407 
408 	/* Pad to a page boundary. */
409 	addr = roundup(addr, PAGE_SIZE);
410 
411 #if defined(LOADER_FDT_SUPPORT)
412 	/* Handle device tree blob */
413 	dtbp = addr;
414 	dtb_size = fdt_copy(addr);
415 
416 	/* Pad to a page boundary */
417 	if (dtb_size)
418 		addr += roundup(dtb_size, PAGE_SIZE);
419 #endif
420 
421 	kfp = file_findfile(NULL, "elf kernel");
422 	if (kfp == NULL)
423 		kfp = file_findfile(NULL, "elf64 kernel");
424 	if (kfp == NULL)
425 		panic("can't find kernel file");
426 	kernend = 0;	/* fill it in later */
427 	file_addmetadata(kfp, MODINFOMD_HOWTO, sizeof howto, &howto);
428 	file_addmetadata(kfp, MODINFOMD_ENVP, sizeof envp, &envp);
429 #if defined(LOADER_FDT_SUPPORT)
430 	if (dtb_size)
431 		file_addmetadata(kfp, MODINFOMD_DTBP, sizeof dtbp, &dtbp);
432 	else
433 		printf("WARNING! Trying to fire up the kernel, but no "
434 		    "device tree blob found!\n");
435 #endif
436 	file_addmetadata(kfp, MODINFOMD_KERNEND, sizeof kernend, &kernend);
437 	file_addmetadata(kfp, MODINFOMD_FW_HANDLE, sizeof ST, &ST);
438 
439 	bi_load_efi_data(kfp);
440 
441 	/* Figure out the size and location of the metadata. */
442 	*modulep = addr;
443 	size = bi_copymodules(0);
444 	kernend = roundup(addr + size, PAGE_SIZE);
445 	*kernendp = kernend;
446 
447 	/* patch MODINFOMD_KERNEND */
448 	md = file_findmetadata(kfp, MODINFOMD_KERNEND);
449 	bcopy(&kernend, md->md_data, sizeof kernend);
450 
451 #if defined(__arm__)
452 	*modulep -= __elfN(relocation_offset);
453 
454 	/* Do relocation fixup on metadata of each module. */
455 	for (xp = file_findfile(NULL, NULL); xp != NULL; xp = xp->f_next) {
456 		for (i = 0; i < nitems(mdt); i++) {
457 			md = file_findmetadata(xp, mdt[i]);
458 			if (md) {
459 				bcopy(md->md_data, &vaddr, sizeof vaddr);
460 				vaddr -= __elfN(relocation_offset);
461 				bcopy(&vaddr, md->md_data, sizeof vaddr);
462 			}
463 		}
464 	}
465 #endif
466 
467 	/* Copy module list and metadata. */
468 	(void)bi_copymodules(addr);
469 
470 	return (0);
471 }
472