git clone https://garage44.eu/jeroen/pinnacle.git.. /kernel/src/x86_64/loader.rs
//! What the loader hands over, by either protocol a PC is booted with:
//!
//! - PVH (Xen's, which QEMU's `-kernel` speaks): its start info
//! (`hvm_start_info`, from Xen's `arch-x86/hvm/start_info.h`).
//! - Multiboot2 (GRUB's, on a real PC's UEFI): its boot information, a list
//! of tags (the Multiboot2 specification, section 3.6), asked for by the
//! header in `boot`.
//!
//! Either becomes a [`Boot`]: the RAM, ACPI's root pointer, the command line
//! and, from Multiboot2, the framebuffer the firmware left on. Everything is
//! copied out at once: Multiboot2's information lies in memory its own map
//! calls free, which the page allocator hands out next.
use crate::sync::Global;
/// What EAX holds when a Multiboot2 loader enters.
pub const MULTIBOOT2: u32 = 0x36d7_6289;
/// "xEn3" with its top bit flipped, as PVH's start info begins.
const PVH_MAGIC: u32 = 0x336e_c578;
#[repr(C)]
struct StartInfo {
magic: u32,
version: u32,
flags: u32,
nr_modules: u32,
modlist_paddr: u64,
cmdline_paddr: u64,
rsdp_paddr: u64,
memmap_paddr: u64,
memmap_entries: u32,
reserved: u32,
}
/// An entry of either protocol's memory map: the same layout in both.
#[repr(C)]
#[derive(Clone, Copy)]
struct MemmapEntry {
addr: u64,
size: u64,
kind: u32,
reserved: u32,
}
/// A range of RAM, as the loader's map gives it (type 1 in both).
#[derive(Clone, Copy)]
pub struct Ram {
pub start: u64,
pub end: u64,
}
/// The most RAM ranges kept, after adjacent ones are merged: a PC's map has
/// a handful, a laptop's dozens (firmware's own ranges cut it up, and the
/// large one above 4 GiB comes last); 64 still fits the handover's page.
const MAX_RAM: usize = 64;
/// The longest command line kept.
const MAX_COMMAND_LINE: usize = 512;
/// The framebuffer the firmware set up (UEFI's GOP, as GRUB reports it).
#[derive(Clone, Copy)]
pub struct Framebuffer {
/// Physical.
pub address: u64,
/// Bytes from one row to the next.
pub pitch: u32,
pub width: u32,
pub height: u32,
pub bits_per_pixel: u8,
/// Each colour's (position, size) in bits: red, green, blue.
pub colours: [(u8, u8); 3],
}
/// The loader's ACPI root pointer, copied: Multiboot2 gives a copy in its
/// own information, which is not kept. Written once, by [`read`] on the
/// first core before any other runs.
static RSDP: Global<[u8; 36]> = Global::new([0; 36]);
#[derive(Clone, Copy)]
pub struct Boot {
/// Which protocol entered: "PVH" or "Multiboot2".
pub protocol: &'static str,
/// ACPI's root pointer, physical; 0 when the loader gave none.
pub rsdp: u64,
/// RAM ranges, sorted and merged, in the first `ranges` places. An
/// array, not a `Vec`: read before the heap exists, to keep the rest out
/// of it.
pub ram: [Ram; MAX_RAM],
pub ranges: usize,
/// RAM ranges the map listed beyond [`MAX_RAM`]: left out, and so
/// never handed out.
pub dropped: usize,
pub framebuffer: Option<Framebuffer>,
command_line: [u8; MAX_COMMAND_LINE],
command_line_len: usize,
}
impl Boot {
fn new(protocol: &'static str) -> Self {
Self {
protocol,
rsdp: 0,
ram: [Ram { start: 0, end: 0 }; MAX_RAM],
ranges: 0,
dropped: 0,
framebuffer: None,
command_line: [0; MAX_COMMAND_LINE],
command_line_len: 0,
}
}
/// The command line the loader passed (`-append` in QEMU, after the
/// kernel's name on GRUB's `multiboot2` line).
pub fn command_line(&self) -> &str {
core::str::from_utf8(&self.command_line[..self.command_line_len]).unwrap_or("")
}
pub fn ram(&self) -> &[Ram] {
&self.ram[..self.ranges]
}
/// Where the last range of RAM ends: 0 for an empty map.
pub fn ram_end(&self) -> u64 {
self.ram().iter().map(|r| r.end).max().unwrap_or(0)
}
/// What lies between the RAM ranges within `0..end`: the firmware's,
/// never the allocator's.
pub fn holes(&self, end: u64) -> impl Iterator<Item = (usize, usize)> + '_ {
let mut at = 0;
let mut i = 0;
core::iter::from_fn(move || {
while at < end {
let next = self.ram().get(i).copied();
match next {
Some(r) if r.start <= at => {
at = at.max(r.end);
i += 1;
}
_ => {
let to = next.map_or(end, |r| r.start.min(end));
let hole = (at as usize, to as usize);
at = to;
return Some(hole);
}
}
}
None
})
}
/// Adds a range of RAM, merged with one it touches; sorted at the end
/// by [`Boot::finish`].
fn add_ram(&mut self, start: u64, end: u64) {
if end <= start {
return;
}
for r in &mut self.ram[..self.ranges] {
if start <= r.end && end >= r.start {
r.start = r.start.min(start);
r.end = r.end.max(end);
return;
}
}
if self.ranges < MAX_RAM {
self.ram[self.ranges] = Ram { start, end };
self.ranges += 1;
} else {
self.dropped += 1;
}
}
/// Sorts the ranges and merges those that touch since being added.
fn finish(&mut self) {
let n = self.ranges;
self.ram[..n].sort_unstable_by_key(|r| r.start);
let mut kept = 0;
for i in 0..n {
let r = self.ram[i];
if kept > 0 && r.start <= self.ram[kept - 1].end {
self.ram[kept - 1].end = self.ram[kept - 1].end.max(r.end);
} else {
self.ram[kept] = r;
kept += 1;
}
}
self.ranges = kept;
}
fn set_command_line(&mut self, bytes: &[u8]) {
let len = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());
let len = len.min(MAX_COMMAND_LINE);
self.command_line[..len].copy_from_slice(&bytes[..len]);
self.command_line_len = len;
}
/// Keeps a copy of the root pointer, and points [`Boot::rsdp`] at it.
fn set_rsdp(&mut self, rsdp: &[u8]) {
// SAFETY: only the first core runs, once, before ACPI is read.
let copy = unsafe { RSDP.get() };
let n = rsdp.len().min(copy.len());
copy[..n].copy_from_slice(&rsdp[..n]);
self.rsdp = crate::mmu::physical(copy.as_ptr() as usize) as u64;
}
}
/// What [`read`] read, kept for a handover to another kernel (`chain`).
/// Written once, by `read` on the first core before any other runs.
static KEPT: Global<Option<Boot>> = Global::new(None);
/// What the loader handed over, as [`read`] read it.
pub fn kept() -> Option<Boot> {
// SAFETY: written once before any other core runs, only read after.
unsafe { *KEPT.get() }
}
/// What a boot kernel adds to the command line of a kernel it hands over
/// to (`chain`): the slot's number.
pub const SLOT_ARGUMENT: &str = "pinnacle.slot=";
impl Boot {
/// The slot a boot kernel handed over from, if one did.
pub fn slot(&self) -> Option<u64> {
self.command_line()
.split(' ')
.find_map(|arg| arg.strip_prefix(SLOT_ARGUMENT)?.parse().ok())
}
/// This as Multiboot2's boot information (its specification, section
/// 3.6), with `extra` after the command line: what a boot kernel hands
/// the next kernel, which reads it as GRUB's (the memory map's RAM, the
/// framebuffer, ACPI's root pointer). Into `out`, 8-aligned; its length.
pub fn multiboot2(&self, extra: &str, out: &mut [u8]) -> Option<usize> {
let mut at = 8;
let mut tag = |out: &mut [u8], kind: u32, body: &[&[u8]]| -> Option<()> {
let len: usize = 8 + body.iter().map(|b| b.len()).sum::<usize>();
let end = at + len;
let slot = out.get_mut(at..end.next_multiple_of(8))?;
slot.fill(0);
slot[..4].copy_from_slice(&kind.to_le_bytes());
slot[4..8].copy_from_slice(&(len as u32).to_le_bytes());
let mut i = 8;
for b in body {
slot[i..i + b.len()].copy_from_slice(b);
i += b.len();
}
at = end.next_multiple_of(8);
Some(())
};
let line = self.command_line();
let space: &[u8] = if line.is_empty() { b"" } else { b" " };
tag(out, 1, &[line.as_bytes(), space, extra.as_bytes(), b"\0"])?;
let mut map = [0u8; 8 + 24 * MAX_RAM];
map[..4].copy_from_slice(&24u32.to_le_bytes());
for (i, r) in self.ram().iter().enumerate() {
let e = &mut map[8 + 24 * i..8 + 24 * (i + 1)];
e[..8].copy_from_slice(&r.start.to_le_bytes());
e[8..16].copy_from_slice(&(r.end - r.start).to_le_bytes());
e[16..20].copy_from_slice(&1u32.to_le_bytes());
}
tag(out, 6, &[&map[..8 + 24 * self.ranges]])?;
if let Some(fb) = self.framebuffer {
let mut body = [0u8; 30];
body[..8].copy_from_slice(&fb.address.to_le_bytes());
body[8..12].copy_from_slice(&fb.pitch.to_le_bytes());
body[12..16].copy_from_slice(&fb.width.to_le_bytes());
body[16..20].copy_from_slice(&fb.height.to_le_bytes());
body[20] = fb.bits_per_pixel;
body[21] = 1;
for (i, (position, size)) in fb.colours.iter().enumerate() {
body[24 + 2 * i] = *position;
body[25 + 2 * i] = *size;
}
tag(out, 8, &[&body])?;
}
if self.rsdp != 0 {
// SAFETY: ACPI's root pointer, below 4 GiB: 20 bytes, 36 from
// revision 2.
let rsdp = unsafe { bytes(self.rsdp, 36) };
if rsdp[15] >= 2 {
tag(out, 15, &[rsdp])?;
} else {
tag(out, 14, &[&rsdp[..20]])?;
}
}
tag(out, 0, &[])?;
out[..4].copy_from_slice(&(at as u32).to_le_bytes());
out[4..8].fill(0);
Some(at)
}
}
/// Bytes of physical memory, through the direct map.
///
/// # Safety
/// The range is mapped (below 4 GiB, as every loader's information is) and
/// not written meanwhile.
unsafe fn bytes(physical: u64, len: usize) -> &'static [u8] {
unsafe { core::slice::from_raw_parts(crate::mmu::virt(physical as usize) as *const u8, len) }
}
/// Reads what the loader left at physical `address`, `magic` being what it
/// left in EAX.
pub fn read(address: usize, magic: u32) -> Option<Boot> {
let boot = if magic == MULTIBOOT2 {
multiboot2(address as u64)
} else {
pvh(address)
};
// SAFETY: only the first core runs, once.
unsafe { *KEPT.get() = boot };
boot
}
fn pvh(address: usize) -> Option<Boot> {
let info = crate::mmu::virt(address) as *const StartInfo;
// SAFETY: the loader put its start info here, in RAM the kernel keeps
// out of its allocator (the first MiB).
let info = unsafe { info.read() };
if info.magic != PVH_MAGIC {
return None;
}
let mut boot = Boot::new("PVH");
// The map exists from version 1.
if info.version >= 1 && info.memmap_paddr != 0 {
let entries = crate::mmu::virt(info.memmap_paddr as usize) as *const MemmapEntry;
for i in 0..info.memmap_entries as usize {
// SAFETY: `memmap_entries` entries at `memmap_paddr`.
let entry = unsafe { entries.add(i).read() };
if entry.kind == 1 {
boot.add_ram(entry.addr, entry.addr + entry.size);
}
}
}
boot.finish();
boot.rsdp = info.rsdp_paddr;
if info.cmdline_paddr != 0 {
// SAFETY: a NUL-terminated string the loader left in the first
// MiB; up to the longest kept is read.
boot.set_command_line(unsafe { bytes(info.cmdline_paddr, MAX_COMMAND_LINE) });
}
Some(boot)
}
fn u32_at(b: &[u8], at: usize) -> u32 {
u32::from_le_bytes(b[at..at + 4].try_into().unwrap())
}
fn u64_at(b: &[u8], at: usize) -> u64 {
u64::from_le_bytes(b[at..at + 8].try_into().unwrap())
}
fn multiboot2(address: u64) -> Option<Boot> {
const END: u32 = 0;
const COMMAND_LINE: u32 = 1;
const MEMORY_MAP: u32 = 6;
const FRAMEBUFFER: u32 = 8;
const ACPI_OLD: u32 = 14;
const ACPI_NEW: u32 = 15;
// SAFETY: the information's first word is its size, the loader's
// information below 4 GiB; the whole of it is read only after.
let total = u32_at(unsafe { bytes(address, 8) }, 0) as usize;
if !(16..=1 << 20).contains(&total) {
return None;
}
// SAFETY: as above, `total` bytes.
let info = unsafe { bytes(address, total) };
let mut boot = Boot::new("Multiboot2");
let mut rsdp_new = false;
let mut at = 8;
while at + 8 <= total {
let kind = u32_at(info, at);
let size = u32_at(info, at + 4) as usize;
if kind == END || size < 8 || at + size > total {
break;
}
let tag = &info[at..at + size];
match kind {
COMMAND_LINE => boot.set_command_line(&tag[8..]),
MEMORY_MAP if size >= 16 => {
let entry_size = u32_at(tag, 8) as usize;
if entry_size >= 24 {
for e in tag[16..].chunks_exact(entry_size) {
if u32_at(e, 16) == 1 {
let (start, len) = (u64_at(e, 0), u64_at(e, 8));
boot.add_ram(start, start + len);
}
}
}
}
// RGB only (type 1); an EGA text mode is no framebuffer, nor is
// a GOP that only copies (OVMF's on a virtio-gpu: at 0).
FRAMEBUFFER if size >= 38 && tag[29] == 1 && u64_at(tag, 8) != 0 => {
boot.framebuffer = Some(Framebuffer {
address: u64_at(tag, 8),
pitch: u32_at(tag, 16),
width: u32_at(tag, 20),
height: u32_at(tag, 24),
bits_per_pixel: tag[28],
colours: [(tag[32], tag[33]), (tag[34], tag[35]), (tag[36], tag[37])],
});
}
// ACPI 2's root pointer before the first's, where both are.
ACPI_NEW => {
boot.set_rsdp(&tag[8..]);
rsdp_new = true;
}
ACPI_OLD if !rsdp_new => boot.set_rsdp(&tag[8..]),
_ => {}
}
at += size.next_multiple_of(8);
}
boot.finish();
Some(boot)
}