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