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