Path: blob/main/stand/efi/loader/arch/amd64/multiboot2.c
106465 views
/*-1* Copyright (c) 2021 Roger Pau Monné <[email protected]>2* All rights reserved.3*4* Redistribution and use in source and binary forms, with or without5* modification, are permitted provided that the following conditions6* are met:7* 1. Redistributions of source code must retain the above copyright8* notice, this list of conditions and the following disclaimer.9* 2. Redistributions in binary form must reproduce the above copyright10* notice, this list of conditions and the following disclaimer in the11* documentation and/or other materials provided with the distribution.12*13* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND14* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE15* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE16* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE17* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL18* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS19* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)20* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT21* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY22* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF23* SUCH DAMAGE.24*/2526/*27* This multiboot2 implementation only implements a subset of the full28* multiboot2 specification in order to be able to boot Xen and a29* FreeBSD Dom0. Trying to use it to boot other multiboot2 compliant30* kernels will most surely fail.31*32* The full multiboot specification can be found here:33* https://www.gnu.org/software/grub/manual/multiboot2/multiboot.html34*/3536#include <sys/param.h>37#include <sys/exec.h>38#include <sys/linker.h>39#include <sys/module.h>40#include <sys/stdint.h>41#define _MACHINE_ELF_WANT_32BIT42#include <machine/elf.h>43#include <machine/metadata.h>44#include <string.h>45#include <stand.h>4647#include <efi.h>48#include <efilib.h>4950#include "bootstrap.h"51#include "multiboot2.h"52#include "loader_efi.h"53#include "modinfo.h"5455extern int elf32_loadfile_raw(char *filename, uint64_t dest,56struct preloaded_file **result, int multiboot);57extern int elf64_load_modmetadata(struct preloaded_file *fp, uint64_t dest);58extern int elf64_obj_loadfile(char *filename, uint64_t dest,59struct preloaded_file **result);6061extern void multiboot2_exec(void *entry, uint64_t multiboot_info,62uint64_t stack);6364/*65* Multiboot2 header information to pass between the loading and the exec66* functions.67*/68struct mb2hdr {69uint32_t efi64_entry;70};7172static int73loadfile(char *filename, uint64_t dest, struct preloaded_file **result)74{75unsigned int i;76int error, fd;77void *header_search = NULL;78void *multiboot = NULL;79ssize_t search_size;80struct multiboot_header *header;81struct mb2hdr hdr;82bool keep_bs = false;8384/*85* Read MULTIBOOT_SEARCH size in order to search for the86* multiboot magic header.87*/88if (filename == NULL)89return (EFTYPE);90if ((fd = open(filename, O_RDONLY)) == -1)91return (errno);92header_search = malloc(MULTIBOOT_SEARCH);93if (header_search == NULL) {94error = ENOMEM;95goto out;96}97search_size = read(fd, header_search, MULTIBOOT_SEARCH);9899for (i = 0; i < search_size; i += MULTIBOOT_HEADER_ALIGN) {100header = header_search + i;101if (header->magic == MULTIBOOT2_HEADER_MAGIC)102break;103}104105if (i >= search_size) {106error = EFTYPE;107goto out;108}109110/* Valid multiboot header has been found, validate checksum */111if (header->magic + header->architecture + header->header_length +112header->checksum != 0) {113printf("Multiboot checksum failed, magic: %#x "114"architecture: %#x header_length %#x checksum: %#x\n",115header->magic, header->architecture, header->header_length,116header->checksum);117error = EFTYPE;118goto out;119}120121if (header->architecture != MULTIBOOT2_ARCHITECTURE_I386) {122printf("Unsupported architecture: %#x\n",123header->architecture);124error = EFTYPE;125goto out;126}127128multiboot = malloc(header->header_length - sizeof(*header));129error = lseek(fd, i + sizeof(*header), SEEK_SET);130if (error != i + sizeof(*header)) {131printf("Unable to set file pointer to header location: %d\n",132error);133goto out;134}135search_size = read(fd, multiboot,136header->header_length - sizeof(*header));137138bzero(&hdr, sizeof(hdr));139for (i = 0; i < search_size; ) {140struct multiboot_header_tag *tag;141struct multiboot_header_tag_entry_address *entry;142struct multiboot_header_tag_information_request *req;143unsigned int j;144145tag = multiboot + i;146147switch(tag->type) {148case MULTIBOOT_HEADER_TAG_INFORMATION_REQUEST:149req = (void *)tag;150for (j = 0;151j < (tag->size - sizeof(*tag)) / sizeof(uint32_t);152j++) {153switch (req->requests[j]) {154case MULTIBOOT_TAG_TYPE_MMAP:155case MULTIBOOT_TAG_TYPE_BASIC_MEMINFO:156/* Only applicable to BIOS. */157break;158159case MULTIBOOT_TAG_TYPE_EFI_BS:160case MULTIBOOT_TAG_TYPE_EFI64:161case MULTIBOOT_TAG_TYPE_EFI64_IH:162/* Tags unconditionally added. */163break;164165default:166if (req->flags &167MULTIBOOT_HEADER_TAG_OPTIONAL)168break;169170printf(171"Unknown non-optional information request %u\n",172req->requests[j]);173error = EINVAL;174goto out;175}176}177break;178179case MULTIBOOT_HEADER_TAG_EFI_BS:180/* Never shut down BS. */181keep_bs = true;182break;183184case MULTIBOOT_HEADER_TAG_MODULE_ALIGN:185/* We will align modules by default already. */186case MULTIBOOT_HEADER_TAG_END:187break;188189case MULTIBOOT_HEADER_TAG_ENTRY_ADDRESS_EFI64:190entry = (void *)tag;191hdr.efi64_entry = entry->entry_addr;192break;193194default:195if (tag->flags & MULTIBOOT_HEADER_TAG_OPTIONAL)196break;197printf("Unknown header tag %#x not optional\n",198tag->type);199error = EINVAL;200goto out;201}202203i += roundup2(tag->size, MULTIBOOT_TAG_ALIGN);204if (tag->type == MULTIBOOT_HEADER_TAG_END)205break;206}207208if (hdr.efi64_entry == 0) {209printf("No EFI64 entry address provided\n");210error = EINVAL;211goto out;212}213if (!keep_bs) {214printf("Unable to boot MB2 with BS exited\n");215error = EINVAL;216goto out;217}218219error = elf32_loadfile_raw(filename, dest, result, 1);220if (error != 0) {221printf(222"elf32_loadfile_raw failed: %d unable to load multiboot kernel\n",223error);224goto out;225}226227file_addmetadata(*result, MODINFOMD_NOCOPY | MODINFOMD_MB2HDR,228sizeof(hdr), &hdr);229230/*231* f_addr is already aligned to PAGE_SIZE, make sure232* f_size it's also aligned so when the modules are loaded233* they are aligned to PAGE_SIZE.234*/235(*result)->f_size = roundup((*result)->f_size, PAGE_SIZE);236237out:238if (header_search != NULL)239free(header_search);240if (multiboot != NULL)241free(multiboot);242close(fd);243return (error);244}245246static unsigned int add_string(void *buf, unsigned int type, const char *str)247{248struct multiboot_tag *tag;249250tag = buf;251tag->type = type;252tag->size = sizeof(*tag) + strlen(str) + 1;253strcpy(buf + sizeof(*tag), str);254return (roundup2(tag->size, MULTIBOOT_TAG_ALIGN));255}256257static unsigned int add_efi(void *buf)258{259struct multiboot_tag *bs;260struct multiboot_tag_efi64 *efi64;261struct multiboot_tag_efi64_ih *ih;262unsigned int len;263264len = 0;265bs = buf;266bs->type = MULTIBOOT_TAG_TYPE_EFI_BS;267bs->size = sizeof(*bs);268len += roundup2(bs->size, MULTIBOOT_TAG_ALIGN);269270efi64 = buf + len;271efi64->type = MULTIBOOT_TAG_TYPE_EFI64;272efi64->size = sizeof(*efi64);273efi64->pointer = (uintptr_t)ST;274len += roundup2(efi64->size, MULTIBOOT_TAG_ALIGN);275276ih = buf + len;277ih->type = MULTIBOOT_TAG_TYPE_EFI64_IH;278ih->size = sizeof(*ih);279ih->pointer = (uintptr_t)IH;280281return (len + roundup2(ih->size, MULTIBOOT_TAG_ALIGN));282}283284static unsigned int add_module(void *buf, vm_offset_t start, vm_offset_t end,285const char *cmdline)286{287struct multiboot_tag_module *mod;288289mod = buf;290mod->type = MULTIBOOT_TAG_TYPE_MODULE;291mod->size = sizeof(*mod);292mod->mod_start = start;293mod->mod_end = end;294if (cmdline != NULL)295{296strcpy(buf + sizeof(*mod), cmdline);297mod->size += strlen(cmdline) + 1;298}299300return (roundup2(mod->size, MULTIBOOT_TAG_ALIGN));301}302303static unsigned int add_end(void *buf)304{305struct multiboot_tag *tag;306307tag = buf;308tag->type = MULTIBOOT_TAG_TYPE_END;309tag->size = sizeof(*tag);310311return (roundup2(tag->size, MULTIBOOT_TAG_ALIGN));312}313314static int315exec(struct preloaded_file *fp)316{317EFI_PHYSICAL_ADDRESS addr = 0;318EFI_PHYSICAL_ADDRESS stack = 0;319EFI_STATUS status;320void *multiboot_space;321vm_offset_t modulep, kernend, kern_base,322payload_base;323char *cmdline = NULL;324size_t len;325int error;326uint32_t *total_size;327struct file_metadata *md;328struct xen_header header;329struct mb2hdr *hdr;330331332_Static_assert(sizeof(header) <= PAGE_SIZE, "header too big");333334if ((md = file_findmetadata(fp,335MODINFOMD_NOCOPY | MODINFOMD_MB2HDR)) == NULL) {336printf("Missing Multiboot2 EFI64 entry point\n");337return(EFTYPE);338}339hdr = (void *)&md->md_data;340341status = BS->AllocatePages(AllocateAnyPages, EfiLoaderData,342EFI_SIZE_TO_PAGES(PAGE_SIZE), &addr);343if (EFI_ERROR(status)) {344printf("Failed to allocate pages for multiboot2 header: %lu\n",345DECODE_ERROR(status));346error = ENOMEM;347goto error;348}349status = BS->AllocatePages(AllocateAnyPages, EfiLoaderData,350EFI_SIZE_TO_PAGES(128 * 1024), &stack);351if (EFI_ERROR(status)) {352printf("Failed to allocate pages for Xen stack: %lu\n",353DECODE_ERROR(status));354error = ENOMEM;355goto error;356}357358/*359* Scratch space to build the multiboot2 header. Reserve the start of360* the space to place the header with the size, which we don't know361* yet.362*/363multiboot_space = (void *)(uintptr_t)(addr + sizeof(uint32_t) * 2);364365/*366* Don't pass the memory size found by the bootloader, the memory367* available to Dom0 will be lower than that.368*/369unsetenv("smbios.memory.enabled");370371/* Set the Xen command line. */372if (fp->f_args == NULL) {373/* Add the Xen command line if it is set. */374cmdline = getenv("xen_cmdline");375if (cmdline != NULL) {376fp->f_args = strdup(cmdline);377if (fp->f_args == NULL) {378error = ENOMEM;379goto error;380}381}382}383if (fp->f_args != NULL) {384len = strlen(fp->f_name) + 1 + strlen(fp->f_args) + 1;385cmdline = malloc(len);386if (cmdline == NULL) {387error = ENOMEM;388goto error;389}390snprintf(cmdline, len, "%s %s", fp->f_name, fp->f_args);391multiboot_space += add_string(multiboot_space,392MULTIBOOT_TAG_TYPE_CMDLINE, cmdline);393free(cmdline);394}395396multiboot_space += add_string(multiboot_space,397MULTIBOOT_TAG_TYPE_BOOT_LOADER_NAME, "FreeBSD Loader");398multiboot_space += add_efi(multiboot_space);399400/*401* Prepare the multiboot module list, Xen assumes the first402* module is the Dom0 kernel, and the second one is the initramfs.403* This is not optimal for FreeBSD, that doesn't have a initramfs404* but instead loads modules dynamically and creates the metadata405* info on-the-fly.406*407* As expected, the first multiboot module is going to be the408* FreeBSD kernel loaded as a raw file. The second module is going409* to contain the metadata info and the loaded modules.410*411* There's a small header prefixed in the second module that contains412* some information required to calculate the relocated address of413* modulep based on the original offset of modulep from the start of414* the module address. Note other fields might be added to this header415* if required.416*417* Native layout:418* fp->f_addr + fp->f_size419* +---------+----------------+------------+420* | | | |421* | Kernel | Modules | Metadata |422* | | | |423* +---------+----------------+------------+424* fp->f_addr modulep kernend425*426* Xen dom0 layout:427* fp->f_addr fp->f_addr + fp->f_size428* +---------+------------+----------------+------------+429* | | | | |430* | Kernel | xen_header | Modules | Metadata |431* | | | | |432* +---------+------------+----------------+------------+433* modulep kernend434* \________/\__________________________________________/435* module 0 module 1436*/437438fp = file_findfile(NULL, md_kerntype);439if (fp == NULL) {440printf("No FreeBSD kernel provided, aborting\n");441error = EINVAL;442goto error;443}444445error = bi_load(fp->f_args, &modulep, &kernend, false);446if (error != 0)447goto error;448449/*450* Note that the Xen kernel requires to be started with BootServices451* enabled, and hence we cannot use efi_copy_finish to relocate the452* loaded data from the staging area to the expected loaded addresses.453* This is fine because the Xen kernel is relocatable, so it can boot454* fine straight from the staging area. We use efi_translate to get the455* staging addresses where the kernels and metadata are currently456* loaded.457*/458kern_base = (uintptr_t)efi_translate(fp->f_addr);459payload_base = kern_base + fp->f_size - PAGE_SIZE;460multiboot_space += add_module(multiboot_space, kern_base, payload_base,461NULL);462multiboot_space += add_module(multiboot_space, payload_base,463(uintptr_t)efi_translate(kernend), "header");464465header.flags = XENHEADER_HAS_MODULEP_OFFSET;466header.modulep_offset = modulep - (fp->f_addr + fp->f_size - PAGE_SIZE);467archsw.arch_copyin(&header, fp->f_addr + fp->f_size - PAGE_SIZE,468sizeof(header));469470multiboot_space += add_end(multiboot_space);471total_size = (uint32_t *)(uintptr_t)(addr);472*total_size = (uintptr_t)multiboot_space - addr;473474if (*total_size > PAGE_SIZE)475panic("Multiboot header exceeds fixed size");476477efi_time_fini();478dev_cleanup();479multiboot2_exec(efi_translate(hdr->efi64_entry), addr,480stack + 128 * 1024);481482panic("exec returned");483484error:485if (addr)486BS->FreePages(addr, EFI_SIZE_TO_PAGES(PAGE_SIZE));487if (stack)488BS->FreePages(stack, EFI_SIZE_TO_PAGES(128 * 1024));489return (error);490}491492static int493obj_loadfile(char *filename, uint64_t dest, struct preloaded_file **result)494{495struct preloaded_file *mfp, *kfp, *rfp;496int error;497498/* See if there's a multiboot kernel loaded */499mfp = file_findfile(NULL, md_kerntype_mb);500if (mfp == NULL)501return (EFTYPE);502503/*504* We have a multiboot kernel loaded, see if there's a FreeBSD505* kernel loaded also.506*/507kfp = file_findfile(NULL, md_kerntype);508if (kfp == NULL) {509/*510* No kernel loaded, this must be it. The kernel has to511* be loaded as a raw file, it will be processed by512* Xen and correctly loaded as an ELF file.513*/514rfp = file_loadraw(filename, md_kerntype, 0);515if (rfp == NULL) {516printf(517"Unable to load %s as a multiboot payload kernel\n",518filename);519return (EINVAL);520}521522/* Load kernel metadata... */523setenv("kernelname", filename, 1);524error = elf64_load_modmetadata(rfp, rfp->f_addr + rfp->f_size);525if (error) {526printf("Unable to load kernel %s metadata error: %d\n",527rfp->f_name, error);528return (EINVAL);529}530531532/*533* Reserve one page at the end of the kernel to place some534* metadata in order to cope for Xen relocating the modules and535* the metadata information.536*/537rfp->f_size = roundup(rfp->f_size, PAGE_SIZE);538rfp->f_size += PAGE_SIZE;539*result = rfp;540} else {541/* The rest should be loaded as regular modules */542error = elf64_obj_loadfile(filename, dest, result);543if (error != 0) {544printf("Unable to load %s as an object file, error: %d",545filename, error);546return (error);547}548}549550return (0);551}552553static int554obj_exec(struct preloaded_file *fp)555{556557return (EFTYPE);558}559560struct file_format multiboot2 = {561.l_load = loadfile,562.l_exec = exec563};564struct file_format multiboot2_obj = {565.l_load = obj_loadfile,566.l_exec = obj_exec567};568569570