xref: /freebsd/stand/i386/libi386/multiboot.c (revision 62cfcf62f627e5093fb37026a6d8c98e4d2ef04c)
1 /*-
2  * Copyright (c) 2014 Roger Pau Monné <royger@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 /*
28  * This multiboot implementation only implements a subset of the full
29  * multiboot specification in order to be able to boot Xen and a
30  * FreeBSD Dom0. Trying to use it to boot other multiboot compliant
31  * kernels will most surely fail.
32  *
33  * The full multiboot specification can be found here:
34  * http://www.gnu.org/software/grub/manual/multiboot/multiboot.html
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include <sys/param.h>
41 #include <sys/exec.h>
42 #include <sys/linker.h>
43 #include <sys/module.h>
44 #include <sys/stdint.h>
45 #define _MACHINE_ELF_WANT_32BIT
46 #include <machine/elf.h>
47 #include <string.h>
48 #include <stand.h>
49 
50 #include "bootstrap.h"
51 #include "multiboot.h"
52 #include "libi386.h"
53 #include <btxv86.h>
54 
55 #define MULTIBOOT_SUPPORTED_FLAGS \
56 				(MULTIBOOT_PAGE_ALIGN|MULTIBOOT_MEMORY_INFO)
57 #define NUM_MODULES		2
58 #define METADATA_FIXED_SIZE	(PAGE_SIZE*4)
59 #define METADATA_MODULE_SIZE	PAGE_SIZE
60 
61 #define METADATA_RESV_SIZE(mod_num) \
62 	roundup(METADATA_FIXED_SIZE + METADATA_MODULE_SIZE * mod_num, PAGE_SIZE)
63 
64 extern int elf32_loadfile_raw(char *filename, uint64_t dest,
65     struct preloaded_file **result, int multiboot);
66 extern int elf64_load_modmetadata(struct preloaded_file *fp, uint64_t dest);
67 extern int elf64_obj_loadfile(char *filename, uint64_t dest,
68     struct preloaded_file **result);
69 
70 static int multiboot_loadfile(char *, uint64_t, struct preloaded_file **);
71 static int multiboot_exec(struct preloaded_file *);
72 
73 static int multiboot_obj_loadfile(char *, uint64_t, struct preloaded_file **);
74 static int multiboot_obj_exec(struct preloaded_file *fp);
75 
76 struct file_format multiboot = { multiboot_loadfile, multiboot_exec };
77 struct file_format multiboot_obj =
78     { multiboot_obj_loadfile, multiboot_obj_exec };
79 
80 extern void multiboot_tramp();
81 
82 static const char mbl_name[] = "FreeBSD Loader";
83 
84 static int
85 num_modules(struct preloaded_file *kfp)
86 {
87 	struct kernel_module	*kmp;
88 	int			 mod_num = 0;
89 
90 	for (kmp = kfp->f_modules; kmp != NULL; kmp = kmp->m_next)
91 		mod_num++;
92 
93 	return (mod_num);
94 }
95 
96 static vm_offset_t
97 max_addr(void)
98 {
99 	struct preloaded_file	*fp;
100 	vm_offset_t		 addr = 0;
101 
102 	for (fp = file_findfile(NULL, NULL); fp != NULL; fp = fp->f_next) {
103 		if (addr < (fp->f_addr + fp->f_size))
104 			addr = fp->f_addr + fp->f_size;
105 	}
106 
107 	return (addr);
108 }
109 
110 static int
111 multiboot_loadfile(char *filename, uint64_t dest,
112     struct preloaded_file **result)
113 {
114 	uint32_t		*magic;
115 	int			 i, error;
116 	caddr_t			 header_search;
117 	ssize_t			 search_size;
118 	int			 fd;
119 	struct multiboot_header	*header;
120 	char			*cmdline;
121 
122 	/*
123 	 * Read MULTIBOOT_SEARCH size in order to search for the
124 	 * multiboot magic header.
125 	 */
126 	if (filename == NULL)
127 		return (EFTYPE);
128 	if ((fd = open(filename, O_RDONLY)) == -1)
129 		return (errno);
130 	header_search = malloc(MULTIBOOT_SEARCH);
131 	if (header_search == NULL) {
132 		close(fd);
133 		return (ENOMEM);
134 	}
135 	search_size = read(fd, header_search, MULTIBOOT_SEARCH);
136 	magic = (uint32_t *)header_search;
137 
138 	header = NULL;
139 	for (i = 0; i < (search_size / sizeof(uint32_t)); i++) {
140 		if (magic[i] == MULTIBOOT_HEADER_MAGIC) {
141 			header = (struct multiboot_header *)&magic[i];
142 			break;
143 		}
144 	}
145 
146 	if (header == NULL) {
147 		error = EFTYPE;
148 		goto out;
149 	}
150 
151 	/* Valid multiboot header has been found, validate checksum */
152 	if (header->magic + header->flags + header->checksum != 0) {
153 		printf(
154 	"Multiboot checksum failed, magic: 0x%x flags: 0x%x checksum: 0x%x\n",
155 	header->magic, header->flags, header->checksum);
156 		error = EFTYPE;
157 		goto out;
158 	}
159 
160 	if ((header->flags & ~MULTIBOOT_SUPPORTED_FLAGS) != 0) {
161 		printf("Unsupported multiboot flags found: 0x%x\n",
162 		    header->flags);
163 		error = EFTYPE;
164 		goto out;
165 	}
166 
167 	error = elf32_loadfile_raw(filename, dest, result, 1);
168 	if (error != 0) {
169 		printf(
170 	"elf32_loadfile_raw failed: %d unable to load multiboot kernel\n",
171 	error);
172 		goto out;
173 	}
174 
175 	/*
176 	 * f_addr is already aligned to PAGE_SIZE, make sure
177 	 * f_size it's also aligned so when the modules are loaded
178 	 * they are aligned to PAGE_SIZE.
179 	 */
180 	(*result)->f_size = roundup((*result)->f_size, PAGE_SIZE);
181 
182 out:
183 	free(header_search);
184 	close(fd);
185 	return (error);
186 }
187 
188 static int
189 multiboot_exec(struct preloaded_file *fp)
190 {
191 	vm_offset_t			 module_start, last_addr, metadata_size;
192 	vm_offset_t			 modulep, kernend, entry;
193 	struct file_metadata		*md;
194 	Elf_Ehdr			*ehdr;
195 	struct multiboot_info		*mb_info = NULL;
196 	struct multiboot_mod_list	*mb_mod = NULL;
197 	char				*cmdline = NULL;
198 	size_t				 len;
199 	int				 error, mod_num;
200 
201 	/*
202 	 * Don't pass the memory size found by the bootloader, the memory
203 	 * available to Dom0 will be lower than that.
204 	 */
205 	unsetenv("smbios.memory.enabled");
206 
207 	/* Allocate the multiboot struct and fill the basic details. */
208 	mb_info = malloc(sizeof(struct multiboot_info));
209 	if (mb_info == NULL) {
210 		error = ENOMEM;
211 		goto error;
212 	}
213 	bzero(mb_info, sizeof(struct multiboot_info));
214 	mb_info->flags = MULTIBOOT_INFO_MEMORY|MULTIBOOT_INFO_BOOT_LOADER_NAME;
215 	mb_info->mem_lower = bios_basemem / 1024;
216 	mb_info->mem_upper = bios_extmem / 1024;
217 	mb_info->boot_loader_name = VTOP(mbl_name);
218 
219 	/* Set the Xen command line. */
220 	if (fp->f_args == NULL) {
221 		/* Add the Xen command line if it is set. */
222 		cmdline = getenv("xen_cmdline");
223 		if (cmdline != NULL) {
224 			fp->f_args = strdup(cmdline);
225 			if (fp->f_args == NULL) {
226 				error = ENOMEM;
227 				goto error;
228 			}
229 		}
230 	}
231 	if (fp->f_args != NULL) {
232 		len = strlen(fp->f_name) + 1 + strlen(fp->f_args) + 1;
233 		cmdline = malloc(len);
234 		if (cmdline == NULL) {
235 			error = ENOMEM;
236 			goto error;
237 		}
238 		snprintf(cmdline, len, "%s %s", fp->f_name, fp->f_args);
239 		mb_info->cmdline = VTOP(cmdline);
240 		mb_info->flags |= MULTIBOOT_INFO_CMDLINE;
241 	}
242 
243 	/* Find the entry point of the Xen kernel and save it for later */
244 	if ((md = file_findmetadata(fp, MODINFOMD_ELFHDR)) == NULL) {
245 		printf("Unable to find %s entry point\n", fp->f_name);
246 		error = EINVAL;
247 		goto error;
248 	}
249 	ehdr = (Elf_Ehdr *)&(md->md_data);
250 	entry = ehdr->e_entry & 0xffffff;
251 
252 	/*
253 	 * Prepare the multiboot module list, Xen assumes the first
254 	 * module is the Dom0 kernel, and the second one is the initramfs.
255 	 * This is not optimal for FreeBSD, that doesn't have a initramfs
256 	 * but instead loads modules dynamically and creates the metadata
257 	 * info on-the-fly.
258 	 *
259 	 * As expected, the first multiboot module is going to be the
260 	 * FreeBSD kernel loaded as a raw file. The second module is going
261 	 * to contain the metadata info and the loaded modules.
262 	 *
263 	 * On native FreeBSD loads all the modules and then places the
264 	 * metadata info at the end, but this is painful when running on Xen,
265 	 * because it relocates the second multiboot module wherever it
266 	 * likes. In order to workaround this limitation the metadata
267 	 * information is placed at the start of the second module and
268 	 * the original modulep value is saved together with the other
269 	 * metadata, so we can relocate everything.
270 	 *
271 	 * Native layout:
272 	 *           fp->f_addr + fp->f_size
273 	 * +---------+----------------+------------+
274 	 * |         |                |            |
275 	 * | Kernel  |    Modules     |  Metadata  |
276 	 * |         |                |            |
277 	 * +---------+----------------+------------+
278 	 * fp->f_addr                 modulep      kernend
279 	 *
280 	 * Xen layout:
281 	 *
282 	 * Initial:
283 	 *                      fp->f_addr + fp->f_size
284 	 * +---------+----------+----------------+------------+
285 	 * |         |          |                |            |
286 	 * | Kernel  | Reserved |    Modules     |  Metadata  |
287 	 * |         |          |                |  dry run   |
288 	 * +---------+----------+----------------+------------+
289 	 * fp->f_addr
290 	 *
291 	 * After metadata polacement (ie: final):
292 	 *                                  fp->f_addr + fp->f_size
293 	 * +-----------+---------+----------+----------------+
294 	 * |           |         |          |                |
295 	 * |  Kernel   |  Free   | Metadata |    Modules     |
296 	 * |           |         |          |                |
297 	 * +-----------+---------+----------+----------------+
298 	 * fp->f_addr            modulep                     kernend
299 	 * \__________/          \__________________________/
300 	 *  Multiboot module 0    Multiboot module 1
301 	 */
302 
303 	fp = file_findfile(NULL, "elf kernel");
304 	if (fp == NULL) {
305 		printf("No FreeBSD kernel provided, aborting\n");
306 		error = EINVAL;
307 		goto error;
308 	}
309 
310 	if (fp->f_metadata != NULL) {
311 		printf("FreeBSD kernel already contains metadata, aborting\n");
312 		error = EINVAL;
313 		goto error;
314 	}
315 
316 
317 	mb_mod = malloc(sizeof(struct multiboot_mod_list) * NUM_MODULES);
318 	if (mb_mod == NULL) {
319 		error = ENOMEM;
320 		goto error;
321 	}
322 
323 	bzero(mb_mod, sizeof(struct multiboot_mod_list) * NUM_MODULES);
324 
325 	/*
326 	 * Calculate how much memory is needed for the metatdata. We did
327 	 * an approximation of the maximum size when loading the kernel,
328 	 * but now we know the exact size, so we can release some of this
329 	 * preallocated memory if not needed.
330 	 */
331 	last_addr = roundup(max_addr(), PAGE_SIZE);
332 	mod_num = num_modules(fp);
333 
334 	/*
335 	 * Place the metadata after the last used address in order to
336 	 * calculate it's size, this will not be used.
337 	 */
338 	error = bi_load64(fp->f_args, last_addr, &modulep, &kernend, 0);
339 	if (error != 0) {
340 		printf("bi_load64 failed: %d\n", error);
341 		goto error;
342 	}
343 	metadata_size = roundup(kernend - last_addr, PAGE_SIZE);
344 
345 	/* Check that the size is not greater than what we have reserved */
346 	if (metadata_size > METADATA_RESV_SIZE(mod_num)) {
347 		printf("Required memory for metadata is greater than reserved "
348 		    "space, please increase METADATA_FIXED_SIZE and "
349 		    "METADATA_MODULE_SIZE and rebuild the loader\n");
350 		error = ENOMEM;
351 		goto error;
352 	}
353 
354 	/* Clean the metadata added to the kernel in the bi_load64 dry run */
355 	file_removemetadata(fp);
356 
357 	/*
358 	 * This is the position where the second multiboot module
359 	 * will be placed.
360 	 */
361 	module_start = fp->f_addr + fp->f_size - metadata_size;
362 
363 	error = bi_load64(fp->f_args, module_start, &modulep, &kernend, 0);
364 	if (error != 0) {
365 		printf("bi_load64 failed: %d\n", error);
366 		goto error;
367 	}
368 
369 	mb_mod[0].mod_start = fp->f_addr;
370 	mb_mod[0].mod_end = fp->f_addr + fp->f_size;
371 	mb_mod[0].mod_end -= METADATA_RESV_SIZE(mod_num);
372 
373 	mb_mod[1].mod_start = module_start;
374 	mb_mod[1].mod_end = last_addr;
375 
376 	mb_info->mods_count = NUM_MODULES;
377 	mb_info->mods_addr = VTOP(mb_mod);
378 	mb_info->flags |= MULTIBOOT_INFO_MODS;
379 
380 	dev_cleanup();
381 	__exec((void *)VTOP(multiboot_tramp), (void *)entry,
382 	    (void *)VTOP(mb_info));
383 
384 	panic("exec returned");
385 
386 error:
387 	if (mb_mod)
388 		free(mb_mod);
389 	if (mb_info)
390 		free(mb_info);
391 	if (cmdline)
392 		free(cmdline);
393 	return (error);
394 }
395 
396 static int
397 multiboot_obj_loadfile(char *filename, uint64_t dest,
398     struct preloaded_file **result)
399 {
400 	struct preloaded_file	*mfp, *kfp, *rfp;
401 	struct kernel_module	*kmp;
402 	int			 error, mod_num;
403 
404 	/* See if there's a multiboot kernel loaded */
405 	mfp = file_findfile(NULL, "elf multiboot kernel");
406 	if (mfp == NULL)
407 		return (EFTYPE);
408 
409 	/*
410 	 * We have a multiboot kernel loaded, see if there's a FreeBSD
411 	 * kernel loaded also.
412 	 */
413 	kfp = file_findfile(NULL, "elf kernel");
414 	if (kfp == NULL) {
415 		/*
416 		 * No kernel loaded, this must be it. The kernel has to
417 		 * be loaded as a raw file, it will be processed by
418 		 * Xen and correctly loaded as an ELF file.
419 		 */
420 		rfp = file_loadraw(filename, "elf kernel", 0);
421 		if (rfp == NULL) {
422 			printf(
423 			"Unable to load %s as a multiboot payload kernel\n",
424 			filename);
425 			return (EINVAL);
426 		}
427 
428 		/* Load kernel metadata... */
429 		setenv("kernelname", filename, 1);
430 		error = elf64_load_modmetadata(rfp, rfp->f_addr + rfp->f_size);
431 		if (error) {
432 			printf("Unable to load kernel %s metadata error: %d\n",
433 			    rfp->f_name, error);
434 			return (EINVAL);
435 		}
436 
437 		/*
438 		 * Save space at the end of the kernel in order to place
439 		 * the metadata information. We do an approximation of the
440 		 * max metadata size, this is not optimal but it's probably
441 		 * the best we can do at this point. Once all modules are
442 		 * loaded and the size of the metadata is known this
443 		 * space will be recovered if not used.
444 		 */
445 		mod_num = num_modules(rfp);
446 		rfp->f_size = roundup(rfp->f_size, PAGE_SIZE);
447 		rfp->f_size += METADATA_RESV_SIZE(mod_num);
448 		*result = rfp;
449 	} else {
450 		/* The rest should be loaded as regular modules */
451 		error = elf64_obj_loadfile(filename, dest, result);
452 		if (error != 0) {
453 			printf("Unable to load %s as an object file, error: %d",
454 			    filename, error);
455 			return (error);
456 		}
457 	}
458 
459 	return (0);
460 }
461 
462 static int
463 multiboot_obj_exec(struct preloaded_file *fp)
464 {
465 
466 	return (EFTYPE);
467 }
468