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/metadata.h>
40#include <machine/psl.h>
41#include <machine/specialreg.h>
42
43#include <efi.h>
44#include <efilib.h>
45
46#include "bootstrap.h"
47#include "framebuffer.h"
48#include "x86_efi.h"
49
50UINTN x86_efi_mapkey;
51
52static const char howto_switches[] = "aCdrgDmphsv";
53static int howto_masks[] = {
54	RB_ASKNAME, RB_CDROM, RB_KDB, RB_DFLTROOT, RB_GDB, RB_MULTIPLE,
55	RB_MUTE, RB_PAUSE, RB_SERIAL, RB_SINGLE, RB_VERBOSE
56};
57
58static int
59bi_getboothowto(char *kargs)
60{
61	const char *sw;
62	char *opts;
63	char *console;
64	int howto, i;
65
66	howto = 0;
67
68	/* Get the boot options from the environment first. */
69	for (i = 0; howto_names[i].ev != NULL; i++) {
70		if (getenv(howto_names[i].ev) != NULL)
71			howto |= howto_names[i].mask;
72	}
73
74	console = getenv("console");
75	if (console != NULL) {
76		if (strcmp(console, "comconsole") == 0)
77			howto |= RB_SERIAL;
78		if (strcmp(console, "nullconsole") == 0)
79			howto |= RB_MUTE;
80	}
81
82	/* Parse kargs */
83	if (kargs == NULL)
84		return (howto);
85
86	opts = strchr(kargs, '-');
87	while (opts != NULL) {
88		while (*(++opts) != '\0') {
89			sw = strchr(howto_switches, *opts);
90			if (sw == NULL)
91				break;
92			howto |= howto_masks[sw - howto_switches];
93		}
94		opts = strchr(opts, '-');
95	}
96
97	return (howto);
98}
99
100/*
101 * Copy the environment into the load area starting at (addr).
102 * Each variable is formatted as <name>=<value>, with a single nul
103 * separating each variable, and a double nul terminating the environment.
104 */
105static vm_offset_t
106bi_copyenv(vm_offset_t start)
107{
108	struct env_var *ep;
109	vm_offset_t addr, last;
110	size_t len;
111
112	addr = last = start;
113
114	/* Traverse the environment. */
115	for (ep = environ; ep != NULL; ep = ep->ev_next) {
116		len = strlen(ep->ev_name);
117		if (x86_efi_copyin(ep->ev_name, addr, len) != len)
118			break;
119		addr += len;
120		if (x86_efi_copyin("=", addr, 1) != 1)
121			break;
122		addr++;
123		if (ep->ev_value != NULL) {
124			len = strlen(ep->ev_value);
125			if (x86_efi_copyin(ep->ev_value, addr, len) != len)
126				break;
127			addr += len;
128		}
129		if (x86_efi_copyin("", addr, 1) != 1)
130			break;
131		last = ++addr;
132	}
133
134	if (x86_efi_copyin("", last++, 1) != 1)
135		last = start;
136	return(last);
137}
138
139/*
140 * Copy module-related data into the load area, where it can be
141 * used as a directory for loaded modules.
142 *
143 * Module data is presented in a self-describing format.  Each datum
144 * is preceded by a 32-bit identifier and a 32-bit size field.
145 *
146 * Currently, the following data are saved:
147 *
148 * MOD_NAME	(variable)		module name (string)
149 * MOD_TYPE	(variable)		module type (string)
150 * MOD_ARGS	(variable)		module parameters (string)
151 * MOD_ADDR	sizeof(vm_offset_t)	module load address
152 * MOD_SIZE	sizeof(size_t)		module size
153 * MOD_METADATA	(variable)		type-specific metadata
154 */
155#define	COPY32(v, a, c) {					\
156	uint32_t x = (v);					\
157	if (c)							\
158		x86_efi_copyin(&x, a, sizeof(x));		\
159	a += sizeof(x);						\
160}
161
162#define	MOD_STR(t, a, s, c) {					\
163	COPY32(t, a, c);					\
164	COPY32(strlen(s) + 1, a, c);				\
165	if (c)							\
166		x86_efi_copyin(s, a, strlen(s) + 1);		\
167	a += roundup(strlen(s) + 1, sizeof(uint64_t));		\
168}
169
170#define	MOD_NAME(a, s, c)	MOD_STR(MODINFO_NAME, a, s, c)
171#define	MOD_TYPE(a, s, c)	MOD_STR(MODINFO_TYPE, a, s, c)
172#define	MOD_ARGS(a, s, c)	MOD_STR(MODINFO_ARGS, a, s, c)
173
174#define	MOD_VAR(t, a, s, c) {					\
175	COPY32(t, a, c);					\
176	COPY32(sizeof(s), a, c);				\
177	if (c)							\
178		x86_efi_copyin(&s, a, sizeof(s));		\
179	a += roundup(sizeof(s), sizeof(uint64_t));		\
180}
181
182#define	MOD_ADDR(a, s, c)	MOD_VAR(MODINFO_ADDR, a, s, c)
183#define	MOD_SIZE(a, s, c)	MOD_VAR(MODINFO_SIZE, a, s, c)
184
185#define	MOD_METADATA(a, mm, c) {				\
186	COPY32(MODINFO_METADATA | mm->md_type, a, c);		\
187	COPY32(mm->md_size, a, c);				\
188	if (c)							\
189		x86_efi_copyin(mm->md_data, a, mm->md_size);	\
190	a += roundup(mm->md_size, sizeof(uint64_t));		\
191}
192
193#define	MOD_END(a, c) {						\
194	COPY32(MODINFO_END, a, c);				\
195	COPY32(0, a, c);					\
196}
197
198static vm_offset_t
199bi_copymodules(vm_offset_t addr)
200{
201	struct preloaded_file *fp;
202	struct file_metadata *md;
203	int c;
204	uint64_t v;
205
206	c = addr != 0;
207	/* Start with the first module on the list, should be the kernel. */
208	for (fp = file_findfile(NULL, NULL); fp != NULL; fp = fp->f_next) {
209		MOD_NAME(addr, fp->f_name, c); /* This must come first. */
210		MOD_TYPE(addr, fp->f_type, c);
211		if (fp->f_args)
212			MOD_ARGS(addr, fp->f_args, c);
213		v = fp->f_addr;
214		MOD_ADDR(addr, v, c);
215		v = fp->f_size;
216		MOD_SIZE(addr, v, c);
217		for (md = fp->f_metadata; md != NULL; md = md->md_next)
218			if (!(md->md_type & MODINFOMD_NOCOPY))
219				MOD_METADATA(addr, md, c);
220	}
221	MOD_END(addr, c);
222	return(addr);
223}
224
225static int
226bi_load_efi_data(struct preloaded_file *kfp)
227{
228	EFI_MEMORY_DESCRIPTOR *mm;
229	EFI_PHYSICAL_ADDRESS addr;
230	EFI_STATUS status;
231	size_t efisz;
232	UINTN mmsz, pages, sz;
233	UINT32 mmver;
234	struct efi_map_header *efihdr;
235	struct efi_fb efifb;
236
237	if (efi_find_framebuffer(&efifb) == 0)
238		file_addmetadata(kfp, MODINFOMD_EFI_FB, sizeof(efifb), &efifb);
239
240	efisz = (sizeof(struct efi_map_header) + 0xf) & ~0xf;
241
242	/*
243	 * Allocate enough pages to hold the bootinfo block and the memory
244	 * map EFI will return to us. The memory map has an unknown size,
245	 * so we have to determine that first. Note that the AllocatePages
246	 * call can itself modify the memory map, so we have to take that
247	 * into account as well. The changes to the memory map are caused
248	 * by splitting a range of free memory into two (AFAICT), so that
249	 * one is marked as being loader data.
250	 */
251	sz = 0;
252	BS->GetMemoryMap(&sz, NULL, &x86_efi_mapkey, &mmsz, &mmver);
253	sz += mmsz;
254	sz = (sz + 0xf) & ~0xf;
255	pages = EFI_SIZE_TO_PAGES(sz + efisz);
256	status = BS->AllocatePages(AllocateAnyPages, EfiLoaderData, pages,
257	    &addr);
258	if (EFI_ERROR(status)) {
259		printf("%s: AllocatePages() returned 0x%lx\n", __func__,
260		    (long)status);
261		return (ENOMEM);
262	}
263
264	/*
265	 * Read the memory map and stash it after bootinfo. Align the
266	 * memory map on a 16-byte boundary (the bootinfo block is page
267	 * aligned).
268	 */
269	efihdr = (struct efi_map_header *)addr;
270	mm = (void *)((uint8_t *)efihdr + efisz);
271	sz = (EFI_PAGE_SIZE * pages) - efisz;
272	status = BS->GetMemoryMap(&sz, mm, &x86_efi_mapkey, &mmsz, &mmver);
273	if (EFI_ERROR(status)) {
274		printf("%s: GetMemoryMap() returned 0x%lx\n", __func__,
275		    (long)status);
276		return (EINVAL);
277	}
278
279	efihdr->memory_size = sz;
280	efihdr->descriptor_size = mmsz;
281	efihdr->descriptor_version = mmver;
282
283	file_addmetadata(kfp, MODINFOMD_EFI_MAP, efisz + sz, efihdr);
284
285	return (0);
286}
287
288/*
289 * Load the information expected by an amd64 kernel.
290 *
291 * - The 'boothowto' argument is constructed.
292 * - The 'bootdev' argument is constructed.
293 * - The 'bootinfo' struct is constructed, and copied into the kernel space.
294 * - The kernel environment is copied into kernel space.
295 * - Module metadata are formatted and placed in kernel space.
296 */
297int
298bi_load(char *args, vm_offset_t *modulep, vm_offset_t *kernendp)
299{
300	struct preloaded_file *xp, *kfp;
301	struct devdesc *rootdev;
302	struct file_metadata *md;
303	vm_offset_t addr;
304	uint64_t kernend;
305	uint64_t envp;
306	vm_offset_t size;
307	char *rootdevname;
308	int howto;
309
310	howto = bi_getboothowto(args);
311
312	/*
313	 * Allow the environment variable 'rootdev' to override the supplied
314	 * device. This should perhaps go to MI code and/or have $rootdev
315	 * tested/set by MI code before launching the kernel.
316	 */
317	rootdevname = getenv("rootdev");
318	x86_efi_getdev((void**)(&rootdev), rootdevname, NULL);
319	if (rootdev == NULL) {
320		printf("Can't determine root device.\n");
321		return(EINVAL);
322	}
323
324	/* Try reading the /etc/fstab file to select the root device */
325	getrootmount(x86_efi_fmtdev((void *)rootdev));
326
327	addr = 0;
328	for (xp = file_findfile(NULL, NULL); xp != NULL; xp = xp->f_next) {
329		if (addr < (xp->f_addr + xp->f_size))
330			addr = xp->f_addr + xp->f_size;
331	}
332
333	/* Pad to a page boundary. */
334	addr = roundup(addr, PAGE_SIZE);
335
336	/* Copy our environment. */
337	envp = addr;
338	addr = bi_copyenv(addr);
339
340	/* Pad to a page boundary. */
341	addr = roundup(addr, PAGE_SIZE);
342
343	kfp = file_findfile(NULL, "elf kernel");
344	if (kfp == NULL)
345		kfp = file_findfile(NULL, "elf64 kernel");
346	if (kfp == NULL)
347		panic("can't find kernel file");
348	kernend = 0;	/* fill it in later */
349	file_addmetadata(kfp, MODINFOMD_HOWTO, sizeof howto, &howto);
350	file_addmetadata(kfp, MODINFOMD_ENVP, sizeof envp, &envp);
351	file_addmetadata(kfp, MODINFOMD_KERNEND, sizeof kernend, &kernend);
352
353	bi_load_efi_data(kfp);
354
355	/* Figure out the size and location of the metadata. */
356	*modulep = addr;
357	size = bi_copymodules(0);
358	kernend = roundup(addr + size, PAGE_SIZE);
359	*kernendp = kernend;
360
361	/* patch MODINFOMD_KERNEND */
362	md = file_findmetadata(kfp, MODINFOMD_KERNEND);
363	bcopy(&kernend, md->md_data, sizeof kernend);
364
365	/* Copy module list and metadata. */
366	(void)bi_copymodules(addr);
367
368	return (0);
369}
370