Path: blob/main/stand/efi/loader/arch/amd64/multiboot2.c
34907 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;81char *cmdline;82struct mb2hdr hdr;83bool keep_bs = false;8485/*86* Read MULTIBOOT_SEARCH size in order to search for the87* multiboot magic header.88*/89if (filename == NULL)90return (EFTYPE);91if ((fd = open(filename, O_RDONLY)) == -1)92return (errno);93header_search = malloc(MULTIBOOT_SEARCH);94if (header_search == NULL) {95error = ENOMEM;96goto out;97}98search_size = read(fd, header_search, MULTIBOOT_SEARCH);99100for (i = 0; i < search_size; i += MULTIBOOT_HEADER_ALIGN) {101header = header_search + i;102if (header->magic == MULTIBOOT2_HEADER_MAGIC)103break;104}105106if (i >= search_size) {107error = EFTYPE;108goto out;109}110111/* Valid multiboot header has been found, validate checksum */112if (header->magic + header->architecture + header->header_length +113header->checksum != 0) {114printf("Multiboot checksum failed, magic: %#x "115"architecture: %#x header_length %#x checksum: %#x\n",116header->magic, header->architecture, header->header_length,117header->checksum);118error = EFTYPE;119goto out;120}121122if (header->architecture != MULTIBOOT2_ARCHITECTURE_I386) {123printf("Unsupported architecture: %#x\n",124header->architecture);125error = EFTYPE;126goto out;127}128129multiboot = malloc(header->header_length - sizeof(*header));130error = lseek(fd, i + sizeof(*header), SEEK_SET);131if (error != i + sizeof(*header)) {132printf("Unable to set file pointer to header location: %d\n",133error);134goto out;135}136search_size = read(fd, multiboot,137header->header_length - sizeof(*header));138139bzero(&hdr, sizeof(hdr));140for (i = 0; i < search_size; ) {141struct multiboot_header_tag *tag;142struct multiboot_header_tag_entry_address *entry;143struct multiboot_header_tag_information_request *req;144unsigned int j;145146tag = multiboot + i;147148switch(tag->type) {149case MULTIBOOT_HEADER_TAG_INFORMATION_REQUEST:150req = (void *)tag;151for (j = 0;152j < (tag->size - sizeof(*tag)) / sizeof(uint32_t);153j++) {154switch (req->requests[j]) {155case MULTIBOOT_TAG_TYPE_MMAP:156case MULTIBOOT_TAG_TYPE_BASIC_MEMINFO:157/* Only applicable to BIOS. */158break;159160case MULTIBOOT_TAG_TYPE_EFI_BS:161case MULTIBOOT_TAG_TYPE_EFI64:162case MULTIBOOT_TAG_TYPE_EFI64_IH:163/* Tags unconditionally added. */164break;165166default:167if (req->flags &168MULTIBOOT_HEADER_TAG_OPTIONAL)169break;170171printf(172"Unknown non-optional information request %u\n",173req->requests[j]);174error = EINVAL;175goto out;176}177}178break;179180case MULTIBOOT_HEADER_TAG_EFI_BS:181/* Never shut down BS. */182keep_bs = true;183break;184185case MULTIBOOT_HEADER_TAG_MODULE_ALIGN:186/* We will align modules by default already. */187case MULTIBOOT_HEADER_TAG_END:188break;189190case MULTIBOOT_HEADER_TAG_ENTRY_ADDRESS_EFI64:191entry = (void *)tag;192hdr.efi64_entry = entry->entry_addr;193break;194195default:196if (tag->flags & MULTIBOOT_HEADER_TAG_OPTIONAL)197break;198printf("Unknown header tag %#x not optional\n",199tag->type);200error = EINVAL;201goto out;202}203204i += roundup2(tag->size, MULTIBOOT_TAG_ALIGN);205if (tag->type == MULTIBOOT_HEADER_TAG_END)206break;207}208209if (hdr.efi64_entry == 0) {210printf("No EFI64 entry address provided\n");211error = EINVAL;212goto out;213}214if (!keep_bs) {215printf("Unable to boot MB2 with BS exited\n");216error = EINVAL;217goto out;218}219220error = elf32_loadfile_raw(filename, dest, result, 1);221if (error != 0) {222printf(223"elf32_loadfile_raw failed: %d unable to load multiboot kernel\n",224error);225goto out;226}227228file_addmetadata(*result, MODINFOMD_NOCOPY | MODINFOMD_MB2HDR,229sizeof(hdr), &hdr);230231/*232* f_addr is already aligned to PAGE_SIZE, make sure233* f_size it's also aligned so when the modules are loaded234* they are aligned to PAGE_SIZE.235*/236(*result)->f_size = roundup((*result)->f_size, PAGE_SIZE);237238out:239if (header_search != NULL)240free(header_search);241if (multiboot != NULL)242free(multiboot);243close(fd);244return (error);245}246247static unsigned int add_string(void *buf, unsigned int type, const char *str)248{249struct multiboot_tag *tag;250251tag = buf;252tag->type = type;253tag->size = sizeof(*tag) + strlen(str) + 1;254strcpy(buf + sizeof(*tag), str);255return (roundup2(tag->size, MULTIBOOT_TAG_ALIGN));256}257258static unsigned int add_efi(void *buf)259{260struct multiboot_tag *bs;261struct multiboot_tag_efi64 *efi64;262struct multiboot_tag_efi64_ih *ih;263unsigned int len;264265len = 0;266bs = buf;267bs->type = MULTIBOOT_TAG_TYPE_EFI_BS;268bs->size = sizeof(*bs);269len += roundup2(bs->size, MULTIBOOT_TAG_ALIGN);270271efi64 = buf + len;272efi64->type = MULTIBOOT_TAG_TYPE_EFI64;273efi64->size = sizeof(*efi64);274efi64->pointer = (uintptr_t)ST;275len += roundup2(efi64->size, MULTIBOOT_TAG_ALIGN);276277ih = buf + len;278ih->type = MULTIBOOT_TAG_TYPE_EFI64_IH;279ih->size = sizeof(*ih);280ih->pointer = (uintptr_t)IH;281282return (len + roundup2(ih->size, MULTIBOOT_TAG_ALIGN));283}284285static unsigned int add_module(void *buf, vm_offset_t start, vm_offset_t end,286const char *cmdline)287{288struct multiboot_tag_module *mod;289290mod = buf;291mod->type = MULTIBOOT_TAG_TYPE_MODULE;292mod->size = sizeof(*mod);293mod->mod_start = start;294mod->mod_end = end;295if (cmdline != NULL)296{297strcpy(buf + sizeof(*mod), cmdline);298mod->size += strlen(cmdline) + 1;299}300301return (roundup2(mod->size, MULTIBOOT_TAG_ALIGN));302}303304static unsigned int add_end(void *buf)305{306struct multiboot_tag *tag;307308tag = buf;309tag->type = MULTIBOOT_TAG_TYPE_END;310tag->size = sizeof(*tag);311312return (roundup2(tag->size, MULTIBOOT_TAG_ALIGN));313}314315static int316exec(struct preloaded_file *fp)317{318EFI_PHYSICAL_ADDRESS addr = 0;319EFI_PHYSICAL_ADDRESS stack = 0;320EFI_STATUS status;321void *multiboot_space;322vm_offset_t modulep, kernend, kern_base,323payload_base;324char *cmdline = NULL;325size_t len;326int error;327uint32_t *total_size;328struct file_metadata *md;329struct xen_header header;330struct mb2hdr *hdr;331332333_Static_assert(sizeof(header) <= PAGE_SIZE, "header too big");334335if ((md = file_findmetadata(fp,336MODINFOMD_NOCOPY | MODINFOMD_MB2HDR)) == NULL) {337printf("Missing Multiboot2 EFI64 entry point\n");338return(EFTYPE);339}340hdr = (void *)&md->md_data;341342status = BS->AllocatePages(AllocateAnyPages, EfiLoaderData,343EFI_SIZE_TO_PAGES(PAGE_SIZE), &addr);344if (EFI_ERROR(status)) {345printf("Failed to allocate pages for multiboot2 header: %lu\n",346EFI_ERROR_CODE(status));347error = ENOMEM;348goto error;349}350status = BS->AllocatePages(AllocateAnyPages, EfiLoaderData,351EFI_SIZE_TO_PAGES(128 * 1024), &stack);352if (EFI_ERROR(status)) {353printf("Failed to allocate pages for Xen stack: %lu\n",354EFI_ERROR_CODE(status));355error = ENOMEM;356goto error;357}358359/*360* Scratch space to build the multiboot2 header. Reserve the start of361* the space to place the header with the size, which we don't know362* yet.363*/364multiboot_space = (void *)(uintptr_t)(addr + sizeof(uint32_t) * 2);365366/*367* Don't pass the memory size found by the bootloader, the memory368* available to Dom0 will be lower than that.369*/370unsetenv("smbios.memory.enabled");371372/* Set the Xen command line. */373if (fp->f_args == NULL) {374/* Add the Xen command line if it is set. */375cmdline = getenv("xen_cmdline");376if (cmdline != NULL) {377fp->f_args = strdup(cmdline);378if (fp->f_args == NULL) {379error = ENOMEM;380goto error;381}382}383}384if (fp->f_args != NULL) {385len = strlen(fp->f_name) + 1 + strlen(fp->f_args) + 1;386cmdline = malloc(len);387if (cmdline == NULL) {388error = ENOMEM;389goto error;390}391snprintf(cmdline, len, "%s %s", fp->f_name, fp->f_args);392multiboot_space += add_string(multiboot_space,393MULTIBOOT_TAG_TYPE_CMDLINE, cmdline);394free(cmdline);395}396397multiboot_space += add_string(multiboot_space,398MULTIBOOT_TAG_TYPE_BOOT_LOADER_NAME, "FreeBSD Loader");399multiboot_space += add_efi(multiboot_space);400401/*402* Prepare the multiboot module list, Xen assumes the first403* module is the Dom0 kernel, and the second one is the initramfs.404* This is not optimal for FreeBSD, that doesn't have a initramfs405* but instead loads modules dynamically and creates the metadata406* info on-the-fly.407*408* As expected, the first multiboot module is going to be the409* FreeBSD kernel loaded as a raw file. The second module is going410* to contain the metadata info and the loaded modules.411*412* There's a small header prefixed in the second module that contains413* some information required to calculate the relocated address of414* modulep based on the original offset of modulep from the start of415* the module address. Note other fields might be added to this header416* if required.417*418* Native layout:419* fp->f_addr + fp->f_size420* +---------+----------------+------------+421* | | | |422* | Kernel | Modules | Metadata |423* | | | |424* +---------+----------------+------------+425* fp->f_addr modulep kernend426*427* Xen dom0 layout:428* fp->f_addr fp->f_addr + fp->f_size429* +---------+------------+----------------+------------+430* | | | | |431* | Kernel | xen_header | Modules | Metadata |432* | | | | |433* +---------+------------+----------------+------------+434* modulep kernend435* \________/\__________________________________________/436* module 0 module 1437*/438439fp = file_findfile(NULL, md_kerntype);440if (fp == NULL) {441printf("No FreeBSD kernel provided, aborting\n");442error = EINVAL;443goto error;444}445446error = bi_load(fp->f_args, &modulep, &kernend, false);447if (error != 0)448goto error;449450/*451* Note that the Xen kernel requires to be started with BootServices452* enabled, and hence we cannot use efi_copy_finish to relocate the453* loaded data from the staging area to the expected loaded addresses.454* This is fine because the Xen kernel is relocatable, so it can boot455* fine straight from the staging area. We use efi_translate to get the456* staging addresses where the kernels and metadata are currently457* loaded.458*/459kern_base = (uintptr_t)efi_translate(fp->f_addr);460payload_base = kern_base + fp->f_size - PAGE_SIZE;461multiboot_space += add_module(multiboot_space, kern_base, payload_base,462NULL);463multiboot_space += add_module(multiboot_space, payload_base,464(uintptr_t)efi_translate(kernend), "header");465466header.flags = XENHEADER_HAS_MODULEP_OFFSET;467header.modulep_offset = modulep - (fp->f_addr + fp->f_size - PAGE_SIZE);468archsw.arch_copyin(&header, fp->f_addr + fp->f_size - PAGE_SIZE,469sizeof(header));470471multiboot_space += add_end(multiboot_space);472total_size = (uint32_t *)(uintptr_t)(addr);473*total_size = (uintptr_t)multiboot_space - addr;474475if (*total_size > PAGE_SIZE)476panic("Multiboot header exceeds fixed size");477478efi_time_fini();479dev_cleanup();480multiboot2_exec(efi_translate(hdr->efi64_entry), addr,481stack + 128 * 1024);482483panic("exec returned");484485error:486if (addr)487BS->FreePages(addr, EFI_SIZE_TO_PAGES(PAGE_SIZE));488if (stack)489BS->FreePages(stack, EFI_SIZE_TO_PAGES(128 * 1024));490return (error);491}492493static int494obj_loadfile(char *filename, uint64_t dest, struct preloaded_file **result)495{496struct preloaded_file *mfp, *kfp, *rfp;497struct kernel_module *kmp;498int error;499500/* See if there's a multiboot kernel loaded */501mfp = file_findfile(NULL, md_kerntype_mb);502if (mfp == NULL)503return (EFTYPE);504505/*506* We have a multiboot kernel loaded, see if there's a FreeBSD507* kernel loaded also.508*/509kfp = file_findfile(NULL, md_kerntype);510if (kfp == NULL) {511/*512* No kernel loaded, this must be it. The kernel has to513* be loaded as a raw file, it will be processed by514* Xen and correctly loaded as an ELF file.515*/516rfp = file_loadraw(filename, md_kerntype, 0);517if (rfp == NULL) {518printf(519"Unable to load %s as a multiboot payload kernel\n",520filename);521return (EINVAL);522}523524/* Load kernel metadata... */525setenv("kernelname", filename, 1);526error = elf64_load_modmetadata(rfp, rfp->f_addr + rfp->f_size);527if (error) {528printf("Unable to load kernel %s metadata error: %d\n",529rfp->f_name, error);530return (EINVAL);531}532533534/*535* Reserve one page at the end of the kernel to place some536* metadata in order to cope for Xen relocating the modules and537* the metadata information.538*/539rfp->f_size = roundup(rfp->f_size, PAGE_SIZE);540rfp->f_size += PAGE_SIZE;541*result = rfp;542} else {543/* The rest should be loaded as regular modules */544error = elf64_obj_loadfile(filename, dest, result);545if (error != 0) {546printf("Unable to load %s as an object file, error: %d",547filename, error);548return (error);549}550}551552return (0);553}554555static int556obj_exec(struct preloaded_file *fp)557{558559return (EFTYPE);560}561562struct file_format multiboot2 = { loadfile, exec };563struct file_format multiboot2_obj = { obj_loadfile, obj_exec };564565566