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